Ada 2.8.0
Fast spec-compliant URL parser
Loading...
Searching...
No Matches
serializers.cpp
Go to the documentation of this file.
1#include "ada.h"
2
3#include <array>
4#include <string>
5
6namespace ada::serializers {
7
9 const std::array<uint16_t, 8>& address, size_t& compress,
10 size_t& compress_length) noexcept {
11 for (size_t i = 0; i < 8; i++) {
12 if (address[i] == 0) {
13 size_t next = i + 1;
14 while (next != 8 && address[next] == 0) ++next;
15 const size_t count = next - i;
16 if (compress_length < count) {
17 compress_length = count;
18 compress = i;
19 if (next == 8) break;
20 i = next;
21 }
22 }
23 }
24}
25
26std::string ipv6(const std::array<uint16_t, 8>& address) noexcept {
27 size_t compress_length = 0; // The length of a long sequence of zeros.
28 size_t compress = 0; // The start of a long sequence of zeros.
29 find_longest_sequence_of_ipv6_pieces(address, compress, compress_length);
30
31 if (compress_length <= 1) {
32 // Optimization opportunity: Find a faster way then snprintf for imploding
33 // and return here.
34 compress = compress_length = 8;
35 }
36
37 std::string output(4 * 8 + 7 + 2, '\0');
38 size_t piece_index = 0;
39 char* point = output.data();
40 char* point_end = output.data() + output.size();
41 *point++ = '[';
42 while (true) {
43 if (piece_index == compress) {
44 *point++ = ':';
45 // If we skip a value initially, we need to write '::', otherwise
46 // a single ':' will do since it follows a previous ':'.
47 if (piece_index == 0) {
48 *point++ = ':';
49 }
50 piece_index += compress_length;
51 if (piece_index == 8) {
52 break;
53 }
54 }
55 point = std::to_chars(point, point_end, address[piece_index], 16).ptr;
56 piece_index++;
57 if (piece_index == 8) {
58 break;
59 }
60 *point++ = ':';
61 }
62 *point++ = ']';
63 output.resize(point - output.data());
64 return output;
65}
66
67std::string ipv4(const uint64_t address) noexcept {
68 std::string output(15, '\0');
69 char* point = output.data();
70 char* point_end = output.data() + output.size();
71 point = std::to_chars(point, point_end, uint8_t(address >> 24)).ptr;
72 for (int i = 2; i >= 0; i--) {
73 *point++ = '.';
74 point = std::to_chars(point, point_end, uint8_t(address >> (i * 8))).ptr;
75 }
76 output.resize(point - output.data());
77 return output;
78}
79
80} // namespace ada::serializers
Includes all definitions for Ada.
Includes the definitions for URL serializers.
std::string ipv6(const std::array< uint16_t, 8 > &address) noexcept
void find_longest_sequence_of_ipv6_pieces(const std::array< uint16_t, 8 > &address, size_t &compress, size_t &compress_length) noexcept
std::string ipv4(uint64_t address) noexcept