Coverage Report

Created: 2026-12-01 06:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ada-url/build/singleheader/ada.h
Line
Count
Source
1
/* auto-generated on 2026-12-01 06:38:24 +0100. Do not edit! */
2
/* begin file include/ada.h */
3
/**
4
 * @file ada.h
5
 * @brief Main header for the Ada URL parser library.
6
 *
7
 * This is the primary entry point for the Ada URL parser library. Including
8
 * this single header provides access to the complete Ada API, including:
9
 *
10
 * - URL parsing via `ada::parse()` function
11
 * - Two URL representations: `ada::url` and `ada::url_aggregator`
12
 * - URL search parameters via `ada::url_search_params`
13
 * - URL pattern matching via `ada::url_pattern` (URLPattern API)
14
 * - IDNA (Internationalized Domain Names) support
15
 *
16
 * @example
17
 * ```cpp
18
 *
19
 * // Parse a URL
20
 * auto url = ada::parse("https://example.com/path?query=1");
21
 * if (url) {
22
 *     std::cout << url->get_hostname(); // "example.com"
23
 * }
24
 * ```
25
 *
26
 * @see https://url.spec.whatwg.org/ - WHATWG URL Standard
27
 * @see https://github.com/ada-url/ada - Ada URL Parser GitHub Repository
28
 */
29
#ifndef ADA_H
30
#define ADA_H
31
32
/* begin file include/ada/ada_idna.h */
33
/* auto-generated on 2026-11-29 18:03:30 -0500. Do not edit! */
34
/* begin file include/idna.h */
35
#ifndef ADA_IDNA_H
36
#define ADA_IDNA_H
37
38
/* begin file include/ada/idna/unicode_transcoding.h */
39
#ifndef ADA_IDNA_UNICODE_TRANSCODING_H
40
#define ADA_IDNA_UNICODE_TRANSCODING_H
41
42
#include <string>
43
#include <string_view>
44
45
namespace ada::idna {
46
47
size_t utf8_to_utf32(const char* buf, size_t len, char32_t* utf32_output);
48
49
size_t utf8_length_from_utf32(const char32_t* buf, size_t len);
50
51
size_t utf32_length_from_utf8(const char* buf, size_t len);
52
53
size_t utf32_to_utf8(const char32_t* buf, size_t len, char* utf8_output);
54
55
}  // namespace ada::idna
56
57
#endif  // ADA_IDNA_UNICODE_TRANSCODING_H
58
/* end file include/ada/idna/unicode_transcoding.h */
59
/* begin file include/ada/idna/mapping.h */
60
#ifndef ADA_IDNA_MAPPING_H
61
#define ADA_IDNA_MAPPING_H
62
63
#include <string>
64
#include <string_view>
65
66
namespace ada::idna {
67
68
// If the input is ascii, then the mapping is just -> lower case.
69
void ascii_map(char* input, size_t length);
70
// Map the characters according to IDNA, returning the empty string on error.
71
std::u32string map(std::u32string_view input);
72
// Map into an existing buffer (cleared on entry). Returns false if any code
73
// point is disallowed. Reusing the buffer avoids repeated heap allocations
74
// when called in a loop over multiple labels.
75
bool map(std::u32string_view input, std::u32string& out);
76
77
}  // namespace ada::idna
78
79
#endif
80
/* end file include/ada/idna/mapping.h */
81
/* begin file include/ada/idna/normalization.h */
82
#ifndef ADA_IDNA_NORMALIZATION_H
83
#define ADA_IDNA_NORMALIZATION_H
84
85
#include <string>
86
#include <string_view>
87
88
namespace ada::idna {
89
90
// Returns true if `input` is already in Unicode Normalization Form C.
91
// Requires that internal tables have been loaded (call ensure via normalize
92
// or map first, or this returns false if tables are unavailable).
93
[[nodiscard]] bool is_already_nfc(std::u32string_view input) noexcept;
94
95
// Normalize the characters according to IDNA (Unicode Normalization Form C).
96
// Returns false if the internal Unicode tables could not be loaded; in that
97
// case `input` is left unchanged. Skips work when the string is already NFC.
98
[[nodiscard]] bool normalize(std::u32string& input);
99
100
}  // namespace ada::idna
101
#endif
102
/* end file include/ada/idna/normalization.h */
103
/* begin file include/ada/idna/punycode.h */
104
#ifndef ADA_IDNA_PUNYCODE_H
105
#define ADA_IDNA_PUNYCODE_H
106
107
#include <string>
108
#include <string_view>
109
110
namespace ada::idna {
111
112
bool punycode_to_utf32(std::string_view input, std::u32string& out);
113
bool verify_punycode(std::string_view input);
114
bool utf32_to_punycode(std::u32string_view input, std::string& out);
115
116
}  // namespace ada::idna
117
118
#endif  // ADA_IDNA_PUNYCODE_H
119
/* end file include/ada/idna/punycode.h */
120
/* begin file include/ada/idna/validity.h */
121
#ifndef ADA_IDNA_VALIDITY_H
122
#define ADA_IDNA_VALIDITY_H
123
124
#include <string>
125
#include <string_view>
126
127
namespace ada::idna {
128
129
/**
130
 * @see https://www.unicode.org/reports/tr46/#Validity_Criteria
131
 */
132
bool is_label_valid(std::u32string_view label);
133
134
}  // namespace ada::idna
135
136
#endif  // ADA_IDNA_VALIDITY_H
137
/* end file include/ada/idna/validity.h */
138
/* begin file include/ada/idna/to_ascii.h */
139
#ifndef ADA_IDNA_TO_ASCII_H
140
#define ADA_IDNA_TO_ASCII_H
141
142
#include <string>
143
#include <string_view>
144
145
/* begin file include/ada/idna/limits.h */
146
#ifndef ADA_IDNA_LIMITS_H
147
#define ADA_IDNA_LIMITS_H
148
149
#include <cstddef>
150
151
namespace ada::idna {
152
153
// Maximum accepted UTF-8 domain length for non-ASCII to_ascii input and for
154
// to_unicode input.
155
// Bounds heap growth under untrusted input (DoS resistance). DNS wire limits
156
// are smaller; this allows long Unicode labels used in URL tests/fixtures.
157
inline constexpr size_t max_domain_input_bytes = 16384;
158
159
}  // namespace ada::idna
160
161
#endif  // ADA_IDNA_LIMITS_H
162
/* end file include/ada/idna/limits.h */
163
164
namespace ada::idna {
165
166
// Converts a domain (e.g., www.google.com) possibly containing international
167
// characters to an ascii domain (with punycode). It will not do percent
168
// decoding: percent decoding should be done prior to calling this function. We
169
// do not remove tabs and spaces, they should have been removed prior to calling
170
// this function. We also do not trim control characters. We also assume that
171
// the input is not empty. We return "" on error. Non-ASCII inputs longer than
172
// max_domain_input_bytes are rejected; ASCII inputs of any length are accepted
173
// (they are only lowercased).
174
//
175
// This function may accept or even produce invalid domains (WHATWG carve-outs).
176
std::string to_ascii(std::string_view ut8_string);
177
178
// Same as to_ascii, but writes into `out` and returns false on error without
179
// relying on empty-string ambiguity.
180
[[nodiscard]] bool to_ascii(std::string_view ut8_string, std::string& out);
181
182
// Returns true if the string contains a forbidden code point according to the
183
// WHATGL URL specification:
184
// https://url.spec.whatwg.org/#forbidden-domain-code-point
185
bool contains_forbidden_domain_code_point(std::string_view ascii_string);
186
187
bool constexpr is_ascii(std::u32string_view view);
188
bool constexpr is_ascii(std::string_view view);
189
190
}  // namespace ada::idna
191
192
#endif  // ADA_IDNA_TO_ASCII_H
193
/* end file include/ada/idna/to_ascii.h */
194
/* begin file include/ada/idna/to_unicode.h */
195
#ifndef ADA_IDNA_TO_UNICODE_H
196
#define ADA_IDNA_TO_UNICODE_H
197
198
#include <string>
199
#include <string_view>
200
201
namespace ada::idna {
202
203
// UTS #46 ToUnicode. Never fails per the standard: on step failure the original
204
// label is kept. Inputs longer than max_domain_input_bytes are returned
205
// unchanged as a safety measure under untrusted input.
206
std::string to_unicode(std::string_view input);
207
208
// Writes into `out`. Returns false only if the input exceeds
209
// max_domain_input_bytes (out is left empty). Otherwise always returns true
210
// (ToUnicode does not fail).
211
[[nodiscard]] bool to_unicode(std::string_view input, std::string& out);
212
213
}  // namespace ada::idna
214
215
#endif  // ADA_IDNA_TO_UNICODE_H
216
/* end file include/ada/idna/to_unicode.h */
217
/* begin file include/ada/idna/identifier.h */
218
#ifndef ADA_IDNA_IDENTIFIER_H
219
#define ADA_IDNA_IDENTIFIER_H
220
221
#include <string>
222
#include <string_view>
223
224
namespace ada::idna {
225
226
// Verify if it is valid name code point given a Unicode code point and a
227
// boolean first: If first is true return the result of checking if code point
228
// is contained in the IdentifierStart set of code points. Otherwise return the
229
// result of checking if code point is contained in the IdentifierPart set of
230
// code points. Returns false if the input is empty or the code point is not
231
// valid. There is minimal Unicode error handling: the input should be valid
232
// UTF-8. https://urlpattern.spec.whatwg.org/#is-a-valid-name-code-point
233
bool valid_name_code_point(char32_t code_point, bool first);
234
235
}  // namespace ada::idna
236
237
#endif
238
/* end file include/ada/idna/identifier.h */
239
240
#endif
241
/* end file include/idna.h */
242
/* end file include/ada/ada_idna.h */
243
/* begin file include/ada/character_sets.h */
244
/**
245
 * @file character_sets.h
246
 * @brief Declaration of the character sets used by unicode functions.
247
 * @author Node.js
248
 * @see https://github.com/nodejs/node/blob/main/src/node_url_tables.cc
249
 */
250
#ifndef ADA_CHARACTER_SETS_H
251
#define ADA_CHARACTER_SETS_H
252
253
/* begin file include/ada/common_defs.h */
254
/**
255
 * @file common_defs.h
256
 * @brief Cross-platform compiler macros and common definitions.
257
 *
258
 * This header provides compiler-specific macros for optimization hints,
259
 * platform detection, SIMD support detection, and development/debug utilities.
260
 * It ensures consistent behavior across different compilers (GCC, Clang, MSVC).
261
 */
262
#ifndef ADA_COMMON_DEFS_H
263
#define ADA_COMMON_DEFS_H
264
265
// https://en.cppreference.com/w/cpp/feature_test#Library_features
266
// detect C++20 features
267
#include <version>
268
269
#ifdef _MSC_VER
270
#define ADA_VISUAL_STUDIO 1
271
/**
272
 * We want to differentiate carefully between
273
 * clang under visual studio and regular visual
274
 * studio.
275
 */
276
#ifdef __clang__
277
// clang under visual studio
278
#define ADA_CLANG_VISUAL_STUDIO 1
279
#else
280
// just regular visual studio (best guess)
281
#define ADA_REGULAR_VISUAL_STUDIO 1
282
#endif  // __clang__
283
#endif  // _MSC_VER
284
285
#if defined(__GNUC__)
286
// Marks a block with a name so that MCA analysis can see it.
287
#define ADA_BEGIN_DEBUG_BLOCK(name) __asm volatile("# LLVM-MCA-BEGIN " #name);
288
#define ADA_END_DEBUG_BLOCK(name) __asm volatile("# LLVM-MCA-END " #name);
289
#define ADA_DEBUG_BLOCK(name, block) \
290
  BEGIN_DEBUG_BLOCK(name);           \
291
  block;                             \
292
  END_DEBUG_BLOCK(name);
293
#else
294
#define ADA_BEGIN_DEBUG_BLOCK(name)
295
#define ADA_END_DEBUG_BLOCK(name)
296
#define ADA_DEBUG_BLOCK(name, block)
297
#endif
298
299
// Align to N-byte boundary
300
#define ADA_ROUNDUP_N(a, n) (((a) + ((n) - 1)) & ~((n) - 1))
301
#define ADA_ROUNDDOWN_N(a, n) ((a) & ~((n) - 1))
302
303
#define ADA_ISALIGNED_N(ptr, n) (((uintptr_t)(ptr) & ((n) - 1)) == 0)
304
305
#if defined(ADA_REGULAR_VISUAL_STUDIO)
306
307
#define ada_really_inline __forceinline
308
#define ada_never_inline __declspec(noinline)
309
310
#define ada_unused
311
#define ada_warn_unused
312
313
#define ADA_PUSH_DISABLE_WARNINGS __pragma(warning(push))
314
#define ADA_PUSH_DISABLE_ALL_WARNINGS __pragma(warning(push, 0))
315
#define ADA_DISABLE_VS_WARNING(WARNING_NUMBER) \
316
  __pragma(warning(disable : WARNING_NUMBER))
317
// Get rid of Intellisense-only warnings (Code Analysis)
318
// Though __has_include is C++17, it is supported in Visual Studio 2017 or
319
// better (_MSC_VER>=1910).
320
#ifdef __has_include
321
#if __has_include(<CppCoreCheck\Warnings.h>)
322
#include <CppCoreCheck\Warnings.h>
323
#define ADA_DISABLE_UNDESIRED_WARNINGS \
324
  ADA_DISABLE_VS_WARNING(ALL_CPPCORECHECK_WARNINGS)
325
#endif
326
#endif
327
328
#ifndef ADA_DISABLE_UNDESIRED_WARNINGS
329
#define ADA_DISABLE_UNDESIRED_WARNINGS
330
#endif
331
332
#define ADA_DISABLE_DEPRECATED_WARNING ADA_DISABLE_VS_WARNING(4996)
333
#define ADA_DISABLE_STRICT_OVERFLOW_WARNING
334
#define ADA_POP_DISABLE_WARNINGS __pragma(warning(pop))
335
336
#else  // ADA_REGULAR_VISUAL_STUDIO
337
338
#define ada_really_inline inline __attribute__((always_inline))
339
#define ada_never_inline inline __attribute__((noinline))
340
341
#define ada_unused __attribute__((unused))
342
#define ada_warn_unused __attribute__((warn_unused_result))
343
344
#define ADA_PUSH_DISABLE_WARNINGS _Pragma("GCC diagnostic push")
345
// gcc doesn't seem to disable all warnings with all and extra, add warnings
346
// here as necessary
347
#define ADA_PUSH_DISABLE_ALL_WARNINGS               \
348
  ADA_PUSH_DISABLE_WARNINGS                         \
349
  ADA_DISABLE_GCC_WARNING("-Weffc++")               \
350
  ADA_DISABLE_GCC_WARNING("-Wall")                  \
351
  ADA_DISABLE_GCC_WARNING("-Wconversion")           \
352
  ADA_DISABLE_GCC_WARNING("-Wextra")                \
353
  ADA_DISABLE_GCC_WARNING("-Wattributes")           \
354
  ADA_DISABLE_GCC_WARNING("-Wimplicit-fallthrough") \
355
  ADA_DISABLE_GCC_WARNING("-Wnon-virtual-dtor")     \
356
  ADA_DISABLE_GCC_WARNING("-Wreturn-type")          \
357
  ADA_DISABLE_GCC_WARNING("-Wshadow")               \
358
  ADA_DISABLE_GCC_WARNING("-Wunused-parameter")     \
359
  ADA_DISABLE_GCC_WARNING("-Wunused-variable")      \
360
  ADA_DISABLE_GCC_WARNING("-Wsign-compare")
361
#define ADA_PRAGMA(P) _Pragma(#P)
362
#define ADA_DISABLE_GCC_WARNING(WARNING) \
363
  ADA_PRAGMA(GCC diagnostic ignored WARNING)
364
#if defined(ADA_CLANG_VISUAL_STUDIO)
365
#define ADA_DISABLE_UNDESIRED_WARNINGS \
366
  ADA_DISABLE_GCC_WARNING("-Wmicrosoft-include")
367
#else
368
#define ADA_DISABLE_UNDESIRED_WARNINGS
369
#endif
370
#define ADA_DISABLE_DEPRECATED_WARNING \
371
  ADA_DISABLE_GCC_WARNING("-Wdeprecated-declarations")
372
#define ADA_DISABLE_STRICT_OVERFLOW_WARNING \
373
  ADA_DISABLE_GCC_WARNING("-Wstrict-overflow")
374
#define ADA_POP_DISABLE_WARNINGS _Pragma("GCC diagnostic pop")
375
376
#endif  // MSC_VER
377
378
#if defined(ADA_VISUAL_STUDIO)
379
/**
380
 * It does not matter here whether you are using
381
 * the regular visual studio or clang under visual
382
 * studio.
383
 */
384
#if ADA_USING_LIBRARY
385
#define ADA_DLLIMPORTEXPORT __declspec(dllimport)
386
#else
387
#define ADA_DLLIMPORTEXPORT __declspec(dllexport)
388
#endif
389
#else
390
#define ADA_DLLIMPORTEXPORT
391
#endif
392
393
/// If EXPR is an error, returns it.
394
#define ADA_TRY(EXPR)   \
395
  {                     \
396
    auto _err = (EXPR); \
397
    if (_err) {         \
398
      return _err;      \
399
    }                   \
400
  }
401
402
// __has_cpp_attribute is part of C++20
403
#if !defined(__has_cpp_attribute)
404
#define __has_cpp_attribute(x) 0
405
#endif
406
407
#if __has_cpp_attribute(gnu::noinline)
408
#define ADA_ATTRIBUTE_NOINLINE [[gnu::noinline]]
409
#else
410
#define ADA_ATTRIBUTE_NOINLINE
411
#endif
412
413
namespace ada {
414
0
[[noreturn]] inline void unreachable() {
415
0
#ifdef __GNUC__
416
0
  __builtin_unreachable();
417
#elif defined(_MSC_VER)
418
  __assume(false);
419
#else
420
#endif
421
0
}
422
}  // namespace ada
423
424
// Unless the programmer has already set ADA_DEVELOPMENT_CHECKS,
425
// we want to set it under debug builds. We detect a debug build
426
// under Visual Studio when the _DEBUG macro is set. Under the other
427
// compilers, we use the fact that they define __OPTIMIZE__ whenever
428
// they allow optimizations.
429
// It is possible that this could miss some cases where ADA_DEVELOPMENT_CHECKS
430
// is helpful, but the programmer can set the macro ADA_DEVELOPMENT_CHECKS.
431
// It could also wrongly set ADA_DEVELOPMENT_CHECKS (e.g., if the programmer
432
// sets _DEBUG in a release build under Visual Studio, or if some compiler fails
433
// to set the __OPTIMIZE__ macro).
434
#if !defined(ADA_DEVELOPMENT_CHECKS) && !defined(NDEBUG)
435
#ifdef _MSC_VER
436
// Visual Studio seems to set _DEBUG for debug builds.
437
#ifdef _DEBUG
438
#define ADA_DEVELOPMENT_CHECKS 1
439
#endif  // _DEBUG
440
#else   // _MSC_VER
441
// All other compilers appear to set __OPTIMIZE__ to a positive integer
442
// when the compiler is optimizing.
443
#ifndef __OPTIMIZE__
444
#define ADA_DEVELOPMENT_CHECKS 1
445
#endif  // __OPTIMIZE__
446
#endif  // _MSC_VER
447
#endif  // ADA_DEVELOPMENT_CHECKS
448
449
#define ADA_STR(x) #x
450
451
#if ADA_DEVELOPMENT_CHECKS
452
#define ADA_REQUIRE(EXPR) \
453
  {                       \
454
    if (!(EXPR) { abort(); }) }
455
456
#define ADA_FAIL(MESSAGE)                            \
457
  do {                                               \
458
    std::cerr << "FAIL: " << (MESSAGE) << std::endl; \
459
    abort();                                         \
460
  } while (0);
461
#define ADA_ASSERT_EQUAL(LHS, RHS, MESSAGE)                                    \
462
  do {                                                                         \
463
    if (LHS != RHS) {                                                          \
464
      std::cerr << "Mismatch: '" << LHS << "' - '" << RHS << "'" << std::endl; \
465
      ADA_FAIL(MESSAGE);                                                       \
466
    }                                                                          \
467
  } while (0);
468
#define ADA_ASSERT_TRUE(COND)                                               \
469
  do {                                                                      \
470
    if (!(COND)) {                                                          \
471
      std::cerr << "Assert at line " << __LINE__ << " of file " << __FILE__ \
472
                << std::endl;                                               \
473
      ADA_FAIL(ADA_STR(COND));                                              \
474
    }                                                                       \
475
  } while (0);
476
#else
477
#define ADA_FAIL(MESSAGE)
478
#define ADA_ASSERT_EQUAL(LHS, RHS, MESSAGE)
479
#define ADA_ASSERT_TRUE(COND)
480
#endif
481
482
#ifdef ADA_VISUAL_STUDIO
483
#define ADA_ASSUME(COND) __assume(COND)
484
#else
485
#define ADA_ASSUME(COND)       \
486
  do {                         \
487
    if (!(COND)) {             \
488
      __builtin_unreachable(); \
489
    }                          \
490
  } while (0)
491
#endif
492
493
#if defined(__SSSE3__)
494
#define ADA_SSSE3 1
495
#endif
496
497
#if defined(__SSE2__) || defined(__x86_64__) || defined(__x86_64) || \
498
    (defined(_M_AMD64) || defined(_M_X64) ||                         \
499
     (defined(_M_IX86_FP) && _M_IX86_FP == 2))
500
#define ADA_SSE2 1
501
#endif
502
503
// AVX-512 byte/word ops + 128/256-bit vectors of AVX-512 instructions.
504
// Used for optional high-performance IP address parsing kernels.
505
#if defined(__AVX512BW__) && defined(__AVX512VL__)
506
#define ADA_AVX512 1
507
#endif
508
509
#if defined(__aarch64__) || defined(_M_ARM64)
510
#define ADA_NEON 1
511
#endif
512
513
#if defined(__loongarch_sx)
514
#define ADA_LSX 1
515
#endif
516
517
#if defined(__riscv_v) && __riscv_v_intrinsic >= 11000
518
// Support RVV intrinsics v0.11 and above
519
#define ADA_RVV 1
520
#endif
521
522
#ifndef __has_cpp_attribute
523
#define ada_lifetime_bound
524
#elif __has_cpp_attribute(msvc::lifetimebound)
525
#define ada_lifetime_bound [[msvc::lifetimebound]]
526
#elif __has_cpp_attribute(clang::lifetimebound)
527
#define ada_lifetime_bound [[clang::lifetimebound]]
528
#elif __has_cpp_attribute(lifetimebound)
529
#define ada_lifetime_bound [[lifetimebound]]
530
#else
531
#define ada_lifetime_bound
532
#endif
533
534
#ifdef __cpp_lib_format
535
#if __cpp_lib_format >= 202110L
536
#include <format>
537
#define ADA_HAS_FORMAT 1
538
#endif
539
#endif
540
541
#ifndef ADA_INCLUDE_URL_PATTERN
542
#define ADA_INCLUDE_URL_PATTERN 1
543
#endif  // ADA_INCLUDE_URL_PATTERN
544
545
// When set (the default), NEON all-zero tests use an integer compare. Define
546
// it to 0 to reinterpret the bits as a double and compare against 0.0: that
547
// avoids a GPR transfer but is incorrect if flush-to-zero is enabled (e.g.,
548
// when the application is built with -ffast-math).
549
#ifndef ADA_NEON_SAFE_ZERO_CHECK
550
#define ADA_NEON_SAFE_ZERO_CHECK 1
551
#endif  // ADA_NEON_SAFE_ZERO_CHECK
552
553
#endif  // ADA_COMMON_DEFS_H
554
/* end file include/ada/common_defs.h */
555
#include <cstdint>
556
557
/**
558
 * These functions are not part of our public API and may
559
 * change at any time.
560
 * @private
561
 * @namespace ada::character_sets
562
 * @brief Includes the definitions for unicode character sets.
563
 */
564
namespace ada::character_sets {
565
ada_really_inline constexpr bool bit_at(const uint8_t a[], uint8_t i);
566
}  // namespace ada::character_sets
567
568
#endif  // ADA_CHARACTER_SETS_H
569
/* end file include/ada/character_sets.h */
570
/* begin file include/ada/character_sets-inl.h */
571
/**
572
 * @file character_sets-inl.h
573
 * @brief Definitions of the character sets used by unicode functions.
574
 * @author Node.js
575
 * @see https://github.com/nodejs/node/blob/main/src/node_url_tables.cc
576
 */
577
#ifndef ADA_CHARACTER_SETS_INL_H
578
#define ADA_CHARACTER_SETS_INL_H
579
580
581
#include <cstdint>
582
583
/**
584
 * These functions are not part of our public API and may
585
 * change at any time.
586
 * @private
587
 */
588
namespace ada::character_sets {
589
590
constexpr char hex[1024] =
591
    "%00\0%01\0%02\0%03\0%04\0%05\0%06\0%07\0"
592
    "%08\0%09\0%0A\0%0B\0%0C\0%0D\0%0E\0%0F\0"
593
    "%10\0%11\0%12\0%13\0%14\0%15\0%16\0%17\0"
594
    "%18\0%19\0%1A\0%1B\0%1C\0%1D\0%1E\0%1F\0"
595
    "%20\0%21\0%22\0%23\0%24\0%25\0%26\0%27\0"
596
    "%28\0%29\0%2A\0%2B\0%2C\0%2D\0%2E\0%2F\0"
597
    "%30\0%31\0%32\0%33\0%34\0%35\0%36\0%37\0"
598
    "%38\0%39\0%3A\0%3B\0%3C\0%3D\0%3E\0%3F\0"
599
    "%40\0%41\0%42\0%43\0%44\0%45\0%46\0%47\0"
600
    "%48\0%49\0%4A\0%4B\0%4C\0%4D\0%4E\0%4F\0"
601
    "%50\0%51\0%52\0%53\0%54\0%55\0%56\0%57\0"
602
    "%58\0%59\0%5A\0%5B\0%5C\0%5D\0%5E\0%5F\0"
603
    "%60\0%61\0%62\0%63\0%64\0%65\0%66\0%67\0"
604
    "%68\0%69\0%6A\0%6B\0%6C\0%6D\0%6E\0%6F\0"
605
    "%70\0%71\0%72\0%73\0%74\0%75\0%76\0%77\0"
606
    "%78\0%79\0%7A\0%7B\0%7C\0%7D\0%7E\0%7F\0"
607
    "%80\0%81\0%82\0%83\0%84\0%85\0%86\0%87\0"
608
    "%88\0%89\0%8A\0%8B\0%8C\0%8D\0%8E\0%8F\0"
609
    "%90\0%91\0%92\0%93\0%94\0%95\0%96\0%97\0"
610
    "%98\0%99\0%9A\0%9B\0%9C\0%9D\0%9E\0%9F\0"
611
    "%A0\0%A1\0%A2\0%A3\0%A4\0%A5\0%A6\0%A7\0"
612
    "%A8\0%A9\0%AA\0%AB\0%AC\0%AD\0%AE\0%AF\0"
613
    "%B0\0%B1\0%B2\0%B3\0%B4\0%B5\0%B6\0%B7\0"
614
    "%B8\0%B9\0%BA\0%BB\0%BC\0%BD\0%BE\0%BF\0"
615
    "%C0\0%C1\0%C2\0%C3\0%C4\0%C5\0%C6\0%C7\0"
616
    "%C8\0%C9\0%CA\0%CB\0%CC\0%CD\0%CE\0%CF\0"
617
    "%D0\0%D1\0%D2\0%D3\0%D4\0%D5\0%D6\0%D7\0"
618
    "%D8\0%D9\0%DA\0%DB\0%DC\0%DD\0%DE\0%DF\0"
619
    "%E0\0%E1\0%E2\0%E3\0%E4\0%E5\0%E6\0%E7\0"
620
    "%E8\0%E9\0%EA\0%EB\0%EC\0%ED\0%EE\0%EF\0"
621
    "%F0\0%F1\0%F2\0%F3\0%F4\0%F5\0%F6\0%F7\0"
622
    "%F8\0%F9\0%FA\0%FB\0%FC\0%FD\0%FE\0%FF";
623
624
constexpr uint8_t C0_CONTROL_PERCENT_ENCODE[32] = {
625
    // 00     01     02     03     04     05     06     07
626
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
627
    // 08     09     0A     0B     0C     0D     0E     0F
628
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
629
    // 10     11     12     13     14     15     16     17
630
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
631
    // 18     19     1A     1B     1C     1D     1E     1F
632
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
633
    // 20     21     22     23     24     25     26     27
634
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
635
    // 28     29     2A     2B     2C     2D     2E     2F
636
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
637
    // 30     31     32     33     34     35     36     37
638
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
639
    // 38     39     3A     3B     3C     3D     3E     3F
640
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
641
    // 40     41     42     43     44     45     46     47
642
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
643
    // 48     49     4A     4B     4C     4D     4E     4F
644
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
645
    // 50     51     52     53     54     55     56     57
646
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
647
    // 58     59     5A     5B     5C     5D     5E     5F
648
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
649
    // 60     61     62     63     64     65     66     67
650
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
651
    // 68     69     6A     6B     6C     6D     6E     6F
652
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
653
    // 70     71     72     73     74     75     76     77
654
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
655
    // 78     79     7A     7B     7C     7D     7E     7F
656
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x80,
657
    // 80     81     82     83     84     85     86     87
658
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
659
    // 88     89     8A     8B     8C     8D     8E     8F
660
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
661
    // 90     91     92     93     94     95     96     97
662
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
663
    // 98     99     9A     9B     9C     9D     9E     9F
664
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
665
    // A0     A1     A2     A3     A4     A5     A6     A7
666
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
667
    // A8     A9     AA     AB     AC     AD     AE     AF
668
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
669
    // B0     B1     B2     B3     B4     B5     B6     B7
670
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
671
    // B8     B9     BA     BB     BC     BD     BE     BF
672
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
673
    // C0     C1     C2     C3     C4     C5     C6     C7
674
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
675
    // C8     C9     CA     CB     CC     CD     CE     CF
676
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
677
    // D0     D1     D2     D3     D4     D5     D6     D7
678
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
679
    // D8     D9     DA     DB     DC     DD     DE     DF
680
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
681
    // E0     E1     E2     E3     E4     E5     E6     E7
682
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
683
    // E8     E9     EA     EB     EC     ED     EE     EF
684
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
685
    // F0     F1     F2     F3     F4     F5     F6     F7
686
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
687
    // F8     F9     FA     FB     FC     FD     FE     FF
688
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80};
689
690
constexpr uint8_t SPECIAL_QUERY_PERCENT_ENCODE[32] = {
691
    // 00     01     02     03     04     05     06     07
692
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
693
    // 08     09     0A     0B     0C     0D     0E     0F
694
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
695
    // 10     11     12     13     14     15     16     17
696
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
697
    // 18     19     1A     1B     1C     1D     1E     1F
698
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
699
    // 20     21     22     23     24     25     26     27
700
    0x01 | 0x00 | 0x04 | 0x08 | 0x00 | 0x00 | 0x00 | 0x80,
701
    // 28     29     2A     2B     2C     2D     2E     2F
702
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
703
    // 30     31     32     33     34     35     36     37
704
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
705
    // 38     39     3A     3B     3C     3D     3E     3F
706
    0x00 | 0x00 | 0x00 | 0x00 | 0x10 | 0x00 | 0x40 | 0x00,
707
    // 40     41     42     43     44     45     46     47
708
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
709
    // 48     49     4A     4B     4C     4D     4E     4F
710
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
711
    // 50     51     52     53     54     55     56     57
712
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
713
    // 58     59     5A     5B     5C     5D     5E     5F
714
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
715
    // 60     61     62     63     64     65     66     67
716
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
717
    // 68     69     6A     6B     6C     6D     6E     6F
718
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
719
    // 70     71     72     73     74     75     76     77
720
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
721
    // 78     79     7A     7B     7C     7D     7E     7F
722
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x80,
723
    // 80     81     82     83     84     85     86     87
724
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
725
    // 88     89     8A     8B     8C     8D     8E     8F
726
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
727
    // 90     91     92     93     94     95     96     97
728
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
729
    // 98     99     9A     9B     9C     9D     9E     9F
730
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
731
    // A0     A1     A2     A3     A4     A5     A6     A7
732
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
733
    // A8     A9     AA     AB     AC     AD     AE     AF
734
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
735
    // B0     B1     B2     B3     B4     B5     B6     B7
736
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
737
    // B8     B9     BA     BB     BC     BD     BE     BF
738
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
739
    // C0     C1     C2     C3     C4     C5     C6     C7
740
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
741
    // C8     C9     CA     CB     CC     CD     CE     CF
742
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
743
    // D0     D1     D2     D3     D4     D5     D6     D7
744
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
745
    // D8     D9     DA     DB     DC     DD     DE     DF
746
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
747
    // E0     E1     E2     E3     E4     E5     E6     E7
748
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
749
    // E8     E9     EA     EB     EC     ED     EE     EF
750
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
751
    // F0     F1     F2     F3     F4     F5     F6     F7
752
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
753
    // F8     F9     FA     FB     FC     FD     FE     FF
754
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80};
755
756
constexpr uint8_t QUERY_PERCENT_ENCODE[32] = {
757
    // 00     01     02     03     04     05     06     07
758
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
759
    // 08     09     0A     0B     0C     0D     0E     0F
760
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
761
    // 10     11     12     13     14     15     16     17
762
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
763
    // 18     19     1A     1B     1C     1D     1E     1F
764
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
765
    // 20     21     22     23     24     25     26     27
766
    0x01 | 0x00 | 0x04 | 0x08 | 0x00 | 0x00 | 0x00 | 0x00,
767
    // 28     29     2A     2B     2C     2D     2E     2F
768
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
769
    // 30     31     32     33     34     35     36     37
770
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
771
    // 38     39     3A     3B     3C     3D     3E     3F
772
    0x00 | 0x00 | 0x00 | 0x00 | 0x10 | 0x00 | 0x40 | 0x00,
773
    // 40     41     42     43     44     45     46     47
774
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
775
    // 48     49     4A     4B     4C     4D     4E     4F
776
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
777
    // 50     51     52     53     54     55     56     57
778
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
779
    // 58     59     5A     5B     5C     5D     5E     5F
780
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
781
    // 60     61     62     63     64     65     66     67
782
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
783
    // 68     69     6A     6B     6C     6D     6E     6F
784
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
785
    // 70     71     72     73     74     75     76     77
786
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
787
    // 78     79     7A     7B     7C     7D     7E     7F
788
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x80,
789
    // 80     81     82     83     84     85     86     87
790
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
791
    // 88     89     8A     8B     8C     8D     8E     8F
792
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
793
    // 90     91     92     93     94     95     96     97
794
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
795
    // 98     99     9A     9B     9C     9D     9E     9F
796
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
797
    // A0     A1     A2     A3     A4     A5     A6     A7
798
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
799
    // A8     A9     AA     AB     AC     AD     AE     AF
800
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
801
    // B0     B1     B2     B3     B4     B5     B6     B7
802
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
803
    // B8     B9     BA     BB     BC     BD     BE     BF
804
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
805
    // C0     C1     C2     C3     C4     C5     C6     C7
806
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
807
    // C8     C9     CA     CB     CC     CD     CE     CF
808
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
809
    // D0     D1     D2     D3     D4     D5     D6     D7
810
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
811
    // D8     D9     DA     DB     DC     DD     DE     DF
812
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
813
    // E0     E1     E2     E3     E4     E5     E6     E7
814
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
815
    // E8     E9     EA     EB     EC     ED     EE     EF
816
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
817
    // F0     F1     F2     F3     F4     F5     F6     F7
818
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
819
    // F8     F9     FA     FB     FC     FD     FE     FF
820
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80};
821
822
constexpr uint8_t FRAGMENT_PERCENT_ENCODE[32] = {
823
    // 00     01     02     03     04     05     06     07
824
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
825
    // 08     09     0A     0B     0C     0D     0E     0F
826
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
827
    // 10     11     12     13     14     15     16     17
828
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
829
    // 18     19     1A     1B     1C     1D     1E     1F
830
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
831
    // 20     21     22     23     24     25     26     27
832
    0x01 | 0x00 | 0x04 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
833
    // 28     29     2A     2B     2C     2D     2E     2F
834
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
835
    // 30     31     32     33     34     35     36     37
836
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
837
    // 38     39     3A     3B     3C     3D     3E     3F
838
    0x00 | 0x00 | 0x00 | 0x00 | 0x10 | 0x00 | 0x40 | 0x00,
839
    // 40     41     42     43     44     45     46     47
840
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
841
    // 48     49     4A     4B     4C     4D     4E     4F
842
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
843
    // 50     51     52     53     54     55     56     57
844
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
845
    // 58     59     5A     5B     5C     5D     5E     5F
846
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
847
    // 60     61     62     63     64     65     66     67
848
    0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
849
    // 68     69     6A     6B     6C     6D     6E     6F
850
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
851
    // 70     71     72     73     74     75     76     77
852
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
853
    // 78     79     7A     7B     7C     7D     7E     7F
854
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x80,
855
    // 80     81     82     83     84     85     86     87
856
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
857
    // 88     89     8A     8B     8C     8D     8E     8F
858
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
859
    // 90     91     92     93     94     95     96     97
860
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
861
    // 98     99     9A     9B     9C     9D     9E     9F
862
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
863
    // A0     A1     A2     A3     A4     A5     A6     A7
864
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
865
    // A8     A9     AA     AB     AC     AD     AE     AF
866
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
867
    // B0     B1     B2     B3     B4     B5     B6     B7
868
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
869
    // B8     B9     BA     BB     BC     BD     BE     BF
870
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
871
    // C0     C1     C2     C3     C4     C5     C6     C7
872
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
873
    // C8     C9     CA     CB     CC     CD     CE     CF
874
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
875
    // D0     D1     D2     D3     D4     D5     D6     D7
876
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
877
    // D8     D9     DA     DB     DC     DD     DE     DF
878
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
879
    // E0     E1     E2     E3     E4     E5     E6     E7
880
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
881
    // E8     E9     EA     EB     EC     ED     EE     EF
882
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
883
    // F0     F1     F2     F3     F4     F5     F6     F7
884
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
885
    // F8     F9     FA     FB     FC     FD     FE     FF
886
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80};
887
888
constexpr uint8_t USERINFO_PERCENT_ENCODE[32] = {
889
    // 00     01     02     03     04     05     06     07
890
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
891
    // 08     09     0A     0B     0C     0D     0E     0F
892
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
893
    // 10     11     12     13     14     15     16     17
894
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
895
    // 18     19     1A     1B     1C     1D     1E     1F
896
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
897
    // 20     21     22     23     24     25     26     27
898
    0x01 | 0x00 | 0x04 | 0x08 | 0x00 | 0x00 | 0x00 | 0x00,
899
    // 28     29     2A     2B     2C     2D     2E     2F
900
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x80,
901
    // 30     31     32     33     34     35     36     37
902
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
903
    // 38     39     3A     3B     3C     3D     3E     3F
904
    0x00 | 0x00 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
905
    // 40     41     42     43     44     45     46     47
906
    0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
907
    // 48     49     4A     4B     4C     4D     4E     4F
908
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
909
    // 50     51     52     53     54     55     56     57
910
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
911
    // 58     59     5A     5B     5C     5D     5E     5F
912
    0x00 | 0x00 | 0x00 | 0x08 | 0x10 | 0x20 | 0x40 | 0x00,
913
    // 60     61     62     63     64     65     66     67
914
    0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
915
    // 68     69     6A     6B     6C     6D     6E     6F
916
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
917
    // 70     71     72     73     74     75     76     77
918
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
919
    // 78     79     7A     7B     7C     7D     7E     7F
920
    0x00 | 0x00 | 0x00 | 0x08 | 0x10 | 0x20 | 0x00 | 0x80,
921
    // 80     81     82     83     84     85     86     87
922
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
923
    // 88     89     8A     8B     8C     8D     8E     8F
924
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
925
    // 90     91     92     93     94     95     96     97
926
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
927
    // 98     99     9A     9B     9C     9D     9E     9F
928
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
929
    // A0     A1     A2     A3     A4     A5     A6     A7
930
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
931
    // A8     A9     AA     AB     AC     AD     AE     AF
932
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
933
    // B0     B1     B2     B3     B4     B5     B6     B7
934
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
935
    // B8     B9     BA     BB     BC     BD     BE     BF
936
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
937
    // C0     C1     C2     C3     C4     C5     C6     C7
938
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
939
    // C8     C9     CA     CB     CC     CD     CE     CF
940
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
941
    // D0     D1     D2     D3     D4     D5     D6     D7
942
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
943
    // D8     D9     DA     DB     DC     DD     DE     DF
944
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
945
    // E0     E1     E2     E3     E4     E5     E6     E7
946
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
947
    // E8     E9     EA     EB     EC     ED     EE     EF
948
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
949
    // F0     F1     F2     F3     F4     F5     F6     F7
950
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
951
    // F8     F9     FA     FB     FC     FD     FE     FF
952
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80};
953
954
constexpr uint8_t PATH_PERCENT_ENCODE[32] = {
955
    // 00     01     02     03     04     05     06     07
956
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
957
    // 08     09     0A     0B     0C     0D     0E     0F
958
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
959
    // 10     11     12     13     14     15     16     17
960
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
961
    // 18     19     1A     1B     1C     1D     1E     1F
962
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
963
    // 20     21     22     23     24     25     26     27
964
    0x01 | 0x00 | 0x04 | 0x08 | 0x00 | 0x00 | 0x00 | 0x00,
965
    // 28     29     2A     2B     2C     2D     2E     2F
966
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
967
    // 30     31     32     33     34     35     36     37
968
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
969
    // 38     39     3A     3B     3C     3D     3E     3F
970
    0x00 | 0x00 | 0x00 | 0x00 | 0x10 | 0x00 | 0x40 | 0x80,
971
    // 40     41     42     43     44     45     46     47
972
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
973
    // 48     49     4A     4B     4C     4D     4E     4F
974
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
975
    // 50     51     52     53     54     55     56     57
976
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
977
    // 58     59     5A     5B     5C     5D     5E     5F
978
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x40 | 0x00,
979
    // 60     61     62     63     64     65     66     67
980
    0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
981
    // 68     69     6A     6B     6C     6D     6E     6F
982
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
983
    // 70     71     72     73     74     75     76     77
984
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
985
    // 78     79     7A     7B     7C     7D     7E     7F
986
    0x00 | 0x00 | 0x00 | 0x08 | 0x00 | 0x20 | 0x00 | 0x80,
987
    // 80     81     82     83     84     85     86     87
988
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
989
    // 88     89     8A     8B     8C     8D     8E     8F
990
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
991
    // 90     91     92     93     94     95     96     97
992
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
993
    // 98     99     9A     9B     9C     9D     9E     9F
994
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
995
    // A0     A1     A2     A3     A4     A5     A6     A7
996
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
997
    // A8     A9     AA     AB     AC     AD     AE     AF
998
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
999
    // B0     B1     B2     B3     B4     B5     B6     B7
1000
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1001
    // B8     B9     BA     BB     BC     BD     BE     BF
1002
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1003
    // C0     C1     C2     C3     C4     C5     C6     C7
1004
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1005
    // C8     C9     CA     CB     CC     CD     CE     CF
1006
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1007
    // D0     D1     D2     D3     D4     D5     D6     D7
1008
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1009
    // D8     D9     DA     DB     DC     DD     DE     DF
1010
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1011
    // E0     E1     E2     E3     E4     E5     E6     E7
1012
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1013
    // E8     E9     EA     EB     EC     ED     EE     EF
1014
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1015
    // F0     F1     F2     F3     F4     F5     F6     F7
1016
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1017
    // F8     F9     FA     FB     FC     FD     FE     FF
1018
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80};
1019
1020
constexpr uint8_t WWW_FORM_URLENCODED_PERCENT_ENCODE[32] = {
1021
    // 00     01     02     03     04     05     06     07
1022
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1023
    // 08     09     0A     0B     0C     0D     0E     0F
1024
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1025
    // 10     11     12     13     14     15     16     17
1026
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1027
    // 18     19     1A     1B     1C     1D     1E     1F
1028
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1029
    // 20     21     22     23     24     25     26     27
1030
    0x00 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1031
    // 28     29     2A     2B     2C     2D     2E     2F
1032
    0x01 | 0x02 | 0x00 | 0x08 | 0x10 | 0x00 | 0x00 | 0x80,
1033
    // 30     31     32     33     34     35     36     37
1034
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
1035
    // 38     39     3A     3B     3C     3D     3E     3F
1036
    0x00 | 0x00 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1037
    // 40     41     42     43     44     45     46     47
1038
    0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
1039
    // 48     49     4A     4B     4C     4D     4E     4F
1040
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
1041
    // 50     51     52     53     54     55     56     57
1042
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
1043
    // 58     59     5A     5B     5C     5D     5E     5F
1044
    0x00 | 0x00 | 0x00 | 0x08 | 0x10 | 0x20 | 0x40 | 0x00,
1045
    // 60     61     62     63     64     65     66     67
1046
    0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
1047
    // 68     69     6A     6B     6C     6D     6E     6F
1048
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
1049
    // 70     71     72     73     74     75     76     77
1050
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
1051
    // 78     79     7A     7B     7C     7D     7E     7F
1052
    0x00 | 0x00 | 0x00 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1053
    // 80     81     82     83     84     85     86     87
1054
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1055
    // 88     89     8A     8B     8C     8D     8E     8F
1056
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1057
    // 90     91     92     93     94     95     96     97
1058
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1059
    // 98     99     9A     9B     9C     9D     9E     9F
1060
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1061
    // A0     A1     A2     A3     A4     A5     A6     A7
1062
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1063
    // A8     A9     AA     AB     AC     AD     AE     AF
1064
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1065
    // B0     B1     B2     B3     B4     B5     B6     B7
1066
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1067
    // B8     B9     BA     BB     BC     BD     BE     BF
1068
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1069
    // C0     C1     C2     C3     C4     C5     C6     C7
1070
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1071
    // C8     C9     CA     CB     CC     CD     CE     CF
1072
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1073
    // D0     D1     D2     D3     D4     D5     D6     D7
1074
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1075
    // D8     D9     DA     DB     DC     DD     DE     DF
1076
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1077
    // E0     E1     E2     E3     E4     E5     E6     E7
1078
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1079
    // E8     E9     EA     EB     EC     ED     EE     EF
1080
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1081
    // F0     F1     F2     F3     F4     F5     F6     F7
1082
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1083
    // F8     F9     FA     FB     FC     FD     FE     FF
1084
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80};
1085
1086
480k
ada_really_inline constexpr bool bit_at(const uint8_t a[], const uint8_t i) {
1087
480k
  return !!(a[i >> 3] & (1 << (i & 7)));
1088
480k
}
1089
1090
}  // namespace ada::character_sets
1091
1092
#endif  // ADA_CHARACTER_SETS_INL_H
1093
/* end file include/ada/character_sets-inl.h */
1094
/* begin file include/ada/checkers-inl.h */
1095
/**
1096
 * @file checkers-inl.h
1097
 * @brief Definitions for URL specific checkers used within Ada.
1098
 */
1099
#ifndef ADA_CHECKERS_INL_H
1100
#define ADA_CHECKERS_INL_H
1101
1102
#include <bit>
1103
#include <cstddef>
1104
#include <cstdint>
1105
#include <cstring>
1106
#include <string_view>
1107
/* begin file include/ada/checkers.h */
1108
/**
1109
 * @file checkers.h
1110
 * @brief Declarations for URL specific checkers used within Ada.
1111
 */
1112
#ifndef ADA_CHECKERS_H
1113
#define ADA_CHECKERS_H
1114
1115
1116
#include <cstdint>
1117
#include <cstring>
1118
#include <string_view>
1119
1120
/**
1121
 * These functions are not part of our public API and may
1122
 * change at any time.
1123
 * @private
1124
 * @namespace ada::checkers
1125
 * @brief Includes the definitions for validation functions
1126
 */
1127
namespace ada::checkers {
1128
1129
/**
1130
 * @private
1131
 * Assuming that x is an ASCII letter, this function returns the lower case
1132
 * equivalent.
1133
 * @details More likely to be inlined by the compiler and constexpr.
1134
 */
1135
constexpr char to_lower(char x) noexcept;
1136
1137
/**
1138
 * @private
1139
 * Returns true if the character is an ASCII letter. Equivalent to std::isalpha
1140
 * but more likely to be inlined by the compiler.
1141
 *
1142
 * @attention std::isalpha is not constexpr generally.
1143
 */
1144
constexpr bool is_alpha(char x) noexcept;
1145
1146
/**
1147
 * @private
1148
 * Check whether x is an ASCII digit. More likely to be inlined than
1149
 * std::isdigit.
1150
 */
1151
constexpr bool is_digit(char x) noexcept;
1152
1153
/**
1154
 * @private
1155
 * @details A string starts with a Windows drive letter if all of the following
1156
 * are true:
1157
 *
1158
 *   - its length is greater than or equal to 2
1159
 *   - its first two code points are a Windows drive letter
1160
 *   - its length is 2 or its third code point is U+002F (/), U+005C (\), U+003F
1161
 * (?), or U+0023 (#).
1162
 *
1163
 * https://url.spec.whatwg.org/#start-with-a-windows-drive-letter
1164
 */
1165
inline constexpr bool is_windows_drive_letter(std::string_view input) noexcept;
1166
1167
/**
1168
 * @private
1169
 * @details A normalized Windows drive letter is a Windows drive letter of which
1170
 * the second code point is U+003A (:).
1171
 */
1172
inline constexpr bool is_normalized_windows_drive_letter(
1173
    std::string_view input) noexcept;
1174
1175
/**
1176
 * @private
1177
 * Returns true if an input is an ipv4 address. It is assumed that the string
1178
 * does not contain uppercase ASCII characters (the input should have been
1179
 * lowered cased before calling this function) and is not empty.
1180
 */
1181
ada_really_inline constexpr bool is_ipv4(std::string_view view) noexcept;
1182
1183
/**
1184
 * @private
1185
 * Cheap pre-check for the WHATWG "ends in a number" / IPv4-host cases.
1186
 * False means the host cannot be IPv4: the last label is empty, does not
1187
 * start with an ASCII digit, or contains a character other than a hex
1188
 * digit or x/X. True means the slower IPv4 parsers should run.
1189
 *
1190
 * Safe on mixed-case input (unlike is_ipv4, which expects a lowercased
1191
 * host).
1192
 */
1193
ada_really_inline constexpr bool last_label_may_be_a_number(
1194
    std::string_view view) noexcept;
1195
1196
/**
1197
 * @private
1198
 * Returns a bitset. If the first bit is set, then at least one character needs
1199
 * percent encoding. If the second bit is set, a \\ is found. If the third bit
1200
 * is set then we have a dot. If the fourth bit is set, then we have a percent
1201
 * character.
1202
 */
1203
ada_really_inline constexpr uint8_t path_signature(
1204
    std::string_view input) noexcept;
1205
1206
/**
1207
 * @private
1208
 * Returns true if the length of the domain name and its labels are according to
1209
 * the specifications. The length of the domain must be 255 octets (253
1210
 * characters not including the last 2 which are the empty label reserved at the
1211
 * end). When the empty label is included (a dot at the end), the domain name
1212
 * can have 254 characters. The length of a label must be at least 1 and at most
1213
 * 63 characters.
1214
 * @see section 3.1. of https://www.rfc-editor.org/rfc/rfc1034
1215
 * @see https://www.unicode.org/reports/tr46/#ToASCII
1216
 */
1217
ada_really_inline constexpr bool verify_dns_length(
1218
    std::string_view input) noexcept;
1219
1220
/**
1221
 * @private
1222
 * Fast-path parser for pure decimal IPv4 addresses (e.g., "192.168.1.1").
1223
 * Returns the packed 32-bit IPv4 address on success, or a value > 0xFFFFFFFF
1224
 * to indicate failure (caller should fall back to general parser).
1225
 * This is optimized for the common case where the input is a well-formed
1226
 * decimal IPv4 address with exactly 4 octets.
1227
 */
1228
ada_really_inline uint64_t try_parse_ipv4_fast(std::string_view input) noexcept;
1229
1230
/**
1231
 * Sentinel value indicating try_parse_ipv4_fast() did not succeed.
1232
 * Any value > 0xFFFFFFFF indicates the fast path should not be used.
1233
 */
1234
constexpr uint64_t ipv4_fast_fail = uint64_t(1) << 32;
1235
1236
}  // namespace ada::checkers
1237
1238
#endif  // ADA_CHECKERS_H
1239
/* end file include/ada/checkers.h */
1240
1241
#if defined(ADA_AVX512) && defined(__AVX512VBMI2__)
1242
#define ADA_AVX512_IPV4 1
1243
#elif defined(__x86_64__) && defined(__AVX2__) && defined(__BMI2__)
1244
#define ADA_HYBRID_IPV4 1
1245
#endif
1246
1247
#if defined(ADA_AVX512_IPV4) || defined(ADA_HYBRID_IPV4)
1248
#include <immintrin.h>
1249
#endif
1250
#if defined(ADA_HYBRID_IPV4)
1251
/* begin file include/ada/ipv4_hybrid_table.h */
1252
/**
1253
 * @file ipv4_hybrid_table.h
1254
 * @brief Compile-time lookup table for parse_ipv4_hybrid (checkers-inl.h).
1255
 *
1256
 * An address is 7-15 chars, so its first 8 chars (head) always hold "A.B."
1257
 * and its last 8 (tail) always hold ".C.D": the table has a low half indexed
1258
 * by the head and a high half indexed by the tail. The pext masks keep only
1259
 * bits that tell digits from dots, so each half's index says where its dots
1260
 * are: 9 shapes (1-3 digits per octet) among 32 indices. An entry is 16 B: a
1261
 * pshufb pattern moving each digit to a fixed lane for pmaddubsw, and a
1262
 * per-lane offset (sub) for the range check, 1 on leading digits to reject
1263
 * leading zeros and the dot's value on dot lanes. Byte 5 of the pattern also
1264
 * holds the half's share of the address length, in bits pshufb ignores: the
1265
 * parser requires the two shares to add up to the real length, so a read that
1266
 * isn't a real entry gets rejected. That lets the halves overlap and keeps the
1267
 * table small.
1268
 */
1269
#ifndef ADA_IPV4_HYBRID_TABLE_H
1270
#define ADA_IPV4_HYBRID_TABLE_H
1271
1272
#include <array>
1273
#include <cstddef>
1274
#include <cstdint>
1275
#include <optional>
1276
1277
namespace ada::checkers::detail::ipv4_hybrid {
1278
1279
inline constexpr size_t entries_per_half = 32;
1280
1281
// Bit 7 of char 0 is always clear, so the index comes out doubled for the
1282
// 16-byte entries.
1283
inline constexpr uint64_t head_digit_bits = 0x0010101010001080;
1284
inline constexpr uint64_t tail_digit_bits = 0x0010001010101080;
1285
1286
// The dot lane of the half's second octet (B or D), see place_octet.
1287
inline constexpr size_t share_byte = 5;
1288
1289
enum half : size_t { high = 0, low = 1 };
1290
1291
using slot = std::array<uint8_t, 8>;
1292
1293
constexpr slot splat(uint8_t value) noexcept {
1294
  slot result{};
1295
  for (uint8_t& byte : result) {
1296
    byte = value;
1297
  }
1298
  return result;
1299
}
1300
1301
struct entry {
1302
  slot pattern = splat(0x80);
1303
  slot sub{};
1304
};
1305
1306
// Not constexpr: reaching it while the table is built stops compilation.
1307
inline void table_check_failed() noexcept {}
1308
1309
constexpr void table_check(bool ok) noexcept {
1310
  if (!ok) {
1311
    table_check_failed();
1312
  }
1313
}
1314
1315
// Within a half's 8 bytes, a lane pair holds tens and ones at 2 * pair and
1316
// 2 * pair + 1, hundreds and dot at 4 + 2 * pair and 5 + 2 * pair. The half's
1317
// first octet takes pair 1 and its second pair 0, so the octets come out last
1318
// to first: the packed address, with no byte swap.
1319
constexpr void place_octet(entry& e, size_t pair, size_t start, size_t digits,
1320
                           bool dot) noexcept {
1321
  const size_t lanes[3] = {4 + 2 * pair, 2 * pair, 2 * pair + 1};
1322
  const size_t* digit_lanes = lanes + (3 - digits);
1323
  for (size_t i = 0; i < digits; ++i) {
1324
    e.pattern[digit_lanes[i]] = static_cast<uint8_t>(start + i);
1325
  }
1326
  if (digits > 1) {
1327
    e.sub[digit_lanes[0]] = 1;
1328
  }
1329
1330
  const size_t dot_lane = 5 + 2 * pair;
1331
  if (dot) {
1332
    e.pattern[dot_lane] = static_cast<uint8_t>(start + digits);
1333
    e.sub[dot_lane] = static_cast<uint8_t>('.' - '0');
1334
  }
1335
}
1336
1337
constexpr entry low_entry(size_t a_digits, size_t b_digits) noexcept {
1338
  entry e;
1339
  place_octet(e, 1, 0, a_digits, true);
1340
  place_octet(e, 0, a_digits + 1, b_digits, true);
1341
  // B's dot lane doubles as the low length share: pshufb ignores the 0x10.
1342
  e.pattern[share_byte] += 0x10;
1343
  return e;
1344
}
1345
1346
constexpr entry high_entry(size_t c_digits, size_t d_digits) noexcept {
1347
  entry e;
1348
  // The tail is right-aligned, ending at byte 16 of head_tail.
1349
  place_octet(e, 1, 16 - d_digits - 1 - c_digits, c_digits, true);
1350
  place_octet(e, 0, 16 - d_digits, d_digits, false);
1351
  // D has no dot, so its dot lane holds the high length share instead,
1352
  // negative so pshufb zeroes the lane; with the low's +16, the two shares add
1353
  // up to the address length.
1354
  e.pattern[share_byte] =
1355
      static_cast<uint8_t>(static_cast<int>(c_digits + 1 + d_digits) - 15);
1356
  return e;
1357
}
1358
1359
// _pext_u64 isn't constexpr on every compiler.
1360
constexpr size_t pext(const char* chars, uint64_t mask) noexcept {
1361
  uint64_t word = 0;
1362
  for (size_t i = 0; i < 8; ++i) {
1363
    word |= uint64_t(static_cast<uint8_t>(chars[i])) << (8 * i);
1364
  }
1365
  size_t index = 0;
1366
  size_t bit = 0;
1367
  for (uint64_t remaining = mask; remaining != 0;
1368
       remaining &= remaining - 1, ++bit) {
1369
    if ((word & remaining & (~remaining + 1)) != 0) {
1370
      index |= size_t(1) << bit;
1371
    }
1372
  }
1373
  return index;
1374
}
1375
1376
constexpr int length_sum(uint8_t low_share, uint8_t high_share) noexcept {
1377
  return int(low_share) + int(static_cast<int8_t>(high_share));
1378
}
1379
1380
using half_entries = std::array<std::optional<entry>, entries_per_half>;
1381
1382
constexpr void set(half_entries& entries, size_t doubled_index,
1383
                   const entry& e) noexcept {
1384
  table_check(doubled_index % 2 == 0);
1385
1386
  std::optional<entry>& existing = entries[doubled_index / 2];
1387
  if (existing) {
1388
    table_check(existing->pattern == e.pattern && existing->sub == e.sub);
1389
  }
1390
  existing = e;
1391
}
1392
1393
// One sample address per shape (1-3 digits per octet, 81 shapes), hashed by
1394
// head and tail like the parser does: octets A.B go to the low half, C.D to
1395
// the high half. The hash only tells digits from dots, so any digit works.
1396
// Result: two halves of 32 entries, empty where no shape lands.
1397
constexpr std::array<half_entries, 2> compute_entries() noexcept {
1398
  std::array<half_entries, 2> entries{};
1399
  for (size_t a = 1; a <= 3; ++a) {
1400
    for (size_t b = 1; b <= 3; ++b) {
1401
      for (size_t c = 1; c <= 3; ++c) {
1402
        for (size_t d = 1; d <= 3; ++d) {
1403
          char address[15] = {};
1404
          size_t len = 0;
1405
          const size_t digits[4] = {a, b, c, d};
1406
          for (size_t octet = 0; octet < 4; ++octet) {
1407
            for (size_t i = 0; i < digits[octet]; ++i) {
1408
              address[len++] = '1';
1409
            }
1410
            if (octet < 3) {
1411
              address[len++] = '.';
1412
            }
1413
          }
1414
          // parse_ipv4_seven_chars never reads the table.
1415
          if (len == 7) {
1416
            continue;
1417
          }
1418
1419
          const entry low_e = low_entry(a, b);
1420
          const entry high_e = high_entry(c, d);
1421
          table_check(length_sum(low_e.pattern[share_byte],
1422
                                 high_e.pattern[share_byte]) == int(len));
1423
1424
          set(entries[low], pext(address, head_digit_bits), low_e);
1425
          set(entries[high], pext(address + len - 8, tail_digit_bits), high_e);
1426
        }
1427
      }
1428
    }
1429
  }
1430
  return entries;
1431
}
1432
1433
inline constexpr std::array<half_entries, 2> entries = compute_entries();
1434
1435
// High goes first, low starts right where high's last entry ends, minus its
1436
// own unused leading indices: those overlap high's entries, harmless since
1437
// spare indices fail the length check.
1438
// Result: each half's first slot.
1439
constexpr std::array<size_t, 2> compute_starts() noexcept {
1440
  size_t high_end = 0;
1441
  for (size_t index = 0; index < entries_per_half; ++index) {
1442
    if (entries[high][index]) {
1443
      high_end = 2 * index + 2;
1444
    }
1445
  }
1446
  size_t low_first = 0;
1447
  while (!entries[low][low_first]) {
1448
    ++low_first;
1449
  }
1450
1451
  std::array<size_t, 2> starts{};
1452
  starts[high] = 0;
1453
  starts[low] = high_end - 2 * low_first;
1454
  return starts;
1455
}
1456
1457
inline constexpr std::array<size_t, 2> starts = compute_starts();
1458
1459
// The extra slot is for an odd index (non-ASCII first char), which reads one
1460
// slot past the last entry.
1461
inline constexpr size_t slot_count = starts[low] + 2 * entries_per_half + 1;
1462
1463
struct table {
1464
  alignas(64) std::array<slot, slot_count> slots{};
1465
1466
  template <half h>
1467
  constexpr const slot* get(size_t doubled_index) const noexcept {
1468
    return &slots[starts[h] + doubled_index];
1469
  }
1470
1471
  // The low share is read zero-extended, the high one sign-extended.
1472
  template <half h>
1473
  constexpr uint64_t get_length(size_t doubled_index) const noexcept {
1474
    const uint8_t share = (*get<h>(doubled_index))[share_byte];
1475
    if constexpr (h == low) {
1476
      return share;
1477
    } else {
1478
      return static_cast<uint64_t>(int64_t(static_cast<int8_t>(share)));
1479
    }
1480
  }
1481
};
1482
1483
// Each entry becomes two slots, pattern then sub, at its half's start +
1484
// doubled index. Then any pair of reads the parser can make, odd and spare
1485
// indices included, must fail the length check unless both are real entries,
1486
// or leftover bytes could accept an invalid address.
1487
constexpr table compute_table() noexcept {
1488
  table result;
1489
  for (size_t h = 0; h < 2; ++h) {
1490
    for (size_t index = 0; index < entries_per_half; ++index) {
1491
      if (const std::optional<entry>& e = entries[h][index]) {
1492
        result.slots[starts[h] + 2 * index] = e->pattern;
1493
        result.slots[starts[h] + 2 * index + 1] = e->sub;
1494
      }
1495
    }
1496
  }
1497
1498
  for (size_t index_low = 0; index_low < 2 * entries_per_half; ++index_low) {
1499
    for (size_t index_high = 0; index_high < 2 * entries_per_half;
1500
         ++index_high) {
1501
      const uint64_t sum = result.get_length<low>(index_low) +
1502
                           result.get_length<high>(index_high);
1503
      const bool both_entries =
1504
          index_low % 2 == 0 && entries[low][index_low / 2] &&
1505
          index_high % 2 == 0 && entries[high][index_high / 2];
1506
      if (sum >= 7 && sum <= 15) {
1507
        table_check(both_entries);
1508
      }
1509
    }
1510
  }
1511
  return result;
1512
}
1513
1514
inline constexpr table hybrid_table = compute_table();
1515
1516
}  // namespace ada::checkers::detail::ipv4_hybrid
1517
1518
#endif  // ADA_IPV4_HYBRID_TABLE_H
1519
/* end file include/ada/ipv4_hybrid_table.h */
1520
#endif
1521
1522
namespace ada::checkers {
1523
1524
0
constexpr bool is_digit(char x) noexcept { return (x >= '0') & (x <= '9'); }
1525
1526
3.42k
constexpr bool is_ipv4_number_char(char x) noexcept {
1527
3.42k
  const unsigned char c = static_cast<unsigned char>(x);
1528
3.42k
  return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
1529
3.42k
         (c >= 'A' && c <= 'F') || c == 'x' || c == 'X';
1530
3.42k
}
1531
1532
3.42k
constexpr bool last_label_may_be_a_number(std::string_view view) noexcept {
1533
3.42k
  if (view.empty()) {
1534
0
    return false;
1535
0
  }
1536
3.42k
  const char* start = view.data();
1537
3.42k
  const char* end = start + view.size();
1538
3.42k
  if (end[-1] == '.') {
1539
0
    --end;
1540
0
    if (end == start) {
1541
0
      return false;
1542
0
    }
1543
0
  }
1544
3.42k
  if (!is_ipv4_number_char(end[-1])) {
1545
3.42k
    return false;
1546
3.42k
  }
1547
0
  const char* label = end;
1548
0
  while (label != start && is_ipv4_number_char(label[-1])) {
1549
0
    --label;
1550
0
  }
1551
0
  if (label != start && label[-1] != '.') {
1552
0
    return false;
1553
0
  }
1554
0
  return label != end && is_digit(*label);
1555
0
}
1556
1557
982
constexpr char to_lower(char x) noexcept { return (x | 0x20); }
1558
1559
491
constexpr bool is_alpha(char x) noexcept {
1560
491
  return (to_lower(x) >= 'a') && (to_lower(x) <= 'z');
1561
491
}
1562
1563
0
constexpr bool is_windows_drive_letter(std::string_view input) noexcept {
1564
0
  return input.size() >= 2 &&
1565
0
         (is_alpha(input[0]) && ((input[1] == ':') || (input[1] == '|'))) &&
1566
0
         ((input.size() == 2) || (input[2] == '/' || input[2] == '\\' ||
1567
0
                                  input[2] == '?' || input[2] == '#'));
1568
0
}
1569
1570
constexpr bool is_normalized_windows_drive_letter(
1571
0
    std::string_view input) noexcept {
1572
0
  return input.size() == 2 && (is_alpha(input[0]) && (input[1] == ':'));
1573
0
}
1574
1575
namespace detail {
1576
1577
// Unrolled pure-decimal IPv4. The common portable path for 7-16 byte hosts.
1578
ada_really_inline uint64_t
1579
491
parse_ipv4_decimal_scalar(const char* p, const char* pend) noexcept {
1580
491
  uint32_t ipv4 = 0;
1581
491
  for (int i = 0; i < 4; ++i) {
1582
491
    if (p == pend) [[unlikely]] {
1583
0
      return ipv4_fast_fail;
1584
0
    }
1585
491
    uint32_t val;
1586
491
    char c = *p;
1587
491
    if (c >= '0' && c <= '9') [[likely]] {
1588
0
      val = static_cast<uint32_t>(c - '0');
1589
0
      ++p;
1590
491
    } else {
1591
491
      return ipv4_fast_fail;
1592
491
    }
1593
0
    if (p < pend) {
1594
0
      c = *p;
1595
0
      if (c >= '0' && c <= '9') {
1596
0
        if (val == 0) [[unlikely]] {
1597
0
          return ipv4_fast_fail;
1598
0
        }
1599
0
        val = val * 10u + static_cast<uint32_t>(c - '0');
1600
0
        ++p;
1601
0
        if (p < pend) {
1602
0
          c = *p;
1603
0
          if (c >= '0' && c <= '9') {
1604
0
            val = val * 10u + static_cast<uint32_t>(c - '0');
1605
0
            ++p;
1606
0
            if (val > 255u) [[unlikely]] {
1607
0
              return ipv4_fast_fail;
1608
0
            }
1609
0
          }
1610
0
        }
1611
0
      }
1612
0
    }
1613
0
    ipv4 = (ipv4 << 8) | val;
1614
0
    if (i < 3) {
1615
0
      if (p == pend || *p != '.') [[unlikely]] {
1616
0
        return ipv4_fast_fail;
1617
0
      }
1618
0
      ++p;
1619
0
    }
1620
0
  }
1621
0
  if (p != pend) {
1622
0
    if (p == pend - 1 && *p == '.') {
1623
0
      return ipv4;
1624
0
    }
1625
0
    return ipv4_fast_fail;
1626
0
  }
1627
0
  return ipv4;
1628
0
}
1629
1630
#if defined(ADA_AVX512_IPV4)
1631
// Table-free AVX-512VL IPv4 parse (simdip parse_ipv4_avx512vl_notab5).
1632
// Needs VBMI2 for vpcompressb; ADA_AVX512 stays BW+VL (IPv6 does not use
1633
// VBMI2). Masked load of exactly `len` bytes (no over-read). Digit
1634
// placement is computed from compressed delimiter positions; octet > 255
1635
// is a dword compare on the zero-padded reversed digit group, in parallel
1636
// with the convert. Unusual-but-valid forms (octal, hex, leading zeros,
1637
// fewer than four parts) return ipv4_fast_fail so the general parser runs.
1638
ada_really_inline uint64_t try_parse_ipv4_avx512(const char* data,
1639
                                                 size_t len) noexcept {
1640
  // One trailing dot is WHATWG-legal ("1.2.3.4."); the SIMD kernel is
1641
  // strict four-group dotted-decimal.
1642
  if (data[len - 1] == '.') {
1643
    --len;
1644
  }
1645
  if (len > 15) [[unlikely]] {
1646
    return ipv4_fast_fail;
1647
  }
1648
1649
#if defined(__BMI2__)
1650
  const uint32_t len_mask = _bzhi_u32(0xFFFFFFFFu, static_cast<unsigned>(len));
1651
#else
1652
  const uint32_t len_mask = (1u << static_cast<unsigned>(len)) - 1u;
1653
#endif
1654
  const __mmask16 len_k = static_cast<__mmask16>(len_mask);
1655
  const __m128i dot = _mm_set1_epi8('.');
1656
  const __m128i v =
1657
      _mm_mask_loadu_epi8(dot, len_k, reinterpret_cast<const void*>(data));
1658
1659
  const __mmask16 delim = _mm_cmpeq_epi8_mask(v, dot);
1660
  const uint32_t dots = static_cast<uint32_t>(delim) & len_mask;
1661
  const uint32_t keep = len_mask & ~dots;
1662
1663
  const __m128i zero = _mm_set1_epi8('0');
1664
  const __m128i digits = _mm_sub_epi8(v, zero);
1665
  const __mmask16 is_digit = _mm_cmple_epu8_mask(digits, _mm_set1_epi8(9));
1666
  // Junk in a digit slot: inside [0, len) yet neither a digit nor a dot.
1667
  const __mmask16 hole = _kandn_mask16(_kor_mask16(delim, is_digit), len_k);
1668
  const __m128i v0 = _mm_maskz_mov_epi8(is_digit, digits);
1669
1670
  const __m128i iota =
1671
      _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
1672
  const __m128i c = _mm_maskz_compress_epi8(delim, iota);
1673
  const __m128i k_rep =
1674
      _mm_setr_epi8(0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3);
1675
  const __m128i qi = _mm_shuffle_epi8(c, k_rep);
1676
  const __m128i prev =
1677
      _mm_shuffle_epi8(_mm_alignr_epi8(c, _mm_set1_epi8(-1), 15), k_rep);
1678
  // Reversed group order: lane 4i+j fetches q_i-(j+1), so the dword is
1679
  // ones | tens<<8 | hundreds<<16, monotone in the decimal value.
1680
  const __m128i offr = _mm_setr_epi8(-1, -2, -3, -4, -1, -2, -3, -4, -1, -2, -3,
1681
                                     -4, -1, -2, -3, -4);
1682
  const __m128i idx = _mm_max_epi8(_mm_add_epi8(qi, offr), prev);
1683
  const __m128i padded = _mm_shuffle_epi8(v0, idx);
1684
1685
  const __m128i lim =
1686
      _mm_setr_epi8(5, 5, 2, 0, 5, 5, 2, 0, 5, 5, 2, 0, 5, 5, 2, 0);
1687
  const __mmask8 over = _mm_cmpgt_epu32_mask(padded, lim);
1688
  const __m128i wtsr =
1689
      _mm_setr_epi8(1, 10, 100, 0, 1, 10, 100, 0, 1, 10, 100, 0, 1, 10, 100, 0);
1690
#if defined(__AVX512VNNI__)
1691
  const __m128i res = _mm_dpbusd_epi32(_mm_setzero_si128(), padded, wtsr);
1692
#else
1693
  const __m128i res =
1694
      _mm_madd_epi16(_mm_maddubs_epi16(padded, wtsr), _mm_set1_epi16(1));
1695
#endif
1696
1697
  const __m128i gmin =
1698
      _mm_setr_epi8(1, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1699
  const __m128i gmax =
1700
      _mm_setr_epi8(2, 2, 2, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
1701
  const __m128i gap = _mm_sub_epi8(c, _mm_slli_si128(c, 1));
1702
  const __mmask16 bad_gap = _mm_cmpgt_epu8_mask(_mm_sub_epi8(gap, gmin), gmax);
1703
1704
  const uint32_t zero_bits =
1705
      static_cast<uint32_t>(_mm_cmpeq_epi8_mask(v, zero));
1706
  const uint32_t start_bits = (dots << 1) | 1u;
1707
1708
  const __mmask16 kerr =
1709
      _kor_mask16(_kor_mask16(hole, static_cast<__mmask16>(over)), bad_gap);
1710
  const uint32_t gerr = static_cast<uint32_t>(_mm_popcnt_u32(dots) ^ 3u) |
1711
                        (zero_bits & start_bits & (keep >> 1));
1712
1713
  if ((gerr | static_cast<uint32_t>(kerr)) == 0) [[likely]] {
1714
    const uint32_t packed =
1715
        static_cast<uint32_t>(_mm_cvtsi128_si32(_mm_cvtepi32_epi8(res)));
1716
#if defined(__GNUC__) || defined(__clang__)
1717
    return static_cast<uint64_t>(__builtin_bswap32(packed));
1718
#else
1719
    return static_cast<uint64_t>(_byteswap_ulong(packed));
1720
#endif
1721
  }
1722
  return ipv4_fast_fail;
1723
}
1724
#endif  // ADA_AVX512_IPV4
1725
1726
#if defined(ADA_HYBRID_IPV4)
1727
// pext turns where the dots are into a table index; the entry's pshufb pattern
1728
// lines up the digits for pmaddubsw, and its offsets range-check every lane.
1729
//
1730
// Lanes after the shuffle (T/O/H = tens/ones/hundreds of an octet):
1731
//   lane:    0  1  2  3  4  5  6  7    8  9 10 11 12 13 14 15
1732
//   holds:  Td Od Tc Oc Tb Ob Ta Oa   Hd  - Hc  . Hb  . Ha  .
1733
//   weight: 10  1 10  1 10  1 10  1  100  0 100 0 100 0 100 0
1734
namespace ipv4_hybrid {
1735
1736
#if defined(__znver1__) || defined(__znver2__)
1737
// Zen 1 and Zen 2 run pext in microcode, so a mask and a multiply stand in for
1738
// it: the multiply's partial products move the five digit bits to bits 59-63,
1739
// with no two of them landing on the same bit (so no carries), and the shift
1740
// leaves them in bits 1-5, the same doubled index pext gives for ASCII. Bit 7
1741
// of char 0 is dropped: that char is a digit lane of every entry, so the range
1742
// check rejects it anyway.
1743
template <uint64_t mask>
1744
constexpr size_t pext(uint64_t word) noexcept {
1745
  constexpr uint64_t bits = mask & ~uint64_t(0x80);
1746
  constexpr uint64_t magic = [] {
1747
    uint64_t result = 0;
1748
    int target = 59;
1749
    for (uint64_t remaining = bits; remaining != 0;
1750
         remaining &= remaining - 1, ++target) {
1751
      result |= uint64_t(1) << (target - std::countr_zero(remaining));
1752
    }
1753
    return result;
1754
  }();
1755
  return ((word & bits) * magic) >> 58;
1756
}
1757
1758
// Every placement of the five digit bits, with the other bits clear or set,
1759
// must give pext's doubled index.
1760
template <uint64_t mask>
1761
constexpr bool pext_is_exact() noexcept {
1762
  constexpr uint64_t bits = mask & ~uint64_t(0x80);
1763
  for (size_t index = 0; index < entries_per_half; ++index) {
1764
    uint64_t word = 0;
1765
    size_t bit = 0;
1766
    for (uint64_t remaining = bits; remaining != 0;
1767
         remaining &= remaining - 1, ++bit) {
1768
      if (((index >> bit) & 1) != 0) {
1769
        word |= remaining & (~remaining + 1);
1770
      }
1771
    }
1772
    if (pext<mask>(word) != 2 * index ||
1773
        pext<mask>(word | ~bits) != 2 * index) {
1774
      return false;
1775
    }
1776
  }
1777
  return true;
1778
}
1779
1780
static_assert(pext_is_exact<head_digit_bits>() &&
1781
                  pext_is_exact<tail_digit_bits>(),
1782
              "the multiply must match pext");
1783
#else
1784
template <uint64_t mask>
1785
ada_really_inline size_t pext(uint64_t word) noexcept {
1786
  return static_cast<size_t>(_pext_u64(word, mask));
1787
}
1788
#endif
1789
1790
}  // namespace ipv4_hybrid
1791
1792
// Only 7 chars: every octet is a single digit, so check the chars directly.
1793
ada_really_inline uint64_t parse_ipv4_seven_chars(const char* data,
1794
                                                  size_t len) noexcept {
1795
  if (len != 7) {
1796
    return ipv4_fast_fail;
1797
  }
1798
1799
  uint32_t head;
1800
  uint32_t tail;
1801
  std::memcpy(&head, data, 4);
1802
  std::memcpy(&tail, data + 3, 4);
1803
1804
  const __m128i values =
1805
      _mm_sub_epi8(_mm_insert_epi32(_mm_cvtsi32_si128(static_cast<int>(head)),
1806
                                    static_cast<int>(tail), 1),
1807
                   _mm_setr_epi8('0', '.', '0', '.', '.', '0', '.', '0', 0, 0,
1808
                                 0, 0, 0, 0, 0, 0));
1809
1810
  const __m128i over_max = _mm_subs_epu8(
1811
      values, _mm_setr_epi8(9, 0, 9, 0, 0, 9, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0));
1812
  if (_mm_cvtsi128_si64(over_max) != 0) {
1813
    return ipv4_fast_fail;
1814
  }
1815
1816
  // d, c, b, a: the packed address.
1817
  return static_cast<uint32_t>(_mm_cvtsi128_si32(
1818
      _mm_shuffle_epi8(values, _mm_setr_epi8(7, 5, 2, 0, -1, -1, -1, -1, -1, -1,
1819
                                             -1, -1, -1, -1, -1, -1))));
1820
}
1821
1822
// Strict four-group dotted-decimal, no trailing dot: unusual-but-valid forms
1823
// (octal, hex, leading zeros, fewer than four parts) return ipv4_fast_fail so
1824
// the general parser runs.
1825
ada_really_inline uint64_t parse_ipv4_hybrid(const char* data,
1826
                                             size_t len) noexcept {
1827
  using ipv4_hybrid::high;
1828
  using ipv4_hybrid::hybrid_table;
1829
  using ipv4_hybrid::low;
1830
1831
  const size_t tail_offset = len - 8;
1832
  if (tail_offset > 7) [[unlikely]] {
1833
    return parse_ipv4_seven_chars(data, len);
1834
  }
1835
1836
  uint64_t head;
1837
  uint64_t tail;
1838
  std::memcpy(&head, data, 8);
1839
  std::memcpy(&tail, data + tail_offset, 8);
1840
  // Loaded again from memory, which beats moving head and tail over from the
1841
  // general purpose registers: the empty asm stops the compiler from reusing
1842
  // the two loads above.
1843
  const char* vector_data = data;
1844
  __asm__("" : "+r"(vector_data));
1845
  const __m128i head_tail = _mm_blend_epi32(
1846
      _mm_loadl_epi64(reinterpret_cast<const __m128i*>(vector_data)),
1847
      _mm_broadcastq_epi64(_mm_loadl_epi64(
1848
          reinterpret_cast<const __m128i*>(vector_data + tail_offset))),
1849
      0b1100);
1850
1851
  const size_t index_low =
1852
      ipv4_hybrid::pext<ipv4_hybrid::head_digit_bits>(head);
1853
  const size_t index_high =
1854
      ipv4_hybrid::pext<ipv4_hybrid::tail_digit_bits>(tail);
1855
1856
  if (len - hybrid_table.get_length<low>(index_low) !=
1857
      hybrid_table.get_length<high>(index_high)) {
1858
    return ipv4_fast_fail;
1859
  }
1860
1861
  const __m128i low_entry = _mm_loadu_si128(
1862
      reinterpret_cast<const __m128i*>(hybrid_table.get<low>(index_low)));
1863
  const __m128i high_entry = _mm_loadu_si128(
1864
      reinterpret_cast<const __m128i*>(hybrid_table.get<high>(index_high)));
1865
1866
  // Interlaced 4 bytes at a time, high first.
1867
  const __m128i pattern = _mm_unpacklo_epi32(high_entry, low_entry);
1868
  const __m128i lanes =
1869
      _mm_shuffle_epi8(_mm_sub_epi8(head_tail, _mm_set1_epi8('0')), pattern);
1870
  const __m128i products =
1871
      _mm_maddubs_epi16(lanes, _mm_setr_epi8(10, 1, 10, 1, 10, 1, 10, 1, 100, 0,
1872
                                             100, 0, 100, 0, 100, 0));
1873
  const __m128i sums =
1874
      _mm_add_epi16(products, _mm_shuffle_epi32(products, 0xEE));
1875
1876
  const __m128i too_big = _mm_and_si128(
1877
      sums,
1878
      _mm_setr_epi16(static_cast<short>(0xFF00), static_cast<short>(0xFF00),
1879
                     static_cast<short>(0xFF00), static_cast<short>(0xFF00), 0,
1880
                     0, 0, 0));
1881
1882
  const __m128i sub = _mm_unpackhi_epi32(high_entry, low_entry);
1883
  const __m128i flips = _mm_setr_epi8(9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
1884
                                      char(0xFE), 9, char(0xFE), 9, char(0xFE));
1885
  const __m128i bad_lanes =
1886
      _mm_subs_epu8(_mm_sub_epi8(lanes, sub), _mm_xor_si128(sub, flips));
1887
1888
  const __m128i errors = _mm_or_si128(too_big, bad_lanes);
1889
  if (!_mm_testz_si128(errors, errors)) [[unlikely]] {
1890
    return ipv4_fast_fail;
1891
  }
1892
1893
  return static_cast<uint32_t>(_mm_cvtsi128_si32(_mm_packus_epi16(sums, sums)));
1894
}
1895
1896
// The same, after dropping the trailing dot. Kept out of line: it only runs
1897
// for the rare "1.2.3.4." form.
1898
ada_never_inline uint64_t parse_ipv4_hybrid_trailing_dot(const char* data,
1899
                                                         size_t len) noexcept {
1900
  return parse_ipv4_hybrid(data, len - 1);
1901
}
1902
1903
// One trailing dot is WHATWG-legal ("1.2.3.4."), but a strict address never
1904
// ends with one: the dot is only looked at once the strict parse has failed,
1905
// which keeps it off the common path.
1906
ada_really_inline uint64_t try_parse_ipv4_hybrid(const char* data,
1907
                                                 size_t len) noexcept {
1908
  const uint64_t result = parse_ipv4_hybrid(data, len);
1909
  if (result != ipv4_fast_fail || data[len - 1] != '.') {
1910
    return result;
1911
  }
1912
  return parse_ipv4_hybrid_trailing_dot(data, len);
1913
}
1914
#endif  // ADA_HYBRID_IPV4
1915
1916
}  // namespace detail
1917
1918
/**
1919
 * Fast pure-decimal IPv4 parse. Returns packed address or ipv4_fast_fail.
1920
 * Accepts an optional single trailing dot.
1921
 *
1922
 * On AVX-512BW+VL+VBMI2 targets, uses a table-free SIMD parse (masked
1923
 * load, no source over-read) based on parse_ipv4_avx512vl_notab5.
1924
 * On x86-64 AVX2 + BMI2 targets, uses the hybrid pext + pshufb parse (two
1925
 * 8-byte loads, no source over-read, small compile-time lookup table).
1926
 * Otherwise uses an unrolled scalar path (typically faster than SSE2/NEON
1927
 * pre-validation for these 7-16 byte hosts).
1928
 */
1929
ada_really_inline uint64_t
1930
491
try_parse_ipv4_fast(std::string_view input) noexcept {
1931
491
  const size_t len = input.size();
1932
  // Shortest pure decimal: "0.0.0.0" (7). Longest + trailing dot: 16.
1933
491
  if (len < 7 || len > 16) [[unlikely]] {
1934
0
    return ipv4_fast_fail;
1935
0
  }
1936
491
  const char* data = input.data();
1937
1938
#if defined(ADA_AVX512_IPV4)
1939
  return detail::try_parse_ipv4_avx512(data, len);
1940
#elif defined(ADA_HYBRID_IPV4)
1941
  return detail::try_parse_ipv4_hybrid(data, len);
1942
#else
1943
491
  return detail::parse_ipv4_decimal_scalar(data, data + len);
1944
491
#endif
1945
491
}
1946
1947
}  // namespace ada::checkers
1948
1949
#endif  // ADA_CHECKERS_INL_H
1950
/* end file include/ada/checkers-inl.h */
1951
/* begin file include/ada/log.h */
1952
/**
1953
 * @file log.h
1954
 * @brief Includes the definitions for logging.
1955
 * @private Excluded from docs through the doxygen file.
1956
 */
1957
#ifndef ADA_LOG_H
1958
#define ADA_LOG_H
1959
1960
// To enable logging, set ADA_LOGGING to 1:
1961
#ifndef ADA_LOGGING
1962
#define ADA_LOGGING 0
1963
#endif
1964
1965
#if ADA_LOGGING
1966
#include <iostream>
1967
#endif  // ADA_LOGGING
1968
1969
namespace ada {
1970
1971
/**
1972
 * Log a message. If you want to have no overhead when logging is disabled, use
1973
 * the ada_log macro.
1974
 * @private
1975
 */
1976
template <typename... Args>
1977
constexpr ada_really_inline void log([[maybe_unused]] Args... args) {
1978
#if ADA_LOGGING
1979
  ((std::cout << "ADA_LOG: ") << ... << args) << std::endl;
1980
#endif  // ADA_LOGGING
1981
}
1982
}  // namespace ada
1983
1984
#if ADA_LOGGING
1985
#ifndef ada_log
1986
#define ada_log(...)       \
1987
  do {                     \
1988
    ada::log(__VA_ARGS__); \
1989
  } while (0)
1990
#endif  // ada_log
1991
#else
1992
#define ada_log(...)
1993
#endif  // ADA_LOGGING
1994
1995
#endif  // ADA_LOG_H
1996
/* end file include/ada/log.h */
1997
/* begin file include/ada/encoding_type.h */
1998
/**
1999
 * @file encoding_type.h
2000
 * @brief Character encoding type definitions.
2001
 *
2002
 * Defines the encoding types supported for URL processing.
2003
 *
2004
 * @see https://encoding.spec.whatwg.org/
2005
 */
2006
#ifndef ADA_ENCODING_TYPE_H
2007
#define ADA_ENCODING_TYPE_H
2008
2009
#include <string>
2010
#include <string_view>
2011
2012
namespace ada {
2013
2014
/**
2015
 * @brief Character encoding types for URL processing.
2016
 *
2017
 * Specifies the character encoding used for percent-decoding and other
2018
 * string operations. UTF-8 is the most commonly used encoding for URLs.
2019
 *
2020
 * @see https://encoding.spec.whatwg.org/#encodings
2021
 */
2022
enum class encoding_type {
2023
  UTF8,     /**< UTF-8 encoding (default for URLs) */
2024
  UTF_16LE, /**< UTF-16 Little Endian encoding */
2025
  UTF_16BE, /**< UTF-16 Big Endian encoding */
2026
};
2027
2028
/**
2029
 * Converts an encoding_type to its string representation.
2030
 * @param type The encoding type to convert.
2031
 * @return A string view of the encoding name.
2032
 */
2033
ada_warn_unused std::string_view to_string(encoding_type type);
2034
2035
}  // namespace ada
2036
2037
#endif  // ADA_ENCODING_TYPE_H
2038
/* end file include/ada/encoding_type.h */
2039
/* begin file include/ada/helpers.h */
2040
/**
2041
 * @file helpers.h
2042
 * @brief Definitions for helper functions used within Ada.
2043
 */
2044
#ifndef ADA_HELPERS_H
2045
#define ADA_HELPERS_H
2046
2047
/* begin file include/ada/url_base.h */
2048
/**
2049
 * @file url_base.h
2050
 * @brief Base class and common definitions for URL types.
2051
 *
2052
 * This file defines the `url_base` abstract base class from which both
2053
 * `ada::url` and `ada::url_aggregator` inherit. It also defines common
2054
 * enumerations like `url_host_type`.
2055
 */
2056
#ifndef ADA_URL_BASE_H
2057
#define ADA_URL_BASE_H
2058
2059
/* begin file include/ada/scheme.h */
2060
/**
2061
 * @file scheme.h
2062
 * @brief URL scheme type definitions and utilities.
2063
 *
2064
 * This header defines the URL scheme types (http, https, etc.) and provides
2065
 * functions to identify special schemes and their default ports according
2066
 * to the WHATWG URL Standard.
2067
 *
2068
 * @see https://url.spec.whatwg.org/#special-scheme
2069
 */
2070
#ifndef ADA_SCHEME_H
2071
#define ADA_SCHEME_H
2072
2073
2074
#include <cstdint>
2075
#include <string>
2076
#include <string_view>
2077
2078
/**
2079
 * @namespace ada::scheme
2080
 * @brief URL scheme utilities and constants.
2081
 *
2082
 * Provides functions for working with URL schemes, including identification
2083
 * of special schemes and retrieval of default port numbers.
2084
 */
2085
namespace ada::scheme {
2086
2087
/**
2088
 * @brief Enumeration of URL scheme types.
2089
 *
2090
 * Special schemes have specific parsing rules and default ports.
2091
 * Using an enum allows efficient scheme comparisons without string operations.
2092
 *
2093
 * Default ports:
2094
 * - HTTP: 80
2095
 * - HTTPS: 443
2096
 * - WS: 80
2097
 * - WSS: 443
2098
 * - FTP: 21
2099
 * - FILE: (none)
2100
 */
2101
enum type : uint8_t {
2102
  HTTP = 0,        /**< http:// scheme (port 80) */
2103
  NOT_SPECIAL = 1, /**< Non-special scheme (no default port) */
2104
  HTTPS = 2,       /**< https:// scheme (port 443) */
2105
  WS = 3,          /**< ws:// WebSocket scheme (port 80) */
2106
  FTP = 4,         /**< ftp:// scheme (port 21) */
2107
  WSS = 5,         /**< wss:// secure WebSocket scheme (port 443) */
2108
  FILE = 6         /**< file:// scheme (no default port) */
2109
};
2110
2111
/**
2112
 * Checks if a scheme string is a special scheme.
2113
 * @param scheme The scheme string to check (e.g., "http", "https").
2114
 * @return `true` if the scheme is special, `false` otherwise.
2115
 * @see https://url.spec.whatwg.org/#special-scheme
2116
 */
2117
ada_really_inline constexpr bool is_special(std::string_view scheme);
2118
2119
/**
2120
 * Returns the default port for a special scheme string.
2121
 * @param scheme The scheme string (e.g., "http", "https").
2122
 * @return The default port number, or 0 if not a special scheme.
2123
 * @see https://url.spec.whatwg.org/#special-scheme
2124
 */
2125
constexpr uint16_t get_special_port(std::string_view scheme) noexcept;
2126
2127
/**
2128
 * Returns the default port for a scheme type.
2129
 * @param type The scheme type enum value.
2130
 * @return The default port number, or 0 if not applicable.
2131
 * @see https://url.spec.whatwg.org/#special-scheme
2132
 */
2133
constexpr uint16_t get_special_port(ada::scheme::type type) noexcept;
2134
2135
/**
2136
 * Converts a scheme string to its type enum.
2137
 * @param scheme The scheme string to convert.
2138
 * @return The corresponding scheme type, or NOT_SPECIAL if not recognized.
2139
 */
2140
constexpr ada::scheme::type get_scheme_type(std::string_view scheme) noexcept;
2141
2142
}  // namespace ada::scheme
2143
2144
#endif  // ADA_SCHEME_H
2145
/* end file include/ada/scheme.h */
2146
2147
#include <cstddef>
2148
#include <cstdint>
2149
#include <string>
2150
#include <string_view>
2151
2152
namespace ada {
2153
2154
/**
2155
 * @brief Enum representing the type of host in a URL.
2156
 *
2157
 * Used to distinguish between regular domain names, IPv4 addresses,
2158
 * and IPv6 addresses for proper parsing and serialization.
2159
 */
2160
enum url_host_type : uint8_t {
2161
  /** Regular domain name (e.g., "www.example.com") */
2162
  DEFAULT = 0,
2163
  /** IPv4 address (e.g., "127.0.0.1") */
2164
  IPV4 = 1,
2165
  /** IPv6 address (e.g., "[::1]" or "[2001:db8::1]") */
2166
  IPV6 = 2,
2167
};
2168
2169
/**
2170
 * @brief Abstract base class for URL representations.
2171
 *
2172
 * The `url_base` class provides the common interface and state shared by
2173
 * both `ada::url` and `ada::url_aggregator`. It contains basic URL attributes
2174
 * like validity status and scheme type, but delegates component storage and
2175
 * access to derived classes.
2176
 *
2177
 * @note This is an abstract class and cannot be instantiated directly.
2178
 *       Use `ada::url` or `ada::url_aggregator` instead.
2179
 *
2180
 * @see url
2181
 * @see url_aggregator
2182
 */
2183
struct url_base {
2184
5.86k
  virtual ~url_base() = default;
2185
2186
  /**
2187
   * Indicates whether the URL was successfully parsed.
2188
   * Set to `false` if parsing failed (e.g., invalid URL syntax).
2189
   */
2190
  bool is_valid{true};
2191
2192
  /**
2193
   * Indicates whether the URL has an opaque path (non-hierarchical).
2194
   * Opaque paths occur in non-special URLs like `mailto:` or `javascript:`.
2195
   */
2196
  bool has_opaque_path{false};
2197
2198
  /**
2199
   * The type of the URL's host (domain, IPv4, or IPv6).
2200
   */
2201
  url_host_type host_type = url_host_type::DEFAULT;
2202
2203
  /**
2204
   * @private
2205
   * Internal representation of the URL's scheme type.
2206
   */
2207
  ada::scheme::type type{ada::scheme::type::NOT_SPECIAL};
2208
2209
  /**
2210
   * Checks if the URL has a special scheme (http, https, ws, wss, ftp, file).
2211
   * Special schemes have specific parsing rules and default ports.
2212
   * @return `true` if the scheme is special, `false` otherwise.
2213
   */
2214
  [[nodiscard]] ada_really_inline constexpr bool is_special() const noexcept;
2215
2216
  /**
2217
   * Returns the URL's origin (scheme + host + port for special URLs).
2218
   * @return A newly allocated string containing the serialized origin.
2219
   * @see https://url.spec.whatwg.org/#concept-url-origin
2220
   */
2221
  [[nodiscard]] virtual std::string get_origin() const = 0;
2222
2223
  /**
2224
   * Validates whether the hostname is a valid domain according to RFC 1034.
2225
   * Checks that the domain and its labels have valid lengths.
2226
   * @return `true` if the domain is valid, `false` otherwise.
2227
   */
2228
  [[nodiscard]] virtual bool has_valid_domain() const noexcept = 0;
2229
2230
  /**
2231
   * @private
2232
   * Returns the default port for special schemes (e.g., 443 for https).
2233
   * Returns 0 for file:// URLs or non-special schemes.
2234
   */
2235
  [[nodiscard]] inline uint16_t get_special_port() const noexcept;
2236
2237
  /**
2238
   * @private
2239
   * Returns the default port for the URL's scheme, or 0 if none.
2240
   */
2241
  [[nodiscard]] ada_really_inline uint16_t scheme_default_port() const noexcept;
2242
2243
  /**
2244
   * @private
2245
   * Parses a port number from the input string.
2246
   * @param view The string containing the port to parse.
2247
   * @param check_trailing_content Whether to validate no trailing characters.
2248
   * @return Number of bytes consumed on success, 0 on failure.
2249
   */
2250
  virtual size_t parse_port(std::string_view view,
2251
                            bool check_trailing_content) = 0;
2252
2253
  /** @private */
2254
0
  virtual ada_really_inline size_t parse_port(std::string_view view) {
2255
0
    return this->parse_port(view, false);
2256
0
  }
2257
2258
  /**
2259
   * Returns a JSON string representation of this URL for debugging.
2260
   * @return A JSON-formatted string with URL information.
2261
   */
2262
  [[nodiscard]] virtual std::string to_string() const = 0;
2263
2264
  /** @private */
2265
  virtual inline void clear_pathname() = 0;
2266
2267
  /** @private */
2268
  virtual inline void clear_search() = 0;
2269
2270
  /** @private */
2271
  [[nodiscard]] virtual inline bool has_hash() const noexcept = 0;
2272
2273
  /** @private */
2274
  [[nodiscard]] virtual inline bool has_search() const noexcept = 0;
2275
2276
};  // url_base
2277
2278
}  // namespace ada
2279
2280
#endif
2281
/* end file include/ada/url_base.h */
2282
2283
#include <cstddef>
2284
#include <cstdint>
2285
#include <optional>
2286
#include <string>
2287
#include <string_view>
2288
#include <utility>
2289
2290
#if ADA_DEVELOPMENT_CHECKS
2291
#include <cstdlib>
2292
#include <iostream>
2293
#endif  // ADA_DEVELOPMENT_CHECKS
2294
2295
/**
2296
 * These functions are not part of our public API and may
2297
 * change at any time.
2298
 *
2299
 * @private
2300
 * @namespace ada::helpers
2301
 * @brief Includes the definitions for helper functions
2302
 */
2303
namespace ada::helpers {
2304
2305
/**
2306
 * @private
2307
 */
2308
template <typename out_iter>
2309
void encode_json(std::string_view view, out_iter out);
2310
2311
/**
2312
 * @private
2313
 * This function is used to prune a fragment from a url, and returning the
2314
 * removed string if input has fragment.
2315
 *
2316
 * @details prune_hash seeks the first '#' and returns everything after it
2317
 * as a string_view, and modifies (in place) the input so that it points at
2318
 * everything before the '#'. If no '#' is found, the input is left unchanged
2319
 * and std::nullopt is returned.
2320
 *
2321
 * @attention The function is non-allocating and it does not throw.
2322
 * @returns Note that the returned string_view might be empty!
2323
 */
2324
ada_really_inline std::optional<std::string_view> prune_hash(
2325
    std::string_view& input) noexcept;
2326
2327
/**
2328
 * @private
2329
 * Defined by the URL specification, shorten a URLs paths.
2330
 * @see https://url.spec.whatwg.org/#shorten-a-urls-path
2331
 * @returns Returns true if path is shortened.
2332
 */
2333
ada_really_inline bool shorten_path(std::string& path, ada::scheme::type type);
2334
2335
/**
2336
 * @private
2337
 * Defined by the URL specification, shorten a URLs paths.
2338
 * @see https://url.spec.whatwg.org/#shorten-a-urls-path
2339
 * @returns Returns true if path is shortened.
2340
 */
2341
ada_really_inline bool shorten_path(std::string_view& path,
2342
                                    ada::scheme::type type);
2343
2344
/**
2345
 * @private
2346
 *
2347
 * Parse the path from the provided input and append to the existing
2348
 * (possibly empty) path. The input cannot contain tabs and spaces: it
2349
 * is the user's responsibility to check.
2350
 *
2351
 * The input is expected to be UTF-8.
2352
 *
2353
 * @see https://url.spec.whatwg.org/
2354
 */
2355
ada_really_inline void parse_prepared_path(std::string_view input,
2356
                                           ada::scheme::type type,
2357
                                           std::string& path);
2358
2359
/**
2360
 * @private
2361
 * Remove and mutate all ASCII tab or newline characters from an input.
2362
 */
2363
ada_really_inline void remove_ascii_tab_or_newline(std::string& input);
2364
2365
/**
2366
 * @private
2367
 * Return the substring from input going from index pos to the end.
2368
 */
2369
ada_really_inline constexpr std::string_view substring(std::string_view input,
2370
                                                       size_t pos);
2371
2372
/**
2373
 * @private
2374
 * Returns true if the string_view points within the string.
2375
 */
2376
bool overlaps(std::string_view input1, const std::string& input2) noexcept;
2377
2378
/**
2379
 * @private
2380
 * Return the substring from input going from index pos1 to the pos2 (non
2381
 * included). The length of the substring is pos2 - pos1.
2382
 */
2383
ada_really_inline constexpr std::string_view substring(std::string_view input,
2384
                                                       size_t pos1,
2385
1.62k
                                                       size_t pos2) {
2386
#if ADA_DEVELOPMENT_CHECKS
2387
  if (pos2 < pos1) {
2388
    std::cerr << "Negative-length substring: [" << pos1 << " to " << pos2 << ")"
2389
              << std::endl;
2390
    abort();
2391
  }
2392
#endif
2393
1.62k
  return input.substr(pos1, pos2 - pos1);
2394
1.62k
}
2395
2396
/**
2397
 * @private
2398
 * Modify the string_view so that it has the new size pos, assuming that pos <=
2399
 * input.size(). This function cannot throw.
2400
 */
2401
ada_really_inline void resize(std::string_view& input, size_t pos) noexcept;
2402
2403
/**
2404
 * @private
2405
 * Returns a host's delimiter location depending on the state of the instance,
2406
 * and whether a colon was found outside brackets. Used by the host parser.
2407
 */
2408
ada_really_inline std::pair<size_t, bool> get_host_delimiter_location(
2409
    bool is_special, std::string_view& view) noexcept;
2410
2411
/**
2412
 * @private
2413
 * Removes leading and trailing C0 control and whitespace characters from
2414
 * string.
2415
 */
2416
void trim_c0_whitespace(std::string_view& input) noexcept;
2417
2418
/**
2419
 * @private
2420
 * @see
2421
 * https://url.spec.whatwg.org/#potentially-strip-trailing-spaces-from-an-opaque-path
2422
 */
2423
template <class url_type>
2424
ada_really_inline void strip_trailing_spaces_from_opaque_path(url_type& url);
2425
2426
/**
2427
 * @private
2428
 * Finds the delimiter of a view in authority state.
2429
 */
2430
ada_really_inline size_t
2431
find_authority_delimiter_special(std::string_view view) noexcept;
2432
2433
/**
2434
 * @private
2435
 * Finds the delimiter of a view in authority state.
2436
 */
2437
ada_really_inline size_t
2438
find_authority_delimiter(std::string_view view) noexcept;
2439
2440
/**
2441
 * @private
2442
 */
2443
template <typename T, typename... Args>
2444
0
inline void inner_concat(std::string& buffer, T t) {
2445
0
  buffer.append(t);
2446
0
}
Unexecuted instantiation: void ada::helpers::inner_concat<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)
Unexecuted instantiation: void ada::helpers::inner_concat<char const*>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&, char const*)
Unexecuted instantiation: void ada::helpers::inner_concat<std::__1::basic_string_view<char, std::__1::char_traits<char> >>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&, std::__1::basic_string_view<char, std::__1::char_traits<char> >)
2447
2448
/**
2449
 * @private
2450
 */
2451
template <typename T, typename... Args>
2452
0
inline void inner_concat(std::string& buffer, T t, Args... args) {
2453
0
  buffer.append(t);
2454
0
  return inner_concat(buffer, args...);
2455
0
}
Unexecuted instantiation: void ada::helpers::inner_concat<char const*, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&, char const*, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)
Unexecuted instantiation: void ada::helpers::inner_concat<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, char const*, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, char const*, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)
Unexecuted instantiation: void ada::helpers::inner_concat<std::__1::basic_string_view<char, std::__1::char_traits<char> >, char const*>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&, std::__1::basic_string_view<char, std::__1::char_traits<char> >, char const*)
Unexecuted instantiation: void ada::helpers::inner_concat<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, char const*>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, char const*)
Unexecuted instantiation: void ada::helpers::inner_concat<char const*, std::__1::basic_string_view<char, std::__1::char_traits<char> > >(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&, char const*, std::__1::basic_string_view<char, std::__1::char_traits<char> >)
Unexecuted instantiation: void ada::helpers::inner_concat<std::__1::basic_string_view<char, std::__1::char_traits<char> >, char const*, std::__1::basic_string_view<char, std::__1::char_traits<char> > >(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&, std::__1::basic_string_view<char, std::__1::char_traits<char> >, char const*, std::__1::basic_string_view<char, std::__1::char_traits<char> >)
2456
2457
/**
2458
 * @private
2459
 * Concatenate the arguments and return a string.
2460
 * @returns a string
2461
 */
2462
template <typename... Args>
2463
0
std::string concat(Args... args) {
2464
0
  std::string answer;
2465
0
  inner_concat(answer, args...);
2466
0
  return answer;
2467
0
}
Unexecuted instantiation: std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > ada::helpers::concat<char const*, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(char const*, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)
Unexecuted instantiation: std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > ada::helpers::concat<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, char const*, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, char const*, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)
Unexecuted instantiation: std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > ada::helpers::concat<std::__1::basic_string_view<char, std::__1::char_traits<char> >, char const*>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, char const*)
Unexecuted instantiation: std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > ada::helpers::concat<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, char const*>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, char const*)
Unexecuted instantiation: std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > ada::helpers::concat<char const*, std::__1::basic_string_view<char, std::__1::char_traits<char> > >(char const*, std::__1::basic_string_view<char, std::__1::char_traits<char> >)
Unexecuted instantiation: std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > ada::helpers::concat<std::__1::basic_string_view<char, std::__1::char_traits<char> >, char const*, std::__1::basic_string_view<char, std::__1::char_traits<char> > >(std::__1::basic_string_view<char, std::__1::char_traits<char> >, char const*, std::__1::basic_string_view<char, std::__1::char_traits<char> >)
2468
2469
/**
2470
 * @private
2471
 * @return Number of leading zeroes.
2472
 */
2473
491
inline int leading_zeroes(uint32_t input_num) noexcept {
2474
#if ADA_REGULAR_VISUAL_STUDIO
2475
  unsigned long leading_zero(0);
2476
  unsigned long in(input_num);
2477
  return _BitScanReverse(&leading_zero, in) ? int(31 - leading_zero) : 32;
2478
#else
2479
491
  return __builtin_clz(input_num);
2480
491
#endif  // ADA_REGULAR_VISUAL_STUDIO
2481
491
}
2482
2483
/**
2484
 * @private
2485
 * Counts the number of decimal digits necessary to represent x.
2486
 * faster than std::to_string(x).size().
2487
 * @return digit count
2488
 */
2489
0
inline int fast_digit_count(uint32_t x) noexcept {
2490
0
  auto int_log2 = [](uint32_t z) -> int {
2491
0
    return 31 - ada::helpers::leading_zeroes(z | 1);
2492
0
  };
2493
  // Compiles to very few instructions. Note that the
2494
  // table is static and thus effectively a constant.
2495
  // We leave it inside the function because it is meaningless
2496
  // outside of it (this comes at no performance cost).
2497
0
  const static uint64_t table[] = {
2498
0
      4294967296,  8589934582,  8589934582,  8589934582,  12884901788,
2499
0
      12884901788, 12884901788, 17179868184, 17179868184, 17179868184,
2500
0
      21474826480, 21474826480, 21474826480, 21474826480, 25769703776,
2501
0
      25769703776, 25769703776, 30063771072, 30063771072, 30063771072,
2502
0
      34349738368, 34349738368, 34349738368, 34349738368, 38554705664,
2503
0
      38554705664, 38554705664, 41949672960, 41949672960, 41949672960,
2504
0
      42949672960, 42949672960};
2505
0
  return int((x + table[int_log2(x)]) >> 32);
2506
0
}
2507
}  // namespace ada::helpers
2508
2509
#endif  // ADA_HELPERS_H
2510
/* end file include/ada/helpers.h */
2511
/* begin file include/ada/parser.h */
2512
/**
2513
 * @file parser.h
2514
 * @brief Low-level URL parsing functions.
2515
 *
2516
 * This header provides the internal URL parsing implementation. Most users
2517
 * should use `ada::parse()` from implementation.h instead of these functions
2518
 * directly.
2519
 *
2520
 * @see implementation.h for the recommended public API
2521
 */
2522
#ifndef ADA_PARSER_H
2523
#define ADA_PARSER_H
2524
2525
#include <cstddef>
2526
#include <cstdint>
2527
#include <string_view>
2528
#include <variant>
2529
2530
/* begin file include/ada/expected.h */
2531
/**
2532
 * @file expected.h
2533
 * @brief Definitions for std::expected
2534
 * @private Excluded from docs through the doxygen file.
2535
 */
2536
///
2537
// expected - An implementation of std::expected with extensions
2538
// Written in 2017 by Sy Brand (tartanllama@gmail.com, @TartanLlama)
2539
//
2540
// Documentation available at http://tl.tartanllama.xyz/
2541
//
2542
// To the extent possible under law, the author(s) have dedicated all
2543
// copyright and related and neighboring rights to this software to the
2544
// public domain worldwide. This software is distributed without any warranty.
2545
//
2546
// You should have received a copy of the CC0 Public Domain Dedication
2547
// along with this software. If not, see
2548
// <http://creativecommons.org/publicdomain/zero/1.0/>.
2549
///
2550
2551
#ifndef TL_EXPECTED_HPP
2552
#define TL_EXPECTED_HPP
2553
2554
#define TL_EXPECTED_VERSION_MAJOR 1
2555
#define TL_EXPECTED_VERSION_MINOR 1
2556
#define TL_EXPECTED_VERSION_PATCH 0
2557
2558
#include <cstddef>
2559
#include <exception>
2560
#include <functional>
2561
#include <initializer_list>
2562
#include <type_traits>
2563
#include <utility>
2564
2565
#if defined(__EXCEPTIONS) || defined(_CPPUNWIND)
2566
#define TL_EXPECTED_EXCEPTIONS_ENABLED
2567
#endif
2568
2569
#if (defined(_MSC_VER) && _MSC_VER == 1900)
2570
#define TL_EXPECTED_MSVC2015
2571
#define TL_EXPECTED_MSVC2015_CONSTEXPR
2572
#else
2573
#define TL_EXPECTED_MSVC2015_CONSTEXPR constexpr
2574
#endif
2575
2576
#if (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ <= 9 && \
2577
     !defined(__clang__))
2578
#define TL_EXPECTED_GCC49
2579
#endif
2580
2581
#if (defined(__GNUC__) && __GNUC__ == 5 && __GNUC_MINOR__ <= 4 && \
2582
     !defined(__clang__))
2583
#define TL_EXPECTED_GCC54
2584
#endif
2585
2586
#if (defined(__GNUC__) && __GNUC__ == 5 && __GNUC_MINOR__ <= 5 && \
2587
     !defined(__clang__))
2588
#define TL_EXPECTED_GCC55
2589
#endif
2590
2591
#if !defined(TL_ASSERT)
2592
// can't have assert in constexpr in C++11 and GCC 4.9 has a compiler bug
2593
#if (__cplusplus > 201103L) && !defined(TL_EXPECTED_GCC49)
2594
#include <cassert>
2595
8.79k
#define TL_ASSERT(x) assert(x)
2596
#else
2597
#define TL_ASSERT(x)
2598
#endif
2599
#endif
2600
2601
#if (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ <= 9 && \
2602
     !defined(__clang__))
2603
// GCC < 5 doesn't support overloading on const&& for member functions
2604
2605
#define TL_EXPECTED_NO_CONSTRR
2606
// GCC < 5 doesn't support some standard C++11 type traits
2607
#define TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T) \
2608
  std::has_trivial_copy_constructor<T>
2609
#define TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T) \
2610
  std::has_trivial_copy_assign<T>
2611
2612
// This one will be different for GCC 5.7 if it's ever supported
2613
#define TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T) \
2614
  std::is_trivially_destructible<T>
2615
2616
// GCC 5 < v < 8 has a bug in is_trivially_copy_constructible which breaks
2617
// std::vector for non-copyable types
2618
#elif (defined(__GNUC__) && __GNUC__ < 8 && !defined(__clang__))
2619
#ifndef TL_GCC_LESS_8_TRIVIALLY_COPY_CONSTRUCTIBLE_MUTEX
2620
#define TL_GCC_LESS_8_TRIVIALLY_COPY_CONSTRUCTIBLE_MUTEX
2621
namespace tl {
2622
namespace detail {
2623
template <class T>
2624
struct is_trivially_copy_constructible
2625
    : std::is_trivially_copy_constructible<T> {};
2626
#ifdef _GLIBCXX_VECTOR
2627
template <class T, class A>
2628
struct is_trivially_copy_constructible<std::vector<T, A>> : std::false_type {};
2629
#endif
2630
}  // namespace detail
2631
}  // namespace tl
2632
#endif
2633
2634
#define TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T) \
2635
  tl::detail::is_trivially_copy_constructible<T>
2636
#define TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T) \
2637
  std::is_trivially_copy_assignable<T>
2638
#define TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T) \
2639
  std::is_trivially_destructible<T>
2640
#else
2641
#define TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T) \
2642
  std::is_trivially_copy_constructible<T>
2643
#define TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T) \
2644
  std::is_trivially_copy_assignable<T>
2645
#define TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T) \
2646
  std::is_trivially_destructible<T>
2647
#endif
2648
2649
#if __cplusplus > 201103L
2650
#define TL_EXPECTED_CXX14
2651
#endif
2652
2653
#ifdef TL_EXPECTED_GCC49
2654
#define TL_EXPECTED_GCC49_CONSTEXPR
2655
#else
2656
#define TL_EXPECTED_GCC49_CONSTEXPR constexpr
2657
#endif
2658
2659
#if (__cplusplus == 201103L || defined(TL_EXPECTED_MSVC2015) || \
2660
     defined(TL_EXPECTED_GCC49))
2661
#define TL_EXPECTED_11_CONSTEXPR
2662
#else
2663
#define TL_EXPECTED_11_CONSTEXPR constexpr
2664
#endif
2665
2666
namespace tl {
2667
template <class T, class E>
2668
class expected;
2669
2670
#ifndef TL_MONOSTATE_INPLACE_MUTEX
2671
#define TL_MONOSTATE_INPLACE_MUTEX
2672
class monostate {};
2673
2674
struct in_place_t {
2675
  explicit in_place_t() = default;
2676
};
2677
static constexpr in_place_t in_place{};
2678
#endif
2679
2680
template <class E>
2681
class unexpected {
2682
 public:
2683
  static_assert(!std::is_same<E, void>::value, "E must not be void");
2684
2685
  unexpected() = delete;
2686
  constexpr explicit unexpected(const E& e) : m_val(e) {}
2687
2688
0
  constexpr explicit unexpected(E&& e) : m_val(std::move(e)) {}
2689
2690
  template <class... Args, typename std::enable_if<std::is_constructible<
2691
                               E, Args&&...>::value>::type* = nullptr>
2692
  constexpr explicit unexpected(Args&&... args)
2693
0
      : m_val(std::forward<Args>(args)...) {}
2694
  template <
2695
      class U, class... Args,
2696
      typename std::enable_if<std::is_constructible<
2697
          E, std::initializer_list<U>&, Args&&...>::value>::type* = nullptr>
2698
  constexpr explicit unexpected(std::initializer_list<U> l, Args&&... args)
2699
      : m_val(l, std::forward<Args>(args)...) {}
2700
2701
  constexpr const E& value() const& { return m_val; }
2702
0
  TL_EXPECTED_11_CONSTEXPR E& value() & { return m_val; }
2703
  TL_EXPECTED_11_CONSTEXPR E&& value() && { return std::move(m_val); }
2704
  constexpr const E&& value() const&& { return std::move(m_val); }
2705
2706
 private:
2707
  E m_val;
2708
};
2709
2710
#ifdef __cpp_deduction_guides
2711
template <class E>
2712
unexpected(E) -> unexpected<E>;
2713
#endif
2714
2715
template <class E>
2716
constexpr bool operator==(const unexpected<E>& lhs, const unexpected<E>& rhs) {
2717
  return lhs.value() == rhs.value();
2718
}
2719
template <class E>
2720
constexpr bool operator!=(const unexpected<E>& lhs, const unexpected<E>& rhs) {
2721
  return lhs.value() != rhs.value();
2722
}
2723
template <class E>
2724
constexpr bool operator<(const unexpected<E>& lhs, const unexpected<E>& rhs) {
2725
  return lhs.value() < rhs.value();
2726
}
2727
template <class E>
2728
constexpr bool operator<=(const unexpected<E>& lhs, const unexpected<E>& rhs) {
2729
  return lhs.value() <= rhs.value();
2730
}
2731
template <class E>
2732
constexpr bool operator>(const unexpected<E>& lhs, const unexpected<E>& rhs) {
2733
  return lhs.value() > rhs.value();
2734
}
2735
template <class E>
2736
constexpr bool operator>=(const unexpected<E>& lhs, const unexpected<E>& rhs) {
2737
  return lhs.value() >= rhs.value();
2738
}
2739
2740
template <class E>
2741
unexpected<typename std::decay<E>::type> make_unexpected(E&& e) {
2742
  return unexpected<typename std::decay<E>::type>(std::forward<E>(e));
2743
}
2744
2745
struct unexpect_t {
2746
  unexpect_t() = default;
2747
};
2748
static constexpr unexpect_t unexpect{};
2749
2750
namespace detail {
2751
template <typename E>
2752
0
[[noreturn]] TL_EXPECTED_11_CONSTEXPR void throw_exception(E&& e) {
2753
0
#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED
2754
0
  throw std::forward<E>(e);
2755
#else
2756
  (void)e;
2757
#ifdef _MSC_VER
2758
  __assume(0);
2759
#else
2760
  __builtin_unreachable();
2761
#endif
2762
#endif
2763
0
}
2764
2765
#ifndef TL_TRAITS_MUTEX
2766
#define TL_TRAITS_MUTEX
2767
// C++14-style aliases for brevity
2768
template <class T>
2769
using remove_const_t = typename std::remove_const<T>::type;
2770
template <class T>
2771
using remove_reference_t = typename std::remove_reference<T>::type;
2772
template <class T>
2773
using decay_t = typename std::decay<T>::type;
2774
template <bool E, class T = void>
2775
using enable_if_t = typename std::enable_if<E, T>::type;
2776
template <bool B, class T, class F>
2777
using conditional_t = typename std::conditional<B, T, F>::type;
2778
2779
// std::conjunction from C++17
2780
template <class...>
2781
struct conjunction : std::true_type {};
2782
template <class B>
2783
struct conjunction<B> : B {};
2784
template <class B, class... Bs>
2785
struct conjunction<B, Bs...>
2786
    : std::conditional<bool(B::value), conjunction<Bs...>, B>::type {};
2787
2788
#if defined(_LIBCPP_VERSION) && __cplusplus == 201103L
2789
#define TL_TRAITS_LIBCXX_MEM_FN_WORKAROUND
2790
#endif
2791
2792
// In C++11 mode, there's an issue in libc++'s std::mem_fn
2793
// which results in a hard-error when using it in a noexcept expression
2794
// in some cases. This is a check to workaround the common failing case.
2795
#ifdef TL_TRAITS_LIBCXX_MEM_FN_WORKAROUND
2796
template <class T>
2797
struct is_pointer_to_non_const_member_func : std::false_type {};
2798
template <class T, class Ret, class... Args>
2799
struct is_pointer_to_non_const_member_func<Ret (T::*)(Args...)>
2800
    : std::true_type {};
2801
template <class T, class Ret, class... Args>
2802
struct is_pointer_to_non_const_member_func<Ret (T::*)(Args...) &>
2803
    : std::true_type {};
2804
template <class T, class Ret, class... Args>
2805
struct is_pointer_to_non_const_member_func<Ret (T::*)(Args...) &&>
2806
    : std::true_type {};
2807
template <class T, class Ret, class... Args>
2808
struct is_pointer_to_non_const_member_func<Ret (T::*)(Args...) volatile>
2809
    : std::true_type {};
2810
template <class T, class Ret, class... Args>
2811
struct is_pointer_to_non_const_member_func<Ret (T::*)(Args...) volatile&>
2812
    : std::true_type {};
2813
template <class T, class Ret, class... Args>
2814
struct is_pointer_to_non_const_member_func<Ret (T::*)(Args...) volatile&&>
2815
    : std::true_type {};
2816
2817
template <class T>
2818
struct is_const_or_const_ref : std::false_type {};
2819
template <class T>
2820
struct is_const_or_const_ref<T const&> : std::true_type {};
2821
template <class T>
2822
struct is_const_or_const_ref<T const> : std::true_type {};
2823
#endif
2824
2825
// std::invoke from C++17
2826
// https://stackoverflow.com/questions/38288042/c11-14-invoke-workaround
2827
template <
2828
    typename Fn, typename... Args,
2829
#ifdef TL_TRAITS_LIBCXX_MEM_FN_WORKAROUND
2830
    typename = enable_if_t<!(is_pointer_to_non_const_member_func<Fn>::value &&
2831
                             is_const_or_const_ref<Args...>::value)>,
2832
#endif
2833
    typename = enable_if_t<std::is_member_pointer<decay_t<Fn>>::value>, int = 0>
2834
constexpr auto invoke(Fn&& f, Args&&... args) noexcept(
2835
    noexcept(std::mem_fn(f)(std::forward<Args>(args)...)))
2836
    -> decltype(std::mem_fn(f)(std::forward<Args>(args)...)) {
2837
  return std::mem_fn(f)(std::forward<Args>(args)...);
2838
}
2839
2840
template <typename Fn, typename... Args,
2841
          typename = enable_if_t<!std::is_member_pointer<decay_t<Fn>>::value>>
2842
constexpr auto invoke(Fn&& f, Args&&... args) noexcept(
2843
    noexcept(std::forward<Fn>(f)(std::forward<Args>(args)...)))
2844
    -> decltype(std::forward<Fn>(f)(std::forward<Args>(args)...)) {
2845
  return std::forward<Fn>(f)(std::forward<Args>(args)...);
2846
}
2847
2848
// std::invoke_result from C++17
2849
template <class F, class, class... Us>
2850
struct invoke_result_impl;
2851
2852
template <class F, class... Us>
2853
struct invoke_result_impl<
2854
    F,
2855
    decltype(detail::invoke(std::declval<F>(), std::declval<Us>()...), void()),
2856
    Us...> {
2857
  using type =
2858
      decltype(detail::invoke(std::declval<F>(), std::declval<Us>()...));
2859
};
2860
2861
template <class F, class... Us>
2862
using invoke_result = invoke_result_impl<F, void, Us...>;
2863
2864
template <class F, class... Us>
2865
using invoke_result_t = typename invoke_result<F, Us...>::type;
2866
2867
#if defined(_MSC_VER) && _MSC_VER <= 1900
2868
// TODO make a version which works with MSVC 2015
2869
template <class T, class U = T>
2870
struct is_swappable : std::true_type {};
2871
2872
template <class T, class U = T>
2873
struct is_nothrow_swappable : std::true_type {};
2874
#else
2875
// https://stackoverflow.com/questions/26744589/what-is-a-proper-way-to-implement-is-swappable-to-test-for-the-swappable-concept
2876
namespace swap_adl_tests {
2877
// if swap ADL finds this then it would call std::swap otherwise (same
2878
// signature)
2879
struct tag {};
2880
2881
template <class T>
2882
tag swap(T&, T&);
2883
template <class T, std::size_t N>
2884
tag swap(T (&a)[N], T (&b)[N]);
2885
2886
// helper functions to test if an unqualified swap is possible, and if it
2887
// becomes std::swap
2888
template <class, class>
2889
std::false_type can_swap(...) noexcept(false);
2890
template <class T, class U,
2891
          class = decltype(swap(std::declval<T&>(), std::declval<U&>()))>
2892
std::true_type can_swap(int) noexcept(noexcept(swap(std::declval<T&>(),
2893
                                                    std::declval<U&>())));
2894
2895
template <class, class>
2896
std::false_type uses_std(...);
2897
template <class T, class U>
2898
std::is_same<decltype(swap(std::declval<T&>(), std::declval<U&>())), tag>
2899
uses_std(int);
2900
2901
template <class T>
2902
struct is_std_swap_noexcept
2903
    : std::integral_constant<bool,
2904
                             std::is_nothrow_move_constructible<T>::value &&
2905
                                 std::is_nothrow_move_assignable<T>::value> {};
2906
2907
template <class T, std::size_t N>
2908
struct is_std_swap_noexcept<T[N]> : is_std_swap_noexcept<T> {};
2909
2910
template <class T, class U>
2911
struct is_adl_swap_noexcept
2912
    : std::integral_constant<bool, noexcept(can_swap<T, U>(0))> {};
2913
}  // namespace swap_adl_tests
2914
2915
template <class T, class U = T>
2916
struct is_swappable
2917
    : std::integral_constant<
2918
          bool,
2919
          decltype(detail::swap_adl_tests::can_swap<T, U>(0))::value &&
2920
              (!decltype(detail::swap_adl_tests::uses_std<T, U>(0))::value ||
2921
               (std::is_move_assignable<T>::value &&
2922
                std::is_move_constructible<T>::value))> {};
2923
2924
template <class T, std::size_t N>
2925
struct is_swappable<T[N], T[N]>
2926
    : std::integral_constant<
2927
          bool,
2928
          decltype(detail::swap_adl_tests::can_swap<T[N], T[N]>(0))::value &&
2929
              (!decltype(detail::swap_adl_tests::uses_std<T[N], T[N]>(
2930
                   0))::value ||
2931
               is_swappable<T, T>::value)> {};
2932
2933
template <class T, class U = T>
2934
struct is_nothrow_swappable
2935
    : std::integral_constant<
2936
          bool,
2937
          is_swappable<T, U>::value &&
2938
              ((decltype(detail::swap_adl_tests::uses_std<T, U>(0))::value &&
2939
                detail::swap_adl_tests::is_std_swap_noexcept<T>::value) ||
2940
               (!decltype(detail::swap_adl_tests::uses_std<T, U>(0))::value &&
2941
                detail::swap_adl_tests::is_adl_swap_noexcept<T, U>::value))> {};
2942
#endif
2943
#endif
2944
2945
// Trait for checking if a type is a tl::expected
2946
template <class T>
2947
struct is_expected_impl : std::false_type {};
2948
template <class T, class E>
2949
struct is_expected_impl<expected<T, E>> : std::true_type {};
2950
template <class T>
2951
using is_expected = is_expected_impl<decay_t<T>>;
2952
2953
template <class T, class E, class U>
2954
using expected_enable_forward_value = detail::enable_if_t<
2955
    std::is_constructible<T, U&&>::value &&
2956
    !std::is_same<detail::decay_t<U>, in_place_t>::value &&
2957
    !std::is_same<expected<T, E>, detail::decay_t<U>>::value &&
2958
    !std::is_same<unexpected<E>, detail::decay_t<U>>::value>;
2959
2960
template <class T, class E, class U, class G, class UR, class GR>
2961
using expected_enable_from_other = detail::enable_if_t<
2962
    std::is_constructible<T, UR>::value &&
2963
    std::is_constructible<E, GR>::value &&
2964
    !std::is_constructible<T, expected<U, G>&>::value &&
2965
    !std::is_constructible<T, expected<U, G>&&>::value &&
2966
    !std::is_constructible<T, const expected<U, G>&>::value &&
2967
    !std::is_constructible<T, const expected<U, G>&&>::value &&
2968
    !std::is_convertible<expected<U, G>&, T>::value &&
2969
    !std::is_convertible<expected<U, G>&&, T>::value &&
2970
    !std::is_convertible<const expected<U, G>&, T>::value &&
2971
    !std::is_convertible<const expected<U, G>&&, T>::value>;
2972
2973
template <class T, class U>
2974
using is_void_or = conditional_t<std::is_void<T>::value, std::true_type, U>;
2975
2976
template <class T>
2977
using is_copy_constructible_or_void =
2978
    is_void_or<T, std::is_copy_constructible<T>>;
2979
2980
template <class T>
2981
using is_move_constructible_or_void =
2982
    is_void_or<T, std::is_move_constructible<T>>;
2983
2984
template <class T>
2985
using is_copy_assignable_or_void = is_void_or<T, std::is_copy_assignable<T>>;
2986
2987
template <class T>
2988
using is_move_assignable_or_void = is_void_or<T, std::is_move_assignable<T>>;
2989
2990
}  // namespace detail
2991
2992
namespace detail {
2993
struct no_init_t {};
2994
static constexpr no_init_t no_init{};
2995
2996
// Implements the storage of the values, and ensures that the destructor is
2997
// trivial if it can be.
2998
//
2999
// This specialization is for where neither `T` or `E` is trivially
3000
// destructible, so the destructors must be called on destruction of the
3001
// `expected`
3002
template <class T, class E, bool = std::is_trivially_destructible<T>::value,
3003
          bool = std::is_trivially_destructible<E>::value>
3004
struct expected_storage_base {
3005
  constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {}
3006
  constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {}
3007
3008
  template <class... Args,
3009
            detail::enable_if_t<std::is_constructible<T, Args&&...>::value>* =
3010
                nullptr>
3011
  constexpr expected_storage_base(in_place_t, Args&&... args)
3012
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
3013
3014
  template <class U, class... Args,
3015
            detail::enable_if_t<std::is_constructible<
3016
                T, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
3017
  constexpr expected_storage_base(in_place_t, std::initializer_list<U> il,
3018
                                  Args&&... args)
3019
      : m_val(il, std::forward<Args>(args)...), m_has_val(true) {}
3020
  template <class... Args,
3021
            detail::enable_if_t<std::is_constructible<E, Args&&...>::value>* =
3022
                nullptr>
3023
  constexpr explicit expected_storage_base(unexpect_t, Args&&... args)
3024
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
3025
3026
  template <class U, class... Args,
3027
            detail::enable_if_t<std::is_constructible<
3028
                E, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
3029
  constexpr explicit expected_storage_base(unexpect_t,
3030
                                           std::initializer_list<U> il,
3031
                                           Args&&... args)
3032
      : m_unexpect(il, std::forward<Args>(args)...), m_has_val(false) {}
3033
3034
  ~expected_storage_base() {
3035
    if (m_has_val) {
3036
      m_val.~T();
3037
    } else {
3038
      m_unexpect.~unexpected<E>();
3039
    }
3040
  }
3041
  union {
3042
    T m_val;
3043
    unexpected<E> m_unexpect;
3044
    char m_no_init;
3045
  };
3046
  bool m_has_val;
3047
};
3048
3049
// This specialization is for when both `T` and `E` are trivially-destructible,
3050
// so the destructor of the `expected` can be trivial.
3051
template <class T, class E>
3052
struct expected_storage_base<T, E, true, true> {
3053
  constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {}
3054
  constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {}
3055
3056
  template <class... Args,
3057
            detail::enable_if_t<std::is_constructible<T, Args&&...>::value>* =
3058
                nullptr>
3059
  constexpr expected_storage_base(in_place_t, Args&&... args)
3060
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
3061
3062
  template <class U, class... Args,
3063
            detail::enable_if_t<std::is_constructible<
3064
                T, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
3065
  constexpr expected_storage_base(in_place_t, std::initializer_list<U> il,
3066
                                  Args&&... args)
3067
      : m_val(il, std::forward<Args>(args)...), m_has_val(true) {}
3068
  template <class... Args,
3069
            detail::enable_if_t<std::is_constructible<E, Args&&...>::value>* =
3070
                nullptr>
3071
  constexpr explicit expected_storage_base(unexpect_t, Args&&... args)
3072
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
3073
3074
  template <class U, class... Args,
3075
            detail::enable_if_t<std::is_constructible<
3076
                E, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
3077
  constexpr explicit expected_storage_base(unexpect_t,
3078
                                           std::initializer_list<U> il,
3079
                                           Args&&... args)
3080
      : m_unexpect(il, std::forward<Args>(args)...), m_has_val(false) {}
3081
3082
  ~expected_storage_base() = default;
3083
  union {
3084
    T m_val;
3085
    unexpected<E> m_unexpect;
3086
    char m_no_init;
3087
  };
3088
  bool m_has_val;
3089
};
3090
3091
// T is trivial, E is not.
3092
template <class T, class E>
3093
struct expected_storage_base<T, E, true, false> {
3094
  constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {}
3095
  TL_EXPECTED_MSVC2015_CONSTEXPR expected_storage_base(no_init_t)
3096
      : m_no_init(), m_has_val(false) {}
3097
3098
  template <class... Args,
3099
            detail::enable_if_t<std::is_constructible<T, Args&&...>::value>* =
3100
                nullptr>
3101
  constexpr expected_storage_base(in_place_t, Args&&... args)
3102
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
3103
3104
  template <class U, class... Args,
3105
            detail::enable_if_t<std::is_constructible<
3106
                T, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
3107
  constexpr expected_storage_base(in_place_t, std::initializer_list<U> il,
3108
                                  Args&&... args)
3109
      : m_val(il, std::forward<Args>(args)...), m_has_val(true) {}
3110
  template <class... Args,
3111
            detail::enable_if_t<std::is_constructible<E, Args&&...>::value>* =
3112
                nullptr>
3113
  constexpr explicit expected_storage_base(unexpect_t, Args&&... args)
3114
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
3115
3116
  template <class U, class... Args,
3117
            detail::enable_if_t<std::is_constructible<
3118
                E, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
3119
  constexpr explicit expected_storage_base(unexpect_t,
3120
                                           std::initializer_list<U> il,
3121
                                           Args&&... args)
3122
      : m_unexpect(il, std::forward<Args>(args)...), m_has_val(false) {}
3123
3124
  ~expected_storage_base() {
3125
    if (!m_has_val) {
3126
      m_unexpect.~unexpected<E>();
3127
    }
3128
  }
3129
3130
  union {
3131
    T m_val;
3132
    unexpected<E> m_unexpect;
3133
    char m_no_init;
3134
  };
3135
  bool m_has_val;
3136
};
3137
3138
// E is trivial, T is not.
3139
template <class T, class E>
3140
struct expected_storage_base<T, E, false, true> {
3141
  constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {}
3142
0
  constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {}
3143
3144
  template <class... Args,
3145
            detail::enable_if_t<std::is_constructible<T, Args&&...>::value>* =
3146
                nullptr>
3147
  constexpr expected_storage_base(in_place_t, Args&&... args)
3148
2.93k
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
Unexecuted instantiation: _ZN2tl6detail21expected_storage_baseIN3ada3urlENS2_6errorsELb0ELb1EEC2IJS3_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS3_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESB_
_ZN2tl6detail21expected_storage_baseIN3ada14url_aggregatorENS2_6errorsELb0ELb1EEC2IJS3_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS3_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESB_
Line
Count
Source
3148
2.93k
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
Unexecuted instantiation: _ZN2tl6detail21expected_storage_baseIN3ada16url_pattern_initENS2_6errorsELb0ELb1EEC2IJS3_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS3_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESB_
Unexecuted instantiation: _ZN2tl6detail21expected_storage_baseINSt3__112basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEEN3ada6errorsELb0ELb1EEC2IJS8_ETnPNS2_9enable_ifIXsr3std16is_constructibleIS8_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESG_
Unexecuted instantiation: _ZN2tl6detail21expected_storage_baseINSt3__112basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEEN3ada6errorsELb0ELb1EEC2IJRA1_KcETnPNS2_9enable_ifIXsr3std16is_constructibleIS8_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESJ_
Unexecuted instantiation: _ZN2tl6detail21expected_storage_baseINSt3__112basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEEN3ada6errorsELb0ELb1EEC2IJRA2_KcETnPNS2_9enable_ifIXsr3std16is_constructibleIS8_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESJ_
Unexecuted instantiation: _ZN2tl6detail21expected_storage_baseINSt3__16vectorIN3ada19url_pattern_helpers5tokenENS2_9allocatorIS6_EEEENS4_6errorsELb0ELb1EEC2IJRS9_ETnPNS2_9enable_ifIXsr3std16is_constructibleIS9_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESH_
Unexecuted instantiation: _ZN2tl6detail21expected_storage_baseIN3ada23url_pattern_list_detail15compiled_routesENS2_6errorsELb0ELb1EEC2IJS4_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS4_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESC_
Unexecuted instantiation: _ZN2tl6detail21expected_storage_baseIN3ada17url_search_paramsENS2_6errorsELb0ELb1EEC2IJS3_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS3_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESB_
Unexecuted instantiation: _ZN2tl6detail21expected_storage_baseINSt3__16vectorINS2_12basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEENS7_IS9_EEEEN3ada6errorsELb0ELb1EEC2IJSB_ETnPNS2_9enable_ifIXsr3std16is_constructibleISB_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESJ_
Unexecuted instantiation: _ZN2tl6detail21expected_storage_baseINSt3__16vectorIN3ada16url_pattern_partENS2_9allocatorIS5_EEEENS4_6errorsELb0ELb1EEC2IJRS8_ETnPNS2_9enable_ifIXsr3std16is_constructibleIS8_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESG_
3149
3150
  template <class U, class... Args,
3151
            detail::enable_if_t<std::is_constructible<
3152
                T, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
3153
  constexpr expected_storage_base(in_place_t, std::initializer_list<U> il,
3154
                                  Args&&... args)
3155
      : m_val(il, std::forward<Args>(args)...), m_has_val(true) {}
3156
  template <class... Args,
3157
            detail::enable_if_t<std::is_constructible<E, Args&&...>::value>* =
3158
                nullptr>
3159
  constexpr explicit expected_storage_base(unexpect_t, Args&&... args)
3160
0
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
Unexecuted instantiation: _ZN2tl6detail21expected_storage_baseIN3ada3urlENS2_6errorsELb0ELb1EEC2IJS4_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS4_DpOT_EE5valueEvE4typeELPv0EEENS_10unexpect_tESB_
Unexecuted instantiation: _ZN2tl6detail21expected_storage_baseIN3ada14url_aggregatorENS2_6errorsELb0ELb1EEC2IJS4_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS4_DpOT_EE5valueEvE4typeELPv0EEENS_10unexpect_tESB_
Unexecuted instantiation: _ZN2tl6detail21expected_storage_baseIN3ada16url_pattern_initENS2_6errorsELb0ELb1EEC2IJS4_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS4_DpOT_EE5valueEvE4typeELPv0EEENS_10unexpect_tESB_
Unexecuted instantiation: _ZN2tl6detail21expected_storage_baseINSt3__112basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEEN3ada6errorsELb0ELb1EEC2IJSA_ETnPNS2_9enable_ifIXsr3std16is_constructibleISA_DpOT_EE5valueEvE4typeELPv0EEENS_10unexpect_tESG_
Unexecuted instantiation: _ZN2tl6detail21expected_storage_baseINSt3__16vectorIN3ada19url_pattern_helpers5tokenENS2_9allocatorIS6_EEEENS4_6errorsELb0ELb1EEC2IJSA_ETnPNS2_9enable_ifIXsr3std16is_constructibleISA_DpOT_EE5valueEvE4typeELPv0EEENS_10unexpect_tESG_
Unexecuted instantiation: _ZN2tl6detail21expected_storage_baseIN3ada23url_pattern_list_detail15compiled_routesENS2_6errorsELb0ELb1EEC2IJS5_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS5_DpOT_EE5valueEvE4typeELPv0EEENS_10unexpect_tESC_
Unexecuted instantiation: _ZN2tl6detail21expected_storage_baseINSt3__16vectorIN3ada16url_pattern_partENS2_9allocatorIS5_EEEENS4_6errorsELb0ELb1EEC2IJS9_ETnPNS2_9enable_ifIXsr3std16is_constructibleIS9_DpOT_EE5valueEvE4typeELPv0EEENS_10unexpect_tESF_
3161
3162
  template <class U, class... Args,
3163
            detail::enable_if_t<std::is_constructible<
3164
                E, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
3165
  constexpr explicit expected_storage_base(unexpect_t,
3166
                                           std::initializer_list<U> il,
3167
                                           Args&&... args)
3168
      : m_unexpect(il, std::forward<Args>(args)...), m_has_val(false) {}
3169
3170
2.93k
  ~expected_storage_base() {
3171
2.93k
    if (m_has_val) {
3172
2.93k
      m_val.~T();
3173
2.93k
    }
3174
2.93k
  }
Unexecuted instantiation: tl::detail::expected_storage_base<ada::url, ada::errors, false, true>::~expected_storage_base()
tl::detail::expected_storage_base<ada::url_aggregator, ada::errors, false, true>::~expected_storage_base()
Line
Count
Source
3170
2.93k
  ~expected_storage_base() {
3171
2.93k
    if (m_has_val) {
3172
2.93k
      m_val.~T();
3173
2.93k
    }
3174
2.93k
  }
Unexecuted instantiation: tl::detail::expected_storage_base<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, ada::errors, false, true>::~expected_storage_base()
Unexecuted instantiation: tl::detail::expected_storage_base<ada::url_pattern_list_detail::compiled_routes, ada::errors, false, true>::~expected_storage_base()
Unexecuted instantiation: tl::detail::expected_storage_base<std::__1::vector<ada::url_pattern_part, std::__1::allocator<ada::url_pattern_part> >, ada::errors, false, true>::~expected_storage_base()
Unexecuted instantiation: tl::detail::expected_storage_base<ada::url_search_params, ada::errors, false, true>::~expected_storage_base()
Unexecuted instantiation: tl::detail::expected_storage_base<std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >, ada::errors, false, true>::~expected_storage_base()
Unexecuted instantiation: tl::detail::expected_storage_base<std::__1::vector<ada::url_pattern_helpers::token, std::__1::allocator<ada::url_pattern_helpers::token> >, ada::errors, false, true>::~expected_storage_base()
3175
  union {
3176
    T m_val;
3177
    unexpected<E> m_unexpect;
3178
    char m_no_init;
3179
  };
3180
  bool m_has_val;
3181
};
3182
3183
// `T` is `void`, `E` is trivially-destructible
3184
template <class E>
3185
struct expected_storage_base<void, E, false, true> {
3186
#if __GNUC__ <= 5
3187
// no constexpr for GCC 4/5 bug
3188
#else
3189
  TL_EXPECTED_MSVC2015_CONSTEXPR
3190
#endif
3191
  expected_storage_base() : m_has_val(true) {}
3192
3193
  constexpr expected_storage_base(no_init_t) : m_val(), m_has_val(false) {}
3194
3195
  constexpr expected_storage_base(in_place_t) : m_has_val(true) {}
3196
3197
  template <class... Args,
3198
            detail::enable_if_t<std::is_constructible<E, Args&&...>::value>* =
3199
                nullptr>
3200
  constexpr explicit expected_storage_base(unexpect_t, Args&&... args)
3201
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
3202
3203
  template <class U, class... Args,
3204
            detail::enable_if_t<std::is_constructible<
3205
                E, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
3206
  constexpr explicit expected_storage_base(unexpect_t,
3207
                                           std::initializer_list<U> il,
3208
                                           Args&&... args)
3209
      : m_unexpect(il, std::forward<Args>(args)...), m_has_val(false) {}
3210
3211
  ~expected_storage_base() = default;
3212
  struct dummy {};
3213
  union {
3214
    unexpected<E> m_unexpect;
3215
    dummy m_val;
3216
  };
3217
  bool m_has_val;
3218
};
3219
3220
// `T` is `void`, `E` is not trivially-destructible
3221
template <class E>
3222
struct expected_storage_base<void, E, false, false> {
3223
  constexpr expected_storage_base() : m_dummy(), m_has_val(true) {}
3224
  constexpr expected_storage_base(no_init_t) : m_dummy(), m_has_val(false) {}
3225
3226
  constexpr expected_storage_base(in_place_t) : m_dummy(), m_has_val(true) {}
3227
3228
  template <class... Args,
3229
            detail::enable_if_t<std::is_constructible<E, Args&&...>::value>* =
3230
                nullptr>
3231
  constexpr explicit expected_storage_base(unexpect_t, Args&&... args)
3232
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
3233
3234
  template <class U, class... Args,
3235
            detail::enable_if_t<std::is_constructible<
3236
                E, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
3237
  constexpr explicit expected_storage_base(unexpect_t,
3238
                                           std::initializer_list<U> il,
3239
                                           Args&&... args)
3240
      : m_unexpect(il, std::forward<Args>(args)...), m_has_val(false) {}
3241
3242
  ~expected_storage_base() {
3243
    if (!m_has_val) {
3244
      m_unexpect.~unexpected<E>();
3245
    }
3246
  }
3247
3248
  union {
3249
    unexpected<E> m_unexpect;
3250
    char m_dummy;
3251
  };
3252
  bool m_has_val;
3253
};
3254
3255
// This base class provides some handy member functions which can be used in
3256
// further derived classes
3257
template <class T, class E>
3258
struct expected_operations_base : expected_storage_base<T, E> {
3259
  using expected_storage_base<T, E>::expected_storage_base;
3260
3261
  template <class... Args>
3262
  void construct(Args&&... args) noexcept {
3263
    new (std::addressof(this->m_val)) T(std::forward<Args>(args)...);
3264
    this->m_has_val = true;
3265
  }
3266
3267
  template <class Rhs>
3268
  // NOLINTNEXTLINE(bugprone-exception-escape)
3269
0
  void construct_with(Rhs&& rhs) noexcept {
3270
0
    new (std::addressof(this->m_val)) T(std::forward<Rhs>(rhs).get());
3271
0
    this->m_has_val = true;
3272
0
  }
Unexecuted instantiation: void tl::detail::expected_operations_base<ada::url_aggregator, ada::errors>::construct_with<tl::detail::expected_copy_base<ada::url_aggregator, ada::errors, false> const&>(tl::detail::expected_copy_base<ada::url_aggregator, ada::errors, false> const&)
Unexecuted instantiation: void tl::detail::expected_operations_base<ada::url_pattern_list_detail::compiled_routes, ada::errors>::construct_with<tl::detail::expected_move_base<ada::url_pattern_list_detail::compiled_routes, ada::errors, false> >(tl::detail::expected_move_base<ada::url_pattern_list_detail::compiled_routes, ada::errors, false>&&)
3273
3274
  template <class... Args>
3275
0
  void construct_error(Args&&... args) noexcept {
3276
0
    new (std::addressof(this->m_unexpect))
3277
0
        unexpected<E>(std::forward<Args>(args)...);
3278
0
    this->m_has_val = false;
3279
0
  }
Unexecuted instantiation: void tl::detail::expected_operations_base<ada::url_aggregator, ada::errors>::construct_error<tl::unexpected<ada::errors> const&>(tl::unexpected<ada::errors> const&)
Unexecuted instantiation: void tl::detail::expected_operations_base<ada::url_pattern_list_detail::compiled_routes, ada::errors>::construct_error<tl::unexpected<ada::errors> >(tl::unexpected<ada::errors>&&)
3280
3281
#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED
3282
3283
  // These assign overloads ensure that the most efficient assignment
3284
  // implementation is used while maintaining the strong exception guarantee.
3285
  // The problematic case is where rhs has a value, but *this does not.
3286
  //
3287
  // This overload handles the case where we can just copy-construct `T`
3288
  // directly into place without throwing.
3289
  template <class U = T,
3290
            detail::enable_if_t<std::is_nothrow_copy_constructible<U>::value>* =
3291
                nullptr>
3292
  void assign(const expected_operations_base& rhs) noexcept {
3293
    if (!this->m_has_val && rhs.m_has_val) {
3294
      geterr().~unexpected<E>();
3295
      construct(rhs.get());
3296
    } else {
3297
      assign_common(rhs);
3298
    }
3299
  }
3300
3301
  // This overload handles the case where we can attempt to create a copy of
3302
  // `T`, then no-throw move it into place if the copy was successful.
3303
  template <class U = T,
3304
            detail::enable_if_t<!std::is_nothrow_copy_constructible<U>::value &&
3305
                                std::is_nothrow_move_constructible<U>::value>* =
3306
                nullptr>
3307
  void assign(const expected_operations_base& rhs) noexcept {
3308
    if (!this->m_has_val && rhs.m_has_val) {
3309
      T tmp = rhs.get();
3310
      geterr().~unexpected<E>();
3311
      construct(std::move(tmp));
3312
    } else {
3313
      assign_common(rhs);
3314
    }
3315
  }
3316
3317
  // This overload is the worst-case, where we have to move-construct the
3318
  // unexpected value into temporary storage, then try to copy the T into place.
3319
  // If the construction succeeds, then everything is fine, but if it throws,
3320
  // then we move the old unexpected value back into place before rethrowing the
3321
  // exception.
3322
  template <class U = T,
3323
            detail::enable_if_t<
3324
                !std::is_nothrow_copy_constructible<U>::value &&
3325
                !std::is_nothrow_move_constructible<U>::value>* = nullptr>
3326
  void assign(const expected_operations_base& rhs) {
3327
    if (!this->m_has_val && rhs.m_has_val) {
3328
      auto tmp = std::move(geterr());
3329
      geterr().~unexpected<E>();
3330
3331
#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED
3332
      try {
3333
        construct(rhs.get());
3334
      } catch (...) {
3335
        geterr() = std::move(tmp);
3336
        throw;
3337
      }
3338
#else
3339
      construct(rhs.get());
3340
#endif
3341
    } else {
3342
      assign_common(rhs);
3343
    }
3344
  }
3345
3346
  // These overloads do the same as above, but for rvalues
3347
  template <class U = T,
3348
            detail::enable_if_t<std::is_nothrow_move_constructible<U>::value>* =
3349
                nullptr>
3350
  void assign(expected_operations_base&& rhs) noexcept {
3351
    if (!this->m_has_val && rhs.m_has_val) {
3352
      geterr().~unexpected<E>();
3353
      construct(std::move(rhs).get());
3354
    } else {
3355
      assign_common(std::move(rhs));
3356
    }
3357
  }
3358
3359
  template <class U = T,
3360
            detail::enable_if_t<
3361
                !std::is_nothrow_move_constructible<U>::value>* = nullptr>
3362
  void assign(expected_operations_base&& rhs) {
3363
    if (!this->m_has_val && rhs.m_has_val) {
3364
      auto tmp = std::move(geterr());
3365
      geterr().~unexpected<E>();
3366
#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED
3367
      try {
3368
        construct(std::move(rhs).get());
3369
      } catch (...) {
3370
        geterr() = std::move(tmp);
3371
        throw;
3372
      }
3373
#else
3374
      construct(std::move(rhs).get());
3375
#endif
3376
    } else {
3377
      assign_common(std::move(rhs));
3378
    }
3379
  }
3380
3381
#else
3382
3383
  // If exceptions are disabled then we can just copy-construct
3384
  void assign(const expected_operations_base& rhs) noexcept {
3385
    if (!this->m_has_val && rhs.m_has_val) {
3386
      geterr().~unexpected<E>();
3387
      construct(rhs.get());
3388
    } else {
3389
      assign_common(rhs);
3390
    }
3391
  }
3392
3393
  void assign(expected_operations_base&& rhs) noexcept {
3394
    if (!this->m_has_val && rhs.m_has_val) {
3395
      geterr().~unexpected<E>();
3396
      construct(std::move(rhs).get());
3397
    } else {
3398
      assign_common(std::move(rhs));
3399
    }
3400
  }
3401
3402
#endif
3403
3404
  // The common part of move/copy assigning
3405
  template <class Rhs>
3406
  void assign_common(Rhs&& rhs) {
3407
    if (this->m_has_val) {
3408
      if (rhs.m_has_val) {
3409
        get() = std::forward<Rhs>(rhs).get();
3410
      } else {
3411
        destroy_val();
3412
        construct_error(std::forward<Rhs>(rhs).geterr());
3413
      }
3414
    } else {
3415
      if (!rhs.m_has_val) {
3416
        geterr() = std::forward<Rhs>(rhs).geterr();
3417
      }
3418
    }
3419
  }
3420
3421
0
  bool has_value() const { return this->m_has_val; }
Unexecuted instantiation: tl::detail::expected_operations_base<ada::url_aggregator, ada::errors>::has_value() const
Unexecuted instantiation: tl::detail::expected_operations_base<ada::url_pattern_list_detail::compiled_routes, ada::errors>::has_value() const
3422
3423
  TL_EXPECTED_11_CONSTEXPR T& get() & { return this->m_val; }
3424
0
  constexpr const T& get() const& { return this->m_val; }
3425
0
  TL_EXPECTED_11_CONSTEXPR T&& get() && { return std::move(this->m_val); }
3426
#ifndef TL_EXPECTED_NO_CONSTRR
3427
  constexpr const T&& get() const&& { return std::move(this->m_val); }
3428
#endif
3429
3430
0
  TL_EXPECTED_11_CONSTEXPR unexpected<E>& geterr() & {
3431
0
    return this->m_unexpect;
3432
0
  }
3433
0
  constexpr const unexpected<E>& geterr() const& { return this->m_unexpect; }
3434
  TL_EXPECTED_11_CONSTEXPR unexpected<E>&& geterr() && {
3435
    return std::move(this->m_unexpect);
3436
  }
3437
#ifndef TL_EXPECTED_NO_CONSTRR
3438
  constexpr const unexpected<E>&& geterr() const&& {
3439
    return std::move(this->m_unexpect);
3440
  }
3441
#endif
3442
3443
  TL_EXPECTED_11_CONSTEXPR void destroy_val() { get().~T(); }
3444
};
3445
3446
// This base class provides some handy member functions which can be used in
3447
// further derived classes
3448
template <class E>
3449
struct expected_operations_base<void, E> : expected_storage_base<void, E> {
3450
  using expected_storage_base<void, E>::expected_storage_base;
3451
3452
  template <class... Args>
3453
  void construct() noexcept {
3454
    this->m_has_val = true;
3455
  }
3456
3457
  // This function doesn't use its argument, but needs it so that code in
3458
  // levels above this can work independently of whether T is void
3459
  template <class Rhs>
3460
  void construct_with(Rhs&&) noexcept {
3461
    this->m_has_val = true;
3462
  }
3463
3464
  template <class... Args>
3465
  void construct_error(Args&&... args) noexcept {
3466
    new (std::addressof(this->m_unexpect))
3467
        unexpected<E>(std::forward<Args>(args)...);
3468
    this->m_has_val = false;
3469
  }
3470
3471
  template <class Rhs>
3472
  void assign(Rhs&& rhs) noexcept {
3473
    if (!this->m_has_val) {
3474
      if (rhs.m_has_val) {
3475
        geterr().~unexpected<E>();
3476
        construct();
3477
      } else {
3478
        geterr() = std::forward<Rhs>(rhs).geterr();
3479
      }
3480
    } else {
3481
      if (!rhs.m_has_val) {
3482
        construct_error(std::forward<Rhs>(rhs).geterr());
3483
      }
3484
    }
3485
  }
3486
3487
  bool has_value() const { return this->m_has_val; }
3488
3489
  TL_EXPECTED_11_CONSTEXPR unexpected<E>& geterr() & {
3490
    return this->m_unexpect;
3491
  }
3492
  constexpr const unexpected<E>& geterr() const& { return this->m_unexpect; }
3493
  TL_EXPECTED_11_CONSTEXPR unexpected<E>&& geterr() && {
3494
    return std::move(this->m_unexpect);
3495
  }
3496
#ifndef TL_EXPECTED_NO_CONSTRR
3497
  constexpr const unexpected<E>&& geterr() const&& {
3498
    return std::move(this->m_unexpect);
3499
  }
3500
#endif
3501
3502
  TL_EXPECTED_11_CONSTEXPR void destroy_val() {
3503
    // no-op
3504
  }
3505
};
3506
3507
// This class manages conditionally having a trivial copy constructor
3508
// This specialization is for when T and E are trivially copy constructible
3509
template <class T, class E,
3510
          bool = is_void_or<T, TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(
3511
                                   T)>::value &&
3512
                 TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(E)::value>
3513
struct expected_copy_base : expected_operations_base<T, E> {
3514
  using expected_operations_base<T, E>::expected_operations_base;
3515
};
3516
3517
// This specialization is for when T or E are not trivially copy constructible
3518
template <class T, class E>
3519
struct expected_copy_base<T, E, false> : expected_operations_base<T, E> {
3520
  using expected_operations_base<T, E>::expected_operations_base;
3521
3522
  expected_copy_base() = default;
3523
  expected_copy_base(const expected_copy_base& rhs)
3524
0
      : expected_operations_base<T, E>(no_init) {
3525
0
    if (rhs.has_value()) {
3526
0
      this->construct_with(rhs);
3527
0
    } else {
3528
0
      this->construct_error(rhs.geterr());
3529
0
    }
3530
0
  }
3531
3532
  expected_copy_base(expected_copy_base&& rhs) = default;
3533
  expected_copy_base& operator=(const expected_copy_base& rhs) = default;
3534
  expected_copy_base& operator=(expected_copy_base&& rhs) = default;
3535
};
3536
3537
// This class manages conditionally having a trivial move constructor
3538
// Unfortunately there's no way to achieve this in GCC < 5 AFAIK, since it
3539
// doesn't implement an analogue to std::is_trivially_move_constructible. We
3540
// have to make do with a non-trivial move constructor even if T is trivially
3541
// move constructible
3542
#ifndef TL_EXPECTED_GCC49
3543
template <class T, class E,
3544
          bool =
3545
              is_void_or<T, std::is_trivially_move_constructible<T>>::value &&
3546
              std::is_trivially_move_constructible<E>::value>
3547
struct expected_move_base : expected_copy_base<T, E> {
3548
  using expected_copy_base<T, E>::expected_copy_base;
3549
};
3550
#else
3551
template <class T, class E, bool = false>
3552
struct expected_move_base;
3553
#endif
3554
template <class T, class E>
3555
struct expected_move_base<T, E, false> : expected_copy_base<T, E> {
3556
  using expected_copy_base<T, E>::expected_copy_base;
3557
3558
  expected_move_base() = default;
3559
0
  expected_move_base(const expected_move_base& rhs) = default;
3560
3561
  expected_move_base(expected_move_base&& rhs) noexcept(
3562
      std::is_nothrow_move_constructible<T>::value)
3563
      : expected_copy_base<T, E>(no_init) {
3564
    if (rhs.has_value()) {
3565
      this->construct_with(std::move(rhs));
3566
    } else {
3567
      this->construct_error(std::move(rhs.geterr()));
3568
    }
3569
  }
3570
  expected_move_base& operator=(const expected_move_base& rhs) = default;
3571
  expected_move_base& operator=(expected_move_base&& rhs) = default;
3572
};
3573
3574
// This class manages conditionally having a trivial copy assignment operator
3575
template <
3576
    class T, class E,
3577
    bool =
3578
        is_void_or<
3579
            T, conjunction<TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T),
3580
                           TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T),
3581
                           TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T)>>::value &&
3582
        TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(E)::value &&
3583
        TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(E)::value &&
3584
        TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(E)::value>
3585
struct expected_copy_assign_base : expected_move_base<T, E> {
3586
  using expected_move_base<T, E>::expected_move_base;
3587
};
3588
3589
template <class T, class E>
3590
struct expected_copy_assign_base<T, E, false> : expected_move_base<T, E> {
3591
  using expected_move_base<T, E>::expected_move_base;
3592
3593
  expected_copy_assign_base() = default;
3594
0
  expected_copy_assign_base(const expected_copy_assign_base& rhs) = default;
3595
3596
  expected_copy_assign_base(expected_copy_assign_base&& rhs) = default;
3597
  expected_copy_assign_base& operator=(const expected_copy_assign_base& rhs) {
3598
    this->assign(rhs);
3599
    return *this;
3600
  }
3601
  expected_copy_assign_base& operator=(expected_copy_assign_base&& rhs) =
3602
      default;
3603
};
3604
3605
// This class manages conditionally having a trivial move assignment operator
3606
// Unfortunately there's no way to achieve this in GCC < 5 AFAIK, since it
3607
// doesn't implement an analogue to std::is_trivially_move_assignable. We have
3608
// to make do with a non-trivial move assignment operator even if T is trivially
3609
// move assignable
3610
#ifndef TL_EXPECTED_GCC49
3611
template <
3612
    class T, class E,
3613
    bool = is_void_or<
3614
               T, conjunction<std::is_trivially_destructible<T>,
3615
                              std::is_trivially_move_constructible<T>,
3616
                              std::is_trivially_move_assignable<T>>>::value &&
3617
           std::is_trivially_destructible<E>::value &&
3618
           std::is_trivially_move_constructible<E>::value &&
3619
           std::is_trivially_move_assignable<E>::value>
3620
struct expected_move_assign_base : expected_copy_assign_base<T, E> {
3621
  using expected_copy_assign_base<T, E>::expected_copy_assign_base;
3622
};
3623
#else
3624
template <class T, class E, bool = false>
3625
struct expected_move_assign_base;
3626
#endif
3627
3628
template <class T, class E>
3629
struct expected_move_assign_base<T, E, false>
3630
    : expected_copy_assign_base<T, E> {
3631
  using expected_copy_assign_base<T, E>::expected_copy_assign_base;
3632
3633
  expected_move_assign_base() = default;
3634
0
  expected_move_assign_base(const expected_move_assign_base& rhs) = default;
3635
3636
  expected_move_assign_base(expected_move_assign_base&& rhs) = default;
3637
3638
  expected_move_assign_base& operator=(const expected_move_assign_base& rhs) =
3639
      default;
3640
3641
  expected_move_assign_base&
3642
  operator=(expected_move_assign_base&& rhs) noexcept(
3643
      std::is_nothrow_move_constructible<T>::value &&
3644
      std::is_nothrow_move_assignable<T>::value) {
3645
    this->assign(std::move(rhs));
3646
    return *this;
3647
  }
3648
};
3649
3650
// expected_delete_ctor_base will conditionally delete copy and move
3651
// constructors depending on whether T is copy/move constructible
3652
template <class T, class E,
3653
          bool EnableCopy = (is_copy_constructible_or_void<T>::value &&
3654
                             std::is_copy_constructible<E>::value),
3655
          bool EnableMove = (is_move_constructible_or_void<T>::value &&
3656
                             std::is_move_constructible<E>::value)>
3657
struct expected_delete_ctor_base {
3658
  expected_delete_ctor_base() = default;
3659
  expected_delete_ctor_base(const expected_delete_ctor_base&) = default;
3660
  expected_delete_ctor_base(expected_delete_ctor_base&&) noexcept = default;
3661
  expected_delete_ctor_base& operator=(const expected_delete_ctor_base&) =
3662
      default;
3663
  expected_delete_ctor_base& operator=(expected_delete_ctor_base&&) noexcept =
3664
      default;
3665
};
3666
3667
template <class T, class E>
3668
struct expected_delete_ctor_base<T, E, true, false> {
3669
  expected_delete_ctor_base() = default;
3670
  expected_delete_ctor_base(const expected_delete_ctor_base&) = default;
3671
  expected_delete_ctor_base(expected_delete_ctor_base&&) noexcept = delete;
3672
  expected_delete_ctor_base& operator=(const expected_delete_ctor_base&) =
3673
      default;
3674
  expected_delete_ctor_base& operator=(expected_delete_ctor_base&&) noexcept =
3675
      default;
3676
};
3677
3678
template <class T, class E>
3679
struct expected_delete_ctor_base<T, E, false, true> {
3680
  expected_delete_ctor_base() = default;
3681
  expected_delete_ctor_base(const expected_delete_ctor_base&) = delete;
3682
  expected_delete_ctor_base(expected_delete_ctor_base&&) noexcept = default;
3683
  expected_delete_ctor_base& operator=(const expected_delete_ctor_base&) =
3684
      default;
3685
  expected_delete_ctor_base& operator=(expected_delete_ctor_base&&) noexcept =
3686
      default;
3687
};
3688
3689
template <class T, class E>
3690
struct expected_delete_ctor_base<T, E, false, false> {
3691
  expected_delete_ctor_base() = default;
3692
  expected_delete_ctor_base(const expected_delete_ctor_base&) = delete;
3693
  expected_delete_ctor_base(expected_delete_ctor_base&&) noexcept = delete;
3694
  expected_delete_ctor_base& operator=(const expected_delete_ctor_base&) =
3695
      default;
3696
  expected_delete_ctor_base& operator=(expected_delete_ctor_base&&) noexcept =
3697
      default;
3698
};
3699
3700
// expected_delete_assign_base will conditionally delete copy and move
3701
// constructors depending on whether T and E are copy/move constructible +
3702
// assignable
3703
template <class T, class E,
3704
          bool EnableCopy = (is_copy_constructible_or_void<T>::value &&
3705
                             std::is_copy_constructible<E>::value &&
3706
                             is_copy_assignable_or_void<T>::value &&
3707
                             std::is_copy_assignable<E>::value),
3708
          bool EnableMove = (is_move_constructible_or_void<T>::value &&
3709
                             std::is_move_constructible<E>::value &&
3710
                             is_move_assignable_or_void<T>::value &&
3711
                             std::is_move_assignable<E>::value)>
3712
struct expected_delete_assign_base {
3713
  expected_delete_assign_base() = default;
3714
  expected_delete_assign_base(const expected_delete_assign_base&) = default;
3715
  expected_delete_assign_base(expected_delete_assign_base&&) noexcept = default;
3716
  expected_delete_assign_base& operator=(const expected_delete_assign_base&) =
3717
      default;
3718
  expected_delete_assign_base& operator=(
3719
      expected_delete_assign_base&&) noexcept = default;
3720
};
3721
3722
template <class T, class E>
3723
struct expected_delete_assign_base<T, E, true, false> {
3724
  expected_delete_assign_base() = default;
3725
  expected_delete_assign_base(const expected_delete_assign_base&) = default;
3726
  expected_delete_assign_base(expected_delete_assign_base&&) noexcept = default;
3727
  expected_delete_assign_base& operator=(const expected_delete_assign_base&) =
3728
      default;
3729
  expected_delete_assign_base& operator=(
3730
      expected_delete_assign_base&&) noexcept = delete;
3731
};
3732
3733
template <class T, class E>
3734
struct expected_delete_assign_base<T, E, false, true> {
3735
  expected_delete_assign_base() = default;
3736
  expected_delete_assign_base(const expected_delete_assign_base&) = default;
3737
  expected_delete_assign_base(expected_delete_assign_base&&) noexcept = default;
3738
  expected_delete_assign_base& operator=(const expected_delete_assign_base&) =
3739
      delete;
3740
  expected_delete_assign_base& operator=(
3741
      expected_delete_assign_base&&) noexcept = default;
3742
};
3743
3744
template <class T, class E>
3745
struct expected_delete_assign_base<T, E, false, false> {
3746
  expected_delete_assign_base() = default;
3747
  expected_delete_assign_base(const expected_delete_assign_base&) = default;
3748
  expected_delete_assign_base(expected_delete_assign_base&&) noexcept = default;
3749
  expected_delete_assign_base& operator=(const expected_delete_assign_base&) =
3750
      delete;
3751
  expected_delete_assign_base& operator=(
3752
      expected_delete_assign_base&&) noexcept = delete;
3753
};
3754
3755
// This is needed to be able to construct the expected_default_ctor_base which
3756
// follows, while still conditionally deleting the default constructor.
3757
struct default_constructor_tag {
3758
  explicit constexpr default_constructor_tag() = default;
3759
};
3760
3761
// expected_default_ctor_base will ensure that expected has a deleted default
3762
// consturctor if T is not default constructible.
3763
// This specialization is for when T is default constructible
3764
template <class T, class E,
3765
          bool Enable =
3766
              std::is_default_constructible<T>::value || std::is_void<T>::value>
3767
struct expected_default_ctor_base {
3768
  constexpr expected_default_ctor_base() noexcept = default;
3769
  constexpr expected_default_ctor_base(
3770
      expected_default_ctor_base const&) noexcept = default;
3771
  constexpr expected_default_ctor_base(expected_default_ctor_base&&) noexcept =
3772
      default;
3773
  expected_default_ctor_base& operator=(
3774
      expected_default_ctor_base const&) noexcept = default;
3775
  expected_default_ctor_base& operator=(expected_default_ctor_base&&) noexcept =
3776
      default;
3777
3778
2.93k
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
Unexecuted instantiation: tl::detail::expected_default_ctor_base<ada::url, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
tl::detail::expected_default_ctor_base<ada::url_aggregator, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
Line
Count
Source
3778
2.93k
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
Unexecuted instantiation: tl::detail::expected_default_ctor_base<ada::url_pattern_init, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
Unexecuted instantiation: tl::detail::expected_default_ctor_base<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
Unexecuted instantiation: tl::detail::expected_default_ctor_base<std::__1::vector<ada::url_pattern_helpers::token, std::__1::allocator<ada::url_pattern_helpers::token> >, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
Unexecuted instantiation: tl::detail::expected_default_ctor_base<ada::url_pattern_list_detail::compiled_routes, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
Unexecuted instantiation: tl::detail::expected_default_ctor_base<ada::url_search_params, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
Unexecuted instantiation: tl::detail::expected_default_ctor_base<std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
Unexecuted instantiation: tl::detail::expected_default_ctor_base<std::__1::vector<ada::url_pattern_part, std::__1::allocator<ada::url_pattern_part> >, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
3779
};
3780
3781
// This specialization is for when T is not default constructible
3782
template <class T, class E>
3783
struct expected_default_ctor_base<T, E, false> {
3784
  constexpr expected_default_ctor_base() noexcept = delete;
3785
  constexpr expected_default_ctor_base(
3786
      expected_default_ctor_base const&) noexcept = default;
3787
  constexpr expected_default_ctor_base(expected_default_ctor_base&&) noexcept =
3788
      default;
3789
  expected_default_ctor_base& operator=(
3790
      expected_default_ctor_base const&) noexcept = default;
3791
  expected_default_ctor_base& operator=(expected_default_ctor_base&&) noexcept =
3792
      default;
3793
3794
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
3795
};
3796
}  // namespace detail
3797
3798
template <class E>
3799
class bad_expected_access : public std::exception {
3800
 public:
3801
0
  explicit bad_expected_access(E e) : m_val(std::move(e)) {}
3802
3803
0
  virtual const char* what() const noexcept override {
3804
0
    return "Bad expected access";
3805
0
  }
3806
3807
  const E& error() const& { return m_val; }
3808
  E& error() & { return m_val; }
3809
  const E&& error() const&& { return std::move(m_val); }
3810
  E&& error() && { return std::move(m_val); }
3811
3812
 private:
3813
  E m_val;
3814
};
3815
3816
/// An `expected<T, E>` object is an object that contains the storage for
3817
/// another object and manages the lifetime of this contained object `T`.
3818
/// Alternatively it could contain the storage for another unexpected object
3819
/// `E`. The contained object may not be initialized after the expected object
3820
/// has been initialized, and may not be destroyed before the expected object
3821
/// has been destroyed. The initialization state of the contained object is
3822
/// tracked by the expected object.
3823
template <class T, class E>
3824
class expected : private detail::expected_move_assign_base<T, E>,
3825
                 private detail::expected_delete_ctor_base<T, E>,
3826
                 private detail::expected_delete_assign_base<T, E>,
3827
                 private detail::expected_default_ctor_base<T, E> {
3828
  static_assert(!std::is_reference<T>::value, "T must not be a reference");
3829
  static_assert(!std::is_same<T, std::remove_cv<in_place_t>::type>::value,
3830
                "T must not be in_place_t");
3831
  static_assert(!std::is_same<T, std::remove_cv<unexpect_t>::type>::value,
3832
                "T must not be unexpect_t");
3833
  static_assert(
3834
      !std::is_same<T, typename std::remove_cv<unexpected<E>>::type>::value,
3835
      "T must not be unexpected<E>");
3836
  static_assert(!std::is_reference<E>::value, "E must not be a reference");
3837
3838
8.79k
  T* valptr() { return std::addressof(this->m_val); }
Unexecuted instantiation: tl::expected<ada::url, ada::errors>::valptr()
tl::expected<ada::url_aggregator, ada::errors>::valptr()
Line
Count
Source
3838
8.79k
  T* valptr() { return std::addressof(this->m_val); }
Unexecuted instantiation: tl::expected<ada::url_pattern_list_detail::compiled_routes, ada::errors>::valptr()
Unexecuted instantiation: tl::expected<ada::url_search_params, ada::errors>::valptr()
Unexecuted instantiation: tl::expected<std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >, ada::errors>::valptr()
Unexecuted instantiation: tl::expected<ada::url_pattern_init, ada::errors>::valptr()
3839
  const T* valptr() const { return std::addressof(this->m_val); }
3840
  unexpected<E>* errptr() { return std::addressof(this->m_unexpect); }
3841
  const unexpected<E>* errptr() const {
3842
    return std::addressof(this->m_unexpect);
3843
  }
3844
3845
  template <class U = T,
3846
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
3847
0
  TL_EXPECTED_11_CONSTEXPR U& val() {
3848
0
    return this->m_val;
3849
0
  }
Unexecuted instantiation: _ZN2tl8expectedIN3ada3urlENS1_6errorsEE3valIS2_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERS8_v
Unexecuted instantiation: _ZN2tl8expectedIN3ada14url_aggregatorENS1_6errorsEE3valIS2_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERS8_v
Unexecuted instantiation: _ZN2tl8expectedINSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEN3ada6errorsEE3valIS7_TnPNS1_9enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSD_v
Unexecuted instantiation: _ZN2tl8expectedINSt3__16vectorIN3ada16url_pattern_partENS1_9allocatorIS4_EEEENS3_6errorsEE3valIS7_TnPNS1_9enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSC_v
Unexecuted instantiation: _ZN2tl8expectedIN3ada17url_search_paramsENS1_6errorsEE3valIS2_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERS8_v
Unexecuted instantiation: _ZN2tl8expectedINSt3__16vectorIN3ada19url_pattern_helpers5tokenENS1_9allocatorIS5_EEEENS3_6errorsEE3valIS8_TnPNS1_9enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSD_v
Unexecuted instantiation: _ZN2tl8expectedIN3ada23url_pattern_list_detail15compiled_routesENS1_6errorsEE3valIS3_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERS9_v
3850
0
  TL_EXPECTED_11_CONSTEXPR unexpected<E>& err() { return this->m_unexpect; }
Unexecuted instantiation: tl::expected<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, ada::errors>::err()
Unexecuted instantiation: tl::expected<std::__1::vector<ada::url_pattern_part, std::__1::allocator<ada::url_pattern_part> >, ada::errors>::err()
Unexecuted instantiation: tl::expected<ada::url_aggregator, ada::errors>::err()
Unexecuted instantiation: tl::expected<std::__1::vector<ada::url_pattern_helpers::token, std::__1::allocator<ada::url_pattern_helpers::token> >, ada::errors>::err()
Unexecuted instantiation: tl::expected<ada::url_pattern_init, ada::errors>::err()
Unexecuted instantiation: tl::expected<ada::url_pattern_list_detail::compiled_routes, ada::errors>::err()
3851
3852
  template <class U = T,
3853
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
3854
  constexpr const U& val() const {
3855
    return this->m_val;
3856
  }
3857
  constexpr const unexpected<E>& err() const { return this->m_unexpect; }
3858
3859
  using impl_base = detail::expected_move_assign_base<T, E>;
3860
  using ctor_base = detail::expected_default_ctor_base<T, E>;
3861
3862
 public:
3863
  typedef T value_type;
3864
  typedef E error_type;
3865
  typedef unexpected<E> unexpected_type;
3866
3867
#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \
3868
    !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55)
3869
  template <class F>
3870
  TL_EXPECTED_11_CONSTEXPR auto and_then(F&& f) & {
3871
    return and_then_impl(*this, std::forward<F>(f));
3872
  }
3873
  template <class F>
3874
  TL_EXPECTED_11_CONSTEXPR auto and_then(F&& f) && {
3875
    return and_then_impl(std::move(*this), std::forward<F>(f));
3876
  }
3877
  template <class F>
3878
  constexpr auto and_then(F&& f) const& {
3879
    return and_then_impl(*this, std::forward<F>(f));
3880
  }
3881
3882
#ifndef TL_EXPECTED_NO_CONSTRR
3883
  template <class F>
3884
  constexpr auto and_then(F&& f) const&& {
3885
    return and_then_impl(std::move(*this), std::forward<F>(f));
3886
  }
3887
#endif
3888
3889
#else
3890
  template <class F>
3891
  TL_EXPECTED_11_CONSTEXPR auto and_then(F&& f) & -> decltype(and_then_impl(
3892
      std::declval<expected&>(), std::forward<F>(f))) {
3893
    return and_then_impl(*this, std::forward<F>(f));
3894
  }
3895
  template <class F>
3896
  TL_EXPECTED_11_CONSTEXPR auto and_then(F&& f) && -> decltype(and_then_impl(
3897
      std::declval<expected&&>(), std::forward<F>(f))) {
3898
    return and_then_impl(std::move(*this), std::forward<F>(f));
3899
  }
3900
  template <class F>
3901
  constexpr auto and_then(F&& f) const& -> decltype(and_then_impl(
3902
      std::declval<expected const&>(), std::forward<F>(f))) {
3903
    return and_then_impl(*this, std::forward<F>(f));
3904
  }
3905
3906
#ifndef TL_EXPECTED_NO_CONSTRR
3907
  template <class F>
3908
  constexpr auto and_then(F&& f) const&& -> decltype(and_then_impl(
3909
      std::declval<expected const&&>(), std::forward<F>(f))) {
3910
    return and_then_impl(std::move(*this), std::forward<F>(f));
3911
  }
3912
#endif
3913
#endif
3914
3915
#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \
3916
    !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55)
3917
  template <class F>
3918
  TL_EXPECTED_11_CONSTEXPR auto map(F&& f) & {
3919
    return expected_map_impl(*this, std::forward<F>(f));
3920
  }
3921
  template <class F>
3922
  TL_EXPECTED_11_CONSTEXPR auto map(F&& f) && {
3923
    return expected_map_impl(std::move(*this), std::forward<F>(f));
3924
  }
3925
  template <class F>
3926
  constexpr auto map(F&& f) const& {
3927
    return expected_map_impl(*this, std::forward<F>(f));
3928
  }
3929
  template <class F>
3930
  constexpr auto map(F&& f) const&& {
3931
    return expected_map_impl(std::move(*this), std::forward<F>(f));
3932
  }
3933
#else
3934
  template <class F>
3935
  TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl(
3936
      std::declval<expected&>(), std::declval<F&&>())) map(F&& f) & {
3937
    return expected_map_impl(*this, std::forward<F>(f));
3938
  }
3939
  template <class F>
3940
  TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl(std::declval<expected>(),
3941
                                                      std::declval<F&&>()))
3942
  map(F&& f) && {
3943
    return expected_map_impl(std::move(*this), std::forward<F>(f));
3944
  }
3945
  template <class F>
3946
  constexpr decltype(expected_map_impl(std::declval<const expected&>(),
3947
                                       std::declval<F&&>()))
3948
  map(F&& f) const& {
3949
    return expected_map_impl(*this, std::forward<F>(f));
3950
  }
3951
3952
#ifndef TL_EXPECTED_NO_CONSTRR
3953
  template <class F>
3954
  constexpr decltype(expected_map_impl(std::declval<const expected&&>(),
3955
                                       std::declval<F&&>())) map(F&& f)
3956
      const&& {
3957
    return expected_map_impl(std::move(*this), std::forward<F>(f));
3958
  }
3959
#endif
3960
#endif
3961
3962
#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \
3963
    !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55)
3964
  template <class F>
3965
  TL_EXPECTED_11_CONSTEXPR auto transform(F&& f) & {
3966
    return expected_map_impl(*this, std::forward<F>(f));
3967
  }
3968
  template <class F>
3969
  TL_EXPECTED_11_CONSTEXPR auto transform(F&& f) && {
3970
    return expected_map_impl(std::move(*this), std::forward<F>(f));
3971
  }
3972
  template <class F>
3973
  constexpr auto transform(F&& f) const& {
3974
    return expected_map_impl(*this, std::forward<F>(f));
3975
  }
3976
  template <class F>
3977
  constexpr auto transform(F&& f) const&& {
3978
    return expected_map_impl(std::move(*this), std::forward<F>(f));
3979
  }
3980
#else
3981
  template <class F>
3982
  TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl(
3983
      std::declval<expected&>(), std::declval<F&&>())) transform(F&& f) & {
3984
    return expected_map_impl(*this, std::forward<F>(f));
3985
  }
3986
  template <class F>
3987
  TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl(std::declval<expected>(),
3988
                                                      std::declval<F&&>()))
3989
  transform(F&& f) && {
3990
    return expected_map_impl(std::move(*this), std::forward<F>(f));
3991
  }
3992
  template <class F>
3993
  constexpr decltype(expected_map_impl(std::declval<const expected&>(),
3994
                                       std::declval<F&&>()))
3995
  transform(F&& f) const& {
3996
    return expected_map_impl(*this, std::forward<F>(f));
3997
  }
3998
3999
#ifndef TL_EXPECTED_NO_CONSTRR
4000
  template <class F>
4001
  constexpr decltype(expected_map_impl(std::declval<const expected&&>(),
4002
                                       std::declval<F&&>())) transform(F&& f)
4003
      const&& {
4004
    return expected_map_impl(std::move(*this), std::forward<F>(f));
4005
  }
4006
#endif
4007
#endif
4008
4009
#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \
4010
    !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55)
4011
  template <class F>
4012
  TL_EXPECTED_11_CONSTEXPR auto map_error(F&& f) & {
4013
    return map_error_impl(*this, std::forward<F>(f));
4014
  }
4015
  template <class F>
4016
  TL_EXPECTED_11_CONSTEXPR auto map_error(F&& f) && {
4017
    return map_error_impl(std::move(*this), std::forward<F>(f));
4018
  }
4019
  template <class F>
4020
  constexpr auto map_error(F&& f) const& {
4021
    return map_error_impl(*this, std::forward<F>(f));
4022
  }
4023
  template <class F>
4024
  constexpr auto map_error(F&& f) const&& {
4025
    return map_error_impl(std::move(*this), std::forward<F>(f));
4026
  }
4027
#else
4028
  template <class F>
4029
  TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(
4030
      std::declval<expected&>(), std::declval<F&&>())) map_error(F&& f) & {
4031
    return map_error_impl(*this, std::forward<F>(f));
4032
  }
4033
  template <class F>
4034
  TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(std::declval<expected&&>(),
4035
                                                   std::declval<F&&>()))
4036
  map_error(F&& f) && {
4037
    return map_error_impl(std::move(*this), std::forward<F>(f));
4038
  }
4039
  template <class F>
4040
  constexpr decltype(map_error_impl(std::declval<const expected&>(),
4041
                                    std::declval<F&&>()))
4042
  map_error(F&& f) const& {
4043
    return map_error_impl(*this, std::forward<F>(f));
4044
  }
4045
4046
#ifndef TL_EXPECTED_NO_CONSTRR
4047
  template <class F>
4048
  constexpr decltype(map_error_impl(std::declval<const expected&&>(),
4049
                                    std::declval<F&&>())) map_error(F&& f)
4050
      const&& {
4051
    return map_error_impl(std::move(*this), std::forward<F>(f));
4052
  }
4053
#endif
4054
#endif
4055
#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \
4056
    !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55)
4057
  template <class F>
4058
  TL_EXPECTED_11_CONSTEXPR auto transform_error(F&& f) & {
4059
    return map_error_impl(*this, std::forward<F>(f));
4060
  }
4061
  template <class F>
4062
  TL_EXPECTED_11_CONSTEXPR auto transform_error(F&& f) && {
4063
    return map_error_impl(std::move(*this), std::forward<F>(f));
4064
  }
4065
  template <class F>
4066
  constexpr auto transform_error(F&& f) const& {
4067
    return map_error_impl(*this, std::forward<F>(f));
4068
  }
4069
  template <class F>
4070
  constexpr auto transform_error(F&& f) const&& {
4071
    return map_error_impl(std::move(*this), std::forward<F>(f));
4072
  }
4073
#else
4074
  template <class F>
4075
  TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(
4076
      std::declval<expected&>(),
4077
      std::declval<F&&>())) transform_error(F&& f) & {
4078
    return map_error_impl(*this, std::forward<F>(f));
4079
  }
4080
  template <class F>
4081
  TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(std::declval<expected&&>(),
4082
                                                   std::declval<F&&>()))
4083
  transform_error(F&& f) && {
4084
    return map_error_impl(std::move(*this), std::forward<F>(f));
4085
  }
4086
  template <class F>
4087
  constexpr decltype(map_error_impl(std::declval<const expected&>(),
4088
                                    std::declval<F&&>()))
4089
  transform_error(F&& f) const& {
4090
    return map_error_impl(*this, std::forward<F>(f));
4091
  }
4092
4093
#ifndef TL_EXPECTED_NO_CONSTRR
4094
  template <class F>
4095
  constexpr decltype(map_error_impl(std::declval<const expected&&>(),
4096
                                    std::declval<F&&>())) transform_error(F&& f)
4097
      const&& {
4098
    return map_error_impl(std::move(*this), std::forward<F>(f));
4099
  }
4100
#endif
4101
#endif
4102
  template <class F>
4103
  expected TL_EXPECTED_11_CONSTEXPR or_else(F&& f) & {
4104
    return or_else_impl(*this, std::forward<F>(f));
4105
  }
4106
4107
  template <class F>
4108
  expected TL_EXPECTED_11_CONSTEXPR or_else(F&& f) && {
4109
    return or_else_impl(std::move(*this), std::forward<F>(f));
4110
  }
4111
4112
  template <class F>
4113
  expected constexpr or_else(F&& f) const& {
4114
    return or_else_impl(*this, std::forward<F>(f));
4115
  }
4116
4117
#ifndef TL_EXPECTED_NO_CONSTRR
4118
  template <class F>
4119
  expected constexpr or_else(F&& f) const&& {
4120
    return or_else_impl(std::move(*this), std::forward<F>(f));
4121
  }
4122
#endif
4123
  constexpr expected() = default;
4124
0
  constexpr expected(const expected& rhs) = default;
4125
  constexpr expected(expected&& rhs) = default;
4126
  expected& operator=(const expected& rhs) = default;
4127
  expected& operator=(expected&& rhs) = default;
4128
4129
  template <class... Args,
4130
            detail::enable_if_t<std::is_constructible<T, Args&&...>::value>* =
4131
                nullptr>
4132
  constexpr expected(in_place_t, Args&&... args)
4133
2.93k
      : impl_base(in_place, std::forward<Args>(args)...),
4134
2.93k
        ctor_base(detail::default_constructor_tag{}) {}
Unexecuted instantiation: _ZN2tl8expectedIN3ada3urlENS1_6errorsEEC2IJS2_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS2_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESA_
_ZN2tl8expectedIN3ada14url_aggregatorENS1_6errorsEEC2IJS2_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS2_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESA_
Line
Count
Source
4133
2.93k
      : impl_base(in_place, std::forward<Args>(args)...),
4134
2.93k
        ctor_base(detail::default_constructor_tag{}) {}
Unexecuted instantiation: _ZN2tl8expectedIN3ada16url_pattern_initENS1_6errorsEEC2IJS2_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS2_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESA_
Unexecuted instantiation: _ZN2tl8expectedINSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEN3ada6errorsEEC2IJS7_ETnPNS1_9enable_ifIXsr3std16is_constructibleIS7_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESF_
Unexecuted instantiation: _ZN2tl8expectedINSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEN3ada6errorsEEC2IJRA1_KcETnPNS1_9enable_ifIXsr3std16is_constructibleIS7_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESI_
Unexecuted instantiation: _ZN2tl8expectedINSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEN3ada6errorsEEC2IJRA2_KcETnPNS1_9enable_ifIXsr3std16is_constructibleIS7_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESI_
Unexecuted instantiation: _ZN2tl8expectedINSt3__16vectorIN3ada19url_pattern_helpers5tokenENS1_9allocatorIS5_EEEENS3_6errorsEEC2IJRS8_ETnPNS1_9enable_ifIXsr3std16is_constructibleIS8_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESG_
Unexecuted instantiation: _ZN2tl8expectedIN3ada23url_pattern_list_detail15compiled_routesENS1_6errorsEEC2IJS3_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS3_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESB_
Unexecuted instantiation: _ZN2tl8expectedIN3ada17url_search_paramsENS1_6errorsEEC2IJS2_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS2_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESA_
Unexecuted instantiation: _ZN2tl8expectedINSt3__16vectorINS1_12basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEENS6_IS8_EEEEN3ada6errorsEEC2IJSA_ETnPNS1_9enable_ifIXsr3std16is_constructibleISA_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESI_
Unexecuted instantiation: _ZN2tl8expectedINSt3__16vectorIN3ada16url_pattern_partENS1_9allocatorIS4_EEEENS3_6errorsEEC2IJRS7_ETnPNS1_9enable_ifIXsr3std16is_constructibleIS7_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESF_
4135
4136
  template <class U, class... Args,
4137
            detail::enable_if_t<std::is_constructible<
4138
                T, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
4139
  constexpr expected(in_place_t, std::initializer_list<U> il, Args&&... args)
4140
      : impl_base(in_place, il, std::forward<Args>(args)...),
4141
        ctor_base(detail::default_constructor_tag{}) {}
4142
4143
  template <
4144
      class G = E,
4145
      detail::enable_if_t<std::is_constructible<E, const G&>::value>* = nullptr,
4146
      detail::enable_if_t<!std::is_convertible<const G&, E>::value>* = nullptr>
4147
  explicit constexpr expected(const unexpected<G>& e)
4148
      : impl_base(unexpect, e.value()),
4149
        ctor_base(detail::default_constructor_tag{}) {}
4150
4151
  template <
4152
      class G = E,
4153
      detail::enable_if_t<std::is_constructible<E, const G&>::value>* = nullptr,
4154
      detail::enable_if_t<std::is_convertible<const G&, E>::value>* = nullptr>
4155
  constexpr expected(unexpected<G> const& e)
4156
      : impl_base(unexpect, e.value()),
4157
        ctor_base(detail::default_constructor_tag{}) {}
4158
4159
  template <
4160
      class G = E,
4161
      detail::enable_if_t<std::is_constructible<E, G&&>::value>* = nullptr,
4162
      detail::enable_if_t<!std::is_convertible<G&&, E>::value>* = nullptr>
4163
  explicit constexpr expected(unexpected<G>&& e) noexcept(
4164
      std::is_nothrow_constructible<E, G&&>::value)
4165
      : impl_base(unexpect, std::move(e.value())),
4166
        ctor_base(detail::default_constructor_tag{}) {}
4167
4168
  template <
4169
      class G = E,
4170
      detail::enable_if_t<std::is_constructible<E, G&&>::value>* = nullptr,
4171
      detail::enable_if_t<std::is_convertible<G&&, E>::value>* = nullptr>
4172
  constexpr expected(unexpected<G>&& e) noexcept(
4173
      std::is_nothrow_constructible<E, G&&>::value)
4174
0
      : impl_base(unexpect, std::move(e.value())),
4175
0
        ctor_base(detail::default_constructor_tag{}) {}
Unexecuted instantiation: _ZN2tl8expectedIN3ada3urlENS1_6errorsEEC2IS3_TnPNSt3__19enable_ifIXsr3std16is_constructibleIS3_OT_EE5valueEvE4typeELPv0ETnPNS7_IXsr3std14is_convertibleIS9_S3_EE5valueEvE4typeELSD_0EEEONS_10unexpectedIS8_EE
Unexecuted instantiation: _ZN2tl8expectedIN3ada14url_aggregatorENS1_6errorsEEC2IS3_TnPNSt3__19enable_ifIXsr3std16is_constructibleIS3_OT_EE5valueEvE4typeELPv0ETnPNS7_IXsr3std14is_convertibleIS9_S3_EE5valueEvE4typeELSD_0EEEONS_10unexpectedIS8_EE
Unexecuted instantiation: _ZN2tl8expectedIN3ada16url_pattern_initENS1_6errorsEEC2IS3_TnPNSt3__19enable_ifIXsr3std16is_constructibleIS3_OT_EE5valueEvE4typeELPv0ETnPNS7_IXsr3std14is_convertibleIS9_S3_EE5valueEvE4typeELSD_0EEEONS_10unexpectedIS8_EE
Unexecuted instantiation: _ZN2tl8expectedINSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEN3ada6errorsEEC2IS9_TnPNS1_9enable_ifIXsr3std16is_constructibleIS9_OT_EE5valueEvE4typeELPv0ETnPNSC_IXsr3std14is_convertibleISE_S9_EE5valueEvE4typeELSI_0EEEONS_10unexpectedISD_EE
Unexecuted instantiation: _ZN2tl8expectedINSt3__16vectorIN3ada19url_pattern_helpers5tokenENS1_9allocatorIS5_EEEENS3_6errorsEEC2IS9_TnPNS1_9enable_ifIXsr3std16is_constructibleIS9_OT_EE5valueEvE4typeELPv0ETnPNSC_IXsr3std14is_convertibleISE_S9_EE5valueEvE4typeELSI_0EEEONS_10unexpectedISD_EE
Unexecuted instantiation: _ZN2tl8expectedIN3ada23url_pattern_list_detail15compiled_routesENS1_6errorsEEC2IS4_TnPNSt3__19enable_ifIXsr3std16is_constructibleIS4_OT_EE5valueEvE4typeELPv0ETnPNS8_IXsr3std14is_convertibleISA_S4_EE5valueEvE4typeELSE_0EEEONS_10unexpectedIS9_EE
Unexecuted instantiation: _ZN2tl8expectedINSt3__16vectorIN3ada16url_pattern_partENS1_9allocatorIS4_EEEENS3_6errorsEEC2IS8_TnPNS1_9enable_ifIXsr3std16is_constructibleIS8_OT_EE5valueEvE4typeELPv0ETnPNSB_IXsr3std14is_convertibleISD_S8_EE5valueEvE4typeELSH_0EEEONS_10unexpectedISC_EE
4176
4177
  template <class... Args,
4178
            detail::enable_if_t<std::is_constructible<E, Args&&...>::value>* =
4179
                nullptr>
4180
  constexpr explicit expected(unexpect_t, Args&&... args)
4181
      : impl_base(unexpect, std::forward<Args>(args)...),
4182
        ctor_base(detail::default_constructor_tag{}) {}
4183
4184
  template <class U, class... Args,
4185
            detail::enable_if_t<std::is_constructible<
4186
                E, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
4187
  constexpr explicit expected(unexpect_t, std::initializer_list<U> il,
4188
                              Args&&... args)
4189
      : impl_base(unexpect, il, std::forward<Args>(args)...),
4190
        ctor_base(detail::default_constructor_tag{}) {}
4191
4192
  template <class U, class G,
4193
            detail::enable_if_t<!(std::is_convertible<U const&, T>::value &&
4194
                                  std::is_convertible<G const&, E>::value)>* =
4195
                nullptr,
4196
            detail::expected_enable_from_other<T, E, U, G, const U&,
4197
                                               const G&>* = nullptr>
4198
  explicit TL_EXPECTED_11_CONSTEXPR expected(const expected<U, G>& rhs)
4199
      : ctor_base(detail::default_constructor_tag{}) {
4200
    if (rhs.has_value()) {
4201
      this->construct(*rhs);
4202
    } else {
4203
      this->construct_error(rhs.error());
4204
    }
4205
  }
4206
4207
  template <
4208
      class U, class G,
4209
      detail::enable_if_t<(std::is_convertible<U const&, T>::value &&
4210
                           std::is_convertible<G const&, E>::value)>* = nullptr,
4211
      detail::expected_enable_from_other<T, E, U, G, const U&, const G&>* =
4212
          nullptr>
4213
  TL_EXPECTED_11_CONSTEXPR expected(const expected<U, G>& rhs)
4214
      : ctor_base(detail::default_constructor_tag{}) {
4215
    if (rhs.has_value()) {
4216
      this->construct(*rhs);
4217
    } else {
4218
      this->construct_error(rhs.error());
4219
    }
4220
  }
4221
4222
  template <
4223
      class U, class G,
4224
      detail::enable_if_t<!(std::is_convertible<U&&, T>::value &&
4225
                            std::is_convertible<G&&, E>::value)>* = nullptr,
4226
      detail::expected_enable_from_other<T, E, U, G, U&&, G&&>* = nullptr>
4227
  explicit TL_EXPECTED_11_CONSTEXPR expected(expected<U, G>&& rhs)
4228
      : ctor_base(detail::default_constructor_tag{}) {
4229
    if (rhs.has_value()) {
4230
      this->construct(std::move(*rhs));
4231
    } else {
4232
      this->construct_error(std::move(rhs.error()));
4233
    }
4234
  }
4235
4236
  template <
4237
      class U, class G,
4238
      detail::enable_if_t<(std::is_convertible<U&&, T>::value &&
4239
                           std::is_convertible<G&&, E>::value)>* = nullptr,
4240
      detail::expected_enable_from_other<T, E, U, G, U&&, G&&>* = nullptr>
4241
  TL_EXPECTED_11_CONSTEXPR expected(expected<U, G>&& rhs)
4242
      : ctor_base(detail::default_constructor_tag{}) {
4243
    if (rhs.has_value()) {
4244
      this->construct(std::move(*rhs));
4245
    } else {
4246
      this->construct_error(std::move(rhs.error()));
4247
    }
4248
  }
4249
4250
  template <class U = T,
4251
            detail::enable_if_t<!std::is_convertible<U&&, T>::value>* = nullptr,
4252
            detail::expected_enable_forward_value<T, E, U>* = nullptr>
4253
  explicit TL_EXPECTED_MSVC2015_CONSTEXPR expected(U&& v)
4254
      : expected(in_place, std::forward<U>(v)) {}
4255
4256
  template <class U = T,
4257
            detail::enable_if_t<std::is_convertible<U&&, T>::value>* = nullptr,
4258
            detail::expected_enable_forward_value<T, E, U>* = nullptr>
4259
  TL_EXPECTED_MSVC2015_CONSTEXPR expected(U&& v)
4260
2.93k
      : expected(in_place, std::forward<U>(v)) {}
Unexecuted instantiation: _ZN2tl8expectedIN3ada3urlENS1_6errorsEEC2IS2_TnPNSt3__19enable_ifIXsr3std14is_convertibleIOT_S2_EE5valueEvE4typeELPv0ETnPNS7_IXaaaaaasr3std16is_constructibleIS2_S9_EE5valuentsr3std7is_sameINS6_5decayIS8_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameIS4_SG_EE5valuentsr3std7is_sameINS_10unexpectedIS3_EESG_EE5valueEvE4typeELSD_0EEES9_
_ZN2tl8expectedIN3ada14url_aggregatorENS1_6errorsEEC2IS2_TnPNSt3__19enable_ifIXsr3std14is_convertibleIOT_S2_EE5valueEvE4typeELPv0ETnPNS7_IXaaaaaasr3std16is_constructibleIS2_S9_EE5valuentsr3std7is_sameINS6_5decayIS8_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameIS4_SG_EE5valuentsr3std7is_sameINS_10unexpectedIS3_EESG_EE5valueEvE4typeELSD_0EEES9_
Line
Count
Source
4260
2.93k
      : expected(in_place, std::forward<U>(v)) {}
Unexecuted instantiation: _ZN2tl8expectedIN3ada16url_pattern_initENS1_6errorsEEC2IS2_TnPNSt3__19enable_ifIXsr3std14is_convertibleIOT_S2_EE5valueEvE4typeELPv0ETnPNS7_IXaaaaaasr3std16is_constructibleIS2_S9_EE5valuentsr3std7is_sameINS6_5decayIS8_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameIS4_SG_EE5valuentsr3std7is_sameINS_10unexpectedIS3_EESG_EE5valueEvE4typeELSD_0EEES9_
Unexecuted instantiation: _ZN2tl8expectedINSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEN3ada6errorsEEC2IS7_TnPNS1_9enable_ifIXsr3std14is_convertibleIOT_S7_EE5valueEvE4typeELPv0ETnPNSC_IXaaaaaasr3std16is_constructibleIS7_SE_EE5valuentsr3std7is_sameINS1_5decayISD_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameISA_SL_EE5valuentsr3std7is_sameINS_10unexpectedIS9_EESL_EE5valueEvE4typeELSI_0EEESE_
Unexecuted instantiation: _ZN2tl8expectedINSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEN3ada6errorsEEC2IRA1_KcTnPNS1_9enable_ifIXsr3std14is_convertibleIOT_S7_EE5valueEvE4typeELPv0ETnPNSF_IXaaaaaasr3std16is_constructibleIS7_SH_EE5valuentsr3std7is_sameINS1_5decayISG_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameISA_SO_EE5valuentsr3std7is_sameINS_10unexpectedIS9_EESO_EE5valueEvE4typeELSL_0EEESH_
Unexecuted instantiation: _ZN2tl8expectedINSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEN3ada6errorsEEC2IRA2_KcTnPNS1_9enable_ifIXsr3std14is_convertibleIOT_S7_EE5valueEvE4typeELPv0ETnPNSF_IXaaaaaasr3std16is_constructibleIS7_SH_EE5valuentsr3std7is_sameINS1_5decayISG_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameISA_SO_EE5valuentsr3std7is_sameINS_10unexpectedIS9_EESO_EE5valueEvE4typeELSL_0EEESH_
Unexecuted instantiation: _ZN2tl8expectedINSt3__16vectorIN3ada19url_pattern_helpers5tokenENS1_9allocatorIS5_EEEENS3_6errorsEEC2IRS8_TnPNS1_9enable_ifIXsr3std14is_convertibleIOT_S8_EE5valueEvE4typeELPv0ETnPNSD_IXaaaaaasr3std16is_constructibleIS8_SF_EE5valuentsr3std7is_sameINS1_5decayISE_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameISA_SM_EE5valuentsr3std7is_sameINS_10unexpectedIS9_EESM_EE5valueEvE4typeELSJ_0EEESF_
Unexecuted instantiation: _ZN2tl8expectedIN3ada23url_pattern_list_detail15compiled_routesENS1_6errorsEEC2IS3_TnPNSt3__19enable_ifIXsr3std14is_convertibleIOT_S3_EE5valueEvE4typeELPv0ETnPNS8_IXaaaaaasr3std16is_constructibleIS3_SA_EE5valuentsr3std7is_sameINS7_5decayIS9_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameIS5_SH_EE5valuentsr3std7is_sameINS_10unexpectedIS4_EESH_EE5valueEvE4typeELSE_0EEESA_
Unexecuted instantiation: _ZN2tl8expectedIN3ada17url_search_paramsENS1_6errorsEEC2IS2_TnPNSt3__19enable_ifIXsr3std14is_convertibleIOT_S2_EE5valueEvE4typeELPv0ETnPNS7_IXaaaaaasr3std16is_constructibleIS2_S9_EE5valuentsr3std7is_sameINS6_5decayIS8_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameIS4_SG_EE5valuentsr3std7is_sameINS_10unexpectedIS3_EESG_EE5valueEvE4typeELSD_0EEES9_
Unexecuted instantiation: _ZN2tl8expectedINSt3__16vectorINS1_12basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEENS6_IS8_EEEEN3ada6errorsEEC2ISA_TnPNS1_9enable_ifIXsr3std14is_convertibleIOT_SA_EE5valueEvE4typeELPv0ETnPNSF_IXaaaaaasr3std16is_constructibleISA_SH_EE5valuentsr3std7is_sameINS1_5decayISG_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameISD_SO_EE5valuentsr3std7is_sameINS_10unexpectedISC_EESO_EE5valueEvE4typeELSL_0EEESH_
Unexecuted instantiation: _ZN2tl8expectedINSt3__16vectorIN3ada16url_pattern_partENS1_9allocatorIS4_EEEENS3_6errorsEEC2IRS7_TnPNS1_9enable_ifIXsr3std14is_convertibleIOT_S7_EE5valueEvE4typeELPv0ETnPNSC_IXaaaaaasr3std16is_constructibleIS7_SE_EE5valuentsr3std7is_sameINS1_5decayISD_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameIS9_SL_EE5valuentsr3std7is_sameINS_10unexpectedIS8_EESL_EE5valueEvE4typeELSI_0EEESE_
4261
4262
  template <
4263
      class U = T, class G = T,
4264
      detail::enable_if_t<std::is_nothrow_constructible<T, U&&>::value>* =
4265
          nullptr,
4266
      detail::enable_if_t<!std::is_void<G>::value>* = nullptr,
4267
      detail::enable_if_t<
4268
          (!std::is_same<expected<T, E>, detail::decay_t<U>>::value &&
4269
           !detail::conjunction<std::is_scalar<T>,
4270
                                std::is_same<T, detail::decay_t<U>>>::value &&
4271
           std::is_constructible<T, U>::value &&
4272
           std::is_assignable<G&, U>::value &&
4273
           std::is_nothrow_move_constructible<E>::value)>* = nullptr>
4274
  expected& operator=(U&& v) {
4275
    if (has_value()) {
4276
      val() = std::forward<U>(v);
4277
    } else {
4278
      err().~unexpected<E>();
4279
      ::new (valptr()) T(std::forward<U>(v));
4280
      this->m_has_val = true;
4281
    }
4282
4283
    return *this;
4284
  }
4285
4286
  template <
4287
      class U = T, class G = T,
4288
      detail::enable_if_t<!std::is_nothrow_constructible<T, U&&>::value>* =
4289
          nullptr,
4290
      detail::enable_if_t<!std::is_void<U>::value>* = nullptr,
4291
      detail::enable_if_t<
4292
          (!std::is_same<expected<T, E>, detail::decay_t<U>>::value &&
4293
           !detail::conjunction<std::is_scalar<T>,
4294
                                std::is_same<T, detail::decay_t<U>>>::value &&
4295
           std::is_constructible<T, U>::value &&
4296
           std::is_assignable<G&, U>::value &&
4297
           std::is_nothrow_move_constructible<E>::value)>* = nullptr>
4298
  expected& operator=(U&& v) {
4299
    if (has_value()) {
4300
      val() = std::forward<U>(v);
4301
    } else {
4302
      auto tmp = std::move(err());
4303
      err().~unexpected<E>();
4304
4305
#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED
4306
      try {
4307
        ::new (valptr()) T(std::forward<U>(v));
4308
        this->m_has_val = true;
4309
      } catch (...) {
4310
        err() = std::move(tmp);
4311
        throw;
4312
      }
4313
#else
4314
      ::new (valptr()) T(std::forward<U>(v));
4315
      this->m_has_val = true;
4316
#endif
4317
    }
4318
4319
    return *this;
4320
  }
4321
4322
  template <class G = E,
4323
            detail::enable_if_t<std::is_nothrow_copy_constructible<G>::value &&
4324
                                std::is_assignable<G&, G>::value>* = nullptr>
4325
  expected& operator=(const unexpected<G>& rhs) {
4326
    if (!has_value()) {
4327
      err() = rhs;
4328
    } else {
4329
      this->destroy_val();
4330
      ::new (errptr()) unexpected<E>(rhs);
4331
      this->m_has_val = false;
4332
    }
4333
4334
    return *this;
4335
  }
4336
4337
  template <class G = E,
4338
            detail::enable_if_t<std::is_nothrow_move_constructible<G>::value &&
4339
                                std::is_move_assignable<G>::value>* = nullptr>
4340
  expected& operator=(unexpected<G>&& rhs) noexcept {
4341
    if (!has_value()) {
4342
      err() = std::move(rhs);
4343
    } else {
4344
      this->destroy_val();
4345
      ::new (errptr()) unexpected<E>(std::move(rhs));
4346
      this->m_has_val = false;
4347
    }
4348
4349
    return *this;
4350
  }
4351
4352
  template <class... Args, detail::enable_if_t<std::is_nothrow_constructible<
4353
                               T, Args&&...>::value>* = nullptr>
4354
  void emplace(Args&&... args) {
4355
    if (has_value()) {
4356
      val().~T();
4357
    } else {
4358
      err().~unexpected<E>();
4359
      this->m_has_val = true;
4360
    }
4361
    ::new (valptr()) T(std::forward<Args>(args)...);
4362
  }
4363
4364
  template <class... Args, detail::enable_if_t<!std::is_nothrow_constructible<
4365
                               T, Args&&...>::value>* = nullptr>
4366
  void emplace(Args&&... args) {
4367
    if (has_value()) {
4368
      val().~T();
4369
      ::new (valptr()) T(std::forward<Args>(args)...);
4370
    } else {
4371
      auto tmp = std::move(err());
4372
      err().~unexpected<E>();
4373
4374
#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED
4375
      try {
4376
        ::new (valptr()) T(std::forward<Args>(args)...);
4377
        this->m_has_val = true;
4378
      } catch (...) {
4379
        err() = std::move(tmp);
4380
        throw;
4381
      }
4382
#else
4383
      ::new (valptr()) T(std::forward<Args>(args)...);
4384
      this->m_has_val = true;
4385
#endif
4386
    }
4387
  }
4388
4389
  template <class U, class... Args,
4390
            detail::enable_if_t<std::is_nothrow_constructible<
4391
                T, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
4392
  void emplace(std::initializer_list<U> il, Args&&... args) {
4393
    if (has_value()) {
4394
      T t(il, std::forward<Args>(args)...);
4395
      val() = std::move(t);
4396
    } else {
4397
      err().~unexpected<E>();
4398
      ::new (valptr()) T(il, std::forward<Args>(args)...);
4399
      this->m_has_val = true;
4400
    }
4401
  }
4402
4403
  template <class U, class... Args,
4404
            detail::enable_if_t<!std::is_nothrow_constructible<
4405
                T, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
4406
  void emplace(std::initializer_list<U> il, Args&&... args) {
4407
    if (has_value()) {
4408
      T t(il, std::forward<Args>(args)...);
4409
      val() = std::move(t);
4410
    } else {
4411
      auto tmp = std::move(err());
4412
      err().~unexpected<E>();
4413
4414
#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED
4415
      try {
4416
        ::new (valptr()) T(il, std::forward<Args>(args)...);
4417
        this->m_has_val = true;
4418
      } catch (...) {
4419
        err() = std::move(tmp);
4420
        throw;
4421
      }
4422
#else
4423
      ::new (valptr()) T(il, std::forward<Args>(args)...);
4424
      this->m_has_val = true;
4425
#endif
4426
    }
4427
  }
4428
4429
 private:
4430
  using t_is_void = std::true_type;
4431
  using t_is_not_void = std::false_type;
4432
  using t_is_nothrow_move_constructible = std::true_type;
4433
  using move_constructing_t_can_throw = std::false_type;
4434
  using e_is_nothrow_move_constructible = std::true_type;
4435
  using move_constructing_e_can_throw = std::false_type;
4436
4437
  void swap_where_both_have_value(expected& /*rhs*/, t_is_void) noexcept {
4438
    // swapping void is a no-op
4439
  }
4440
4441
  void swap_where_both_have_value(expected& rhs, t_is_not_void) {
4442
    using std::swap;
4443
    swap(val(), rhs.val());
4444
  }
4445
4446
  void swap_where_only_one_has_value(expected& rhs, t_is_void) noexcept(
4447
      std::is_nothrow_move_constructible<E>::value) {
4448
    ::new (errptr()) unexpected_type(std::move(rhs.err()));
4449
    rhs.err().~unexpected_type();
4450
    std::swap(this->m_has_val, rhs.m_has_val);
4451
  }
4452
4453
  void swap_where_only_one_has_value(expected& rhs, t_is_not_void) {
4454
    swap_where_only_one_has_value_and_t_is_not_void(
4455
        rhs, typename std::is_nothrow_move_constructible<T>::type{},
4456
        typename std::is_nothrow_move_constructible<E>::type{});
4457
  }
4458
4459
  void swap_where_only_one_has_value_and_t_is_not_void(
4460
      expected& rhs, t_is_nothrow_move_constructible,
4461
      e_is_nothrow_move_constructible) noexcept {
4462
    auto temp = std::move(val());
4463
    val().~T();
4464
    ::new (errptr()) unexpected_type(std::move(rhs.err()));
4465
    rhs.err().~unexpected_type();
4466
    ::new (rhs.valptr()) T(std::move(temp));
4467
    std::swap(this->m_has_val, rhs.m_has_val);
4468
  }
4469
4470
  void swap_where_only_one_has_value_and_t_is_not_void(
4471
      expected& rhs, t_is_nothrow_move_constructible,
4472
      move_constructing_e_can_throw) {
4473
    auto temp = std::move(val());
4474
    val().~T();
4475
#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED
4476
    try {
4477
      ::new (errptr()) unexpected_type(std::move(rhs.err()));
4478
      rhs.err().~unexpected_type();
4479
      ::new (rhs.valptr()) T(std::move(temp));
4480
      std::swap(this->m_has_val, rhs.m_has_val);
4481
    } catch (...) {
4482
      val() = std::move(temp);
4483
      throw;
4484
    }
4485
#else
4486
    ::new (errptr()) unexpected_type(std::move(rhs.err()));
4487
    rhs.err().~unexpected_type();
4488
    ::new (rhs.valptr()) T(std::move(temp));
4489
    std::swap(this->m_has_val, rhs.m_has_val);
4490
#endif
4491
  }
4492
4493
  void swap_where_only_one_has_value_and_t_is_not_void(
4494
      expected& rhs, move_constructing_t_can_throw,
4495
      e_is_nothrow_move_constructible) {
4496
    auto temp = std::move(rhs.err());
4497
    rhs.err().~unexpected_type();
4498
#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED
4499
    try {
4500
      ::new (rhs.valptr()) T(std::move(val()));
4501
      val().~T();
4502
      ::new (errptr()) unexpected_type(std::move(temp));
4503
      std::swap(this->m_has_val, rhs.m_has_val);
4504
    } catch (...) {
4505
      rhs.err() = std::move(temp);
4506
      throw;
4507
    }
4508
#else
4509
    ::new (rhs.valptr()) T(std::move(val()));
4510
    val().~T();
4511
    ::new (errptr()) unexpected_type(std::move(temp));
4512
    std::swap(this->m_has_val, rhs.m_has_val);
4513
#endif
4514
  }
4515
4516
 public:
4517
  template <class OT = T, class OE = E>
4518
  detail::enable_if_t<detail::is_swappable<OT>::value &&
4519
                      detail::is_swappable<OE>::value &&
4520
                      (std::is_nothrow_move_constructible<OT>::value ||
4521
                       std::is_nothrow_move_constructible<OE>::value)>
4522
  swap(expected& rhs) noexcept(std::is_nothrow_move_constructible<T>::value &&
4523
                               detail::is_nothrow_swappable<T>::value &&
4524
                               std::is_nothrow_move_constructible<E>::value &&
4525
                               detail::is_nothrow_swappable<E>::value) {
4526
    if (has_value() && rhs.has_value()) {
4527
      swap_where_both_have_value(rhs, typename std::is_void<T>::type{});
4528
    } else if (!has_value() && rhs.has_value()) {
4529
      rhs.swap(*this);
4530
    } else if (has_value()) {
4531
      swap_where_only_one_has_value(rhs, typename std::is_void<T>::type{});
4532
    } else {
4533
      using std::swap;
4534
      swap(err(), rhs.err());
4535
    }
4536
  }
4537
4538
  constexpr const T* operator->() const {
4539
    TL_ASSERT(has_value());
4540
    return valptr();
4541
  }
4542
8.79k
  TL_EXPECTED_11_CONSTEXPR T* operator->() {
4543
8.79k
    TL_ASSERT(has_value());
4544
8.79k
    return valptr();
4545
8.79k
  }
Unexecuted instantiation: tl::expected<ada::url, ada::errors>::operator->()
tl::expected<ada::url_aggregator, ada::errors>::operator->()
Line
Count
Source
4542
8.79k
  TL_EXPECTED_11_CONSTEXPR T* operator->() {
4543
8.79k
    TL_ASSERT(has_value());
4544
8.79k
    return valptr();
4545
8.79k
  }
Unexecuted instantiation: tl::expected<ada::url_pattern_list_detail::compiled_routes, ada::errors>::operator->()
Unexecuted instantiation: tl::expected<ada::url_search_params, ada::errors>::operator->()
Unexecuted instantiation: tl::expected<std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >, ada::errors>::operator->()
Unexecuted instantiation: tl::expected<ada::url_pattern_init, ada::errors>::operator->()
4546
4547
  template <class U = T,
4548
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
4549
  constexpr const U& operator*() const& {
4550
    TL_ASSERT(has_value());
4551
    return val();
4552
  }
4553
  template <class U = T,
4554
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
4555
0
  TL_EXPECTED_11_CONSTEXPR U& operator*() & {
4556
0
    TL_ASSERT(has_value());
4557
0
    return val();
4558
0
  }
Unexecuted instantiation: _ZNR2tl8expectedIN3ada3urlENS1_6errorsEEdeIS2_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERS8_v
Unexecuted instantiation: _ZNR2tl8expectedIN3ada14url_aggregatorENS1_6errorsEEdeIS2_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERS8_v
Unexecuted instantiation: _ZNR2tl8expectedINSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEN3ada6errorsEEdeIS7_TnPNS1_9enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSD_v
Unexecuted instantiation: _ZNR2tl8expectedINSt3__16vectorIN3ada16url_pattern_partENS1_9allocatorIS4_EEEENS3_6errorsEEdeIS7_TnPNS1_9enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSC_v
Unexecuted instantiation: _ZNR2tl8expectedIN3ada17url_search_paramsENS1_6errorsEEdeIS2_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERS8_v
Unexecuted instantiation: _ZNR2tl8expectedINSt3__16vectorIN3ada19url_pattern_helpers5tokenENS1_9allocatorIS5_EEEENS3_6errorsEEdeIS8_TnPNS1_9enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSD_v
Unexecuted instantiation: _ZNR2tl8expectedIN3ada23url_pattern_list_detail15compiled_routesENS1_6errorsEEdeIS3_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERS9_v
4559
  template <class U = T,
4560
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
4561
  constexpr const U&& operator*() const&& {
4562
    TL_ASSERT(has_value());
4563
    return std::move(val());
4564
  }
4565
  template <class U = T,
4566
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
4567
  TL_EXPECTED_11_CONSTEXPR U&& operator*() && {
4568
    TL_ASSERT(has_value());
4569
    return std::move(val());
4570
  }
4571
4572
8.79k
  constexpr bool has_value() const noexcept { return this->m_has_val; }
Unexecuted instantiation: tl::expected<ada::url, ada::errors>::has_value() const
tl::expected<ada::url_aggregator, ada::errors>::has_value() const
Line
Count
Source
4572
8.79k
  constexpr bool has_value() const noexcept { return this->m_has_val; }
Unexecuted instantiation: tl::expected<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, ada::errors>::has_value() const
Unexecuted instantiation: tl::expected<ada::url_pattern_list_detail::compiled_routes, ada::errors>::has_value() const
Unexecuted instantiation: tl::expected<std::__1::vector<ada::url_pattern_part, std::__1::allocator<ada::url_pattern_part> >, ada::errors>::has_value() const
Unexecuted instantiation: tl::expected<ada::url_search_params, ada::errors>::has_value() const
Unexecuted instantiation: tl::expected<std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >, ada::errors>::has_value() const
Unexecuted instantiation: tl::expected<std::__1::vector<ada::url_pattern_helpers::token, std::__1::allocator<ada::url_pattern_helpers::token> >, ada::errors>::has_value() const
Unexecuted instantiation: tl::expected<ada::url_pattern_init, ada::errors>::has_value() const
4573
2.93k
  constexpr explicit operator bool() const noexcept { return this->m_has_val; }
Unexecuted instantiation: tl::expected<ada::url, ada::errors>::operator bool() const
tl::expected<ada::url_aggregator, ada::errors>::operator bool() const
Line
Count
Source
4573
2.93k
  constexpr explicit operator bool() const noexcept { return this->m_has_val; }
Unexecuted instantiation: tl::expected<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, ada::errors>::operator bool() const
Unexecuted instantiation: tl::expected<ada::url_pattern_list_detail::compiled_routes, ada::errors>::operator bool() const
Unexecuted instantiation: tl::expected<std::__1::vector<ada::url_pattern_part, std::__1::allocator<ada::url_pattern_part> >, ada::errors>::operator bool() const
Unexecuted instantiation: tl::expected<ada::url_search_params, ada::errors>::operator bool() const
Unexecuted instantiation: tl::expected<std::__1::vector<ada::url_pattern_helpers::token, std::__1::allocator<ada::url_pattern_helpers::token> >, ada::errors>::operator bool() const
Unexecuted instantiation: tl::expected<ada::url_pattern_init, ada::errors>::operator bool() const
4574
4575
  template <class U = T,
4576
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
4577
  TL_EXPECTED_11_CONSTEXPR const U& value() const& {
4578
    if (!has_value())
4579
      detail::throw_exception(bad_expected_access<E>(err().value()));
4580
    return val();
4581
  }
4582
  template <class U = T,
4583
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
4584
0
  TL_EXPECTED_11_CONSTEXPR U& value() & {
4585
0
    if (!has_value())
4586
0
      detail::throw_exception(bad_expected_access<E>(err().value()));
4587
0
    return val();
4588
0
  }
4589
  template <class U = T,
4590
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
4591
  TL_EXPECTED_11_CONSTEXPR const U&& value() const&& {
4592
    if (!has_value())
4593
      detail::throw_exception(bad_expected_access<E>(std::move(err()).value()));
4594
    return std::move(val());
4595
  }
4596
  template <class U = T,
4597
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
4598
  TL_EXPECTED_11_CONSTEXPR U&& value() && {
4599
    if (!has_value())
4600
      detail::throw_exception(bad_expected_access<E>(std::move(err()).value()));
4601
    return std::move(val());
4602
  }
4603
4604
  constexpr const E& error() const& {
4605
    TL_ASSERT(!has_value());
4606
    return err().value();
4607
  }
4608
0
  TL_EXPECTED_11_CONSTEXPR E& error() & {
4609
0
    TL_ASSERT(!has_value());
4610
0
    return err().value();
4611
0
  }
Unexecuted instantiation: tl::expected<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, ada::errors>::error() &
Unexecuted instantiation: tl::expected<std::__1::vector<ada::url_pattern_part, std::__1::allocator<ada::url_pattern_part> >, ada::errors>::error() &
Unexecuted instantiation: tl::expected<std::__1::vector<ada::url_pattern_helpers::token, std::__1::allocator<ada::url_pattern_helpers::token> >, ada::errors>::error() &
Unexecuted instantiation: tl::expected<ada::url_pattern_init, ada::errors>::error() &
Unexecuted instantiation: tl::expected<ada::url_pattern_list_detail::compiled_routes, ada::errors>::error() &
4612
  constexpr const E&& error() const&& {
4613
    TL_ASSERT(!has_value());
4614
    return std::move(err().value());
4615
  }
4616
  TL_EXPECTED_11_CONSTEXPR E&& error() && {
4617
    TL_ASSERT(!has_value());
4618
    return std::move(err().value());
4619
  }
4620
4621
  template <class U>
4622
  constexpr T value_or(U&& v) const& {
4623
    static_assert(std::is_copy_constructible<T>::value &&
4624
                      std::is_convertible<U&&, T>::value,
4625
                  "T must be copy-constructible and convertible to from U&&");
4626
    return bool(*this) ? **this : static_cast<T>(std::forward<U>(v));
4627
  }
4628
  template <class U>
4629
  TL_EXPECTED_11_CONSTEXPR T value_or(U&& v) && {
4630
    static_assert(std::is_move_constructible<T>::value &&
4631
                      std::is_convertible<U&&, T>::value,
4632
                  "T must be move-constructible and convertible to from U&&");
4633
    return bool(*this) ? std::move(**this) : static_cast<T>(std::forward<U>(v));
4634
  }
4635
};
4636
4637
namespace detail {
4638
template <class Exp>
4639
using exp_t = typename detail::decay_t<Exp>::value_type;
4640
template <class Exp>
4641
using err_t = typename detail::decay_t<Exp>::error_type;
4642
template <class Exp, class Ret>
4643
using ret_t = expected<Ret, err_t<Exp>>;
4644
4645
#ifdef TL_EXPECTED_CXX14
4646
template <class Exp, class F,
4647
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr,
4648
          class Ret = decltype(detail::invoke(std::declval<F>(),
4649
                                              *std::declval<Exp>()))>
4650
constexpr auto and_then_impl(Exp&& exp, F&& f) {
4651
  static_assert(detail::is_expected<Ret>::value, "F must return an expected");
4652
4653
  return exp.has_value()
4654
             ? detail::invoke(std::forward<F>(f), *std::forward<Exp>(exp))
4655
             : Ret(unexpect, std::forward<Exp>(exp).error());
4656
}
4657
4658
template <class Exp, class F,
4659
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr,
4660
          class Ret = decltype(detail::invoke(std::declval<F>()))>
4661
constexpr auto and_then_impl(Exp&& exp, F&& f) {
4662
  static_assert(detail::is_expected<Ret>::value, "F must return an expected");
4663
4664
  return exp.has_value() ? detail::invoke(std::forward<F>(f))
4665
                         : Ret(unexpect, std::forward<Exp>(exp).error());
4666
}
4667
#else
4668
template <class>
4669
struct TC;
4670
template <class Exp, class F,
4671
          class Ret = decltype(detail::invoke(std::declval<F>(),
4672
                                              *std::declval<Exp>())),
4673
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr>
4674
auto and_then_impl(Exp&& exp, F&& f) -> Ret {
4675
  static_assert(detail::is_expected<Ret>::value, "F must return an expected");
4676
4677
  return exp.has_value()
4678
             ? detail::invoke(std::forward<F>(f), *std::forward<Exp>(exp))
4679
             : Ret(unexpect, std::forward<Exp>(exp).error());
4680
}
4681
4682
template <class Exp, class F,
4683
          class Ret = decltype(detail::invoke(std::declval<F>())),
4684
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr>
4685
constexpr auto and_then_impl(Exp&& exp, F&& f) -> Ret {
4686
  static_assert(detail::is_expected<Ret>::value, "F must return an expected");
4687
4688
  return exp.has_value() ? detail::invoke(std::forward<F>(f))
4689
                         : Ret(unexpect, std::forward<Exp>(exp).error());
4690
}
4691
#endif
4692
4693
#ifdef TL_EXPECTED_CXX14
4694
template <class Exp, class F,
4695
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr,
4696
          class Ret = decltype(detail::invoke(std::declval<F>(),
4697
                                              *std::declval<Exp>())),
4698
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4699
constexpr auto expected_map_impl(Exp&& exp, F&& f) {
4700
  using result = ret_t<Exp, detail::decay_t<Ret>>;
4701
  return exp.has_value() ? result(detail::invoke(std::forward<F>(f),
4702
                                                 *std::forward<Exp>(exp)))
4703
                         : result(unexpect, std::forward<Exp>(exp).error());
4704
}
4705
4706
template <class Exp, class F,
4707
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr,
4708
          class Ret = decltype(detail::invoke(std::declval<F>(),
4709
                                              *std::declval<Exp>())),
4710
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4711
auto expected_map_impl(Exp&& exp, F&& f) {
4712
  using result = expected<void, err_t<Exp>>;
4713
  if (exp.has_value()) {
4714
    detail::invoke(std::forward<F>(f), *std::forward<Exp>(exp));
4715
    return result();
4716
  }
4717
4718
  return result(unexpect, std::forward<Exp>(exp).error());
4719
}
4720
4721
template <class Exp, class F,
4722
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr,
4723
          class Ret = decltype(detail::invoke(std::declval<F>())),
4724
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4725
constexpr auto expected_map_impl(Exp&& exp, F&& f) {
4726
  using result = ret_t<Exp, detail::decay_t<Ret>>;
4727
  return exp.has_value() ? result(detail::invoke(std::forward<F>(f)))
4728
                         : result(unexpect, std::forward<Exp>(exp).error());
4729
}
4730
4731
template <class Exp, class F,
4732
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr,
4733
          class Ret = decltype(detail::invoke(std::declval<F>())),
4734
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4735
auto expected_map_impl(Exp&& exp, F&& f) {
4736
  using result = expected<void, err_t<Exp>>;
4737
  if (exp.has_value()) {
4738
    detail::invoke(std::forward<F>(f));
4739
    return result();
4740
  }
4741
4742
  return result(unexpect, std::forward<Exp>(exp).error());
4743
}
4744
#else
4745
template <class Exp, class F,
4746
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr,
4747
          class Ret = decltype(detail::invoke(std::declval<F>(),
4748
                                              *std::declval<Exp>())),
4749
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4750
4751
constexpr auto expected_map_impl(Exp&& exp, F&& f)
4752
    -> ret_t<Exp, detail::decay_t<Ret>> {
4753
  using result = ret_t<Exp, detail::decay_t<Ret>>;
4754
4755
  return exp.has_value() ? result(detail::invoke(std::forward<F>(f),
4756
                                                 *std::forward<Exp>(exp)))
4757
                         : result(unexpect, std::forward<Exp>(exp).error());
4758
}
4759
4760
template <class Exp, class F,
4761
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr,
4762
          class Ret = decltype(detail::invoke(std::declval<F>(),
4763
                                              *std::declval<Exp>())),
4764
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4765
4766
auto expected_map_impl(Exp&& exp, F&& f) -> expected<void, err_t<Exp>> {
4767
  if (exp.has_value()) {
4768
    detail::invoke(std::forward<F>(f), *std::forward<Exp>(exp));
4769
    return {};
4770
  }
4771
4772
  return unexpected<err_t<Exp>>(std::forward<Exp>(exp).error());
4773
}
4774
4775
template <class Exp, class F,
4776
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr,
4777
          class Ret = decltype(detail::invoke(std::declval<F>())),
4778
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4779
4780
constexpr auto expected_map_impl(Exp&& exp, F&& f)
4781
    -> ret_t<Exp, detail::decay_t<Ret>> {
4782
  using result = ret_t<Exp, detail::decay_t<Ret>>;
4783
4784
  return exp.has_value() ? result(detail::invoke(std::forward<F>(f)))
4785
                         : result(unexpect, std::forward<Exp>(exp).error());
4786
}
4787
4788
template <class Exp, class F,
4789
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr,
4790
          class Ret = decltype(detail::invoke(std::declval<F>())),
4791
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4792
4793
auto expected_map_impl(Exp&& exp, F&& f) -> expected<void, err_t<Exp>> {
4794
  if (exp.has_value()) {
4795
    detail::invoke(std::forward<F>(f));
4796
    return {};
4797
  }
4798
4799
  return unexpected<err_t<Exp>>(std::forward<Exp>(exp).error());
4800
}
4801
#endif
4802
4803
#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \
4804
    !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55)
4805
template <class Exp, class F,
4806
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr,
4807
          class Ret = decltype(detail::invoke(std::declval<F>(),
4808
                                              std::declval<Exp>().error())),
4809
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4810
constexpr auto map_error_impl(Exp&& exp, F&& f) {
4811
  using result = expected<exp_t<Exp>, detail::decay_t<Ret>>;
4812
  return exp.has_value()
4813
             ? result(*std::forward<Exp>(exp))
4814
             : result(unexpect, detail::invoke(std::forward<F>(f),
4815
                                               std::forward<Exp>(exp).error()));
4816
}
4817
template <class Exp, class F,
4818
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr,
4819
          class Ret = decltype(detail::invoke(std::declval<F>(),
4820
                                              std::declval<Exp>().error())),
4821
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4822
auto map_error_impl(Exp&& exp, F&& f) {
4823
  using result = expected<exp_t<Exp>, monostate>;
4824
  if (exp.has_value()) {
4825
    return result(*std::forward<Exp>(exp));
4826
  }
4827
4828
  detail::invoke(std::forward<F>(f), std::forward<Exp>(exp).error());
4829
  return result(unexpect, monostate{});
4830
}
4831
template <class Exp, class F,
4832
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr,
4833
          class Ret = decltype(detail::invoke(std::declval<F>(),
4834
                                              std::declval<Exp>().error())),
4835
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4836
constexpr auto map_error_impl(Exp&& exp, F&& f) {
4837
  using result = expected<exp_t<Exp>, detail::decay_t<Ret>>;
4838
  return exp.has_value()
4839
             ? result()
4840
             : result(unexpect, detail::invoke(std::forward<F>(f),
4841
                                               std::forward<Exp>(exp).error()));
4842
}
4843
template <class Exp, class F,
4844
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr,
4845
          class Ret = decltype(detail::invoke(std::declval<F>(),
4846
                                              std::declval<Exp>().error())),
4847
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4848
auto map_error_impl(Exp&& exp, F&& f) {
4849
  using result = expected<exp_t<Exp>, monostate>;
4850
  if (exp.has_value()) {
4851
    return result();
4852
  }
4853
4854
  detail::invoke(std::forward<F>(f), std::forward<Exp>(exp).error());
4855
  return result(unexpect, monostate{});
4856
}
4857
#else
4858
template <class Exp, class F,
4859
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr,
4860
          class Ret = decltype(detail::invoke(std::declval<F>(),
4861
                                              std::declval<Exp>().error())),
4862
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4863
constexpr auto map_error_impl(Exp&& exp, F&& f)
4864
    -> expected<exp_t<Exp>, detail::decay_t<Ret>> {
4865
  using result = expected<exp_t<Exp>, detail::decay_t<Ret>>;
4866
4867
  return exp.has_value()
4868
             ? result(*std::forward<Exp>(exp))
4869
             : result(unexpect, detail::invoke(std::forward<F>(f),
4870
                                               std::forward<Exp>(exp).error()));
4871
}
4872
4873
template <class Exp, class F,
4874
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr,
4875
          class Ret = decltype(detail::invoke(std::declval<F>(),
4876
                                              std::declval<Exp>().error())),
4877
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4878
auto map_error_impl(Exp&& exp, F&& f) -> expected<exp_t<Exp>, monostate> {
4879
  using result = expected<exp_t<Exp>, monostate>;
4880
  if (exp.has_value()) {
4881
    return result(*std::forward<Exp>(exp));
4882
  }
4883
4884
  detail::invoke(std::forward<F>(f), std::forward<Exp>(exp).error());
4885
  return result(unexpect, monostate{});
4886
}
4887
4888
template <class Exp, class F,
4889
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr,
4890
          class Ret = decltype(detail::invoke(std::declval<F>(),
4891
                                              std::declval<Exp>().error())),
4892
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4893
constexpr auto map_error_impl(Exp&& exp, F&& f)
4894
    -> expected<exp_t<Exp>, detail::decay_t<Ret>> {
4895
  using result = expected<exp_t<Exp>, detail::decay_t<Ret>>;
4896
4897
  return exp.has_value()
4898
             ? result()
4899
             : result(unexpect, detail::invoke(std::forward<F>(f),
4900
                                               std::forward<Exp>(exp).error()));
4901
}
4902
4903
template <class Exp, class F,
4904
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr,
4905
          class Ret = decltype(detail::invoke(std::declval<F>(),
4906
                                              std::declval<Exp>().error())),
4907
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4908
auto map_error_impl(Exp&& exp, F&& f) -> expected<exp_t<Exp>, monostate> {
4909
  using result = expected<exp_t<Exp>, monostate>;
4910
  if (exp.has_value()) {
4911
    return result();
4912
  }
4913
4914
  detail::invoke(std::forward<F>(f), std::forward<Exp>(exp).error());
4915
  return result(unexpect, monostate{});
4916
}
4917
#endif
4918
4919
#ifdef TL_EXPECTED_CXX14
4920
template <class Exp, class F,
4921
          class Ret = decltype(detail::invoke(std::declval<F>(),
4922
                                              std::declval<Exp>().error())),
4923
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4924
constexpr auto or_else_impl(Exp&& exp, F&& f) {
4925
  static_assert(detail::is_expected<Ret>::value, "F must return an expected");
4926
  return exp.has_value() ? std::forward<Exp>(exp)
4927
                         : detail::invoke(std::forward<F>(f),
4928
                                          std::forward<Exp>(exp).error());
4929
}
4930
4931
template <class Exp, class F,
4932
          class Ret = decltype(detail::invoke(std::declval<F>(),
4933
                                              std::declval<Exp>().error())),
4934
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4935
detail::decay_t<Exp> or_else_impl(Exp&& exp, F&& f) {
4936
  return exp.has_value() ? std::forward<Exp>(exp)
4937
                         : (detail::invoke(std::forward<F>(f),
4938
                                           std::forward<Exp>(exp).error()),
4939
                            std::forward<Exp>(exp));
4940
}
4941
#else
4942
template <class Exp, class F,
4943
          class Ret = decltype(detail::invoke(std::declval<F>(),
4944
                                              std::declval<Exp>().error())),
4945
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4946
auto or_else_impl(Exp&& exp, F&& f) -> Ret {
4947
  static_assert(detail::is_expected<Ret>::value, "F must return an expected");
4948
  return exp.has_value() ? std::forward<Exp>(exp)
4949
                         : detail::invoke(std::forward<F>(f),
4950
                                          std::forward<Exp>(exp).error());
4951
}
4952
4953
template <class Exp, class F,
4954
          class Ret = decltype(detail::invoke(std::declval<F>(),
4955
                                              std::declval<Exp>().error())),
4956
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4957
detail::decay_t<Exp> or_else_impl(Exp&& exp, F&& f) {
4958
  return exp.has_value() ? std::forward<Exp>(exp)
4959
                         : (detail::invoke(std::forward<F>(f),
4960
                                           std::forward<Exp>(exp).error()),
4961
                            std::forward<Exp>(exp));
4962
}
4963
#endif
4964
}  // namespace detail
4965
4966
template <class T, class E, class U, class F>
4967
constexpr bool operator==(const expected<T, E>& lhs,
4968
                          const expected<U, F>& rhs) {
4969
  return (lhs.has_value() != rhs.has_value())
4970
             ? false
4971
             : (!lhs.has_value() ? lhs.error() == rhs.error() : *lhs == *rhs);
4972
}
4973
template <class T, class E, class U, class F>
4974
constexpr bool operator!=(const expected<T, E>& lhs,
4975
                          const expected<U, F>& rhs) {
4976
  return (lhs.has_value() != rhs.has_value())
4977
             ? true
4978
             : (!lhs.has_value() ? lhs.error() != rhs.error() : *lhs != *rhs);
4979
}
4980
template <class E, class F>
4981
constexpr bool operator==(const expected<void, E>& lhs,
4982
                          const expected<void, F>& rhs) {
4983
  return (lhs.has_value() != rhs.has_value())
4984
             ? false
4985
             : (!lhs.has_value() ? lhs.error() == rhs.error() : true);
4986
}
4987
template <class E, class F>
4988
constexpr bool operator!=(const expected<void, E>& lhs,
4989
                          const expected<void, F>& rhs) {
4990
  return (lhs.has_value() != rhs.has_value())
4991
             ? true
4992
             : (!lhs.has_value() ? lhs.error() == rhs.error() : false);
4993
}
4994
4995
template <class T, class E, class U>
4996
constexpr bool operator==(const expected<T, E>& x, const U& v) {
4997
  return x.has_value() ? *x == v : false;
4998
}
4999
template <class T, class E, class U>
5000
constexpr bool operator==(const U& v, const expected<T, E>& x) {
5001
  return x.has_value() ? *x == v : false;
5002
}
5003
template <class T, class E, class U>
5004
constexpr bool operator!=(const expected<T, E>& x, const U& v) {
5005
  return x.has_value() ? *x != v : true;
5006
}
5007
template <class T, class E, class U>
5008
constexpr bool operator!=(const U& v, const expected<T, E>& x) {
5009
  return x.has_value() ? *x != v : true;
5010
}
5011
5012
template <class T, class E>
5013
constexpr bool operator==(const expected<T, E>& x, const unexpected<E>& e) {
5014
  return x.has_value() ? false : x.error() == e.value();
5015
}
5016
template <class T, class E>
5017
constexpr bool operator==(const unexpected<E>& e, const expected<T, E>& x) {
5018
  return x.has_value() ? false : x.error() == e.value();
5019
}
5020
template <class T, class E>
5021
constexpr bool operator!=(const expected<T, E>& x, const unexpected<E>& e) {
5022
  return x.has_value() ? true : x.error() != e.value();
5023
}
5024
template <class T, class E>
5025
constexpr bool operator!=(const unexpected<E>& e, const expected<T, E>& x) {
5026
  return x.has_value() ? true : x.error() != e.value();
5027
}
5028
5029
template <class T, class E,
5030
          detail::enable_if_t<(std::is_void<T>::value ||
5031
                               std::is_move_constructible<T>::value) &&
5032
                              detail::is_swappable<T>::value &&
5033
                              std::is_move_constructible<E>::value &&
5034
                              detail::is_swappable<E>::value>* = nullptr>
5035
void swap(expected<T, E>& lhs,
5036
          expected<T, E>& rhs) noexcept(noexcept(lhs.swap(rhs))) {
5037
  lhs.swap(rhs);
5038
}
5039
}  // namespace tl
5040
5041
#endif
5042
/* end file include/ada/expected.h */
5043
5044
/* begin file include/ada/url_pattern_regex.h */
5045
/**
5046
 * @file url_search_params.h
5047
 * @brief Declaration for the URL Search Params
5048
 */
5049
#ifndef ADA_URL_PATTERN_REGEX_H
5050
#define ADA_URL_PATTERN_REGEX_H
5051
5052
#include <concepts>
5053
#include <optional>
5054
#include <string>
5055
#include <string_view>
5056
#include <vector>
5057
5058
#ifdef ADA_USE_UNSAFE_STD_REGEX_PROVIDER
5059
#include <regex>
5060
#endif  // ADA_USE_UNSAFE_STD_REGEX_PROVIDER
5061
5062
#if ADA_INCLUDE_URL_PATTERN
5063
namespace ada::url_pattern_regex {
5064
5065
/**
5066
 * @brief Concept defining the interface for regex engine providers used by
5067
 * URLPattern.
5068
 *
5069
 * A regex provider supplies the regular expression engine used for
5070
 * pattern compilation and matching.
5071
 *
5072
 * Requirements:
5073
 * - typename T::regex_type: The compiled regex object type.
5074
 * - T::create_instance(pattern, ignore_case): Compiles the regex pattern
5075
 * string. Returns std::nullopt if the pattern is invalid or cannot be compiled.
5076
 * - T::regex_search(input, pattern): Executes a regex search against the input,
5077
 *     returning a vector of capture group values (with std::nullopt for
5078
 * unmatched optional groups) or std::nullopt if the input does not match.
5079
 * - T::regex_match(input, pattern): Returns true if the input matches the
5080
 * pattern, or false otherwise.
5081
 *
5082
 * Exception contract:
5083
 * Provider methods may throw exceptions (for example, on allocation failure,
5084
 * input length limits, complexity limits, or internal engine errors). In
5085
 * environments where C++ exceptions are enabled, exceptions thrown by the
5086
 * provider will propagate out of URLPattern functions (such as fast_test,
5087
 * fast_match, test, exec, match, etc.). Providers that prefer non-throwing
5088
 * operation should handle internal errors and return false or std::nullopt.
5089
 */
5090
template <typename T>
5091
concept regex_concept = requires(T t, std::string_view pattern,
5092
                                 bool ignore_case, std::string_view input) {
5093
  // Ensure the class has a type alias 'regex_type'
5094
  typename T::regex_type;
5095
5096
  // Function to create a regex instance
5097
  {
5098
    T::create_instance(pattern, ignore_case)
5099
  } -> std::same_as<std::optional<typename T::regex_type>>;
5100
5101
  // Function to perform regex search
5102
  {
5103
    T::regex_search(input, std::declval<typename T::regex_type&>())
5104
  } -> std::same_as<std::optional<std::vector<std::optional<std::string>>>>;
5105
5106
  // Function to match regex pattern
5107
  {
5108
    T::regex_match(input, std::declval<typename T::regex_type&>())
5109
  } -> std::same_as<bool>;
5110
5111
  // Copy constructor
5112
  { T(std::declval<const T&>()) } -> std::same_as<T>;
5113
5114
  // Move constructor
5115
  { T(std::declval<T&&>()) } -> std::same_as<T>;
5116
};
5117
5118
#ifdef ADA_USE_UNSAFE_STD_REGEX_PROVIDER
5119
class std_regex_provider final {
5120
 public:
5121
  std_regex_provider() = default;
5122
  using regex_type = std::regex;
5123
  static std::optional<regex_type> create_instance(std::string_view pattern,
5124
                                                   bool ignore_case);
5125
  static std::optional<std::vector<std::optional<std::string>>> regex_search(
5126
      std::string_view input, const regex_type& pattern);
5127
  static bool regex_match(std::string_view input, const regex_type& pattern);
5128
};
5129
#endif  // ADA_USE_UNSAFE_STD_REGEX_PROVIDER
5130
5131
}  // namespace ada::url_pattern_regex
5132
#endif  // ADA_INCLUDE_URL_PATTERN
5133
#endif  // ADA_URL_PATTERN_REGEX_H
5134
/* end file include/ada/url_pattern_regex.h */
5135
/* begin file include/ada/url_pattern_init.h */
5136
/**
5137
 * @file url_pattern_init.h
5138
 * @brief Declaration for the url_pattern_init implementation.
5139
 */
5140
#ifndef ADA_URL_PATTERN_INIT_H
5141
#define ADA_URL_PATTERN_INIT_H
5142
5143
/* begin file include/ada/errors.h */
5144
/**
5145
 * @file errors.h
5146
 * @brief Error type definitions for URL parsing.
5147
 *
5148
 * Defines the error codes that can be returned when URL parsing fails.
5149
 */
5150
#ifndef ADA_ERRORS_H
5151
#define ADA_ERRORS_H
5152
5153
#include <cstdint>
5154
namespace ada {
5155
/**
5156
 * @brief Error codes for URL parsing operations.
5157
 *
5158
 * Used with `tl::expected` to indicate why a URL parsing operation failed.
5159
 */
5160
enum class errors : uint8_t {
5161
  type_error /**< A type error occurred (e.g., invalid URL syntax). */
5162
};
5163
}  // namespace ada
5164
#endif  // ADA_ERRORS_H
5165
/* end file include/ada/errors.h */
5166
5167
#include <concepts>
5168
#include <cstdint>
5169
#include <iostream>
5170
#include <optional>
5171
#include <string>
5172
#include <string_view>
5173
5174
#if ADA_TESTING
5175
#include <iostream>
5176
#endif  // ADA_TESTING
5177
5178
#if ADA_INCLUDE_URL_PATTERN
5179
namespace ada {
5180
5181
// Important: C++20 allows us to use concept rather than `using` or `typedef
5182
// and allows functions with second argument, which is optional (using either
5183
// std::nullopt or a parameter with default value)
5184
template <typename F>
5185
concept url_pattern_encoding_callback = requires(F f, std::string_view sv) {
5186
  { f(sv) } -> std::same_as<tl::expected<std::string, errors>>;
5187
};
5188
5189
// A structure providing matching patterns for individual components
5190
// of a URL. When a URLPattern is created, or when a URLPattern is
5191
// used to match or test against a URL, the input can be given as
5192
// either a string or a URLPatternInit struct. If a string is given,
5193
// it will be parsed to create a URLPatternInit. The URLPatternInit
5194
// API is defined as part of the URLPattern specification.
5195
// All provided strings must be valid UTF-8.
5196
struct url_pattern_init {
5197
  enum class process_type : uint8_t {
5198
    url,
5199
    pattern,
5200
  };
5201
5202
0
  friend std::ostream& operator<<(std::ostream& os, process_type type) {
5203
0
    switch (type) {
5204
0
      case process_type::url:
5205
0
        return os << "url";
5206
0
      case process_type::pattern:
5207
0
        return os << "pattern";
5208
0
      default:
5209
0
        return os << "unknown";
5210
0
    }
5211
0
  }
5212
5213
  // All strings must be valid UTF-8.
5214
  // @see https://urlpattern.spec.whatwg.org/#process-a-urlpatterninit
5215
  static tl::expected<url_pattern_init, errors> process(
5216
      const url_pattern_init& init, process_type type,
5217
      std::optional<std::string_view> protocol = std::nullopt,
5218
      std::optional<std::string_view> username = std::nullopt,
5219
      std::optional<std::string_view> password = std::nullopt,
5220
      std::optional<std::string_view> hostname = std::nullopt,
5221
      std::optional<std::string_view> port = std::nullopt,
5222
      std::optional<std::string_view> pathname = std::nullopt,
5223
      std::optional<std::string_view> search = std::nullopt,
5224
      std::optional<std::string_view> hash = std::nullopt);
5225
5226
  // @see https://urlpattern.spec.whatwg.org/#process-protocol-for-init
5227
  static tl::expected<std::string, errors> process_protocol(
5228
      std::string_view value, process_type type);
5229
5230
  // @see https://urlpattern.spec.whatwg.org/#process-username-for-init
5231
  static tl::expected<std::string, errors> process_username(
5232
      std::string_view value, process_type type);
5233
5234
  // @see https://urlpattern.spec.whatwg.org/#process-password-for-init
5235
  static tl::expected<std::string, errors> process_password(
5236
      std::string_view value, process_type type);
5237
5238
  // @see https://urlpattern.spec.whatwg.org/#process-hostname-for-init
5239
  static tl::expected<std::string, errors> process_hostname(
5240
      std::string_view value, process_type type);
5241
5242
  // @see https://urlpattern.spec.whatwg.org/#process-port-for-init
5243
  static tl::expected<std::string, errors> process_port(
5244
      std::string_view port, std::string_view protocol, process_type type);
5245
5246
  // @see https://urlpattern.spec.whatwg.org/#process-pathname-for-init
5247
  static tl::expected<std::string, errors> process_pathname(
5248
      std::string_view value, std::string_view protocol, process_type type);
5249
5250
  // @see https://urlpattern.spec.whatwg.org/#process-search-for-init
5251
  static tl::expected<std::string, errors> process_search(
5252
      std::string_view value, process_type type);
5253
5254
  // @see https://urlpattern.spec.whatwg.org/#process-hash-for-init
5255
  static tl::expected<std::string, errors> process_hash(std::string_view value,
5256
                                                        process_type type);
5257
5258
#if ADA_TESTING
5259
  friend void PrintTo(const url_pattern_init& init, std::ostream* os) {
5260
    *os << "protocol: '" << init.protocol.value_or("undefined") << "', ";
5261
    *os << "username: '" << init.username.value_or("undefined") << "', ";
5262
    *os << "password: '" << init.password.value_or("undefined") << "', ";
5263
    *os << "hostname: '" << init.hostname.value_or("undefined") << "', ";
5264
    *os << "port: '" << init.port.value_or("undefined") << "', ";
5265
    *os << "pathname: '" << init.pathname.value_or("undefined") << "', ";
5266
    *os << "search: '" << init.search.value_or("undefined") << "', ";
5267
    *os << "hash: '" << init.hash.value_or("undefined") << "', ";
5268
    *os << "base_url: '" << init.base_url.value_or("undefined") << "', ";
5269
  }
5270
#endif  // ADA_TESTING
5271
5272
  bool operator==(const url_pattern_init&) const;
5273
  // If present, must be valid UTF-8.
5274
  std::optional<std::string> protocol{};
5275
  // If present, must be valid UTF-8.
5276
  std::optional<std::string> username{};
5277
  // If present, must be valid UTF-8.
5278
  std::optional<std::string> password{};
5279
  // If present, must be valid UTF-8.
5280
  std::optional<std::string> hostname{};
5281
  // If present, must be valid UTF-8.
5282
  std::optional<std::string> port{};
5283
  // If present, must be valid UTF-8.
5284
  std::optional<std::string> pathname{};
5285
  // If present, must be valid UTF-8.
5286
  std::optional<std::string> search{};
5287
  // If present, must be valid UTF-8.
5288
  std::optional<std::string> hash{};
5289
  // If present, must be valid UTF-8.
5290
  std::optional<std::string> base_url{};
5291
};
5292
}  // namespace ada
5293
#endif  // ADA_INCLUDE_URL_PATTERN
5294
#endif  // ADA_URL_PATTERN_INIT_H
5295
/* end file include/ada/url_pattern_init.h */
5296
5297
/** @private Forward declarations */
5298
namespace ada {
5299
struct url_aggregator;
5300
struct url;
5301
#if ADA_INCLUDE_URL_PATTERN
5302
template <url_pattern_regex::regex_concept regex_provider>
5303
class url_pattern;
5304
struct url_pattern_options;
5305
#endif  // ADA_INCLUDE_URL_PATTERN
5306
enum class errors : uint8_t;
5307
}  // namespace ada
5308
5309
/**
5310
 * @namespace ada::parser
5311
 * @brief Internal URL parsing implementation.
5312
 *
5313
 * Contains the core URL parsing algorithm as specified by the WHATWG URL
5314
 * Standard. These functions are used internally by `ada::parse()`.
5315
 */
5316
namespace ada::parser {
5317
/**
5318
 * Parses a URL string into a URL object.
5319
 *
5320
 * @tparam result_type The type of URL object to create (url or url_aggregator).
5321
 *
5322
 * @param user_input The URL string to parse (must be valid UTF-8).
5323
 * @param base_url Optional base URL for resolving relative URLs.
5324
 *
5325
 * @return The parsed URL object. Check `is_valid` to determine if parsing
5326
 *         succeeded.
5327
 *
5328
 * @see https://url.spec.whatwg.org/#concept-basic-url-parser
5329
 */
5330
template <typename result_type = url_aggregator>
5331
result_type parse_url(std::string_view user_input,
5332
                      const result_type* base_url = nullptr);
5333
5334
extern template url_aggregator parse_url<url_aggregator>(
5335
    std::string_view user_input, const url_aggregator* base_url);
5336
extern template url parse_url<url>(std::string_view user_input,
5337
                                   const url* base_url);
5338
5339
template <typename result_type = url_aggregator, bool store_values = true>
5340
result_type parse_url_impl(std::string_view user_input,
5341
                           const result_type* base_url = nullptr);
5342
5343
extern template url_aggregator parse_url_impl<url_aggregator, true>(
5344
    std::string_view user_input, const url_aggregator* base_url);
5345
extern template url_aggregator parse_url_impl<url_aggregator, false>(
5346
    std::string_view user_input, const url_aggregator* base_url);
5347
extern template url parse_url_impl<url, true>(std::string_view user_input,
5348
                                              const url* base_url);
5349
5350
/** @private */
5351
template <class result_type>
5352
bool try_parse_simple_absolute(std::string_view input, result_type& out);
5353
5354
/** @private */
5355
template <class result_type>
5356
bool finish_simple_absolute_with_port(std::string_view input, result_type& out,
5357
                                      ada::scheme::type scheme_type,
5358
                                      uint32_t protocol_end, size_t host_start,
5359
                                      size_t host_end, size_t host_len,
5360
                                      bool has_upper);
5361
5362
/** @private */
5363
template <class result_type>
5364
bool try_parse_simple_relative(std::string_view input, const result_type& base,
5365
                               result_type& out);
5366
5367
#if ADA_INCLUDE_URL_PATTERN
5368
template <url_pattern_regex::regex_concept regex_provider>
5369
tl::expected<url_pattern<regex_provider>, errors> parse_url_pattern_impl(
5370
    std::variant<std::string_view, url_pattern_init>&& input,
5371
    const std::string_view* base_url, const url_pattern_options* options);
5372
#endif  // ADA_INCLUDE_URL_PATTERN
5373
5374
}  // namespace ada::parser
5375
5376
#endif  // ADA_PARSER_H
5377
/* end file include/ada/parser.h */
5378
/* begin file include/ada/parser-inl.h */
5379
/**
5380
 * @file parser-inl.h
5381
 */
5382
#ifndef ADA_PARSER_INL_H
5383
#define ADA_PARSER_INL_H
5384
5385
/* begin file include/ada/url_pattern.h */
5386
/**
5387
 * @file url_pattern.h
5388
 * @brief URLPattern API implementation.
5389
 *
5390
 * This header provides the URLPattern API as specified by the WHATWG URL
5391
 * Pattern Standard. URLPattern allows matching URLs against patterns with
5392
 * wildcards and named groups, similar to how regular expressions match strings.
5393
 *
5394
 * @see https://urlpattern.spec.whatwg.org/
5395
 * @see https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API
5396
 */
5397
#ifndef ADA_URL_PATTERN_H
5398
#define ADA_URL_PATTERN_H
5399
5400
/* begin file include/ada/implementation.h */
5401
/**
5402
 * @file implementation.h
5403
 * @brief User-facing functions for URL parsing and manipulation.
5404
 *
5405
 * This header provides the primary public API for parsing URLs in Ada.
5406
 * It includes the main `ada::parse()` function which is the recommended
5407
 * entry point for most users.
5408
 *
5409
 * @see https://url.spec.whatwg.org/#api
5410
 */
5411
#ifndef ADA_IMPLEMENTATION_H
5412
#define ADA_IMPLEMENTATION_H
5413
5414
#include <cstdint>
5415
#include <optional>
5416
#include <span>
5417
#include <string>
5418
#include <string_view>
5419
#include <variant>
5420
5421
/* begin file include/ada/url.h */
5422
/**
5423
 * @file url.h
5424
 * @brief Declaration for the `ada::url` class.
5425
 *
5426
 * This file contains the `ada::url` struct which represents a parsed URL
5427
 * using separate `std::string` instances for each component. This
5428
 * representation is more flexible but uses more memory than `url_aggregator`.
5429
 *
5430
 * @see url_aggregator.h for a more memory-efficient alternative
5431
 */
5432
#ifndef ADA_URL_H
5433
#define ADA_URL_H
5434
5435
#include <algorithm>
5436
#include <cstddef>
5437
#include <cstdint>
5438
#include <optional>
5439
#include <ostream>
5440
#include <string>
5441
#include <string_view>
5442
5443
/* begin file include/ada/url_components.h */
5444
/**
5445
 * @file url_components.h
5446
 * @brief URL component offset representation for url_aggregator.
5447
 *
5448
 * This file defines the `url_components` struct which stores byte offsets
5449
 * into a URL string buffer. It is used internally by `url_aggregator` to
5450
 * efficiently locate URL components without storing separate strings.
5451
 */
5452
#ifndef ADA_URL_COMPONENTS_H
5453
#define ADA_URL_COMPONENTS_H
5454
5455
#include <cstdint>
5456
#include <string>
5457
5458
namespace ada {
5459
5460
/**
5461
 * @brief Stores byte offsets for URL components within a buffer.
5462
 *
5463
 * The `url_components` struct uses 32-bit offsets to track the boundaries
5464
 * of each URL component within a single string buffer. This enables efficient
5465
 * component extraction without additional memory allocations.
5466
 *
5467
 * Component layout in a URL:
5468
 * ```
5469
 * https://user:pass@example.com:1234/foo/bar?baz#quux
5470
 *       |     |    |          | ^^^^|       |   |
5471
 *       |     |    |          | |   |       |   `----- hash_start
5472
 *       |     |    |          | |   |       `--------- search_start
5473
 *       |     |    |          | |   `----------------- pathname_start
5474
 *       |     |    |          | `--------------------- port
5475
 *       |     |    |          `----------------------- host_end
5476
 *       |     |    `---------------------------------- host_start
5477
 *       |     `--------------------------------------- username_end
5478
 *       `--------------------------------------------- protocol_end
5479
 * ```
5480
 *
5481
 * @note The 32-bit offsets limit URLs to 4GB in length.
5482
 * @note A value of `omitted` (UINT32_MAX) indicates the component is not
5483
 * present.
5484
 */
5485
struct url_components {
5486
  /** Sentinel value indicating a component is not present. */
5487
  constexpr static uint32_t omitted = uint32_t(-1);
5488
5489
2.93k
  url_components() = default;
5490
  url_components(const url_components& u) = default;
5491
  url_components(url_components&& u) noexcept = default;
5492
  url_components& operator=(url_components&& u) noexcept = default;
5493
  url_components& operator=(const url_components& u) = default;
5494
  ~url_components() = default;
5495
5496
  /** Offset of the end of the protocol/scheme (position of ':'). */
5497
  uint32_t protocol_end{0};
5498
5499
  /**
5500
   * Offset of the end of the username.
5501
   * Initialized to 0 (not `omitted`) to simplify username/password getters.
5502
   */
5503
  uint32_t username_end{0};
5504
5505
  /** Offset of the start of the host. */
5506
  uint32_t host_start{0};
5507
5508
  /** Offset of the end of the host. */
5509
  uint32_t host_end{0};
5510
5511
  /** Port number, or `omitted` if no port is specified. */
5512
  uint32_t port{omitted};
5513
5514
  /** Offset of the start of the pathname. */
5515
  uint32_t pathname_start{0};
5516
5517
  /** Offset of the '?' starting the query, or `omitted` if no query. */
5518
  uint32_t search_start{omitted};
5519
5520
  /** Offset of the '#' starting the fragment, or `omitted` if no fragment. */
5521
  uint32_t hash_start{omitted};
5522
5523
  /**
5524
   * Validates that offsets are in ascending order and consistent.
5525
   * Useful for debugging to detect internal corruption.
5526
   * @return `true` if offsets are consistent, `false` otherwise.
5527
   */
5528
  [[nodiscard]] constexpr bool check_offset_consistency() const noexcept;
5529
5530
  /**
5531
   * Returns a JSON string representation of the offsets for debugging.
5532
   * @return A JSON-formatted string with all offset values.
5533
   */
5534
  [[nodiscard]] std::string to_string() const;
5535
5536
};  // struct url_components
5537
}  // namespace ada
5538
#endif
5539
/* end file include/ada/url_components.h */
5540
5541
namespace ada {
5542
5543
struct url_aggregator;
5544
5545
// namespace parser {
5546
// template <typename result_type>
5547
// result_type parse_url(std::string_view user_input,
5548
//                       const result_type* base_url = nullptr);
5549
// template <typename result_type, bool store_values>
5550
// result_type parse_url_impl(std::string_view user_input,
5551
//                            const result_type* base_url = nullptr);
5552
// }
5553
5554
/**
5555
 * @brief Represents a parsed URL with individual string components.
5556
 *
5557
 * The `url` struct stores each URL component (scheme, username, password,
5558
 * host, port, path, query, fragment) as a separate `std::string`. This
5559
 * provides flexibility but incurs more memory allocations compared to
5560
 * `url_aggregator`.
5561
 *
5562
 * **When to use `ada::url`:**
5563
 * - When you need to frequently modify individual URL components
5564
 * - When you want independent ownership of component strings
5565
 *
5566
 * **When to use `ada::url_aggregator` instead:**
5567
 * - For read-mostly operations on parsed URLs
5568
 * - When memory efficiency is important
5569
 * - When you only need string_view access to components
5570
 *
5571
 * @note This type is returned when parsing with `ada::parse<ada::url>()`.
5572
 *       By default, `ada::parse()` returns `ada::url_aggregator`.
5573
 *
5574
 * @see url_aggregator For a more memory-efficient URL representation
5575
 * @see https://url.spec.whatwg.org/#url-representation
5576
 */
5577
struct url : url_base {
5578
0
  url() = default;
5579
0
  url(const url& u) = default;
5580
0
  url(url&& u) noexcept = default;
5581
0
  url& operator=(url&& u) noexcept = default;
5582
0
  url& operator=(const url& u) = default;
5583
0
  ~url() override = default;
5584
5585
  // Fields are ordered so that the most frequently accessed components
5586
  // tend to occupy earlier cache lines and remain close together in memory.
5587
  //
5588
  // Note: The exact object layout (including cache-line boundaries, byte
5589
  // offsets, and member sizes) is implementation- and platform-dependent.
5590
  // This ordering expresses an intent for better cache locality but does not
5591
  // guarantee any specific in-memory layout.
5592
5593
  /**
5594
   * @private
5595
   * A URL's host is null or a host. It is initially null.
5596
   */
5597
  std::optional<std::string> host{};
5598
5599
  /**
5600
   * @private
5601
   * A URL's path is either an ASCII string or a list of zero or more ASCII
5602
   * strings, usually identifying a location.
5603
   */
5604
  std::string path{};
5605
5606
  /**
5607
   * @private
5608
   * A URL's query is either null or an ASCII string. It is initially null.
5609
   */
5610
  std::optional<std::string> query{};
5611
5612
  /**
5613
   * @private
5614
   * A URL's fragment is either null or an ASCII string that can be used for
5615
   * further processing on the resource the URL's other components identify. It
5616
   * is initially null.
5617
   */
5618
  std::optional<std::string> hash{};
5619
5620
  /**
5621
   * @private
5622
   * A URL's port is either null or a 16-bit unsigned integer that identifies a
5623
   * networking port. It is initially null.
5624
   */
5625
  std::optional<uint16_t> port{};
5626
5627
  /**
5628
   * @private
5629
   * A URL's username is an ASCII string identifying a username. It is initially
5630
   * the empty string.
5631
   */
5632
  std::string username{};
5633
5634
  /**
5635
   * @private
5636
   * A URL's password is an ASCII string identifying a password. It is initially
5637
   * the empty string.
5638
   */
5639
  std::string password{};
5640
5641
  /**
5642
   * Checks if the URL has an empty hostname (host is set but empty string).
5643
   * @return `true` if host exists but is empty, `false` otherwise.
5644
   */
5645
  [[nodiscard]] inline bool has_empty_hostname() const noexcept;
5646
5647
  /**
5648
   * Checks if the URL has a non-default port explicitly specified.
5649
   * @return `true` if a port is present, `false` otherwise.
5650
   */
5651
  [[nodiscard]] inline bool has_port() const noexcept;
5652
5653
  /**
5654
   * Checks if the URL has a hostname (including empty hostnames).
5655
   * @return `true` if host is present, `false` otherwise.
5656
   */
5657
  [[nodiscard]] inline bool has_hostname() const noexcept;
5658
5659
  /**
5660
   * Validates whether the hostname is a valid domain according to RFC 1034.
5661
   * Checks that the domain and its labels have valid lengths (max 255 octets
5662
   * total, max 63 octets per label).
5663
   * @return `true` if the domain is valid, `false` otherwise.
5664
   */
5665
  [[nodiscard]] bool has_valid_domain() const noexcept override;
5666
5667
  /**
5668
   * Returns a JSON string representation of this URL for debugging.
5669
   * @return A JSON-formatted string with all URL components.
5670
   */
5671
  [[nodiscard]] std::string to_string() const override;
5672
5673
  /**
5674
   * Returns the full serialized URL (the href).
5675
   * @return The complete URL string (allocates a new string).
5676
   * @see https://url.spec.whatwg.org/#dom-url-href
5677
   */
5678
  [[nodiscard]] ada_really_inline std::string get_href() const;
5679
5680
  /**
5681
   * Returns the byte length of the serialized URL without allocating a string.
5682
   * @return Size of the href in bytes.
5683
   */
5684
  [[nodiscard]] size_t get_href_size() const noexcept;
5685
5686
  /**
5687
   * Returns the URL's origin as a string (scheme + host + port for special
5688
   * URLs).
5689
   * @return A newly allocated string containing the serialized origin.
5690
   * @see https://url.spec.whatwg.org/#concept-url-origin
5691
   */
5692
  [[nodiscard]] std::string get_origin() const override;
5693
5694
  /**
5695
   * Returns the URL's scheme followed by a colon (e.g., "https:").
5696
   * @return A newly allocated string with the protocol.
5697
   * @see https://url.spec.whatwg.org/#dom-url-protocol
5698
   */
5699
  [[nodiscard]] std::string get_protocol() const;
5700
5701
  /**
5702
   * Returns the URL's host and port (e.g., "example.com:8080").
5703
   * If no port is set, returns just the host. Returns empty string if no host.
5704
   * @return A newly allocated string with host:port.
5705
   * @see https://url.spec.whatwg.org/#dom-url-host
5706
   */
5707
  [[nodiscard]] std::string get_host() const;
5708
5709
  /**
5710
   * Returns the URL's hostname (without port).
5711
   * Returns empty string if no host is set.
5712
   * @return A newly allocated string with the hostname.
5713
   * @see https://url.spec.whatwg.org/#dom-url-hostname
5714
   */
5715
  [[nodiscard]] std::string get_hostname() const;
5716
5717
  /**
5718
   * Returns the URL's path component.
5719
   * @return A string_view pointing to the path.
5720
   * @see https://url.spec.whatwg.org/#dom-url-pathname
5721
   */
5722
  [[nodiscard]] constexpr std::string_view get_pathname() const noexcept;
5723
5724
  /**
5725
   * Returns the byte length of the pathname without creating a string.
5726
   * @return Size of the pathname in bytes.
5727
   * @see https://url.spec.whatwg.org/#dom-url-pathname
5728
   */
5729
  [[nodiscard]] ada_really_inline size_t get_pathname_length() const noexcept;
5730
5731
  /**
5732
   * Returns the URL's query string prefixed with '?' (e.g., "?foo=bar").
5733
   * Returns empty string if no query is set.
5734
   * @return A newly allocated string with the search/query.
5735
   * @see https://url.spec.whatwg.org/#dom-url-search
5736
   */
5737
  [[nodiscard]] std::string get_search() const;
5738
5739
  /**
5740
   * Returns the URL's username component.
5741
   * @return A constant reference to the username string.
5742
   * @see https://url.spec.whatwg.org/#dom-url-username
5743
   */
5744
  [[nodiscard]] const std::string& get_username() const noexcept;
5745
5746
  /**
5747
   * Sets the URL's username, percent-encoding special characters.
5748
   * @param input The new username value.
5749
   * @return `true` on success, `false` if the URL cannot have credentials.
5750
   * @see https://url.spec.whatwg.org/#dom-url-username
5751
   */
5752
  bool set_username(std::string_view input);
5753
5754
  /**
5755
   * Sets the URL's password, percent-encoding special characters.
5756
   * @param input The new password value.
5757
   * @return `true` on success, `false` if the URL cannot have credentials.
5758
   * @see https://url.spec.whatwg.org/#dom-url-password
5759
   */
5760
  bool set_password(std::string_view input);
5761
5762
  /**
5763
   * Sets the URL's port from a string (e.g., "8080").
5764
   * @param input The port string. Empty string removes the port.
5765
   * @return `true` on success, `false` if the URL cannot have a port.
5766
   * @see https://url.spec.whatwg.org/#dom-url-port
5767
   */
5768
  bool set_port(std::string_view input);
5769
5770
  /**
5771
   * Sets the URL's fragment/hash (the part after '#').
5772
   * @param input The new hash value (with or without leading '#').
5773
   * @see https://url.spec.whatwg.org/#dom-url-hash
5774
   */
5775
  void set_hash(std::string_view input);
5776
5777
  /**
5778
   * Sets the URL's query string (the part after '?').
5779
   * @param input The new query value (with or without leading '?').
5780
   * @see https://url.spec.whatwg.org/#dom-url-search
5781
   */
5782
  void set_search(std::string_view input);
5783
5784
  /**
5785
   * Sets the URL's pathname.
5786
   * @param input The new path value.
5787
   * @return `true` on success, `false` if the URL has an opaque path.
5788
   * @see https://url.spec.whatwg.org/#dom-url-pathname
5789
   */
5790
  bool set_pathname(std::string_view input);
5791
5792
  /**
5793
   * Sets the URL's host (hostname and optionally port).
5794
   * @param input The new host value (e.g., "example.com:8080").
5795
   * @return `true` on success, `false` if parsing fails.
5796
   * @see https://url.spec.whatwg.org/#dom-url-host
5797
   */
5798
  bool set_host(std::string_view input);
5799
5800
  /**
5801
   * Sets the URL's hostname (without port).
5802
   * @param input The new hostname value.
5803
   * @return `true` on success, `false` if parsing fails.
5804
   * @see https://url.spec.whatwg.org/#dom-url-hostname
5805
   */
5806
  bool set_hostname(std::string_view input);
5807
5808
  /**
5809
   * Sets the URL's protocol/scheme.
5810
   * @param input The new protocol (with or without trailing ':').
5811
   * @return `true` on success, `false` if the scheme is invalid.
5812
   * @see https://url.spec.whatwg.org/#dom-url-protocol
5813
   */
5814
  bool set_protocol(std::string_view input);
5815
5816
  /**
5817
   * Replaces the entire URL by parsing a new href string.
5818
   * @param input The new URL string to parse.
5819
   * @return `true` on success, `false` if parsing fails.
5820
   * @see https://url.spec.whatwg.org/#dom-url-href
5821
   */
5822
  bool set_href(std::string_view input);
5823
5824
  /**
5825
   * Returns the URL's password component.
5826
   * @return A constant reference to the password string.
5827
   * @see https://url.spec.whatwg.org/#dom-url-password
5828
   */
5829
  [[nodiscard]] const std::string& get_password() const noexcept;
5830
5831
  /**
5832
   * Returns the URL's port as a string (e.g., "8080").
5833
   * Returns empty string if no port is set.
5834
   * @return A newly allocated string with the port.
5835
   * @see https://url.spec.whatwg.org/#dom-url-port
5836
   */
5837
  [[nodiscard]] std::string get_port() const;
5838
5839
  /**
5840
   * Returns the URL's fragment prefixed with '#' (e.g., "#section").
5841
   * Returns empty string if no fragment is set.
5842
   * @return A newly allocated string with the hash.
5843
   * @see https://url.spec.whatwg.org/#dom-url-hash
5844
   */
5845
  [[nodiscard]] std::string get_hash() const;
5846
5847
  /**
5848
   * Checks if the URL has credentials (non-empty username or password).
5849
   * @return `true` if username or password is non-empty, `false` otherwise.
5850
   */
5851
  [[nodiscard]] ada_really_inline bool has_credentials() const noexcept;
5852
5853
  /**
5854
   * Returns the URL component offsets for efficient serialization.
5855
   *
5856
   * The components represent byte offsets into the serialized URL:
5857
   * ```
5858
   * https://user:pass@example.com:1234/foo/bar?baz#quux
5859
   *       |     |    |          | ^^^^|       |   |
5860
   *       |     |    |          | |   |       |   `----- hash_start
5861
   *       |     |    |          | |   |       `--------- search_start
5862
   *       |     |    |          | |   `----------------- pathname_start
5863
   *       |     |    |          | `--------------------- port
5864
   *       |     |    |          `----------------------- host_end
5865
   *       |     |    `---------------------------------- host_start
5866
   *       |     `--------------------------------------- username_end
5867
   *       `--------------------------------------------- protocol_end
5868
   * ```
5869
   * @return A newly constructed url_components struct.
5870
   * @see https://github.com/servo/rust-url
5871
   */
5872
  [[nodiscard]] ada_really_inline ada::url_components get_components() const;
5873
5874
  /**
5875
   * Checks if the URL has a fragment/hash component.
5876
   * @return `true` if hash is present, `false` otherwise.
5877
   */
5878
  [[nodiscard]] constexpr bool has_hash() const noexcept override;
5879
5880
  /**
5881
   * Checks if the URL has a query/search component.
5882
   * @return `true` if query is present, `false` otherwise.
5883
   */
5884
  [[nodiscard]] constexpr bool has_search() const noexcept override;
5885
5886
 private:
5887
  friend ada::url ada::parser::parse_url<ada::url>(std::string_view,
5888
                                                   const ada::url*);
5889
  friend ada::url_aggregator ada::parser::parse_url<ada::url_aggregator>(
5890
      std::string_view, const ada::url_aggregator*);
5891
  friend void ada::helpers::strip_trailing_spaces_from_opaque_path<ada::url>(
5892
      ada::url& url);
5893
5894
  friend ada::url ada::parser::parse_url_impl<ada::url, true>(std::string_view,
5895
                                                              const ada::url*);
5896
  friend ada::url_aggregator ada::parser::parse_url_impl<
5897
      ada::url_aggregator, true>(std::string_view, const ada::url_aggregator*);
5898
  friend ada::url_aggregator ada::parser::parse_url_impl<
5899
      ada::url_aggregator, false>(std::string_view, const ada::url_aggregator*);
5900
  template <class result_type>
5901
  friend bool ada::parser::try_parse_simple_absolute(std::string_view,
5902
                                                     result_type&);
5903
  template <class result_type>
5904
  friend bool ada::parser::finish_simple_absolute_with_port(
5905
      std::string_view, result_type&, ada::scheme::type, uint32_t, size_t,
5906
      size_t, size_t, bool);
5907
  template <class result_type>
5908
  friend bool ada::parser::try_parse_simple_relative(std::string_view,
5909
                                                     const result_type&,
5910
                                                     result_type&);
5911
5912
  inline void update_unencoded_base_hash(std::string_view input);
5913
  inline void update_base_hostname(std::string_view input);
5914
  inline void update_base_search(std::string_view input,
5915
                                 const uint8_t query_percent_encode_set[]);
5916
  inline void update_base_search(std::optional<std::string>&& input);
5917
  inline void update_base_pathname(std::string_view input);
5918
  inline void update_base_username(std::string_view input);
5919
  inline void update_base_password(std::string_view input);
5920
  inline void update_base_port(std::optional<uint16_t> input);
5921
5922
  /**
5923
   * Returns true if growing href by input_len (worst case) could exceed
5924
   * get_max_input_length(), meaning a rollback snapshot is actually needed.
5925
   */
5926
  [[nodiscard]] bool needs_rollback_snapshot(size_t input_len) const noexcept;
5927
5928
  /**
5929
   * Sets the host or hostname according to override condition.
5930
   * Return true on success.
5931
   * @see https://url.spec.whatwg.org/#hostname-state
5932
   */
5933
  template <bool override_hostname = false>
5934
  bool set_host_or_hostname(std::string_view input);
5935
5936
  /**
5937
   * Return true on success.
5938
   * @see https://url.spec.whatwg.org/#concept-ipv4-parser
5939
   */
5940
  [[nodiscard]] bool parse_ipv4(std::string_view input);
5941
5942
  /**
5943
   * Return true on success.
5944
   * @see https://url.spec.whatwg.org/#concept-ipv6-parser
5945
   */
5946
  [[nodiscard]] bool parse_ipv6(std::string_view input);
5947
5948
  /**
5949
   * Return true on success.
5950
   * @see https://url.spec.whatwg.org/#concept-opaque-host-parser
5951
   */
5952
  [[nodiscard]] bool parse_opaque_host(std::string_view input);
5953
5954
  /**
5955
   * A URL's scheme is an ASCII string that identifies the type of URL and can
5956
   * be used to dispatch a URL for further processing after parsing. It is
5957
   * initially the empty string. We only set non_special_scheme when the scheme
5958
   * is non-special, otherwise we avoid constructing string.
5959
   *
5960
   * Special schemes are stored in ada::scheme::details::is_special_list so we
5961
   * typically do not need to store them in each url instance.
5962
   */
5963
  std::string non_special_scheme{};
5964
5965
  /**
5966
   * A URL cannot have a username/password/port if its host is null or the empty
5967
   * string, or its scheme is "file".
5968
   */
5969
  [[nodiscard]] inline bool cannot_have_credentials_or_port() const;
5970
5971
  ada_really_inline size_t parse_port(
5972
      std::string_view view, bool check_trailing_content) noexcept override;
5973
5974
0
  ada_really_inline size_t parse_port(std::string_view view) noexcept override {
5975
0
    return this->parse_port(view, false);
5976
0
  }
5977
5978
  /**
5979
   * Parse the host from the provided input. We assume that
5980
   * the input does not contain spaces or tabs. Control
5981
   * characters and spaces are not trimmed (they should have
5982
   * been removed if needed).
5983
   * Return true on success.
5984
   * @see https://url.spec.whatwg.org/#host-parsing
5985
   */
5986
  [[nodiscard]] ada_really_inline bool parse_host(std::string_view input);
5987
5988
  template <bool has_state_override = false>
5989
  [[nodiscard]] ada_really_inline bool parse_scheme(std::string_view input);
5990
5991
  constexpr void clear_pathname() override;
5992
  constexpr void clear_search() override;
5993
  constexpr void set_protocol_as_file();
5994
5995
  /**
5996
   * Parse the path from the provided input.
5997
   * Return true on success. Control characters not
5998
   * trimmed from the ends (they should have
5999
   * been removed if needed).
6000
   *
6001
   * The input is expected to be UTF-8.
6002
   *
6003
   * @see https://url.spec.whatwg.org/
6004
   */
6005
  ada_really_inline void parse_path(std::string_view input);
6006
6007
  /**
6008
   * Set the scheme for this URL. The provided scheme should be a valid
6009
   * scheme string, be lower-cased, not contain spaces or tabs. It should
6010
   * have no spurious trailing or leading content.
6011
   */
6012
  inline void set_scheme(std::string&& new_scheme) noexcept;
6013
6014
  /**
6015
   * Take the scheme from another URL. The scheme string is moved from the
6016
   * provided url.
6017
   */
6018
  constexpr void copy_scheme(ada::url&& u);
6019
6020
  /**
6021
   * Take the scheme from another URL. The scheme string is copied from the
6022
   * provided url.
6023
   */
6024
  constexpr void copy_scheme(const ada::url& u);
6025
6026
};  // struct url
6027
6028
inline std::ostream& operator<<(std::ostream& out, const ada::url& u);
6029
}  // namespace ada
6030
6031
#endif  // ADA_URL_H
6032
/* end file include/ada/url.h */
6033
6034
namespace ada {
6035
6036
/**
6037
 * Result type for URL parsing operations.
6038
 *
6039
 * Uses `tl::expected` to represent either a successfully parsed URL or an
6040
 * error. This allows for exception-free error handling.
6041
 *
6042
 * @tparam result_type The URL type to return (default: `ada::url_aggregator`)
6043
 *
6044
 * @example
6045
 * ```cpp
6046
 * ada::result<ada::url_aggregator> result = ada::parse("https://example.com");
6047
 * if (result) {
6048
 *     // Success: use result.value() or *result
6049
 * } else {
6050
 *     // Error: handle result.error()
6051
 * }
6052
 * ```
6053
 */
6054
template <class result_type = ada::url_aggregator>
6055
using result = tl::expected<result_type, ada::errors>;
6056
6057
/**
6058
 * Parses a URL string according to the WHATWG URL Standard.
6059
 *
6060
 * This is the main entry point for URL parsing in Ada. The function takes
6061
 * a string input and optionally a base URL for resolving relative URLs.
6062
 *
6063
 * @tparam result_type The URL type to return. Can be either `ada::url` or
6064
 *         `ada::url_aggregator` (default). The `url_aggregator` type is more
6065
 *         memory-efficient as it stores components as offsets into a single
6066
 *         buffer.
6067
 *
6068
 * @param input The URL string to parse. Must be valid ASCII or UTF-8 encoded.
6069
 *        Leading and trailing whitespace is automatically trimmed.
6070
 * @param base_url Optional pointer to a base URL for resolving relative URLs.
6071
 *        If nullptr (default), only absolute URLs can be parsed successfully.
6072
 *
6073
 * @return A `result<result_type>` containing either the parsed URL on success,
6074
 *         or an error code on failure. Use the boolean conversion or
6075
 *         `has_value()` to check for success.
6076
 *
6077
 * @note The parser is fully compliant with the WHATWG URL Standard.
6078
 *
6079
 * Parsing fails if the input or the resulting normalized URL exceeds
6080
 * `get_max_input_length()` bytes (default ~4 GB, configurable via
6081
 * `set_max_input_length()`). This accounts for percent-encoding expansion:
6082
 * a short input that normalizes into a long URL is still rejected.
6083
 *
6084
 * @example
6085
 * ```cpp
6086
 * // Parse an absolute URL
6087
 * auto url = ada::parse("https://user:pass@example.com:8080/path?query#hash");
6088
 * if (url) {
6089
 *     std::cout << url->get_hostname(); // "example.com"
6090
 *     std::cout << url->get_pathname(); // "/path"
6091
 * }
6092
 *
6093
 * // Parse a relative URL with a base
6094
 * auto base = ada::parse("https://example.com/dir/");
6095
 * if (base) {
6096
 *     auto relative = ada::parse("../other/page", &*base);
6097
 *     if (relative) {
6098
 *         std::cout << relative->get_href(); //
6099
 * "https://example.com/other/page"
6100
 *     }
6101
 * }
6102
 * ```
6103
 *
6104
 * @see https://url.spec.whatwg.org/#url-parsing
6105
 */
6106
template <class result_type = ada::url_aggregator>
6107
ada_warn_unused ada::result<result_type> parse(
6108
    std::string_view input, const result_type* base_url = nullptr);
6109
6110
extern template ada::result<url> parse<url>(std::string_view input,
6111
                                            const url* base_url);
6112
extern template ada::result<url_aggregator> parse<url_aggregator>(
6113
    std::string_view input, const url_aggregator* base_url);
6114
6115
/**
6116
 * Checks whether a URL string can be successfully parsed.
6117
 *
6118
 * Equivalent to `parse(input, base).has_value()` for every input, including
6119
 * when `set_max_input_length` rejects a normalized href that exceeds the limit.
6120
 *
6121
 * @param input The URL string to validate. Must be valid ASCII or UTF-8.
6122
 * @param base_input Optional base URL string for relative inputs.
6123
 * @return `true` if parsing would succeed, `false` otherwise.
6124
 * @see https://url.spec.whatwg.org/#dom-url-canparse
6125
 */
6126
bool can_parse(std::string_view input,
6127
               const std::string_view* base_input = nullptr);
6128
6129
#if ADA_INCLUDE_URL_PATTERN
6130
/**
6131
 * Parses a URL pattern according to the URLPattern specification.
6132
 *
6133
 * URL patterns provide a syntax for matching URLs against patterns, similar
6134
 * to how regular expressions match strings. This is useful for routing and
6135
 * URL-based dispatching.
6136
 *
6137
 * @tparam regex_provider The regex implementation to use for pattern matching.
6138
 *
6139
 * @param input Either a URL pattern string (valid UTF-8) or a URLPatternInit
6140
 *        struct specifying individual component patterns.
6141
 * @param base_url Optional pointer to a base URL string (valid UTF-8) for
6142
 *        resolving relative patterns.
6143
 * @param options Optional pointer to configuration options (e.g., ignore_case).
6144
 *
6145
 * @return A `tl::expected` containing either the parsed url_pattern on success,
6146
 *         or an error code on failure.
6147
 *
6148
 * @see https://urlpattern.spec.whatwg.org
6149
 */
6150
template <url_pattern_regex::regex_concept regex_provider>
6151
ada_warn_unused tl::expected<url_pattern<regex_provider>, errors>
6152
parse_url_pattern(std::variant<std::string_view, url_pattern_init>&& input,
6153
                  const std::string_view* base_url = nullptr,
6154
                  const url_pattern_options* options = nullptr);
6155
6156
template <url_pattern_regex::regex_concept regex_provider>
6157
class url_pattern_list;
6158
6159
/**
6160
 * Compiles a set of URLPattern pathname patterns into an ada::url_pattern_list
6161
 * (experimental): one structure that answers "which route matches this
6162
 * pathname, and what are its group values?" without a loop over the
6163
 * patterns and without executing regular expressions for routes written in
6164
 * the static / ":param" / "*" subset.
6165
 *
6166
 * @tparam regex_provider The regex implementation, as for parse_url_pattern;
6167
 *         it is used only for routes that need URLPattern regexp semantics.
6168
 *
6169
 * @param pathname_patterns URLPattern pathname patterns (valid UTF-8), for
6170
 *        example "/users/:id". The index of a pattern is the route index
6171
 *        reported by url_pattern_list::match; duplicates are allowed.
6172
 * @param base_url Optional pointer to a base URL string (valid UTF-8): each
6173
 *        pattern is then processed as the pathname of a URLPatternInit with
6174
 *        that base URL (relative patterns resolve against its path).
6175
 * @param options Optional pointer to configuration options (ignore_case),
6176
 *        applied to every route as parse_url_pattern applies them.
6177
 *
6178
 * @return A `tl::expected` containing either the compiled list on success,
6179
 *         or an error code when a pattern is not a valid URLPattern pathname
6180
 *         pattern (errors::type_error, as the URLPattern constructor).
6181
 *
6182
 * @see https://github.com/whatwg/urlpattern/issues/166
6183
 */
6184
template <url_pattern_regex::regex_concept regex_provider>
6185
ada_warn_unused tl::expected<url_pattern_list<regex_provider>, errors>
6186
parse_url_pattern_list(std::span<const std::string_view> pathname_patterns,
6187
                       const std::string_view* base_url = nullptr,
6188
                       const url_pattern_options* options = nullptr);
6189
6190
/**
6191
 * Compiles the pathname components of existing url_pattern objects into an
6192
 * ada::url_pattern_list (experimental). Only the pathname component of each
6193
 * pattern is used; routes that need the regex provider reuse the pattern's
6194
 * already compiled pathname component. All patterns must share the same
6195
 * ignore_case setting (errors::type_error otherwise); the pathname is
6196
 * compiled as for a special-scheme URL.
6197
 */
6198
template <url_pattern_regex::regex_concept regex_provider>
6199
ada_warn_unused tl::expected<url_pattern_list<regex_provider>, errors>
6200
parse_url_pattern_list(std::span<const url_pattern<regex_provider>> patterns);
6201
#endif  // ADA_INCLUDE_URL_PATTERN
6202
6203
/**
6204
 * Converts a file system path to a file:// URL.
6205
 *
6206
 * Creates a properly formatted file URL from a local file system path.
6207
 * Handles platform-specific path separators and percent-encoding.
6208
 *
6209
 * Respects `get_max_input_length()`: if the input path or the resulting
6210
 * `file://` href would exceed the limit, returns an empty string.
6211
 *
6212
 * @param path The file system path to convert. Must be valid ASCII or UTF-8.
6213
 *
6214
 * @return A file:// URL string representing the given path, or empty on
6215
 *         length-limit rejection.
6216
 */
6217
std::string href_from_file(std::string_view path);
6218
6219
/**
6220
 * Sets the maximum allowed length for URLs.
6221
 *
6222
 * Both the raw input and the resulting normalized URL (the href) are checked
6223
 * against this limit. Parsing or setter calls that would produce a URL
6224
 * exceeding this length are rejected. The same limit also applies to
6225
 * `href_from_file` and to query strings passed to `url_search_params`
6226
 * construction / `reset`. The value must fit in a uint32_t.
6227
 * The default is std::numeric_limits<uint32_t>::max() (approximately 4 GB).
6228
 *
6229
 * @param length The new maximum URL length in bytes.
6230
 */
6231
void set_max_input_length(uint32_t length);
6232
6233
/**
6234
 * Returns the current maximum allowed length for URLs.
6235
 *
6236
 * @return The current maximum URL length in bytes.
6237
 */
6238
uint32_t get_max_input_length();
6239
6240
}  // namespace ada
6241
6242
#endif  // ADA_IMPLEMENTATION_H
6243
/* end file include/ada/implementation.h */
6244
6245
#include <cstdint>
6246
#include <optional>
6247
#include <ostream>
6248
#include <string>
6249
#include <string_view>
6250
#include <unordered_map>
6251
#include <utility>
6252
#include <variant>
6253
#include <vector>
6254
6255
#if ADA_TESTING
6256
#include <iostream>
6257
#endif  // ADA_TESTING
6258
6259
#if ADA_INCLUDE_URL_PATTERN
6260
namespace ada {
6261
6262
enum class url_pattern_part_type : uint8_t {
6263
  // The part represents a simple fixed text string.
6264
  FIXED_TEXT,
6265
  // The part represents a matching group with a custom regular expression.
6266
  REGEXP,
6267
  // The part represents a matching group that matches code points up to the
6268
  // next separator code point. This is typically used for a named group like
6269
  // ":foo" that does not have a custom regular expression.
6270
  SEGMENT_WILDCARD,
6271
  // The part represents a matching group that greedily matches all code points.
6272
  // This is typically used for the "*" wildcard matching group.
6273
  FULL_WILDCARD,
6274
};
6275
6276
// Pattern type for fast-path matching optimization.
6277
// This allows skipping expensive regex evaluation for common simple patterns.
6278
enum class url_pattern_component_type : uint8_t {
6279
  // Pattern is "^$" - only matches empty string
6280
  EMPTY,
6281
  // Pattern is "^<literal>$" - exact string match (no regex needed)
6282
  EXACT_MATCH,
6283
  // Pattern is "^(.*)$" - matches anything (full wildcard)
6284
  FULL_WILDCARD,
6285
  // Pattern requires actual regex evaluation
6286
  REGEXP,
6287
};
6288
6289
enum class url_pattern_part_modifier : uint8_t {
6290
  // The part does not have a modifier.
6291
  none,
6292
  // The part has an optional modifier indicated by the U+003F (?) code point.
6293
  optional,
6294
  // The part has a "zero or more" modifier indicated by the U+002A (*) code
6295
  // point.
6296
  zero_or_more,
6297
  // The part has a "one or more" modifier indicated by the U+002B (+) code
6298
  // point.
6299
  one_or_more,
6300
};
6301
6302
// @see https://urlpattern.spec.whatwg.org/#part
6303
class url_pattern_part {
6304
 public:
6305
  url_pattern_part(url_pattern_part_type _type, std::string&& _value,
6306
                   url_pattern_part_modifier _modifier)
6307
0
      : type(_type), value(std::move(_value)), modifier(_modifier) {}
6308
6309
  url_pattern_part(url_pattern_part_type _type, std::string&& _value,
6310
                   url_pattern_part_modifier _modifier, std::string&& _name,
6311
                   std::string&& _prefix, std::string&& _suffix)
6312
0
      : type(_type),
6313
0
        value(std::move(_value)),
6314
0
        modifier(_modifier),
6315
0
        name(std::move(_name)),
6316
0
        prefix(std::move(_prefix)),
6317
0
        suffix(std::move(_suffix)) {}
6318
  // A part has an associated type, a string, which must be set upon creation.
6319
  url_pattern_part_type type;
6320
  // A part has an associated value, a string, which must be set upon creation.
6321
  std::string value;
6322
  // A part has an associated modifier a string, which must be set upon
6323
  // creation.
6324
  url_pattern_part_modifier modifier;
6325
  // A part has an associated name, a string, initially the empty string.
6326
  std::string name{};
6327
  // A part has an associated prefix, a string, initially the empty string.
6328
  std::string prefix{};
6329
  // A part has an associated suffix, a string, initially the empty string.
6330
  std::string suffix{};
6331
6332
  inline bool is_regexp() const noexcept;
6333
};
6334
6335
// @see https://urlpattern.spec.whatwg.org/#options-header
6336
struct url_pattern_compile_component_options {
6337
  url_pattern_compile_component_options() = default;
6338
  explicit url_pattern_compile_component_options(
6339
      std::optional<char> new_delimiter = std::nullopt,
6340
      std::optional<char> new_prefix = std::nullopt) noexcept
6341
6
      : delimiter(new_delimiter), prefix(new_prefix) {}
6342
6343
  inline std::string_view get_delimiter() const ada_warn_unused;
6344
  inline std::string_view get_prefix() const ada_warn_unused;
6345
6346
  // @see https://urlpattern.spec.whatwg.org/#options-ignore-case
6347
  bool ignore_case = false;
6348
6349
  static url_pattern_compile_component_options DEFAULT;
6350
  static url_pattern_compile_component_options HOSTNAME;
6351
  static url_pattern_compile_component_options PATHNAME;
6352
6353
 private:
6354
  // @see https://urlpattern.spec.whatwg.org/#options-delimiter-code-point
6355
  std::optional<char> delimiter{};
6356
  // @see https://urlpattern.spec.whatwg.org/#options-prefix-code-point
6357
  std::optional<char> prefix{};
6358
};
6359
6360
// The default options is an options struct with delimiter code point set to
6361
// the empty string and prefix code point set to the empty string.
6362
inline url_pattern_compile_component_options
6363
    url_pattern_compile_component_options::DEFAULT(std::nullopt, std::nullopt);
6364
6365
// The hostname options is an options struct with delimiter code point set
6366
// "." and prefix code point set to the empty string.
6367
inline url_pattern_compile_component_options
6368
    url_pattern_compile_component_options::HOSTNAME('.', std::nullopt);
6369
6370
// The pathname options is an options struct with delimiter code point set
6371
// "/" and prefix code point set to "/".
6372
inline url_pattern_compile_component_options
6373
    url_pattern_compile_component_options::PATHNAME('/', '/');
6374
6375
// A struct providing the URLPattern matching results for a single
6376
// URL component. The URLPatternComponentResult is only ever used
6377
// as a member attribute of a URLPatternResult struct. The
6378
// URLPatternComponentResult API is defined as part of the URLPattern
6379
// specification.
6380
struct url_pattern_component_result {
6381
  std::string input;
6382
  std::unordered_map<std::string, std::optional<std::string>> groups;
6383
6384
  bool operator==(const url_pattern_component_result&) const;
6385
6386
#if ADA_TESTING
6387
  friend void PrintTo(const url_pattern_component_result& result,
6388
                      std::ostream* os) {
6389
    *os << "input: '" << result.input << "', group: ";
6390
    for (const auto& group : result.groups) {
6391
      *os << "(" << group.first << ", " << group.second.value_or("undefined")
6392
          << ") ";
6393
    }
6394
  }
6395
#endif  // ADA_TESTING
6396
};
6397
6398
template <url_pattern_regex::regex_concept regex_provider>
6399
class url_pattern_component {
6400
 public:
6401
  url_pattern_component() = default;
6402
6403
  // This function explicitly takes a std::string because it is moved.
6404
  // To avoid unnecessary copy, move each value while calling the constructor.
6405
  url_pattern_component(std::string&& new_pattern,
6406
                        typename regex_provider::regex_type&& new_regexp,
6407
                        std::vector<std::string>&& new_group_name_list,
6408
                        bool new_has_regexp_groups,
6409
                        url_pattern_component_type new_type,
6410
                        std::string&& new_exact_match_value = {})
6411
      : regexp(std::move(new_regexp)),
6412
        pattern(std::move(new_pattern)),
6413
        group_name_list(std::move(new_group_name_list)),
6414
        exact_match_value(std::move(new_exact_match_value)),
6415
        has_regexp_groups(new_has_regexp_groups),
6416
        type(new_type) {}
6417
6418
  // @see https://urlpattern.spec.whatwg.org/#compile-a-component
6419
  template <url_pattern_encoding_callback F>
6420
  static tl::expected<url_pattern_component, errors> compile(
6421
      std::string_view input, F& encoding_callback,
6422
      url_pattern_compile_component_options& options);
6423
6424
  // @see https://urlpattern.spec.whatwg.org/#create-a-component-match-result
6425
  url_pattern_component_result create_component_match_result(
6426
      std::string&& input,
6427
      std::vector<std::optional<std::string>>&& exec_result);
6428
6429
  // Fast path test that returns true/false without constructing result groups.
6430
  // Uses cached pattern type to skip regex evaluation for simple patterns.
6431
  // Note: Not marked noexcept because the regex provider may throw.
6432
  bool fast_test(std::string_view input) const;
6433
6434
  // Fast path match that returns capture groups without regex for simple
6435
  // patterns. Returns nullopt if pattern doesn't match, otherwise returns
6436
  // capture groups.
6437
  std::optional<std::vector<std::optional<std::string>>> fast_match(
6438
      std::string_view input) const;
6439
6440
#if ADA_TESTING
6441
  friend void PrintTo(const url_pattern_component& component,
6442
                      std::ostream* os) {
6443
    *os << "pattern: '" << component.pattern
6444
        << "', has_regexp_groups: " << component.has_regexp_groups
6445
        << "group_name_list: ";
6446
    for (const auto& name : component.group_name_list) {
6447
      *os << name << ", ";
6448
    }
6449
  }
6450
#endif  // ADA_TESTING
6451
6452
  typename regex_provider::regex_type regexp{};
6453
  std::string pattern{};
6454
  std::vector<std::string> group_name_list{};
6455
  // For EXACT_MATCH type: the literal string to compare against
6456
  std::string exact_match_value{};
6457
  bool has_regexp_groups = false;
6458
  // Cached pattern type for fast-path optimization
6459
  url_pattern_component_type type = url_pattern_component_type::REGEXP;
6460
};
6461
6462
// A URLPattern input can be either a string or a URLPatternInit object.
6463
// If it is a string, it must be a valid UTF-8 string.
6464
using url_pattern_input = std::variant<std::string_view, url_pattern_init>;
6465
6466
// A struct providing the URLPattern matching results for all
6467
// components of a URL. The URLPatternResult API is defined as
6468
// part of the URLPattern specification.
6469
//
6470
// string_view entries in `inputs` that were filled by exec/match
6471
// point at storage owned by this object and stay valid for its
6472
// lifetime, including after copy and move.
6473
struct url_pattern_result {
6474
  std::vector<url_pattern_input> inputs;
6475
  url_pattern_component_result protocol;
6476
  url_pattern_component_result username;
6477
  url_pattern_component_result password;
6478
  url_pattern_component_result hostname;
6479
  url_pattern_component_result port;
6480
  url_pattern_component_result pathname;
6481
  url_pattern_component_result search;
6482
  url_pattern_component_result hash;
6483
6484
  url_pattern_result() = default;
6485
  url_pattern_result(const url_pattern_result& other);
6486
  url_pattern_result(url_pattern_result&& other) noexcept;
6487
  url_pattern_result& operator=(const url_pattern_result& other);
6488
  url_pattern_result& operator=(url_pattern_result&& other) noexcept;
6489
  ~url_pattern_result() = default;
6490
6491
 private:
6492
  // At most two strings: the input URL and the optional base URL.
6493
  // Filled only by store_inputs.
6494
  std::vector<std::string> owned_strings_{};
6495
6496
  // Point each inputs[] view that aliases `from[i]` at the same
6497
  // offset inside owned_strings_[i].
6498
  void rebind_owned_input_views(const std::pair<const char*, size_t>* from,
6499
                                size_t from_size);
6500
  // Move inputs + owned_strings_ from other and rebind. other is
6501
  // left with empty inputs / owned_strings_. Component results are
6502
  // not touched.
6503
  void take_inputs(url_pattern_result& other) noexcept;
6504
  void store_inputs(const url_pattern_input& input,
6505
                    const std::string_view* base_url = nullptr);
6506
6507
  template <url_pattern_regex::regex_concept regex_provider>
6508
  friend class url_pattern;
6509
};
6510
6511
struct url_pattern_options {
6512
  bool ignore_case = false;
6513
6514
#if ADA_TESTING
6515
  friend void PrintTo(const url_pattern_options& options, std::ostream* os) {
6516
    *os << "ignore_case: '" << options.ignore_case;
6517
  }
6518
#endif  // ADA_TESTING
6519
};
6520
6521
/**
6522
 * @brief URL pattern matching class implementing the URLPattern API.
6523
 *
6524
 * URLPattern provides a way to match URLs against patterns with wildcards
6525
 * and named capture groups. It's useful for routing, URL-based dispatching,
6526
 * and URL validation.
6527
 *
6528
 * Pattern syntax supports:
6529
 * - Literal text matching
6530
 * - Named groups: `:name` (matches up to the next separator)
6531
 * - Wildcards: `*` (matches everything)
6532
 * - Custom regex: `(pattern)`
6533
 * - Optional segments: `:name?`
6534
 * - Repeated segments: `:name+`, `:name*`
6535
 *
6536
 * @tparam regex_provider The regex implementation to use for pattern matching.
6537
 *         Must satisfy the url_pattern_regex::regex_concept.
6538
 *
6539
 * @note All string inputs must be valid UTF-8.
6540
 *
6541
 * @see https://urlpattern.spec.whatwg.org/
6542
 */
6543
template <url_pattern_regex::regex_concept regex_provider>
6544
class url_pattern {
6545
 public:
6546
  url_pattern() = default;
6547
6548
  /**
6549
   * If non-null, base_url must pointer at a valid UTF-8 string.
6550
   * @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-exec
6551
   */
6552
  result<std::optional<url_pattern_result>> exec(
6553
      const url_pattern_input& input,
6554
      const std::string_view* base_url = nullptr);
6555
6556
  /**
6557
   * If non-null, base_url must pointer at a valid UTF-8 string.
6558
   * @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-test
6559
   */
6560
  result<bool> test(const url_pattern_input& input,
6561
                    const std::string_view* base_url = nullptr);
6562
6563
  /**
6564
   * @see https://urlpattern.spec.whatwg.org/#url-pattern-match
6565
   * This function expects a valid UTF-8 string if input is a string.
6566
   */
6567
  result<std::optional<url_pattern_result>> match(
6568
      const url_pattern_input& input,
6569
      const std::string_view* base_url_string = nullptr);
6570
6571
  // @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-protocol
6572
  [[nodiscard]] std::string_view get_protocol() const ada_lifetime_bound;
6573
  // @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-username
6574
  [[nodiscard]] std::string_view get_username() const ada_lifetime_bound;
6575
  // @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-password
6576
  [[nodiscard]] std::string_view get_password() const ada_lifetime_bound;
6577
  // @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-hostname
6578
  [[nodiscard]] std::string_view get_hostname() const ada_lifetime_bound;
6579
  // @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-port
6580
  [[nodiscard]] std::string_view get_port() const ada_lifetime_bound;
6581
  // @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-pathname
6582
  [[nodiscard]] std::string_view get_pathname() const ada_lifetime_bound;
6583
  // @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-search
6584
  [[nodiscard]] std::string_view get_search() const ada_lifetime_bound;
6585
  // @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-hash
6586
  [[nodiscard]] std::string_view get_hash() const ada_lifetime_bound;
6587
6588
  // If ignoreCase is true, the JavaScript regular expression created for each
6589
  // pattern must use the `vi` flag. Otherwise, they must use the `v` flag.
6590
  [[nodiscard]] bool ignore_case() const;
6591
6592
  // @see https://urlpattern.spec.whatwg.org/#url-pattern-has-regexp-groups
6593
  [[nodiscard]] bool has_regexp_groups() const;
6594
6595
  // Helper to test all components at once. Returns true if all match.
6596
  [[nodiscard]] bool test_components(
6597
      std::string_view protocol, std::string_view username,
6598
      std::string_view password, std::string_view hostname,
6599
      std::string_view port, std::string_view pathname, std::string_view search,
6600
      std::string_view hash) const;
6601
6602
#if ADA_TESTING
6603
  friend void PrintTo(const url_pattern& c, std::ostream* os) {
6604
    *os << "protocol_component: '" << c.get_protocol() << ", ";
6605
    *os << "username_component: '" << c.get_username() << ", ";
6606
    *os << "password_component: '" << c.get_password() << ", ";
6607
    *os << "hostname_component: '" << c.get_hostname() << ", ";
6608
    *os << "port_component: '" << c.get_port() << ", ";
6609
    *os << "pathname_component: '" << c.get_pathname() << ", ";
6610
    *os << "search_component: '" << c.get_search() << ", ";
6611
    *os << "hash_component: '" << c.get_hash();
6612
  }
6613
#endif  // ADA_TESTING
6614
6615
  template <url_pattern_regex::regex_concept P>
6616
  friend tl::expected<url_pattern<P>, errors> parser::parse_url_pattern_impl(
6617
      std::variant<std::string_view, url_pattern_init>&& input,
6618
      const std::string_view* base_url, const url_pattern_options* options);
6619
6620
  /**
6621
   * @private
6622
   * We can not make this private due to a LLVM bug.
6623
   * Ref: https://github.com/ada-url/ada/pull/859
6624
   */
6625
  url_pattern_component<regex_provider> protocol_component{};
6626
  /**
6627
   * @private
6628
   * We can not make this private due to a LLVM bug.
6629
   * Ref: https://github.com/ada-url/ada/pull/859
6630
   */
6631
  url_pattern_component<regex_provider> username_component{};
6632
  /**
6633
   * @private
6634
   * We can not make this private due to a LLVM bug.
6635
   * Ref: https://github.com/ada-url/ada/pull/859
6636
   */
6637
  url_pattern_component<regex_provider> password_component{};
6638
  /**
6639
   * @private
6640
   * We can not make this private due to a LLVM bug.
6641
   * Ref: https://github.com/ada-url/ada/pull/859
6642
   */
6643
  url_pattern_component<regex_provider> hostname_component{};
6644
  /**
6645
   * @private
6646
   * We can not make this private due to a LLVM bug.
6647
   * Ref: https://github.com/ada-url/ada/pull/859
6648
   */
6649
  url_pattern_component<regex_provider> port_component{};
6650
  /**
6651
   * @private
6652
   * We can not make this private due to a LLVM bug.
6653
   * Ref: https://github.com/ada-url/ada/pull/859
6654
   */
6655
  url_pattern_component<regex_provider> pathname_component{};
6656
  /**
6657
   * @private
6658
   * We can not make this private due to a LLVM bug.
6659
   * Ref: https://github.com/ada-url/ada/pull/859
6660
   */
6661
  url_pattern_component<regex_provider> search_component{};
6662
  /**
6663
   * @private
6664
   * We can not make this private due to a LLVM bug.
6665
   * Ref: https://github.com/ada-url/ada/pull/859
6666
   */
6667
  url_pattern_component<regex_provider> hash_component{};
6668
  /**
6669
   * @private
6670
   * We can not make this private due to a LLVM bug.
6671
   * Ref: https://github.com/ada-url/ada/pull/859
6672
   */
6673
  bool ignore_case_ = false;
6674
};
6675
}  // namespace ada
6676
#endif  // ADA_INCLUDE_URL_PATTERN
6677
#endif
6678
/* end file include/ada/url_pattern.h */
6679
/* begin file include/ada/url_pattern_helpers.h */
6680
/**
6681
 * @file url_pattern_helpers.h
6682
 * @brief Declaration for the URLPattern helpers.
6683
 */
6684
#ifndef ADA_URL_PATTERN_HELPERS_H
6685
#define ADA_URL_PATTERN_HELPERS_H
6686
6687
6688
#include <cstddef>
6689
#include <cstdint>
6690
#include <optional>
6691
#include <string>
6692
#include <string_view>
6693
#include <tuple>
6694
#include <unordered_set>
6695
#include <utility>
6696
#include <vector>
6697
6698
#if ADA_INCLUDE_URL_PATTERN
6699
namespace ada {
6700
enum class errors : uint8_t;
6701
}
6702
6703
namespace ada::url_pattern_helpers {
6704
6705
// @see https://urlpattern.spec.whatwg.org/#token
6706
enum class token_type : uint8_t {
6707
  INVALID_CHAR,    // 0
6708
  OPEN,            // 1
6709
  CLOSE,           // 2
6710
  REGEXP,          // 3
6711
  NAME,            // 4
6712
  CHAR,            // 5
6713
  ESCAPED_CHAR,    // 6
6714
  OTHER_MODIFIER,  // 7
6715
  ASTERISK,        // 8
6716
  END,             // 9
6717
};
6718
6719
#ifdef ADA_TESTING
6720
std::string to_string(token_type type);
6721
#endif  // ADA_TESTING
6722
6723
// @see https://urlpattern.spec.whatwg.org/#tokenize-policy
6724
enum class token_policy {
6725
  strict,
6726
  lenient,
6727
};
6728
6729
// @see https://urlpattern.spec.whatwg.org/#tokens
6730
class token {
6731
 public:
6732
  token(token_type _type, size_t _index, std::string_view _value)
6733
0
      : type(_type), index(_index), value(_value) {}
6734
6735
  // A token has an associated type, a string, initially "invalid-char".
6736
  token_type type = token_type::INVALID_CHAR;
6737
6738
  // A token has an associated index, a number, initially 0. It is the position
6739
  // of the first code point in the pattern string represented by the token.
6740
  size_t index = 0;
6741
6742
  // A token has an associated value, a string, initially the empty string. It
6743
  // contains the code points from the pattern string represented by the token.
6744
  std::string_view value{};
6745
};
6746
6747
// @see https://urlpattern.spec.whatwg.org/#pattern-parser
6748
template <url_pattern_encoding_callback F>
6749
class url_pattern_parser {
6750
 public:
6751
  url_pattern_parser(F& encoding_callback_,
6752
                     std::string_view segment_wildcard_regexp_)
6753
0
      : encoding_callback(encoding_callback_),
6754
0
        segment_wildcard_regexp(segment_wildcard_regexp_) {}
6755
6756
0
  bool can_continue() const { return index < tokens.size(); }
6757
6758
  // @see https://urlpattern.spec.whatwg.org/#try-to-consume-a-token
6759
  token* try_consume_token(token_type type);
6760
  // @see https://urlpattern.spec.whatwg.org/#try-to-consume-a-modifier-token
6761
  token* try_consume_modifier_token();
6762
  // @see
6763
  // https://urlpattern.spec.whatwg.org/#try-to-consume-a-regexp-or-wildcard-token
6764
  token* try_consume_regexp_or_wildcard_token(const token* name_token);
6765
  // @see https://urlpattern.spec.whatwg.org/#consume-text
6766
  std::string consume_text();
6767
  // @see https://urlpattern.spec.whatwg.org/#consume-a-required-token
6768
  bool consume_required_token(token_type type);
6769
  // @see
6770
  // https://urlpattern.spec.whatwg.org/#maybe-add-a-part-from-the-pending-fixed-value
6771
  std::optional<errors> maybe_add_part_from_the_pending_fixed_value()
6772
      ada_warn_unused;
6773
  // @see https://urlpattern.spec.whatwg.org/#add-a-part
6774
  std::optional<errors> add_part(std::string_view prefix, token* name_token,
6775
                                 token* regexp_or_wildcard_token,
6776
                                 std::string_view suyffix,
6777
                                 token* modifier_token) ada_warn_unused;
6778
6779
  std::vector<token> tokens{};
6780
  F& encoding_callback;
6781
  std::string segment_wildcard_regexp;
6782
  std::vector<url_pattern_part> parts{};
6783
  std::string pending_fixed_value{};
6784
  size_t index = 0;
6785
  size_t next_numeric_name = 0;
6786
  // Names already taken by a part, for the "is a duplicate name" check in
6787
  // add_part. A linear scan of the part list there is O(n^2) over a pattern
6788
  // with n named parts (e.g. "/*" repeated); this set keeps it amortized O(1).
6789
  std::unordered_set<std::string> seen_names{};
6790
};
6791
6792
// @see https://urlpattern.spec.whatwg.org/#tokenizer
6793
class Tokenizer {
6794
 public:
6795
  explicit Tokenizer(std::string_view new_input, token_policy new_policy)
6796
0
      : input(new_input), policy(new_policy) {}
6797
6798
  // @see https://urlpattern.spec.whatwg.org/#get-the-next-code-point
6799
  constexpr void get_next_code_point();
6800
6801
  // True when the most recent decoded unit was malformed UTF-8.
6802
0
  bool had_invalid_code_point() const { return invalid_code_point; }
6803
6804
  // @see https://urlpattern.spec.whatwg.org/#seek-and-get-the-next-code-point
6805
  constexpr void seek_and_get_next_code_point(size_t index);
6806
6807
  // @see https://urlpattern.spec.whatwg.org/#add-a-token
6808
6809
  void add_token(token_type type, size_t next_position, size_t value_position,
6810
                 size_t value_length);
6811
6812
  // @see https://urlpattern.spec.whatwg.org/#add-a-token-with-default-length
6813
  void add_token_with_default_length(token_type type, size_t next_position,
6814
                                     size_t value_position);
6815
6816
  // @see
6817
  // https://urlpattern.spec.whatwg.org/#add-a-token-with-default-position-and-length
6818
  void add_token_with_defaults(token_type type);
6819
6820
  // @see https://urlpattern.spec.whatwg.org/#process-a-tokenizing-error
6821
  std::optional<errors> process_tokenizing_error(
6822
      size_t next_position, size_t value_position) ada_warn_unused;
6823
6824
  friend tl::expected<std::vector<token>, errors> tokenize(
6825
      std::string_view input, token_policy policy);
6826
6827
 private:
6828
  // has an associated input, a pattern string, initially the empty string.
6829
  std::string_view input;
6830
  // has an associated policy, a tokenize policy, initially "strict".
6831
  token_policy policy;
6832
  // has an associated token list, a token list, initially an empty list.
6833
  std::vector<token> token_list{};
6834
  // has an associated index, a number, initially 0.
6835
  size_t index = 0;
6836
  // has an associated next index, a number, initially 0.
6837
  size_t next_index = 0;
6838
  // has an associated code point, a Unicode code point, initially null.
6839
  char32_t code_point{};
6840
  // Tracks whether the last decoded code point was malformed UTF-8.
6841
  bool invalid_code_point = false;
6842
};
6843
6844
// @see https://urlpattern.spec.whatwg.org/#constructor-string-parser
6845
template <url_pattern_regex::regex_concept regex_provider>
6846
struct constructor_string_parser {
6847
  explicit constructor_string_parser(std::string_view new_input,
6848
                                     std::vector<token>&& new_token_list)
6849
      : input(new_input), token_list(std::move(new_token_list)) {}
6850
  // @see https://urlpattern.spec.whatwg.org/#parse-a-constructor-string
6851
  static tl::expected<url_pattern_init, errors> parse(std::string_view input);
6852
6853
  // @see https://urlpattern.spec.whatwg.org/#constructor-string-parser-state
6854
  enum class State {
6855
    INIT,
6856
    PROTOCOL,
6857
    AUTHORITY,
6858
    USERNAME,
6859
    PASSWORD,
6860
    HOSTNAME,
6861
    PORT,
6862
    PATHNAME,
6863
    SEARCH,
6864
    HASH,
6865
    DONE,
6866
  };
6867
6868
  // @see
6869
  // https://urlpattern.spec.whatwg.org/#compute-protocol-matches-a-special-scheme-flag
6870
  std::optional<errors> compute_protocol_matches_special_scheme_flag();
6871
6872
 private:
6873
  // @see https://urlpattern.spec.whatwg.org/#rewind
6874
  constexpr void rewind();
6875
6876
  // @see https://urlpattern.spec.whatwg.org/#is-a-hash-prefix
6877
  constexpr bool is_hash_prefix();
6878
6879
  // @see https://urlpattern.spec.whatwg.org/#is-a-search-prefix
6880
  constexpr bool is_search_prefix();
6881
6882
  // @see https://urlpattern.spec.whatwg.org/#change-state
6883
  void change_state(State state, size_t skip);
6884
6885
  // @see https://urlpattern.spec.whatwg.org/#is-a-group-open
6886
  constexpr bool is_group_open() const;
6887
6888
  // @see https://urlpattern.spec.whatwg.org/#is-a-group-close
6889
  constexpr bool is_group_close() const;
6890
6891
  // @see https://urlpattern.spec.whatwg.org/#is-a-protocol-suffix
6892
  constexpr bool is_protocol_suffix() const;
6893
6894
  // @see https://urlpattern.spec.whatwg.org/#next-is-authority-slashes
6895
  constexpr bool next_is_authority_slashes() const;
6896
6897
  // @see https://urlpattern.spec.whatwg.org/#is-an-identity-terminator
6898
  constexpr bool is_an_identity_terminator() const;
6899
6900
  // @see https://urlpattern.spec.whatwg.org/#is-a-pathname-start
6901
  constexpr bool is_pathname_start() const;
6902
6903
  // @see https://urlpattern.spec.whatwg.org/#is-a-password-prefix
6904
  constexpr bool is_password_prefix() const;
6905
6906
  // @see https://urlpattern.spec.whatwg.org/#is-an-ipv6-open
6907
  constexpr bool is_an_ipv6_open() const;
6908
6909
  // @see https://urlpattern.spec.whatwg.org/#is-an-ipv6-close
6910
  constexpr bool is_an_ipv6_close() const;
6911
6912
  // @see https://urlpattern.spec.whatwg.org/#is-a-port-prefix
6913
  constexpr bool is_port_prefix() const;
6914
6915
  // @see https://urlpattern.spec.whatwg.org/#is-a-non-special-pattern-char
6916
  constexpr bool is_non_special_pattern_char(size_t index,
6917
                                             uint32_t value) const;
6918
6919
  // @see https://urlpattern.spec.whatwg.org/#get-a-safe-token
6920
  constexpr const token* get_safe_token(size_t index) const;
6921
6922
  // @see https://urlpattern.spec.whatwg.org/#make-a-component-string
6923
  std::string make_component_string();
6924
  // has an associated input, a string, which must be set upon creation.
6925
  std::string_view input;
6926
  // has an associated token list, a token list, which must be set upon
6927
  // creation.
6928
  std::vector<token> token_list;
6929
  // has an associated result, a URLPatternInit, initially set to a new
6930
  // URLPatternInit.
6931
  url_pattern_init result{};
6932
  // has an associated component start, a number, initially set to 0.
6933
  size_t component_start = 0;
6934
  // has an associated token index, a number, initially set to 0.
6935
  size_t token_index = 0;
6936
  // has an associated token increment, a number, initially set to 1.
6937
  size_t token_increment = 1;
6938
  // has an associated group depth, a number, initially set to 0.
6939
  size_t group_depth = 0;
6940
  // has an associated hostname IPv6 bracket depth, a number, initially set to
6941
  // 0.
6942
  size_t hostname_ipv6_bracket_depth = 0;
6943
  // has an associated protocol matches a special scheme flag, a boolean,
6944
  // initially set to false.
6945
  bool protocol_matches_a_special_scheme_flag = false;
6946
  // has an associated state, a string, initially set to "init".
6947
  State state = State::INIT;
6948
};
6949
6950
// @see https://urlpattern.spec.whatwg.org/#canonicalize-a-protocol
6951
tl::expected<std::string, errors> canonicalize_protocol(std::string_view input);
6952
6953
// @see https://wicg.github.io/urlpattern/#canonicalize-a-username
6954
tl::expected<std::string, errors> canonicalize_username(std::string_view input);
6955
6956
// @see https://wicg.github.io/urlpattern/#canonicalize-a-password
6957
tl::expected<std::string, errors> canonicalize_password(std::string_view input);
6958
6959
// @see https://wicg.github.io/urlpattern/#canonicalize-a-password
6960
tl::expected<std::string, errors> canonicalize_hostname(std::string_view input);
6961
6962
// @see https://wicg.github.io/urlpattern/#canonicalize-an-ipv6-hostname
6963
tl::expected<std::string, errors> canonicalize_ipv6_hostname(
6964
    std::string_view input);
6965
6966
// @see https://wicg.github.io/urlpattern/#canonicalize-a-port
6967
tl::expected<std::string, errors> canonicalize_port(std::string_view input);
6968
6969
// @see https://wicg.github.io/urlpattern/#canonicalize-a-port
6970
tl::expected<std::string, errors> canonicalize_port_with_protocol(
6971
    std::string_view input, std::string_view protocol);
6972
6973
// @see https://wicg.github.io/urlpattern/#canonicalize-a-pathname
6974
tl::expected<std::string, errors> canonicalize_pathname(std::string_view input);
6975
6976
// @see https://wicg.github.io/urlpattern/#canonicalize-an-opaque-pathname
6977
tl::expected<std::string, errors> canonicalize_opaque_pathname(
6978
    std::string_view input);
6979
6980
// @see https://wicg.github.io/urlpattern/#canonicalize-a-search
6981
tl::expected<std::string, errors> canonicalize_search(std::string_view input);
6982
6983
// @see https://wicg.github.io/urlpattern/#canonicalize-a-hash
6984
tl::expected<std::string, errors> canonicalize_hash(std::string_view input);
6985
6986
// @see https://urlpattern.spec.whatwg.org/#tokenize
6987
tl::expected<std::vector<token>, errors> tokenize(std::string_view input,
6988
                                                  token_policy policy);
6989
6990
// @see https://urlpattern.spec.whatwg.org/#process-a-base-url-string
6991
std::string process_base_url_string(std::string_view input,
6992
                                    url_pattern_init::process_type type);
6993
6994
// @see https://urlpattern.spec.whatwg.org/#escape-a-pattern-string
6995
std::string escape_pattern_string(std::string_view input);
6996
6997
// @see https://urlpattern.spec.whatwg.org/#escape-a-regexp-string
6998
std::string escape_regexp_string(std::string_view input);
6999
7000
// @see https://urlpattern.spec.whatwg.org/#is-an-absolute-pathname
7001
constexpr bool is_absolute_pathname(
7002
    std::string_view input, url_pattern_init::process_type type) noexcept;
7003
7004
// @see https://urlpattern.spec.whatwg.org/#parse-a-pattern-string
7005
template <url_pattern_encoding_callback F>
7006
tl::expected<std::vector<url_pattern_part>, errors> parse_pattern_string(
7007
    std::string_view input, url_pattern_compile_component_options& options,
7008
    F& encoding_callback);
7009
7010
// @see https://urlpattern.spec.whatwg.org/#generate-a-pattern-string
7011
std::string generate_pattern_string(
7012
    std::vector<url_pattern_part>& part_list,
7013
    url_pattern_compile_component_options& options);
7014
7015
// @see
7016
// https://urlpattern.spec.whatwg.org/#generate-a-regular-expression-and-name-list
7017
std::tuple<std::string, std::vector<std::string>>
7018
generate_regular_expression_and_name_list(
7019
    const std::vector<url_pattern_part>& part_list,
7020
    url_pattern_compile_component_options options);
7021
7022
// @see https://urlpattern.spec.whatwg.org/#hostname-pattern-is-an-ipv6-address
7023
bool is_ipv6_address(std::string_view input) noexcept;
7024
7025
// @see
7026
// https://urlpattern.spec.whatwg.org/#protocol-component-matches-a-special-scheme
7027
template <url_pattern_regex::regex_concept regex_provider>
7028
bool protocol_component_matches_special_scheme(
7029
    ada::url_pattern_component<regex_provider>& input);
7030
7031
// @see https://urlpattern.spec.whatwg.org/#convert-a-modifier-to-a-string
7032
std::string_view convert_modifier_to_string(url_pattern_part_modifier modifier);
7033
7034
// @see https://urlpattern.spec.whatwg.org/#generate-a-segment-wildcard-regexp
7035
std::string generate_segment_wildcard_regexp(
7036
    url_pattern_compile_component_options options);
7037
7038
}  // namespace ada::url_pattern_helpers
7039
#endif  // ADA_INCLUDE_URL_PATTERN
7040
#endif
7041
/* end file include/ada/url_pattern_helpers.h */
7042
7043
#include <cstdint>
7044
#include <string>
7045
#include <string_view>
7046
#include <utility>
7047
#include <variant>
7048
7049
namespace ada::parser {
7050
#if ADA_INCLUDE_URL_PATTERN
7051
template <url_pattern_regex::regex_concept regex_provider>
7052
tl::expected<url_pattern<regex_provider>, errors> parse_url_pattern_impl(
7053
    std::variant<std::string_view, url_pattern_init>&& input,
7054
    const std::string_view* base_url, const url_pattern_options* options) {
7055
  // Let init be null.
7056
  url_pattern_init init;
7057
7058
  // If input is a scalar value string then:
7059
  if (std::holds_alternative<std::string_view>(input)) {
7060
    // Set init to the result of running parse a constructor string given input.
7061
    auto parse_result =
7062
        url_pattern_helpers::constructor_string_parser<regex_provider>::parse(
7063
            std::get<std::string_view>(input));
7064
    if (!parse_result) {
7065
      ada_log("constructor_string_parser::parse failed");
7066
      return tl::unexpected(parse_result.error());
7067
    }
7068
    init = std::move(*parse_result);
7069
    // If baseURL is null and init["protocol"] does not exist, then throw a
7070
    // TypeError.
7071
    if (!base_url && !init.protocol) {
7072
      ada_log("base url is null and protocol is not set");
7073
      return tl::unexpected(errors::type_error);
7074
    }
7075
7076
    // If baseURL is not null, set init["baseURL"] to baseURL.
7077
    if (base_url) {
7078
      init.base_url = std::string(*base_url);
7079
    }
7080
  } else {
7081
    // Assert: input is a URLPatternInit.
7082
    ADA_ASSERT_TRUE(std::holds_alternative<url_pattern_init>(input));
7083
    // If baseURL is not null, then throw a TypeError.
7084
    if (base_url) {
7085
      ada_log("base url is not null");
7086
      return tl::unexpected(errors::type_error);
7087
    }
7088
    // Optimization: Avoid copy by moving the input value.
7089
    // Set init to input.
7090
    init = std::move(std::get<url_pattern_init>(input));
7091
  }
7092
7093
  // Let processedInit be the result of process a URLPatternInit given init,
7094
  // "pattern", null, null, null, null, null, null, null, and null.
7095
  auto processed_init =
7096
      url_pattern_init::process(init, url_pattern_init::process_type::pattern);
7097
  if (!processed_init) {
7098
    ada_log("url_pattern_init::process failed for init and 'pattern'");
7099
    return tl::unexpected(processed_init.error());
7100
  }
7101
7102
  // For each componentName of  "protocol", "username", "password", "hostname",
7103
  // "port", "pathname", "search", "hash" If processedInit[componentName] does
7104
  // not exist, then set processedInit[componentName] to "*".
7105
  ADA_ASSERT_TRUE(processed_init.has_value());
7106
  if (!processed_init->protocol) processed_init->protocol = "*";
7107
  if (!processed_init->username) processed_init->username = "*";
7108
  if (!processed_init->password) processed_init->password = "*";
7109
  if (!processed_init->hostname) processed_init->hostname = "*";
7110
  if (!processed_init->port) processed_init->port = "*";
7111
  if (!processed_init->pathname) processed_init->pathname = "*";
7112
  if (!processed_init->search) processed_init->search = "*";
7113
  if (!processed_init->hash) processed_init->hash = "*";
7114
7115
  ada_log("-- processed_init->protocol: ", processed_init->protocol.value());
7116
  ada_log("-- processed_init->username: ", processed_init->username.value());
7117
  ada_log("-- processed_init->password: ", processed_init->password.value());
7118
  ada_log("-- processed_init->hostname: ", processed_init->hostname.value());
7119
  ada_log("-- processed_init->port: ", processed_init->port.value());
7120
  ada_log("-- processed_init->pathname: ", processed_init->pathname.value());
7121
  ada_log("-- processed_init->search: ", processed_init->search.value());
7122
  ada_log("-- processed_init->hash: ", processed_init->hash.value());
7123
7124
  // If processedInit["protocol"] is a special scheme and processedInit["port"]
7125
  // is a string which represents its corresponding default port in radix-10
7126
  // using ASCII digits then set processedInit["port"] to the empty string.
7127
  // TODO: Optimization opportunity.
7128
  if (scheme::is_special(*processed_init->protocol)) {
7129
    // file is the only special scheme with no default port; get_special_port
7130
    // returns 0 as its sentinel, so a literal "0" port must not be mistaken for
7131
    // a default and dropped.
7132
    uint16_t default_port = scheme::get_special_port(*processed_init->protocol);
7133
    if (default_port != 0 &&
7134
        std::to_string(default_port) == processed_init->port.value()) {
7135
      processed_init->port->clear();
7136
    }
7137
  }
7138
7139
  // Let urlPattern be a new URL pattern.
7140
  url_pattern<regex_provider> url_pattern_{};
7141
7142
  // Set urlPattern's protocol component to the result of compiling a component
7143
  // given processedInit["protocol"], canonicalize a protocol, and default
7144
  // options.
7145
  auto protocol_component = url_pattern_component<regex_provider>::compile(
7146
      processed_init->protocol.value(),
7147
      url_pattern_helpers::canonicalize_protocol,
7148
      url_pattern_compile_component_options::DEFAULT);
7149
  if (!protocol_component) {
7150
    ada_log("url_pattern_component::compile failed for protocol ",
7151
            processed_init->protocol.value());
7152
    return tl::unexpected(protocol_component.error());
7153
  }
7154
  url_pattern_.protocol_component = std::move(*protocol_component);
7155
7156
  // Set urlPattern's username component to the result of compiling a component
7157
  // given processedInit["username"], canonicalize a username, and default
7158
  // options.
7159
  auto username_component = url_pattern_component<regex_provider>::compile(
7160
      processed_init->username.value(),
7161
      url_pattern_helpers::canonicalize_username,
7162
      url_pattern_compile_component_options::DEFAULT);
7163
  if (!username_component) {
7164
    ada_log("url_pattern_component::compile failed for username ",
7165
            processed_init->username.value());
7166
    return tl::unexpected(username_component.error());
7167
  }
7168
  url_pattern_.username_component = std::move(*username_component);
7169
7170
  // Set urlPattern's password component to the result of compiling a component
7171
  // given processedInit["password"], canonicalize a password, and default
7172
  // options.
7173
  auto password_component = url_pattern_component<regex_provider>::compile(
7174
      processed_init->password.value(),
7175
      url_pattern_helpers::canonicalize_password,
7176
      url_pattern_compile_component_options::DEFAULT);
7177
  if (!password_component) {
7178
    ada_log("url_pattern_component::compile failed for password ",
7179
            processed_init->password.value());
7180
    return tl::unexpected(password_component.error());
7181
  }
7182
  url_pattern_.password_component = std::move(*password_component);
7183
7184
  // TODO: Optimization opportunity. The following if statement can be
7185
  // simplified.
7186
  // If the result running hostname pattern is an IPv6 address given
7187
  // processedInit["hostname"] is true, then set urlPattern's hostname component
7188
  // to the result of compiling a component given processedInit["hostname"],
7189
  // canonicalize an IPv6 hostname, and hostname options.
7190
  if (url_pattern_helpers::is_ipv6_address(processed_init->hostname.value())) {
7191
    ada_log("processed_init->hostname is ipv6 address");
7192
    // then set urlPattern's hostname component to the result of compiling a
7193
    // component given processedInit["hostname"], canonicalize an IPv6 hostname,
7194
    // and hostname options.
7195
    auto hostname_component = url_pattern_component<regex_provider>::compile(
7196
        processed_init->hostname.value(),
7197
        url_pattern_helpers::canonicalize_ipv6_hostname,
7198
        url_pattern_compile_component_options::DEFAULT);
7199
    if (!hostname_component) {
7200
      ada_log("url_pattern_component::compile failed for ipv6 hostname ",
7201
              processed_init->hostname.value());
7202
      return tl::unexpected(hostname_component.error());
7203
    }
7204
    url_pattern_.hostname_component = std::move(*hostname_component);
7205
  } else {
7206
    // Otherwise, set urlPattern's hostname component to the result of compiling
7207
    // a component given processedInit["hostname"], canonicalize a hostname, and
7208
    // hostname options.
7209
    auto hostname_component = url_pattern_component<regex_provider>::compile(
7210
        processed_init->hostname.value(),
7211
        url_pattern_helpers::canonicalize_hostname,
7212
        url_pattern_compile_component_options::HOSTNAME);
7213
    if (!hostname_component) {
7214
      ada_log("url_pattern_component::compile failed for hostname ",
7215
              processed_init->hostname.value());
7216
      return tl::unexpected(hostname_component.error());
7217
    }
7218
    url_pattern_.hostname_component = std::move(*hostname_component);
7219
  }
7220
7221
  // Set urlPattern's port component to the result of compiling a component
7222
  // given processedInit["port"], canonicalize a port, and default options.
7223
  auto port_component = url_pattern_component<regex_provider>::compile(
7224
      processed_init->port.value(), url_pattern_helpers::canonicalize_port,
7225
      url_pattern_compile_component_options::DEFAULT);
7226
  if (!port_component) {
7227
    ada_log("url_pattern_component::compile failed for port ",
7228
            processed_init->port.value());
7229
    return tl::unexpected(port_component.error());
7230
  }
7231
  url_pattern_.port_component = std::move(*port_component);
7232
7233
  // Let compileOptions be a copy of the default options with the ignore case
7234
  // property set to options["ignoreCase"].
7235
  auto compile_options = url_pattern_compile_component_options::DEFAULT;
7236
  if (options) {
7237
    compile_options.ignore_case = options->ignore_case;
7238
    // Recorded on the pattern so that url_pattern::ignore_case() reports the
7239
    // option it was created with.
7240
    url_pattern_.ignore_case_ = options->ignore_case;
7241
  }
7242
7243
  // TODO: Optimization opportunity: Simplify this if statement.
7244
  // If the result of running protocol component matches a special scheme given
7245
  // urlPattern's protocol component is true, then:
7246
  if (url_pattern_helpers::protocol_component_matches_special_scheme<
7247
          regex_provider>(url_pattern_.protocol_component)) {
7248
    // Let pathCompileOptions be copy of the pathname options with the ignore
7249
    // case property set to options["ignoreCase"].
7250
    auto path_compile_options = url_pattern_compile_component_options::PATHNAME;
7251
    if (options) {
7252
      path_compile_options.ignore_case = options->ignore_case;
7253
    }
7254
7255
    // Set urlPattern's pathname component to the result of compiling a
7256
    // component given processedInit["pathname"], canonicalize a pathname, and
7257
    // pathCompileOptions.
7258
    auto pathname_component = url_pattern_component<regex_provider>::compile(
7259
        processed_init->pathname.value(),
7260
        url_pattern_helpers::canonicalize_pathname, path_compile_options);
7261
    if (!pathname_component) {
7262
      ada_log("url_pattern_component::compile failed for pathname ",
7263
              processed_init->pathname.value());
7264
      return tl::unexpected(pathname_component.error());
7265
    }
7266
    url_pattern_.pathname_component = std::move(*pathname_component);
7267
  } else {
7268
    // Otherwise set urlPattern's pathname component to the result of compiling
7269
    // a component given processedInit["pathname"], canonicalize an opaque
7270
    // pathname, and compileOptions.
7271
    auto pathname_component = url_pattern_component<regex_provider>::compile(
7272
        processed_init->pathname.value(),
7273
        url_pattern_helpers::canonicalize_opaque_pathname, compile_options);
7274
    if (!pathname_component) {
7275
      ada_log("url_pattern_component::compile failed for opaque pathname ",
7276
              processed_init->pathname.value());
7277
      return tl::unexpected(pathname_component.error());
7278
    }
7279
    url_pattern_.pathname_component = std::move(*pathname_component);
7280
  }
7281
7282
  // Set urlPattern's search component to the result of compiling a component
7283
  // given processedInit["search"], canonicalize a search, and compileOptions.
7284
  auto search_component = url_pattern_component<regex_provider>::compile(
7285
      processed_init->search.value(), url_pattern_helpers::canonicalize_search,
7286
      compile_options);
7287
  if (!search_component) {
7288
    ada_log("url_pattern_component::compile failed for search ",
7289
            processed_init->search.value());
7290
    return tl::unexpected(search_component.error());
7291
  }
7292
  url_pattern_.search_component = std::move(*search_component);
7293
7294
  // Set urlPattern's hash component to the result of compiling a component
7295
  // given processedInit["hash"], canonicalize a hash, and compileOptions.
7296
  auto hash_component = url_pattern_component<regex_provider>::compile(
7297
      processed_init->hash.value(), url_pattern_helpers::canonicalize_hash,
7298
      compile_options);
7299
  if (!hash_component) {
7300
    ada_log("url_pattern_component::compile failed for hash ",
7301
            processed_init->hash.value());
7302
    return tl::unexpected(hash_component.error());
7303
  }
7304
  url_pattern_.hash_component = std::move(*hash_component);
7305
7306
  // Return urlPattern.
7307
  return url_pattern_;
7308
}
7309
#endif  // ADA_INCLUDE_URL_PATTERN
7310
7311
}  // namespace ada::parser
7312
7313
#endif  // ADA_PARSER_INL_H
7314
/* end file include/ada/parser-inl.h */
7315
/* begin file include/ada/scheme-inl.h */
7316
/**
7317
 * @file scheme-inl.h
7318
 * @brief Definitions for the URL scheme.
7319
 */
7320
#ifndef ADA_SCHEME_INL_H
7321
#define ADA_SCHEME_INL_H
7322
7323
7324
#include <cstddef>
7325
#include <cstdint>
7326
#include <string_view>
7327
7328
namespace ada::scheme {
7329
7330
/**
7331
 * @namespace ada::scheme::details
7332
 * @brief Includes the definitions for scheme specific entities
7333
 */
7334
namespace details {
7335
// for use with is_special and get_special_port
7336
// Spaces, if present, are removed from URL.
7337
constexpr std::string_view is_special_list[] = {"http", " ",   "https", "ws",
7338
                                                "ftp",  "wss", "file",  " "};
7339
// for use with get_special_port
7340
constexpr uint16_t special_ports[] = {80, 0, 443, 80, 21, 443, 0, 0};
7341
7342
// @private
7343
// convert a string_view to a 64-bit integer key for fast comparison
7344
0
constexpr uint64_t make_key(std::string_view sv) {
7345
0
  uint64_t val = 0;
7346
0
  for (size_t i = 0; i < sv.size(); i++)
7347
0
    val |= (uint64_t)(uint8_t)sv[i] << (i * 8);
7348
0
  return val;
7349
0
}
7350
// precomputed keys for the special schemes, indexed by a hash of the input
7351
// string
7352
constexpr uint64_t scheme_keys[] = {
7353
    make_key("http"),   // 0: HTTP
7354
    0,                  // 1: sentinel
7355
    make_key("https"),  // 2: HTTPS
7356
    make_key("ws"),     // 3: WS
7357
    make_key("ftp"),    // 4: FTP
7358
    make_key("wss"),    // 5: WSS
7359
    make_key("file"),   // 6: FILE
7360
    0,                  // 7: sentinel
7361
};
7362
7363
// @private
7364
// branchless load of up to 5 characters into a uint64_t, padding with zeros if
7365
// n < 5
7366
491
inline uint64_t branchless_load5(const char* p, size_t n) {
7367
491
  uint64_t input = (uint8_t)p[0];
7368
491
  input |= ((uint64_t)(uint8_t)p[n > 1] << 8) & (0 - (uint64_t)(n > 1));
7369
491
  input |= ((uint64_t)(uint8_t)p[(n > 2) * 2] << 16) & (0 - (uint64_t)(n > 2));
7370
491
  input |= ((uint64_t)(uint8_t)p[(n > 3) * 3] << 24) & (0 - (uint64_t)(n > 3));
7371
491
  input |= ((uint64_t)(uint8_t)p[(n > 4) * 4] << 32) & (0 - (uint64_t)(n > 4));
7372
491
  return input;
7373
491
}
7374
}  // namespace details
7375
7376
/****
7377
 * @private
7378
 * In is_special, get_scheme_type, and get_special_port, we
7379
 * use a standard hashing technique to find the index of the scheme in
7380
 * the is_special_list. The hashing technique is based on the size of
7381
 * the scheme and the first character of the scheme. It ensures that we
7382
 * do at most one string comparison per call. If the protocol is
7383
 * predictible (e.g., it is always "http"), we can get a better average
7384
 * performance by using a simpler approach where we loop and compare
7385
 * scheme with all possible protocols starting with the most likely
7386
 * protocol. Doing multiple comparisons may have a poor worst case
7387
 * performance, however. In this instance, we choose a potentially
7388
 * slightly lower best-case performance for a better worst-case
7389
 * performance. We can revisit this choice at any time.
7390
 *
7391
 * Reference:
7392
 * Schmidt, Douglas C. "Gperf: A perfect hash function generator."
7393
 * More C++ gems 17 (2000).
7394
 *
7395
 * Reference: https://en.wikipedia.org/wiki/Perfect_hash_function
7396
 *
7397
 * Reference: https://github.com/ada-url/ada/issues/617
7398
 ****/
7399
7400
0
ada_really_inline constexpr bool is_special(std::string_view scheme) {
7401
0
  if (scheme.empty()) {
7402
0
    return false;
7403
0
  }
7404
0
  int hash_value = (2 * scheme.size() + (unsigned)(scheme[0])) & 7;
7405
0
  const std::string_view target = details::is_special_list[hash_value];
7406
0
  return (target[0] == scheme[0]) && (target.substr(1) == scheme.substr(1));
7407
0
}
7408
0
constexpr uint16_t get_special_port(std::string_view scheme) noexcept {
7409
0
  if (scheme.empty()) {
7410
0
    return 0;
7411
0
  }
7412
0
  int hash_value = (2 * scheme.size() + (unsigned)(scheme[0])) & 7;
7413
0
  const std::string_view target = details::is_special_list[hash_value];
7414
0
  if (scheme.size() == target.size() &&
7415
0
      details::branchless_load5(scheme.data(), scheme.size()) ==
7416
0
          details::scheme_keys[hash_value]) {
7417
0
    return details::special_ports[hash_value];
7418
0
  } else {
7419
0
    return 0;
7420
0
  }
7421
0
}
7422
0
constexpr uint16_t get_special_port(ada::scheme::type type) noexcept {
7423
0
  return details::special_ports[int(type)];
7424
0
}
7425
491
constexpr ada::scheme::type get_scheme_type(std::string_view scheme) noexcept {
7426
491
  if (scheme.empty()) {
7427
0
    return ada::scheme::NOT_SPECIAL;
7428
0
  }
7429
491
  int hash_value = (2 * scheme.size() + (unsigned)(scheme[0])) & 7;
7430
491
  const std::string_view target = details::is_special_list[hash_value];
7431
491
  if (scheme.size() == target.size() &&
7432
491
      details::branchless_load5(scheme.data(), scheme.size()) ==
7433
491
          details::scheme_keys[hash_value]) {
7434
491
    return ada::scheme::type(hash_value);
7435
491
  } else {
7436
0
    return ada::scheme::NOT_SPECIAL;
7437
0
  }
7438
491
}
7439
7440
}  // namespace ada::scheme
7441
7442
#endif  // ADA_SCHEME_INL_H
7443
/* end file include/ada/scheme-inl.h */
7444
/* begin file include/ada/serializers.h */
7445
/**
7446
 * @file serializers.h
7447
 * @brief IP address serialization utilities.
7448
 *
7449
 * This header provides functions for converting IP addresses to their
7450
 * string representations according to the WHATWG URL Standard.
7451
 */
7452
#ifndef ADA_SERIALIZERS_H
7453
#define ADA_SERIALIZERS_H
7454
7455
7456
#include <array>
7457
#include <cstddef>
7458
#include <cstdint>
7459
#include <string>
7460
7461
/**
7462
 * @namespace ada::serializers
7463
 * @brief IP address serialization functions.
7464
 *
7465
 * Contains utilities for serializing IPv4 and IPv6 addresses to strings.
7466
 */
7467
namespace ada::serializers {
7468
7469
/**
7470
 * Finds the longest consecutive sequence of zero pieces in an IPv6 address.
7471
 * Used for :: compression in IPv6 serialization.
7472
 *
7473
 * @param address The 8 16-bit pieces of the IPv6 address.
7474
 * @param[out] compress Index of the start of the longest zero sequence.
7475
 * @param[out] compress_length Length of the longest zero sequence.
7476
 */
7477
void find_longest_sequence_of_ipv6_pieces(
7478
    const std::array<uint16_t, 8>& address, size_t& compress,
7479
    size_t& compress_length) noexcept;
7480
7481
/**
7482
 * Serializes an IPv6 address to its string representation.
7483
 *
7484
 * @param address The 8 16-bit pieces of the IPv6 address.
7485
 * @return The serialized IPv6 string (e.g., "2001:db8::1").
7486
 * @see https://url.spec.whatwg.org/#concept-ipv6-serializer
7487
 */
7488
std::string ipv6(const std::array<uint16_t, 8>& address);
7489
7490
/**
7491
 * Serializes an IPv4 address to its dotted-decimal string representation.
7492
 *
7493
 * @param address The 32-bit IPv4 address as an integer.
7494
 * @return The serialized IPv4 string (e.g., "192.168.1.1").
7495
 * @see https://url.spec.whatwg.org/#concept-ipv4-serializer
7496
 */
7497
std::string ipv4(uint64_t address);
7498
7499
}  // namespace ada::serializers
7500
7501
#endif  // ADA_SERIALIZERS_H
7502
/* end file include/ada/serializers.h */
7503
/* begin file include/ada/state.h */
7504
/**
7505
 * @file state.h
7506
 * @brief URL parser state machine states.
7507
 *
7508
 * Defines the states used by the URL parsing state machine as specified
7509
 * in the WHATWG URL Standard.
7510
 *
7511
 * @see https://url.spec.whatwg.org/#url-parsing
7512
 */
7513
#ifndef ADA_STATE_H
7514
#define ADA_STATE_H
7515
7516
7517
#include <string>
7518
7519
namespace ada {
7520
7521
/**
7522
 * @brief States in the URL parsing state machine.
7523
 *
7524
 * The URL parser processes input through a sequence of states, each handling
7525
 * a specific part of the URL syntax.
7526
 *
7527
 * @see https://url.spec.whatwg.org/#url-parsing
7528
 */
7529
enum class state {
7530
  /**
7531
   * @see https://url.spec.whatwg.org/#authority-state
7532
   */
7533
  AUTHORITY,
7534
7535
  /**
7536
   * @see https://url.spec.whatwg.org/#scheme-start-state
7537
   */
7538
  SCHEME_START,
7539
7540
  /**
7541
   * @see https://url.spec.whatwg.org/#scheme-state
7542
   */
7543
  SCHEME,
7544
7545
  /**
7546
   * @see https://url.spec.whatwg.org/#host-state
7547
   */
7548
  HOST,
7549
7550
  /**
7551
   * @see https://url.spec.whatwg.org/#no-scheme-state
7552
   */
7553
  NO_SCHEME,
7554
7555
  /**
7556
   * @see https://url.spec.whatwg.org/#fragment-state
7557
   */
7558
  FRAGMENT,
7559
7560
  /**
7561
   * @see https://url.spec.whatwg.org/#relative-state
7562
   */
7563
  RELATIVE_SCHEME,
7564
7565
  /**
7566
   * @see https://url.spec.whatwg.org/#relative-slash-state
7567
   */
7568
  RELATIVE_SLASH,
7569
7570
  /**
7571
   * @see https://url.spec.whatwg.org/#file-state
7572
   */
7573
  FILE,
7574
7575
  /**
7576
   * @see https://url.spec.whatwg.org/#file-host-state
7577
   */
7578
  FILE_HOST,
7579
7580
  /**
7581
   * @see https://url.spec.whatwg.org/#file-slash-state
7582
   */
7583
  FILE_SLASH,
7584
7585
  /**
7586
   * @see https://url.spec.whatwg.org/#path-or-authority-state
7587
   */
7588
  PATH_OR_AUTHORITY,
7589
7590
  /**
7591
   * @see https://url.spec.whatwg.org/#special-authority-ignore-slashes-state
7592
   */
7593
  SPECIAL_AUTHORITY_IGNORE_SLASHES,
7594
7595
  /**
7596
   * @see https://url.spec.whatwg.org/#special-authority-slashes-state
7597
   */
7598
  SPECIAL_AUTHORITY_SLASHES,
7599
7600
  /**
7601
   * @see https://url.spec.whatwg.org/#special-relative-or-authority-state
7602
   */
7603
  SPECIAL_RELATIVE_OR_AUTHORITY,
7604
7605
  /**
7606
   * @see https://url.spec.whatwg.org/#query-state
7607
   */
7608
  QUERY,
7609
7610
  /**
7611
   * @see https://url.spec.whatwg.org/#path-state
7612
   */
7613
  PATH,
7614
7615
  /**
7616
   * @see https://url.spec.whatwg.org/#path-start-state
7617
   */
7618
  PATH_START,
7619
7620
  /**
7621
   * @see https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state
7622
   */
7623
  OPAQUE_PATH,
7624
7625
  /**
7626
   * @see https://url.spec.whatwg.org/#port-state
7627
   */
7628
  PORT,
7629
};
7630
7631
/**
7632
 * Converts a parser state to its string name for debugging.
7633
 * @param s The state to convert.
7634
 * @return A string representation of the state.
7635
 */
7636
ada_warn_unused std::string to_string(ada::state s);
7637
7638
}  // namespace ada
7639
7640
#endif  // ADA_STATE_H
7641
/* end file include/ada/state.h */
7642
/* begin file include/ada/unicode.h */
7643
/**
7644
 * @file unicode.h
7645
 * @brief Definitions for all unicode specific functions.
7646
 */
7647
#ifndef ADA_UNICODE_H
7648
#define ADA_UNICODE_H
7649
7650
7651
#include <cstddef>
7652
#include <cstdint>
7653
#include <optional>
7654
#include <string>
7655
#include <string_view>
7656
7657
/**
7658
 * Unicode operations. These functions are not part of our public API and may
7659
 * change at any time.
7660
 *
7661
 * @private
7662
 * @namespace ada::unicode
7663
 * @brief Includes the definitions for unicode operations
7664
 */
7665
namespace ada::unicode {
7666
7667
/**
7668
 * @private
7669
 * We receive a UTF-8 string representing a domain name.
7670
 * If the string is percent encoded, we apply percent decoding.
7671
 *
7672
 * Given a domain, we need to identify its labels.
7673
 * They are separated by label-separators:
7674
 *
7675
 * U+002E (.) FULL STOP
7676
 * U+FF0E FULLWIDTH FULL STOP
7677
 * U+3002 IDEOGRAPHIC FULL STOP
7678
 * U+FF61 HALFWIDTH IDEOGRAPHIC FULL STOP
7679
 *
7680
 * They are all mapped to U+002E.
7681
 *
7682
 * We process each label into a string that should not exceed 63 octets.
7683
 * If the string is already punycode (starts with "xn--"), then we must
7684
 * scan it to look for unallowed code points.
7685
 * Otherwise, if the string is not pure ASCII, we need to transcode it
7686
 * to punycode by following RFC 3454 which requires us to
7687
 * - Map characters  (see section 3),
7688
 * - Normalize (see section 4),
7689
 * - Reject forbidden characters,
7690
 * - Check for right-to-left characters and if so, check all requirements (see
7691
 * section 6),
7692
 * - Optionally reject based on unassigned code points (section 7).
7693
 *
7694
 * The Unicode standard provides a table of code points with a mapping, a list
7695
 * of forbidden code points and so forth. This table is subject to change and
7696
 * will vary based on the implementation. For Unicode 15, the table is at
7697
 * https://www.unicode.org/Public/idna/15.0.0/IdnaMappingTable.txt
7698
 * If you use ICU, they parse this table and map it to code using a Python
7699
 * script.
7700
 *
7701
 * The resulting strings should not exceed 255 octets according to RFC 1035
7702
 * section 2.3.4. ICU checks for label size and domain size, but these errors
7703
 * are ignored.
7704
 *
7705
 * @see https://url.spec.whatwg.org/#concept-domain-to-ascii
7706
 *
7707
 */
7708
bool to_ascii(std::optional<std::string>& out, std::string_view plain,
7709
              size_t first_percent);
7710
7711
/**
7712
 * @private
7713
 * Checks if the input has tab or newline characters.
7714
 *
7715
 * @attention The has_tabs_or_newline function is a bottleneck and it is simple
7716
 * enough that compilers like GCC can 'autovectorize it'.
7717
 */
7718
ada_really_inline bool has_tabs_or_newline(
7719
    std::string_view user_input) noexcept;
7720
7721
/**
7722
 * @private
7723
 * Checks if the input is a forbidden host code point.
7724
 * @see https://url.spec.whatwg.org/#forbidden-host-code-point
7725
 */
7726
ada_really_inline constexpr bool is_forbidden_host_code_point(char c) noexcept;
7727
7728
/**
7729
 * @private
7730
 * Checks if the input contains a forbidden domain code point.
7731
 * @see https://url.spec.whatwg.org/#forbidden-domain-code-point
7732
 */
7733
ada_really_inline constexpr bool contains_forbidden_domain_code_point(
7734
    const char* input, size_t length) noexcept;
7735
7736
/**
7737
 * @private
7738
 * Checks if the input contains a forbidden domain code point in which case
7739
 * the first bit is set to 1. If the input contains an upper case ASCII letter,
7740
 * then the second bit is set to 1.
7741
 * @see https://url.spec.whatwg.org/#forbidden-domain-code-point
7742
 */
7743
ada_really_inline constexpr uint8_t
7744
contains_forbidden_domain_code_point_or_upper(const char* input,
7745
                                              size_t length) noexcept;
7746
7747
/**
7748
 * @private
7749
 * Checks if the input is a forbidden domain code point.
7750
 * @see https://url.spec.whatwg.org/#forbidden-domain-code-point
7751
 */
7752
ada_really_inline constexpr bool is_forbidden_domain_code_point(
7753
    char c) noexcept;
7754
7755
/**
7756
 * @private
7757
 * Checks if the input is alphanumeric, '+', '-' or '.'
7758
 */
7759
ada_really_inline constexpr bool is_alnum_plus(char c) noexcept;
7760
7761
/**
7762
 * @private
7763
 * @details An ASCII hex digit is an ASCII upper hex digit or ASCII lower hex
7764
 * digit. An ASCII upper hex digit is an ASCII digit or a code point in the
7765
 * range U+0041 (A) to U+0046 (F), inclusive. An ASCII lower hex digit is an
7766
 * ASCII digit or a code point in the range U+0061 (a) to U+0066 (f), inclusive.
7767
 */
7768
ada_really_inline constexpr bool is_ascii_hex_digit(char c) noexcept;
7769
7770
/**
7771
 * @private
7772
 * An ASCII digit is a code point in the range U+0030 (0) to U+0039 (9),
7773
 * inclusive.
7774
 */
7775
ada_really_inline constexpr bool is_ascii_digit(char c) noexcept;
7776
7777
/**
7778
 * @private
7779
 * @details If a char is between U+0000 and U+007F inclusive, then it's an ASCII
7780
 * character.
7781
 */
7782
ada_really_inline constexpr bool is_ascii(char32_t c) noexcept;
7783
7784
/**
7785
 * @private
7786
 * Checks if the input is a C0 control or space character.
7787
 *
7788
 * @details A C0 control or space is a C0 control or U+0020 SPACE.
7789
 * A C0 control is a code point in the range U+0000 NULL to U+001F INFORMATION
7790
 * SEPARATOR ONE, inclusive.
7791
 */
7792
ada_really_inline constexpr bool is_c0_control_or_space(char c) noexcept;
7793
7794
/**
7795
 * @private
7796
 * Checks if the input is a ASCII tab or newline character.
7797
 *
7798
 * @details An ASCII tab or newline is U+0009 TAB, U+000A LF, or U+000D CR.
7799
 */
7800
ada_really_inline constexpr bool is_ascii_tab_or_newline(char c) noexcept;
7801
7802
/**
7803
 * @private
7804
 * @details A double-dot path segment must be ".." or an ASCII case-insensitive
7805
 * match for ".%2e", "%2e.", or "%2e%2e".
7806
 */
7807
ada_really_inline constexpr bool is_double_dot_path_segment(
7808
    std::string_view input) noexcept;
7809
7810
/**
7811
 * @private
7812
 * @details A single-dot path segment must be "." or an ASCII case-insensitive
7813
 * match for "%2e".
7814
 */
7815
ada_really_inline constexpr bool is_single_dot_path_segment(
7816
    std::string_view input) noexcept;
7817
7818
/**
7819
 * @private
7820
 * @details ipv4 character might contain 0-9 or a-f character ranges.
7821
 */
7822
ada_really_inline constexpr bool is_lowercase_hex(char c) noexcept;
7823
7824
/**
7825
 * @private
7826
 * @details Convert hex to binary. Caller is responsible to ensure that
7827
 * the parameter is an hexadecimal digit (0-9, A-F, a-f).
7828
 */
7829
ada_really_inline unsigned constexpr convert_hex_to_binary(char c) noexcept;
7830
7831
/**
7832
 * @private
7833
 * first_percent should be  = input.find('%')
7834
 *
7835
 * @todo It would be faster as noexcept maybe, but it could be unsafe since.
7836
 * @author Node.js
7837
 * @see https://github.com/nodejs/node/blob/main/src/node_url.cc#L245
7838
 * @see https://encoding.spec.whatwg.org/#utf-8-decode-without-bom
7839
 */
7840
std::string percent_decode(std::string_view input, size_t first_percent);
7841
7842
/**
7843
 * Decode an application/x-www-form-urlencoded component: map '+' to space,
7844
 * then percent-decode. Single allocation; no intermediate string.
7845
 *
7846
 * @param input A form-urlencoded component (key or value).
7847
 * @return The decoded string.
7848
 * @see https://url.spec.whatwg.org/#concept-urlencoded-parser
7849
 */
7850
std::string form_urlencoded_decode(std::string_view input);
7851
7852
/**
7853
 * @private
7854
 * Returns a percent-encoding string whether percent encoding was needed or not.
7855
 * @see https://github.com/nodejs/node/blob/main/src/node_url.cc#L226
7856
 */
7857
std::string percent_encode(std::string_view input,
7858
                           const uint8_t character_set[]);
7859
/**
7860
 * @private
7861
 * Returns a percent-encoded string version of input, while starting the percent
7862
 * encoding at the provided index.
7863
 * @see https://github.com/nodejs/node/blob/main/src/node_url.cc#L226
7864
 */
7865
std::string percent_encode(std::string_view input,
7866
                           const uint8_t character_set[], size_t index);
7867
/**
7868
 * @private
7869
 * Returns true if percent encoding was needed, in which case, we store
7870
 * the percent-encoded content in 'out'. If the boolean 'append' is set to
7871
 * true, the content is appended to 'out'.
7872
 * If percent encoding is not needed, out is left unchanged.
7873
 * @see https://github.com/nodejs/node/blob/main/src/node_url.cc#L226
7874
 */
7875
template <bool append>
7876
bool percent_encode(std::string_view input, const uint8_t character_set[],
7877
                    std::string& out);
7878
/**
7879
 * @private
7880
 * Returns the index at which percent encoding should start, or (equivalently),
7881
 * the length of the prefix that does not require percent encoding.
7882
 */
7883
ada_really_inline size_t percent_encode_index(std::string_view input,
7884
                                              const uint8_t character_set[]);
7885
/**
7886
 * @private
7887
 * Lowers the string in-place, assuming that the content is ASCII.
7888
 * Return true if the content was ASCII.
7889
 */
7890
constexpr bool to_lower_ascii(char* input, size_t length) noexcept;
7891
}  // namespace ada::unicode
7892
7893
#endif  // ADA_UNICODE_H
7894
/* end file include/ada/unicode.h */
7895
/* begin file include/ada/url_base-inl.h */
7896
/**
7897
 * @file url_base-inl.h
7898
 * @brief Inline functions for url base
7899
 */
7900
#ifndef ADA_URL_BASE_INL_H
7901
#define ADA_URL_BASE_INL_H
7902
7903
7904
#include <cstdint>
7905
#include <string>
7906
#if ADA_REGULAR_VISUAL_STUDIO
7907
#include <intrin.h>
7908
#endif  // ADA_REGULAR_VISUAL_STUDIO
7909
7910
namespace ada {
7911
7912
[[nodiscard]] ada_really_inline constexpr bool url_base::is_special()
7913
5.59k
    const noexcept {
7914
5.59k
  return type != ada::scheme::NOT_SPECIAL;
7915
5.59k
}
7916
7917
0
[[nodiscard]] inline uint16_t url_base::get_special_port() const noexcept {
7918
0
  return ada::scheme::get_special_port(type);
7919
0
}
7920
7921
[[nodiscard]] ada_really_inline uint16_t
7922
0
url_base::scheme_default_port() const noexcept {
7923
0
  return scheme::get_special_port(type);
7924
0
}
7925
7926
}  // namespace ada
7927
7928
#endif  // ADA_URL_BASE_INL_H
7929
/* end file include/ada/url_base-inl.h */
7930
/* begin file include/ada/url-inl.h */
7931
/**
7932
 * @file url-inl.h
7933
 * @brief Definitions for the URL
7934
 */
7935
#ifndef ADA_URL_INL_H
7936
#define ADA_URL_INL_H
7937
7938
7939
#include <charconv>
7940
#include <cstdint>
7941
#include <cstring>
7942
#include <optional>
7943
#include <ostream>
7944
#include <string>
7945
#include <string_view>
7946
#include <system_error>
7947
#include <utility>
7948
#if ADA_REGULAR_VISUAL_STUDIO
7949
#include <intrin.h>
7950
#endif  // ADA_REGULAR_VISUAL_STUDIO
7951
7952
namespace ada {
7953
0
[[nodiscard]] ada_really_inline bool url::has_credentials() const noexcept {
7954
0
  return !username.empty() || !password.empty();
7955
0
}
7956
0
[[nodiscard]] ada_really_inline bool url::has_port() const noexcept {
7957
0
  return port.has_value();
7958
0
}
7959
0
[[nodiscard]] inline bool url::cannot_have_credentials_or_port() const {
7960
0
  return !host.has_value() || host->empty() || type == ada::scheme::type::FILE;
7961
0
}
7962
0
[[nodiscard]] inline bool url::has_empty_hostname() const noexcept {
7963
0
  if (!host.has_value()) {
7964
0
    return false;
7965
0
  }
7966
0
  return host->empty();
7967
0
}
7968
0
[[nodiscard]] inline bool url::has_hostname() const noexcept {
7969
0
  return host.has_value();
7970
0
}
7971
0
inline std::ostream& operator<<(std::ostream& out, const ada::url& u) {
7972
0
  return out << u.to_string();
7973
0
}
7974
7975
0
[[nodiscard]] size_t url::get_pathname_length() const noexcept {
7976
0
  return path.size();
7977
0
}
7978
7979
0
[[nodiscard]] constexpr std::string_view url::get_pathname() const noexcept {
7980
0
  return path;
7981
0
}
7982
7983
[[nodiscard]] ada_really_inline ada::url_components url::get_components()
7984
0
    const {
7985
0
  url_components out{};
7986
0
7987
0
  // protocol ends with ':'. for example: "https:"
7988
0
  out.protocol_end = uint32_t(get_protocol().size());
7989
0
7990
0
  // Trailing index is always the next character of the current one.
7991
0
  // NOLINTNEXTLINE(clang-analyzer-deadcode.DeadStores)
7992
0
  size_t running_index = out.protocol_end;
7993
0
7994
0
  if (host.has_value()) {
7995
0
    // 2 characters for "//" and 1 character for starting index
7996
0
    out.host_start = out.protocol_end + 2;
7997
0
7998
0
    if (has_credentials()) {
7999
0
      out.username_end = uint32_t(out.host_start + username.size());
8000
0
8001
0
      out.host_start += uint32_t(username.size());
8002
0
8003
0
      if (!password.empty()) {
8004
0
        out.host_start += uint32_t(password.size() + 1);
8005
0
      }
8006
0
8007
0
      // host_start is the '@' when there are credentials, exactly as
8008
0
      // url_aggregator reports it, so the host itself begins one byte later.
8009
0
      out.host_end = uint32_t(out.host_start + 1 + host->size());
8010
0
    } else {
8011
0
      out.username_end = out.host_start;
8012
0
8013
0
      // Host does not start with "@" if it does not include credentials.
8014
0
      out.host_end = uint32_t(out.host_start + host->size());
8015
0
    }
8016
0
8017
0
    // host_end is one past the host, so it is already the next index.
8018
0
    running_index = out.host_end;
8019
0
  } else {
8020
0
    // Update host start and end date to the same index, since it does not
8021
0
    // exist.
8022
0
    out.host_start = out.protocol_end;
8023
0
    out.host_end = out.host_start;
8024
0
8025
0
    if (!has_opaque_path && path.starts_with("//")) {
8026
0
      // If url's host is null, url does not have an opaque path, url's path's
8027
0
      // size is greater than 1, and url's path[0] is the empty string, then
8028
0
      // append U+002F (/) followed by U+002E (.) to output.
8029
0
      running_index = out.protocol_end + 2;
8030
0
    } else {
8031
0
      running_index = out.protocol_end;
8032
0
    }
8033
0
  }
8034
0
8035
0
  if (port.has_value()) {
8036
0
    out.port = *port;
8037
0
    running_index += helpers::fast_digit_count(*port) + 1;  // Port omits ':'
8038
0
  }
8039
0
8040
0
  out.pathname_start = uint32_t(running_index);
8041
0
8042
0
  running_index += path.size();
8043
0
8044
0
  if (query.has_value()) {
8045
0
    out.search_start = uint32_t(running_index);
8046
0
    running_index += get_search().size();
8047
0
    if (get_search().empty()) {
8048
0
      running_index++;
8049
0
    }
8050
0
  }
8051
0
8052
0
  if (hash.has_value()) {
8053
0
    out.hash_start = uint32_t(running_index);
8054
0
  }
8055
0
8056
0
  return out;
8057
0
}
8058
8059
0
inline void url::update_base_hostname(std::string_view input) { host = input; }
8060
8061
0
inline void url::update_unencoded_base_hash(std::string_view input) {
8062
  // We do the percent encoding
8063
0
  hash = unicode::percent_encode(input,
8064
0
                                 ada::character_sets::FRAGMENT_PERCENT_ENCODE);
8065
0
}
8066
8067
inline void url::update_base_search(std::string_view input,
8068
0
                                    const uint8_t query_percent_encode_set[]) {
8069
0
  query = ada::unicode::percent_encode(input, query_percent_encode_set);
8070
0
}
8071
8072
0
inline void url::update_base_search(std::optional<std::string>&& input) {
8073
0
  query = std::move(input);
8074
0
}
8075
8076
0
inline void url::update_base_pathname(const std::string_view input) {
8077
0
  path = input;
8078
0
}
8079
8080
0
inline void url::update_base_username(const std::string_view input) {
8081
0
  username = input;
8082
0
}
8083
8084
0
inline void url::update_base_password(const std::string_view input) {
8085
0
  password = input;
8086
0
}
8087
8088
0
inline void url::update_base_port(std::optional<uint16_t> input) {
8089
0
  port = input;
8090
0
}
8091
8092
0
constexpr void url::clear_pathname() { path.clear(); }
8093
8094
0
constexpr void url::clear_search() { query = std::nullopt; }
8095
8096
0
[[nodiscard]] constexpr bool url::has_hash() const noexcept {
8097
0
  return hash.has_value();
8098
0
}
8099
8100
0
[[nodiscard]] constexpr bool url::has_search() const noexcept {
8101
0
  return query.has_value();
8102
0
}
8103
8104
0
constexpr void url::set_protocol_as_file() { type = ada::scheme::type::FILE; }
8105
8106
0
inline void url::set_scheme(std::string&& new_scheme) noexcept {
8107
0
  type = ada::scheme::get_scheme_type(new_scheme);
8108
  // We only move the 'scheme' if it is non-special.
8109
0
  if (!is_special()) {
8110
0
    non_special_scheme = std::move(new_scheme);
8111
0
  }
8112
0
}
8113
8114
0
constexpr void url::copy_scheme(ada::url&& u) {
8115
0
  non_special_scheme = u.non_special_scheme;
8116
0
  type = u.type;
8117
0
}
8118
8119
0
constexpr void url::copy_scheme(const ada::url& u) {
8120
0
  non_special_scheme = u.non_special_scheme;
8121
0
  type = u.type;
8122
0
}
8123
8124
0
[[nodiscard]] ada_really_inline std::string url::get_href() const {
8125
0
  if (is_special() && host.has_value() && username.empty() &&
8126
0
      password.empty() && !port.has_value()) [[likely]] {
8127
0
    const std::string_view scheme = ada::scheme::details::is_special_list[type];
8128
0
    const size_t host_size = host->size();
8129
0
    const size_t path_size = path.size();
8130
0
    const size_t query_size = query.has_value() ? query->size() : 0;
8131
0
    const size_t hash_size = hash.has_value() ? hash->size() : 0;
8132
0
    const size_t total = scheme.size() + 3 + host_size + path_size +
8133
0
                         (query.has_value() ? query_size + 1 : 0) +
8134
0
                         (hash.has_value() ? hash_size + 1 : 0);
8135
0
    std::string output(total, '\0');
8136
0
    char* p = output.data();
8137
0
    std::memcpy(p, scheme.data(), scheme.size());
8138
0
    p += scheme.size();
8139
0
    p[0] = ':';
8140
0
    p[1] = '/';
8141
0
    p[2] = '/';
8142
0
    p += 3;
8143
0
    // NOLINTNEXTLINE(bugprone-not-null-terminated-result)
8144
0
    std::memcpy(p, host->data(), host_size);
8145
0
    p += host_size;
8146
0
    std::memcpy(p, path.data(), path_size);
8147
0
    p += path_size;
8148
0
    if (query.has_value()) {
8149
0
      *p++ = '?';
8150
0
      // NOLINTNEXTLINE(bugprone-not-null-terminated-result)
8151
0
      std::memcpy(p, query->data(), query_size);
8152
0
      p += query_size;
8153
0
    }
8154
0
    if (hash.has_value()) {
8155
0
      *p++ = '#';
8156
0
      // NOLINTNEXTLINE(bugprone-not-null-terminated-result)
8157
0
      std::memcpy(p, hash->data(), hash_size);
8158
0
    }
8159
0
    return output;
8160
0
  }
8161
0
8162
0
  std::string output;
8163
0
  output.reserve(get_href_size());
8164
0
8165
0
  if (is_special()) {
8166
0
    output.append(ada::scheme::details::is_special_list[type]);
8167
0
    output += ':';
8168
0
  } else {
8169
0
    output.append(non_special_scheme);
8170
0
    output += ':';
8171
0
  }
8172
0
8173
0
  if (host.has_value()) {
8174
0
    output += '/';
8175
0
    output += '/';
8176
0
    if (has_credentials()) {
8177
0
      output.append(username);
8178
0
      if (!password.empty()) {
8179
0
        output += ':';
8180
0
        output.append(password);
8181
0
      }
8182
0
      output += '@';
8183
0
    }
8184
0
    output.append(*host);
8185
0
    if (port.has_value()) {
8186
0
      output += ':';
8187
0
      char port_buf[5];
8188
0
      auto [ptr, ec] = std::to_chars(port_buf, port_buf + 5, *port);
8189
0
      (void)ec;
8190
0
      output.append(port_buf, static_cast<size_t>(ptr - port_buf));
8191
0
    }
8192
0
  } else if (!has_opaque_path && path.starts_with("//")) {
8193
0
    // If url's host is null, url does not have an opaque path, url's path's
8194
0
    // size is greater than 1, and url's path[0] is the empty string, then
8195
0
    // append U+002F (/) followed by U+002E (.) to output.
8196
0
    output += '/';
8197
0
    output += '.';
8198
0
  }
8199
0
  output.append(path);
8200
0
  if (query.has_value()) {
8201
0
    output += '?';
8202
0
    output.append(*query);
8203
0
  }
8204
0
  if (hash.has_value()) {
8205
0
    output += '#';
8206
0
    output.append(*hash);
8207
0
  }
8208
0
  return output;
8209
0
}
8210
8211
0
[[nodiscard]] inline size_t url::get_href_size() const noexcept {
8212
0
  size_t size = 0;
8213
0
  if (is_special()) {
8214
0
    size += ada::scheme::details::is_special_list[type].size() + 1;
8215
0
  } else {
8216
0
    size += non_special_scheme.size() + 1;
8217
0
  }
8218
0
  if (host.has_value()) {
8219
0
    size += host->size();
8220
0
    size += 2;
8221
0
    if (has_credentials()) {
8222
0
      size += username.size();
8223
0
      if (!password.empty()) {
8224
0
        size += 1 + password.size();
8225
0
      }
8226
0
      size += 1;
8227
0
    }
8228
0
    if (port.has_value()) {
8229
0
      size += 1;
8230
0
      uint16_t p = *port;
8231
0
      size += (p >= 10000)  ? 5
8232
0
              : (p >= 1000) ? 4
8233
0
              : (p >= 100)  ? 3
8234
0
              : (p >= 10)   ? 2
8235
0
                            : 1;
8236
0
    }
8237
0
  } else if (!has_opaque_path && path.starts_with("//")) {
8238
0
    size += 2;
8239
0
  }
8240
0
  size += path.size();
8241
0
  if (query.has_value()) {
8242
0
    size += 1 + query->size();
8243
0
  }
8244
0
  if (hash.has_value()) {
8245
0
    size += 1 + hash->size();
8246
0
  }
8247
0
  return size;
8248
0
}
8249
8250
ada_really_inline size_t url::parse_port(std::string_view view,
8251
0
                                         bool check_trailing_content) noexcept {
8252
0
  ada_log("parse_port('", view, "') ", view.size());
8253
0
  if (!view.empty() && view[0] == '-') {
8254
0
    ada_log("parse_port: view[0] == '0' && view.size() > 1");
8255
0
    is_valid = false;
8256
0
    return 0;
8257
0
  }
8258
0
  uint16_t parsed_port{};
8259
0
  auto r = std::from_chars(view.data(), view.data() + view.size(), parsed_port);
8260
0
  if (r.ec == std::errc::result_out_of_range) {
8261
0
    ada_log("parse_port: r.ec == std::errc::result_out_of_range");
8262
0
    is_valid = false;
8263
0
    return 0;
8264
0
  }
8265
0
  ada_log("parse_port: ", parsed_port);
8266
0
  const auto consumed = size_t(r.ptr - view.data());
8267
0
  ada_log("parse_port: consumed ", consumed);
8268
0
  if (check_trailing_content) {
8269
0
    is_valid &=
8270
0
        (consumed == view.size() || view[consumed] == '/' ||
8271
0
         view[consumed] == '?' || (is_special() && view[consumed] == '\\'));
8272
0
  }
8273
0
  ada_log("parse_port: is_valid = ", is_valid);
8274
0
  if (is_valid) {
8275
    // scheme_default_port can return 0, and we should allow 0 as a base port.
8276
0
    auto default_port = scheme_default_port();
8277
0
    bool is_port_valid = (default_port == 0 && parsed_port == 0) ||
8278
0
                         (default_port != parsed_port);
8279
0
    port = (r.ec == std::errc() && is_port_valid) ? std::optional(parsed_port)
8280
0
                                                  : std::nullopt;
8281
0
  }
8282
0
  return consumed;
8283
0
}
8284
8285
}  // namespace ada
8286
8287
#endif  // ADA_URL_H
8288
/* end file include/ada/url-inl.h */
8289
/* begin file include/ada/url_components-inl.h */
8290
/**
8291
 * @file url_components.h
8292
 * @brief Declaration for the URL Components
8293
 */
8294
#ifndef ADA_URL_COMPONENTS_INL_H
8295
#define ADA_URL_COMPONENTS_INL_H
8296
8297
8298
#include <cstdint>
8299
8300
namespace ada {
8301
8302
[[nodiscard]] constexpr bool url_components::check_offset_consistency()
8303
2.93k
    const noexcept {
8304
  /**
8305
   * https://user:pass@example.com:1234/foo/bar?baz#quux
8306
   *       |     |    |          | ^^^^|       |   |
8307
   *       |     |    |          | |   |       |   `----- hash_start
8308
   *       |     |    |          | |   |       `--------- search_start
8309
   *       |     |    |          | |   `----------------- pathname_start
8310
   *       |     |    |          | `--------------------- port
8311
   *       |     |    |          `----------------------- host_end
8312
   *       |     |    `---------------------------------- host_start
8313
   *       |     `--------------------------------------- username_end
8314
   *       `--------------------------------------------- protocol_end
8315
   */
8316
  // These conditions can be made more strict.
8317
2.93k
  if (protocol_end == url_components::omitted) {
8318
0
    return false;
8319
0
  }
8320
2.93k
  uint32_t index = protocol_end;
8321
8322
2.93k
  if (username_end == url_components::omitted) {
8323
0
    return false;
8324
0
  }
8325
2.93k
  if (username_end < index) {
8326
0
    return false;
8327
0
  }
8328
2.93k
  index = username_end;
8329
8330
2.93k
  if (host_start == url_components::omitted) {
8331
0
    return false;
8332
0
  }
8333
2.93k
  if (host_start < index) {
8334
0
    return false;
8335
0
  }
8336
2.93k
  index = host_start;
8337
8338
2.93k
  if (port != url_components::omitted) {
8339
0
    if (port > 0xffff) {
8340
0
      return false;
8341
0
    }
8342
0
    uint32_t port_length = helpers::fast_digit_count(port) + 1;
8343
0
    if (index + port_length < index) {
8344
0
      return false;
8345
0
    }
8346
0
    index += port_length;
8347
0
  }
8348
8349
2.93k
  if (pathname_start == url_components::omitted) {
8350
0
    return false;
8351
0
  }
8352
2.93k
  if (pathname_start < index) {
8353
0
    return false;
8354
0
  }
8355
2.93k
  index = pathname_start;
8356
8357
2.93k
  if (search_start != url_components::omitted) {
8358
1.57k
    if (search_start < index) {
8359
0
      return false;
8360
0
    }
8361
1.57k
    index = search_start;
8362
1.57k
  }
8363
8364
2.93k
  if (hash_start != url_components::omitted) {
8365
437
    if (hash_start < index) {
8366
0
      return false;
8367
0
    }
8368
437
  }
8369
8370
2.93k
  return true;
8371
2.93k
}
8372
8373
}  // namespace ada
8374
#endif
8375
/* end file include/ada/url_components-inl.h */
8376
/* begin file include/ada/url_aggregator.h */
8377
/**
8378
 * @file url_aggregator.h
8379
 * @brief Declaration for the `ada::url_aggregator` class.
8380
 *
8381
 * This file contains the `ada::url_aggregator` struct which represents a parsed
8382
 * URL using a single buffer with component offsets. This is the default and
8383
 * most memory-efficient URL representation in Ada.
8384
 *
8385
 * @see url.h for an alternative representation using separate strings
8386
 */
8387
#ifndef ADA_URL_AGGREGATOR_H
8388
#define ADA_URL_AGGREGATOR_H
8389
8390
#include <cstddef>
8391
#include <cstdint>
8392
#include <ostream>
8393
#include <string>
8394
#include <string_view>
8395
#include <variant>
8396
8397
8398
namespace ada {
8399
8400
namespace parser {}
8401
8402
/**
8403
 * @brief Memory-efficient URL representation using a single buffer.
8404
 *
8405
 * The `url_aggregator` stores the entire normalized URL in a single string
8406
 * buffer and tracks component boundaries using offsets. This design minimizes
8407
 * memory allocations and is ideal for read-mostly access patterns.
8408
 *
8409
 * Getter methods return `std::string_view` pointing into the internal buffer.
8410
 * These views are lightweight (no allocation) but become invalid if the
8411
 * url_aggregator is modified or destroyed.
8412
 *
8413
 * @warning Views returned by getters (e.g., `get_pathname()`) are invalidated
8414
 * when any setter is called. Do not use a getter's result as input to a
8415
 * setter on the same object without copying first.
8416
 *
8417
 * @note This is the default URL type returned by `ada::parse()`.
8418
 *
8419
 * @see url For an alternative using separate std::string instances
8420
 */
8421
struct url_aggregator : url_base {
8422
2.93k
  url_aggregator() = default;
8423
0
  url_aggregator(const url_aggregator& u) = default;
8424
2.93k
  url_aggregator(url_aggregator&& u) noexcept = default;
8425
0
  url_aggregator& operator=(url_aggregator&& u) noexcept = default;
8426
0
  url_aggregator& operator=(const url_aggregator& u) = default;
8427
5.86k
  ~url_aggregator() override = default;
8428
8429
  /**
8430
   * The setter functions follow the steps defined in the URL Standard.
8431
   *
8432
   * The url_aggregator has a single buffer that contains the entire normalized
8433
   * URL. The various components are represented as offsets into that buffer.
8434
   * When you call get_pathname(), for example, you get a std::string_view that
8435
   * points into that buffer. If the url_aggregator is modified, the buffer may
8436
   * be reallocated, and the std::string_view you obtained earlier may become
8437
   * invalid. In particular, this implies that you cannot modify the URL using
8438
   * a setter function with a std::string_view that points into the
8439
   * url_aggregator E.g., the following is incorrect:
8440
   * url->set_hostname(url->get_pathname()).
8441
   * You must first copy the pathname to a separate string.
8442
   * std::string pathname(url->get_pathname());
8443
   * url->set_hostname(pathname);
8444
   *
8445
   * The caller is responsible for ensuring that the url_aggregator is not
8446
   * modified while any std::string_view obtained from it is in use.
8447
   */
8448
  bool set_href(std::string_view input);
8449
  bool set_host(std::string_view input);
8450
  bool set_hostname(std::string_view input);
8451
  bool set_protocol(std::string_view input);
8452
  bool set_username(std::string_view input);
8453
  bool set_password(std::string_view input);
8454
  bool set_port(std::string_view input);
8455
  bool set_pathname(std::string_view input);
8456
  void set_search(std::string_view input);
8457
  void set_hash(std::string_view input);
8458
8459
  /**
8460
   * Validates whether the hostname is a valid domain according to RFC 1034.
8461
   * @return `true` if the domain is valid, `false` otherwise.
8462
   */
8463
  [[nodiscard]] bool has_valid_domain() const noexcept override;
8464
8465
  /**
8466
   * Returns the URL's origin (scheme + host + port for special URLs).
8467
   * @return A newly allocated string containing the serialized origin.
8468
   * @see https://url.spec.whatwg.org/#concept-url-origin
8469
   */
8470
  [[nodiscard]] std::string get_origin() const override;
8471
8472
  /**
8473
   * Returns the full serialized URL (the href) as a string_view.
8474
   * Does not allocate memory. The returned view becomes invalid if this
8475
   * url_aggregator is modified or destroyed.
8476
   * @return A string_view into the internal buffer.
8477
   * @see https://url.spec.whatwg.org/#dom-url-href
8478
   */
8479
  [[nodiscard]] constexpr std::string_view get_href() const noexcept
8480
      ada_lifetime_bound;
8481
8482
  /**
8483
   * Returns the byte length of the serialized URL without allocating a string.
8484
   * @return Size of the href in bytes.
8485
   */
8486
  [[nodiscard]] constexpr size_t get_href_size() const noexcept;
8487
8488
  /**
8489
   * Returns the URL's username component.
8490
   * Does not allocate memory. The returned view becomes invalid if this
8491
   * url_aggregator is modified or destroyed.
8492
   * @return A string_view of the username.
8493
   * @see https://url.spec.whatwg.org/#dom-url-username
8494
   */
8495
  [[nodiscard]] std::string_view get_username() const ada_lifetime_bound;
8496
8497
  /**
8498
   * Returns the URL's password component.
8499
   * Does not allocate memory. The returned view becomes invalid if this
8500
   * url_aggregator is modified or destroyed.
8501
   * @return A string_view of the password.
8502
   * @see https://url.spec.whatwg.org/#dom-url-password
8503
   */
8504
  [[nodiscard]] std::string_view get_password() const ada_lifetime_bound;
8505
8506
  /**
8507
   * Returns the URL's port as a string (e.g., "8080").
8508
   * Does not allocate memory. Returns empty view if no port is set.
8509
   * The returned view becomes invalid if this url_aggregator is modified.
8510
   * @return A string_view of the port.
8511
   * @see https://url.spec.whatwg.org/#dom-url-port
8512
   */
8513
  [[nodiscard]] std::string_view get_port() const ada_lifetime_bound;
8514
8515
  /**
8516
   * Returns the URL's fragment prefixed with '#' (e.g., "#section").
8517
   * Does not allocate memory. Returns empty view if no fragment is set.
8518
   * The returned view becomes invalid if this url_aggregator is modified.
8519
   * @return A string_view of the hash.
8520
   * @see https://url.spec.whatwg.org/#dom-url-hash
8521
   */
8522
  [[nodiscard]] std::string_view get_hash() const ada_lifetime_bound;
8523
8524
  /**
8525
   * Returns the URL's host and port (e.g., "example.com:8080").
8526
   * Does not allocate memory. Returns empty view if no host is set.
8527
   * The returned view becomes invalid if this url_aggregator is modified.
8528
   * @return A string_view of host:port.
8529
   * @see https://url.spec.whatwg.org/#dom-url-host
8530
   */
8531
  [[nodiscard]] std::string_view get_host() const ada_lifetime_bound;
8532
8533
  /**
8534
   * Returns the URL's hostname (without port).
8535
   * Does not allocate memory. Returns empty view if no host is set.
8536
   * The returned view becomes invalid if this url_aggregator is modified.
8537
   * @return A string_view of the hostname.
8538
   * @see https://url.spec.whatwg.org/#dom-url-hostname
8539
   */
8540
  [[nodiscard]] std::string_view get_hostname() const ada_lifetime_bound;
8541
8542
  /**
8543
   * Returns the URL's path component.
8544
   * Does not allocate memory. The returned view becomes invalid if this
8545
   * url_aggregator is modified or destroyed.
8546
   * @return A string_view of the pathname.
8547
   * @see https://url.spec.whatwg.org/#dom-url-pathname
8548
   */
8549
  [[nodiscard]] constexpr std::string_view get_pathname() const
8550
      ada_lifetime_bound;
8551
8552
  /**
8553
   * Returns the byte length of the pathname without creating a string.
8554
   * @return Size of the pathname in bytes.
8555
   * @see https://url.spec.whatwg.org/#dom-url-pathname
8556
   */
8557
  [[nodiscard]] ada_really_inline uint32_t get_pathname_length() const noexcept;
8558
8559
  /**
8560
   * Returns the URL's query string prefixed with '?' (e.g., "?foo=bar").
8561
   * Does not allocate memory. Returns empty view if no query is set.
8562
   * The returned view becomes invalid if this url_aggregator is modified.
8563
   * @return A string_view of the search/query.
8564
   * @see https://url.spec.whatwg.org/#dom-url-search
8565
   */
8566
  [[nodiscard]] std::string_view get_search() const ada_lifetime_bound;
8567
8568
  /**
8569
   * Returns the URL's scheme followed by a colon (e.g., "https:").
8570
   * Does not allocate memory. The returned view becomes invalid if this
8571
   * url_aggregator is modified or destroyed.
8572
   * @return A string_view of the protocol.
8573
   * @see https://url.spec.whatwg.org/#dom-url-protocol
8574
   */
8575
  [[nodiscard]] std::string_view get_protocol() const ada_lifetime_bound;
8576
8577
  /**
8578
   * Checks if the URL has credentials (non-empty username or password).
8579
   * @return `true` if username or password is non-empty, `false` otherwise.
8580
   */
8581
  [[nodiscard]] ada_really_inline constexpr bool has_credentials()
8582
      const noexcept;
8583
8584
  /**
8585
   * Returns the URL component offsets for efficient serialization.
8586
   *
8587
   * The components represent byte offsets into the serialized URL:
8588
   * ```
8589
   * https://user:pass@example.com:1234/foo/bar?baz#quux
8590
   *       |     |    |          | ^^^^|       |   |
8591
   *       |     |    |          | |   |       |   `----- hash_start
8592
   *       |     |    |          | |   |       `--------- search_start
8593
   *       |     |    |          | |   `----------------- pathname_start
8594
   *       |     |    |          | `--------------------- port
8595
   *       |     |    |          `----------------------- host_end
8596
   *       |     |    `---------------------------------- host_start
8597
   *       |     `--------------------------------------- username_end
8598
   *       `--------------------------------------------- protocol_end
8599
   * ```
8600
   * @return A constant reference to the url_components struct.
8601
   * @see https://github.com/servo/rust-url
8602
   */
8603
  [[nodiscard]] ada_really_inline const url_components& get_components()
8604
      const noexcept;
8605
8606
  /**
8607
   * Returns a JSON string representation of this URL for debugging.
8608
   * @return A JSON-formatted string with all URL components.
8609
   */
8610
  [[nodiscard]] std::string to_string() const override;
8611
8612
  /**
8613
   * Returns a visual diagram showing component boundaries in the URL.
8614
   * Useful for debugging and understanding URL structure.
8615
   * @return A multi-line string diagram.
8616
   */
8617
  [[nodiscard]] std::string to_diagram() const;
8618
8619
  /**
8620
   * Validates internal consistency of component offsets (for debugging).
8621
   * @return `true` if offsets are consistent, `false` if corrupted.
8622
   */
8623
  [[nodiscard]] constexpr bool validate() const noexcept;
8624
8625
  /**
8626
   * Checks if the URL has an empty hostname (host is set but empty string).
8627
   * @return `true` if host exists but is empty, `false` otherwise.
8628
   */
8629
  [[nodiscard]] constexpr bool has_empty_hostname() const noexcept;
8630
8631
  /**
8632
   * Checks if the URL has a hostname (including empty hostnames).
8633
   * @return `true` if host is present, `false` otherwise.
8634
   */
8635
  [[nodiscard]] constexpr bool has_hostname() const noexcept;
8636
8637
  /**
8638
   * Checks if the URL has a non-empty username.
8639
   * @return `true` if username is non-empty, `false` otherwise.
8640
   */
8641
  [[nodiscard]] constexpr bool has_non_empty_username() const noexcept;
8642
8643
  /**
8644
   * Checks if the URL has a non-empty password.
8645
   * @return `true` if password is non-empty, `false` otherwise.
8646
   */
8647
  [[nodiscard]] constexpr bool has_non_empty_password() const noexcept;
8648
8649
  /**
8650
   * Checks if the URL has a non-default port explicitly specified.
8651
   * @return `true` if a port is present, `false` otherwise.
8652
   */
8653
  [[nodiscard]] constexpr bool has_port() const noexcept;
8654
8655
  /**
8656
   * Checks if the URL has a password component (may be empty).
8657
   * @return `true` if password is present, `false` otherwise.
8658
   */
8659
  [[nodiscard]] constexpr bool has_password() const noexcept;
8660
8661
  /**
8662
   * Checks if the URL has a fragment/hash component.
8663
   * @return `true` if hash is present, `false` otherwise.
8664
   */
8665
  [[nodiscard]] constexpr bool has_hash() const noexcept override;
8666
8667
  /**
8668
   * Checks if the URL has a query/search component.
8669
   * @return `true` if query is present, `false` otherwise.
8670
   */
8671
  [[nodiscard]] constexpr bool has_search() const noexcept override;
8672
8673
  /**
8674
   * Removes the port from the URL.
8675
   */
8676
  inline void clear_port();
8677
8678
  /**
8679
   * Removes the hash/fragment from the URL.
8680
   */
8681
  inline void clear_hash();
8682
8683
  /**
8684
   * Removes the query/search string from the URL.
8685
   */
8686
  inline void clear_search() override;
8687
8688
 private:
8689
  // helper methods
8690
  friend void helpers::strip_trailing_spaces_from_opaque_path<url_aggregator>(
8691
      url_aggregator& url);
8692
  // parse_url methods
8693
  friend url_aggregator parser::parse_url<url_aggregator>(
8694
      std::string_view, const url_aggregator*);
8695
8696
  friend url_aggregator parser::parse_url_impl<url_aggregator, true>(
8697
      std::string_view, const url_aggregator*);
8698
  friend url_aggregator parser::parse_url_impl<url_aggregator, false>(
8699
      std::string_view, const url_aggregator*);
8700
  template <class result_type>
8701
  friend bool parser::try_parse_simple_absolute(std::string_view, result_type&);
8702
  template <class result_type>
8703
  friend bool parser::finish_simple_absolute_with_port(std::string_view,
8704
                                                       result_type&,
8705
                                                       ada::scheme::type,
8706
                                                       uint32_t, size_t, size_t,
8707
                                                       size_t, bool);
8708
  template <class result_type>
8709
  friend bool parser::try_parse_simple_relative(std::string_view,
8710
                                                const result_type&,
8711
                                                result_type&);
8712
8713
#if ADA_INCLUDE_URL_PATTERN
8714
  // url_pattern methods
8715
  template <url_pattern_regex::regex_concept regex_provider>
8716
  friend tl::expected<url_pattern<regex_provider>, errors>
8717
  parse_url_pattern_impl(
8718
      std::variant<std::string_view, url_pattern_init>&& input,
8719
      const std::string_view* base_url, const url_pattern_options* options);
8720
#endif  // ADA_INCLUDE_URL_PATTERN
8721
8722
  // components is declared before buffer so that the offset fields land
8723
  // close to url_base in memory, improving cache locality for getter calls.
8724
  // Note: exact cache-line placement is implementation- and platform-dependent.
8725
  url_components components{};
8726
  std::string buffer{};
8727
8728
  /**
8729
   * Returns true if neither the search, nor the hash nor the pathname
8730
   * have been set.
8731
   * @return true if the buffer is ready to receive the path.
8732
   */
8733
  [[nodiscard]] ada_really_inline bool is_at_path() const noexcept;
8734
8735
  inline void add_authority_slashes_if_needed();
8736
8737
  /**
8738
   * To optimize performance, you may indicate how much memory to allocate
8739
   * within this instance.
8740
   */
8741
  constexpr void reserve(uint32_t capacity);
8742
8743
  ada_really_inline size_t parse_port(std::string_view view,
8744
                                      bool check_trailing_content) override;
8745
8746
0
  ada_really_inline size_t parse_port(std::string_view view) override {
8747
0
    return this->parse_port(view, false);
8748
0
  }
8749
8750
  /**
8751
   * Return true on success. The 'in_place' parameter indicates whether the
8752
   * the string_view input is pointing in the buffer. When in_place is false,
8753
   * we must nearly always update the buffer.
8754
   * @see https://url.spec.whatwg.org/#concept-ipv4-parser
8755
   */
8756
  [[nodiscard]] bool parse_ipv4(std::string_view input, bool in_place);
8757
8758
  /**
8759
   * Return true on success.
8760
   * @see https://url.spec.whatwg.org/#concept-ipv6-parser
8761
   */
8762
  [[nodiscard]] bool parse_ipv6(std::string_view input);
8763
8764
  /**
8765
   * Return true on success.
8766
   * @see https://url.spec.whatwg.org/#concept-opaque-host-parser
8767
   */
8768
  [[nodiscard]] bool parse_opaque_host(std::string_view input);
8769
8770
  ada_really_inline void parse_path(std::string_view input);
8771
8772
  /**
8773
   * A URL cannot have a username/password/port if its host is null or the empty
8774
   * string, or its scheme is "file".
8775
   */
8776
  [[nodiscard]] constexpr bool cannot_have_credentials_or_port() const;
8777
8778
  /**
8779
   * @private
8780
   * Several setters restore a saved copy of the URL when the mutation pushes
8781
   * the buffer past get_max_input_length(). A setter grows the buffer by at
8782
   * most input_len * 3 (worst-case percent-encoding) plus a small constant for
8783
   * delimiters, so this returns false when that upper bound stays within the
8784
   * limit. It does not account for parse-failure rollbacks, which are
8785
   * unrelated to the length limit.
8786
   */
8787
  [[nodiscard]] bool needs_rollback_snapshot(size_t input_len) const noexcept;
8788
8789
  template <bool override_hostname = false>
8790
  bool set_host_or_hostname(std::string_view input);
8791
8792
  ada_really_inline bool parse_host(std::string_view input);
8793
8794
  inline void update_base_authority(std::string_view base_buffer,
8795
                                    const url_components& base);
8796
  inline void update_unencoded_base_hash(std::string_view input);
8797
  inline void update_base_hostname(std::string_view input);
8798
  inline void update_base_search(std::string_view input);
8799
  inline void update_base_search(std::string_view input,
8800
                                 const uint8_t* query_percent_encode_set);
8801
  inline void update_base_pathname(std::string_view input);
8802
  inline void update_base_username(std::string_view input);
8803
  inline void append_base_username(std::string_view input);
8804
  inline void update_base_password(std::string_view input);
8805
  inline void append_base_password(std::string_view input);
8806
  inline void update_base_port(uint32_t input);
8807
  inline void append_base_pathname(std::string_view input);
8808
  [[nodiscard]] inline uint32_t retrieve_base_port() const;
8809
  constexpr void clear_hostname();
8810
  constexpr void clear_password();
8811
  constexpr void clear_pathname() override;
8812
  [[nodiscard]] constexpr bool has_dash_dot() const noexcept;
8813
  void delete_dash_dot();
8814
  inline void consume_prepared_path(std::string_view input);
8815
  template <bool has_state_override = false>
8816
  [[nodiscard]] ada_really_inline bool parse_scheme_with_colon(
8817
      std::string_view input);
8818
  ada_really_inline uint32_t replace_and_resize(uint32_t start, uint32_t end,
8819
                                                std::string_view input);
8820
  [[nodiscard]] constexpr bool has_authority() const noexcept;
8821
  constexpr void set_protocol_as_file();
8822
  inline void set_scheme(std::string_view new_scheme);
8823
  /**
8824
   * Fast function to set the scheme from a view with a colon in the
8825
   * buffer, does not change type.
8826
   */
8827
  inline void set_scheme_from_view_with_colon(
8828
      std::string_view new_scheme_with_colon);
8829
  inline void copy_scheme(const url_aggregator& u);
8830
8831
  inline void update_host_to_base_host(const std::string_view input);
8832
8833
};  // url_aggregator
8834
8835
inline std::ostream& operator<<(std::ostream& out, const url& u);
8836
}  // namespace ada
8837
8838
#endif
8839
/* end file include/ada/url_aggregator.h */
8840
/* begin file include/ada/url_aggregator-inl.h */
8841
/**
8842
 * @file url_aggregator-inl.h
8843
 * @brief Inline functions for url aggregator
8844
 */
8845
#ifndef ADA_URL_AGGREGATOR_INL_H
8846
#define ADA_URL_AGGREGATOR_INL_H
8847
8848
/* begin file include/ada/unicode-inl.h */
8849
/**
8850
 * @file unicode-inl.h
8851
 * @brief Definitions for unicode operations.
8852
 */
8853
#ifndef ADA_UNICODE_INL_H
8854
#define ADA_UNICODE_INL_H
8855
8856
#include <cstddef>
8857
#include <cstdint>
8858
#include <cstring>
8859
#include <string_view>
8860
8861
/**
8862
 * Unicode operations. These functions are not part of our public API and may
8863
 * change at any time.
8864
 *
8865
 * private
8866
 * @namespace ada::unicode
8867
 * @brief Includes the declarations for unicode operations
8868
 */
8869
namespace ada::unicode {
8870
ada_really_inline size_t percent_encode_index(const std::string_view input,
8871
252
                                              const uint8_t character_set[]) {
8872
252
  const char* data = input.data();
8873
252
  const size_t size = input.size();
8874
8875
  // Process 8 bytes at a time using unrolled loop
8876
252
  size_t i = 0;
8877
3.71k
  for (; i + 8 <= size; i += 8) {
8878
3.46k
    unsigned char chunk[8];
8879
3.46k
    std::memcpy(&chunk, data + i,
8880
3.46k
                8);  // entices compiler to unconditionally process 8 characters
8881
8882
    // Check 8 characters at once
8883
31.1k
    for (size_t j = 0; j < 8; j++) {
8884
27.7k
      if (character_sets::bit_at(character_set, chunk[j])) {
8885
0
        return i + j;
8886
0
      }
8887
27.7k
    }
8888
3.46k
  }
8889
8890
  // Handle remaining bytes
8891
1.15k
  for (; i < size; i++) {
8892
899
    if (character_sets::bit_at(character_set, data[i])) {
8893
0
      return i;
8894
0
    }
8895
899
  }
8896
8897
252
  return size;
8898
252
}
8899
}  // namespace ada::unicode
8900
8901
#endif  // ADA_UNICODE_INL_H
8902
/* end file include/ada/unicode-inl.h */
8903
8904
#include <charconv>
8905
#include <cstdint>
8906
#include <cstring>
8907
#include <ostream>
8908
#include <string>
8909
#include <string_view>
8910
#include <system_error>
8911
8912
namespace ada {
8913
8914
inline void url_aggregator::update_base_authority(
8915
0
    std::string_view base_buffer, const ada::url_components& base) {
8916
0
  std::string_view input = base_buffer.substr(
8917
0
      base.protocol_end, base.host_start - base.protocol_end);
8918
0
  ada_log("url_aggregator::update_base_authority ", input);
8919
8920
0
  bool input_starts_with_dash = input.starts_with("//");
8921
0
  uint32_t diff = components.host_start - components.protocol_end;
8922
8923
0
  buffer.erase(components.protocol_end,
8924
0
               components.host_start - components.protocol_end);
8925
0
  components.username_end = components.protocol_end;
8926
8927
0
  if (input_starts_with_dash) {
8928
0
    input.remove_prefix(2);
8929
0
    diff += 2;  // add "//"
8930
0
    buffer.insert(components.protocol_end, "//");
8931
0
    components.username_end += 2;
8932
0
  }
8933
8934
0
  size_t password_delimiter = input.find(':');
8935
8936
  // Check if input contains both username and password by checking the
8937
  // delimiter: ":" A typical input that contains authority would be "user:pass"
8938
0
  if (password_delimiter != std::string_view::npos) {
8939
    // Insert both username and password
8940
0
    std::string_view username = input.substr(0, password_delimiter);
8941
0
    std::string_view password = input.substr(password_delimiter + 1);
8942
8943
0
    buffer.insert(components.protocol_end + diff, username);
8944
0
    diff += uint32_t(username.size());
8945
0
    buffer.insert(components.protocol_end + diff, ":");
8946
0
    components.username_end = components.protocol_end + diff;
8947
0
    buffer.insert(components.protocol_end + diff + 1, password);
8948
0
    diff += uint32_t(password.size()) + 1;
8949
0
  } else if (!input.empty()) {
8950
    // Insert only username
8951
0
    buffer.insert(components.protocol_end + diff, input);
8952
0
    components.username_end =
8953
0
        components.protocol_end + diff + uint32_t(input.size());
8954
0
    diff += uint32_t(input.size());
8955
0
  }
8956
8957
0
  components.host_start += diff;
8958
8959
0
  if (buffer.size() > base.host_start && buffer[base.host_start] != '@') {
8960
0
    buffer.insert(components.host_start, "@");
8961
0
    diff++;
8962
0
  }
8963
0
  components.host_end += diff;
8964
0
  components.pathname_start += diff;
8965
0
  if (components.search_start != url_components::omitted) {
8966
0
    components.search_start += diff;
8967
0
  }
8968
0
  if (components.hash_start != url_components::omitted) {
8969
0
    components.hash_start += diff;
8970
0
  }
8971
0
}
8972
8973
353
inline void url_aggregator::update_unencoded_base_hash(std::string_view input) {
8974
353
  ada_log("url_aggregator::update_unencoded_base_hash ", input, " [",
8975
353
          input.size(), " bytes], buffer is '", buffer, "' [", buffer.size(),
8976
353
          " bytes] components.hash_start = ", components.hash_start);
8977
353
  ADA_ASSERT_TRUE(validate());
8978
353
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
8979
353
  if (components.hash_start != url_components::omitted) {
8980
0
    buffer.resize(components.hash_start);
8981
0
  }
8982
353
  components.hash_start = uint32_t(buffer.size());
8983
353
  buffer += "#";
8984
353
  bool encoding_required = unicode::percent_encode<true>(
8985
353
      input, ada::character_sets::FRAGMENT_PERCENT_ENCODE, buffer);
8986
  // When encoding_required is false, then buffer is left unchanged, and percent
8987
  // encoding was not deemed required.
8988
353
  if (!encoding_required) {
8989
165
    buffer.append(input);
8990
165
  }
8991
353
  ada_log("url_aggregator::update_unencoded_base_hash final buffer is '",
8992
353
          buffer, "' [", buffer.size(), " bytes]");
8993
353
  ADA_ASSERT_TRUE(validate());
8994
353
}
8995
8996
ada_really_inline uint32_t url_aggregator::replace_and_resize(
8997
743
    uint32_t start, uint32_t end, std::string_view input) {
8998
743
  uint32_t current_length = end - start;
8999
743
  uint32_t input_size = uint32_t(input.size());
9000
743
  uint32_t new_difference = input_size - current_length;
9001
9002
743
  if (current_length == 0) {
9003
491
    buffer.insert(start, input);
9004
491
  } else if (input_size == current_length) {
9005
4
    if (input_size != 0) {
9006
4
      std::memmove(buffer.data() + start, input.data(), input_size);
9007
4
    }
9008
248
  } else if (input_size < current_length) {
9009
71
    buffer.erase(start, current_length - input_size);
9010
71
    buffer.replace(start, input_size, input);
9011
177
  } else {
9012
177
    buffer.replace(start, current_length, input.substr(0, current_length));
9013
177
    buffer.insert(start + current_length, input.substr(current_length));
9014
177
  }
9015
9016
743
  return new_difference;
9017
743
}
9018
9019
491
inline void url_aggregator::update_base_hostname(const std::string_view input) {
9020
491
  ada_log("url_aggregator::update_base_hostname ", input, " [", input.size(),
9021
491
          " bytes], buffer is '", buffer, "' [", buffer.size(), " bytes]");
9022
491
  ADA_ASSERT_TRUE(validate());
9023
491
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
9024
9025
  // This next line is required for when parsing a URL like `foo://`
9026
491
  add_authority_slashes_if_needed();
9027
9028
491
  bool has_credentials = components.protocol_end + 2 < components.host_start;
9029
491
  uint32_t new_difference =
9030
491
      replace_and_resize(components.host_start, components.host_end, input);
9031
9032
491
  if (has_credentials) {
9033
0
    buffer.insert(components.host_start, "@");
9034
0
    new_difference++;
9035
0
  }
9036
491
  components.host_end += new_difference;
9037
491
  components.pathname_start += new_difference;
9038
491
  if (components.search_start != url_components::omitted) {
9039
0
    components.search_start += new_difference;
9040
0
  }
9041
491
  if (components.hash_start != url_components::omitted) {
9042
0
    components.hash_start += new_difference;
9043
0
  }
9044
491
  ADA_ASSERT_TRUE(validate());
9045
491
}
9046
9047
[[nodiscard]] ada_really_inline uint32_t
9048
0
url_aggregator::get_pathname_length() const noexcept {
9049
0
  ada_log("url_aggregator::get_pathname_length");
9050
0
  uint32_t ending_index = uint32_t(buffer.size());
9051
0
  if (components.search_start != url_components::omitted) {
9052
0
    ending_index = components.search_start;
9053
0
  } else if (components.hash_start != url_components::omitted) {
9054
0
    ending_index = components.hash_start;
9055
0
  }
9056
0
  return ending_index - components.pathname_start;
9057
0
}
9058
9059
[[nodiscard]] ada_really_inline bool url_aggregator::is_at_path()
9060
1.50k
    const noexcept {
9061
1.50k
  return buffer.size() == components.pathname_start;
9062
1.50k
}
9063
9064
0
inline void url_aggregator::update_base_search(std::string_view input) {
9065
0
  ada_log("url_aggregator::update_base_search ", input);
9066
0
  ADA_ASSERT_TRUE(validate());
9067
0
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
9068
0
  if (input.empty()) {
9069
0
    clear_search();
9070
0
    return;
9071
0
  }
9072
9073
0
  if (input[0] == '?') {
9074
0
    input.remove_prefix(1);
9075
0
  }
9076
9077
0
  if (components.hash_start == url_components::omitted) {
9078
0
    if (components.search_start == url_components::omitted) {
9079
0
      components.search_start = uint32_t(buffer.size());
9080
0
      buffer += "?";
9081
0
    } else {
9082
0
      buffer.resize(components.search_start + 1);
9083
0
    }
9084
9085
0
    buffer.append(input);
9086
0
  } else if (components.search_start != url_components::omitted) {
9087
0
    const uint32_t difference = replace_and_resize(
9088
0
        components.search_start + 1, components.hash_start, input);
9089
0
    components.hash_start += difference;
9090
0
  } else {
9091
0
    components.search_start = components.hash_start;
9092
0
    buffer.insert(components.search_start, input.size() + 1, '?');
9093
0
    if (!input.empty()) {
9094
0
      std::memmove(buffer.data() + components.search_start + 1, input.data(),
9095
0
                   input.size());
9096
0
    }
9097
0
    components.hash_start += uint32_t(input.size() + 1);  // Do not forget `?`
9098
0
  }
9099
9100
0
  ADA_ASSERT_TRUE(validate());
9101
0
}
9102
9103
inline void url_aggregator::update_base_search(
9104
3.07k
    std::string_view input, const uint8_t query_percent_encode_set[]) {
9105
3.07k
  ada_log("url_aggregator::update_base_search ", input,
9106
3.07k
          " with encoding parameter ", to_string(), "\n", to_diagram());
9107
3.07k
  ADA_ASSERT_TRUE(validate());
9108
3.07k
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
9109
9110
3.07k
  if (components.hash_start == url_components::omitted) {
9111
2.82k
    if (components.search_start == url_components::omitted) {
9112
1.50k
      components.search_start = uint32_t(buffer.size());
9113
1.50k
      buffer += "?";
9114
1.50k
    } else {
9115
1.32k
      buffer.resize(components.search_start + 1);
9116
1.32k
    }
9117
9118
2.82k
    bool encoding_required =
9119
2.82k
        unicode::percent_encode<true>(input, query_percent_encode_set, buffer);
9120
    // When encoding_required is false, then buffer is left unchanged, and
9121
    // percent encoding was not deemed required.
9122
2.82k
    if (!encoding_required) {
9123
1.63k
      buffer.append(input);
9124
1.63k
    }
9125
2.82k
  } else {
9126
252
    const size_t idx =
9127
252
        ada::unicode::percent_encode_index(input, query_percent_encode_set);
9128
252
    std::string encoded;
9129
252
    std::string_view replacement = input;
9130
252
    if (idx != input.size()) {
9131
0
      encoded =
9132
0
          ada::unicode::percent_encode(input, query_percent_encode_set, idx);
9133
0
      replacement = encoded;
9134
0
    }
9135
9136
252
    if (components.search_start != url_components::omitted) {
9137
252
      const uint32_t difference = replace_and_resize(
9138
252
          components.search_start + 1, components.hash_start, replacement);
9139
252
      components.hash_start += difference;
9140
252
    } else {
9141
0
      components.search_start = components.hash_start;
9142
0
      buffer.insert(components.search_start, replacement.size() + 1, '?');
9143
0
      if (!replacement.empty()) {
9144
0
        std::memmove(buffer.data() + components.search_start + 1,
9145
0
                     replacement.data(), replacement.size());
9146
0
      }
9147
0
      components.hash_start +=
9148
0
          uint32_t(replacement.size() + 1);  // Do not forget `?`
9149
0
    }
9150
252
  }
9151
9152
3.07k
  ADA_ASSERT_TRUE(validate());
9153
3.07k
}
9154
9155
0
inline void url_aggregator::update_base_pathname(const std::string_view input) {
9156
0
  ada_log("url_aggregator::update_base_pathname '", input, "' [", input.size(),
9157
0
          " bytes] \n", to_diagram());
9158
0
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
9159
0
  ADA_ASSERT_TRUE(validate());
9160
9161
0
  const bool begins_with_dashdash = input.starts_with("//");
9162
0
  if (!begins_with_dashdash && has_dash_dot()) {
9163
    // We must delete the ./
9164
0
    delete_dash_dot();
9165
0
  }
9166
9167
0
  if (begins_with_dashdash && !has_opaque_path && !has_authority() &&
9168
0
      !has_dash_dot()) {
9169
    // If url's host is null, url does not have an opaque path, url's path's
9170
    // size is greater than 1, then append U+002F (/) followed by U+002E (.) to
9171
    // output.
9172
0
    buffer.insert(components.pathname_start, "/.");
9173
0
    components.pathname_start += 2;
9174
0
    if (components.search_start != url_components::omitted) {
9175
0
      components.search_start += 2;
9176
0
    }
9177
0
    if (components.hash_start != url_components::omitted) {
9178
0
      components.hash_start += 2;
9179
0
    }
9180
0
  }
9181
9182
0
  uint32_t difference = replace_and_resize(
9183
0
      components.pathname_start,
9184
0
      components.pathname_start + get_pathname_length(), input);
9185
0
  if (components.search_start != url_components::omitted) {
9186
0
    components.search_start += difference;
9187
0
  }
9188
0
  if (components.hash_start != url_components::omitted) {
9189
0
    components.hash_start += difference;
9190
0
  }
9191
0
  ADA_ASSERT_TRUE(validate());
9192
0
}
9193
9194
0
inline void url_aggregator::append_base_pathname(const std::string_view input) {
9195
0
  ada_log("url_aggregator::append_base_pathname ", input, " ", to_string(),
9196
0
          "\n", to_diagram());
9197
0
  ADA_ASSERT_TRUE(validate());
9198
0
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
9199
#if ADA_DEVELOPMENT_CHECKS
9200
  // computing the expected password.
9201
  std::string path_expected(get_pathname());
9202
  path_expected.append(input);
9203
#endif  // ADA_DEVELOPMENT_CHECKS
9204
0
  uint32_t ending_index = uint32_t(buffer.size());
9205
0
  if (components.search_start != url_components::omitted) {
9206
0
    ending_index = components.search_start;
9207
0
  } else if (components.hash_start != url_components::omitted) {
9208
0
    ending_index = components.hash_start;
9209
0
  }
9210
0
  buffer.insert(ending_index, input);
9211
9212
0
  if (components.search_start != url_components::omitted) {
9213
0
    components.search_start += uint32_t(input.size());
9214
0
  }
9215
0
  if (components.hash_start != url_components::omitted) {
9216
0
    components.hash_start += uint32_t(input.size());
9217
0
  }
9218
#if ADA_DEVELOPMENT_CHECKS
9219
  std::string path_after = std::string(get_pathname());
9220
  ADA_ASSERT_EQUAL(
9221
      path_expected, path_after,
9222
      "append_base_pathname problem after inserting " + std::string(input));
9223
#endif  // ADA_DEVELOPMENT_CHECKS
9224
0
  ADA_ASSERT_TRUE(validate());
9225
0
}
9226
9227
0
inline void url_aggregator::update_base_username(const std::string_view input) {
9228
0
  ada_log("url_aggregator::update_base_username '", input, "' ", to_string(),
9229
0
          "\n", to_diagram());
9230
0
  ADA_ASSERT_TRUE(validate());
9231
0
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
9232
9233
0
  add_authority_slashes_if_needed();
9234
9235
0
  bool has_password = has_non_empty_password();
9236
0
  bool host_starts_with_at = buffer.size() > components.host_start &&
9237
0
                             buffer[components.host_start] == '@';
9238
0
  uint32_t diff = replace_and_resize(components.protocol_end + 2,
9239
0
                                     components.username_end, input);
9240
9241
0
  components.username_end += diff;
9242
0
  components.host_start += diff;
9243
9244
0
  if (!input.empty() && !host_starts_with_at) {
9245
0
    buffer.insert(components.host_start, "@");
9246
0
    diff++;
9247
0
  } else if (input.empty() && host_starts_with_at && !has_password) {
9248
    // Input is empty, there is no password, and we need to remove "@" from
9249
    // hostname
9250
0
    buffer.erase(components.host_start, 1);
9251
0
    diff--;
9252
0
  }
9253
9254
0
  components.host_end += diff;
9255
0
  components.pathname_start += diff;
9256
0
  if (components.search_start != url_components::omitted) {
9257
0
    components.search_start += diff;
9258
0
  }
9259
0
  if (components.hash_start != url_components::omitted) {
9260
0
    components.hash_start += diff;
9261
0
  }
9262
0
  ADA_ASSERT_TRUE(validate());
9263
0
}
9264
9265
0
inline void url_aggregator::append_base_username(const std::string_view input) {
9266
0
  ada_log("url_aggregator::append_base_username ", input);
9267
0
  ADA_ASSERT_TRUE(validate());
9268
0
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
9269
#if ADA_DEVELOPMENT_CHECKS
9270
  // computing the expected password.
9271
  std::string username_expected(get_username());
9272
  username_expected.append(input);
9273
#endif  // ADA_DEVELOPMENT_CHECKS
9274
0
  add_authority_slashes_if_needed();
9275
9276
  // If input is empty, do nothing.
9277
0
  if (input.empty()) {
9278
0
    return;
9279
0
  }
9280
9281
0
  uint32_t difference = uint32_t(input.size());
9282
0
  buffer.insert(components.username_end, input);
9283
0
  components.username_end += difference;
9284
0
  components.host_start += difference;
9285
9286
0
  if (buffer[components.host_start] != '@' &&
9287
0
      components.host_start != components.host_end) {
9288
0
    buffer.insert(components.host_start, "@");
9289
0
    difference++;
9290
0
  }
9291
9292
0
  components.host_end += difference;
9293
0
  components.pathname_start += difference;
9294
0
  if (components.search_start != url_components::omitted) {
9295
0
    components.search_start += difference;
9296
0
  }
9297
0
  if (components.hash_start != url_components::omitted) {
9298
0
    components.hash_start += difference;
9299
0
  }
9300
#if ADA_DEVELOPMENT_CHECKS
9301
  std::string username_after(get_username());
9302
  ADA_ASSERT_EQUAL(
9303
      username_expected, username_after,
9304
      "append_base_username problem after inserting " + std::string(input));
9305
#endif  // ADA_DEVELOPMENT_CHECKS
9306
0
  ADA_ASSERT_TRUE(validate());
9307
0
}
9308
9309
0
constexpr void url_aggregator::clear_password() {
9310
0
  ada_log("url_aggregator::clear_password ", to_string());
9311
0
  ADA_ASSERT_TRUE(validate());
9312
0
  if (!has_password()) {
9313
0
    return;
9314
0
  }
9315
9316
0
  uint32_t diff = components.host_start - components.username_end;
9317
0
  buffer.erase(components.username_end, diff);
9318
0
  components.host_start -= diff;
9319
0
  components.host_end -= diff;
9320
0
  components.pathname_start -= diff;
9321
0
  if (components.search_start != url_components::omitted) {
9322
0
    components.search_start -= diff;
9323
0
  }
9324
0
  if (components.hash_start != url_components::omitted) {
9325
0
    components.hash_start -= diff;
9326
0
  }
9327
0
}
9328
9329
0
inline void url_aggregator::update_base_password(const std::string_view input) {
9330
0
  ada_log("url_aggregator::update_base_password ", input);
9331
0
  ADA_ASSERT_TRUE(validate());
9332
0
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
9333
9334
0
  add_authority_slashes_if_needed();
9335
9336
  // TODO: Optimization opportunity. Merge the following removal functions.
9337
0
  if (input.empty()) {
9338
0
    clear_password();
9339
9340
    // Remove username too, if it is empty.
9341
0
    if (!has_non_empty_username()) {
9342
0
      update_base_username("");
9343
0
    }
9344
9345
0
    return;
9346
0
  }
9347
9348
0
  bool password_exists = has_password();
9349
0
  uint32_t difference = uint32_t(input.size());
9350
9351
0
  if (password_exists) {
9352
0
    difference = replace_and_resize(components.username_end + 1,
9353
0
                                    components.host_start, input);
9354
0
  } else {
9355
0
    buffer.insert(components.username_end, input.size() + 1, ':');
9356
0
    std::memmove(buffer.data() + components.username_end + 1, input.data(),
9357
0
                 input.size());
9358
0
    difference++;
9359
0
  }
9360
0
  components.host_start += difference;
9361
9362
  // The following line is required to add "@" to hostname. When updating
9363
  // password if hostname does not start with "@", it is "update_base_password"s
9364
  // responsibility to set it.
9365
0
  if (buffer[components.host_start] != '@') {
9366
0
    buffer.insert(components.host_start, "@");
9367
0
    difference++;
9368
0
  }
9369
9370
0
  components.host_end += difference;
9371
0
  components.pathname_start += difference;
9372
0
  if (components.search_start != url_components::omitted) {
9373
0
    components.search_start += difference;
9374
0
  }
9375
0
  if (components.hash_start != url_components::omitted) {
9376
0
    components.hash_start += difference;
9377
0
  }
9378
0
  ADA_ASSERT_TRUE(validate());
9379
0
}
9380
9381
0
inline void url_aggregator::append_base_password(const std::string_view input) {
9382
0
  ada_log("url_aggregator::append_base_password ", input, " ", to_string(),
9383
0
          "\n", to_diagram());
9384
0
  ADA_ASSERT_TRUE(validate());
9385
0
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
9386
#if ADA_DEVELOPMENT_CHECKS
9387
  // computing the expected password.
9388
  std::string password_expected = std::string(get_password());
9389
  password_expected.append(input);
9390
#endif  // ADA_DEVELOPMENT_CHECKS
9391
0
  add_authority_slashes_if_needed();
9392
9393
  // If input is empty, do nothing.
9394
0
  if (input.empty()) {
9395
0
    return;
9396
0
  }
9397
9398
0
  uint32_t difference = uint32_t(input.size());
9399
0
  if (has_password()) {
9400
0
    buffer.insert(components.host_start, input);
9401
0
  } else {
9402
0
    difference++;  // Increment for ":"
9403
0
    buffer.insert(components.username_end, ":");
9404
0
    buffer.insert(components.username_end + 1, input);
9405
0
  }
9406
0
  components.host_start += difference;
9407
9408
  // The following line is required to add "@" to hostname. When updating
9409
  // password if hostname does not start with "@", it is "append_base_password"s
9410
  // responsibility to set it.
9411
0
  if (buffer[components.host_start] != '@') {
9412
0
    buffer.insert(components.host_start, "@");
9413
0
    difference++;
9414
0
  }
9415
9416
0
  components.host_end += difference;
9417
0
  components.pathname_start += difference;
9418
0
  if (components.search_start != url_components::omitted) {
9419
0
    components.search_start += difference;
9420
0
  }
9421
0
  if (components.hash_start != url_components::omitted) {
9422
0
    components.hash_start += difference;
9423
0
  }
9424
#if ADA_DEVELOPMENT_CHECKS
9425
  std::string password_after(get_password());
9426
  ADA_ASSERT_EQUAL(
9427
      password_expected, password_after,
9428
      "append_base_password problem after inserting " + std::string(input));
9429
#endif  // ADA_DEVELOPMENT_CHECKS
9430
0
  ADA_ASSERT_TRUE(validate());
9431
0
}
9432
9433
0
inline void url_aggregator::update_base_port(uint32_t input) {
9434
0
  ada_log("url_aggregator::update_base_port");
9435
0
  ADA_ASSERT_TRUE(validate());
9436
0
  if (input == url_components::omitted) {
9437
0
    clear_port();
9438
0
    return;
9439
0
  }
9440
  // calling std::to_string(input.value()) is unfortunate given that the port
9441
  // value is probably already available as a string.
9442
0
  std::string value = helpers::concat(":", std::to_string(input));
9443
0
  uint32_t difference = uint32_t(value.size());
9444
9445
0
  if (components.port != url_components::omitted) {
9446
0
    difference -= components.pathname_start - components.host_end;
9447
0
    buffer.erase(components.host_end,
9448
0
                 components.pathname_start - components.host_end);
9449
0
  }
9450
9451
0
  buffer.insert(components.host_end, value);
9452
0
  components.pathname_start += difference;
9453
0
  if (components.search_start != url_components::omitted) {
9454
0
    components.search_start += difference;
9455
0
  }
9456
0
  if (components.hash_start != url_components::omitted) {
9457
0
    components.hash_start += difference;
9458
0
  }
9459
0
  components.port = input;
9460
0
  ADA_ASSERT_TRUE(validate());
9461
0
}
9462
9463
0
inline void url_aggregator::clear_port() {
9464
0
  ada_log("url_aggregator::clear_port");
9465
0
  ADA_ASSERT_TRUE(validate());
9466
0
  if (components.port == url_components::omitted) {
9467
0
    return;
9468
0
  }
9469
0
  uint32_t length = components.pathname_start - components.host_end;
9470
0
  buffer.erase(components.host_end, length);
9471
0
  components.pathname_start -= length;
9472
0
  if (components.search_start != url_components::omitted) {
9473
0
    components.search_start -= length;
9474
0
  }
9475
0
  if (components.hash_start != url_components::omitted) {
9476
0
    components.hash_start -= length;
9477
0
  }
9478
0
  components.port = url_components::omitted;
9479
0
  ADA_ASSERT_TRUE(validate());
9480
0
}
9481
9482
0
[[nodiscard]] inline uint32_t url_aggregator::retrieve_base_port() const {
9483
0
  ada_log("url_aggregator::retrieve_base_port");
9484
0
  return components.port;
9485
0
}
9486
9487
1.35k
inline void url_aggregator::clear_search() {
9488
1.35k
  ada_log("url_aggregator::clear_search");
9489
1.35k
  ADA_ASSERT_TRUE(validate());
9490
1.35k
  if (components.search_start == url_components::omitted) {
9491
0
    return;
9492
0
  }
9493
9494
1.35k
  if (components.hash_start == url_components::omitted) {
9495
1.17k
    buffer.resize(components.search_start);
9496
1.17k
  } else {
9497
185
    buffer.erase(components.search_start,
9498
185
                 components.hash_start - components.search_start);
9499
185
    components.hash_start = components.search_start;
9500
185
  }
9501
9502
1.35k
  components.search_start = url_components::omitted;
9503
9504
#if ADA_DEVELOPMENT_CHECKS
9505
  ADA_ASSERT_EQUAL(get_search(), "",
9506
                   "search should have been cleared on buffer=" + buffer +
9507
                       " with " + components.to_string() + "\n" + to_diagram());
9508
#endif
9509
1.35k
  ADA_ASSERT_TRUE(validate());
9510
1.35k
}
9511
9512
0
inline void url_aggregator::clear_hash() {
9513
0
  ada_log("url_aggregator::clear_hash");
9514
0
  ADA_ASSERT_TRUE(validate());
9515
0
  if (components.hash_start == url_components::omitted) {
9516
0
    return;
9517
0
  }
9518
0
  buffer.resize(components.hash_start);
9519
0
  components.hash_start = url_components::omitted;
9520
9521
#if ADA_DEVELOPMENT_CHECKS
9522
  ADA_ASSERT_EQUAL(get_hash(), "",
9523
                   "hash should have been cleared on buffer=" + buffer +
9524
                       " with " + components.to_string() + "\n" + to_diagram());
9525
#endif
9526
0
  ADA_ASSERT_TRUE(validate());
9527
0
}
9528
9529
0
constexpr void url_aggregator::clear_pathname() {
9530
0
  ada_log("url_aggregator::clear_pathname");
9531
0
  ADA_ASSERT_TRUE(validate());
9532
0
  uint32_t ending_index = uint32_t(buffer.size());
9533
0
  if (components.search_start != url_components::omitted) {
9534
0
    ending_index = components.search_start;
9535
0
  } else if (components.hash_start != url_components::omitted) {
9536
0
    ending_index = components.hash_start;
9537
0
  }
9538
0
  uint32_t pathname_length = ending_index - components.pathname_start;
9539
0
  buffer.erase(components.pathname_start, pathname_length);
9540
0
  uint32_t difference = pathname_length;
9541
0
  if (components.pathname_start == components.host_end + 2 &&
9542
0
      buffer[components.host_end] == '/' &&
9543
0
      buffer[components.host_end + 1] == '.') {
9544
0
    components.pathname_start -= 2;
9545
0
    buffer.erase(components.host_end, 2);
9546
0
    difference += 2;
9547
0
  }
9548
0
  if (components.search_start != url_components::omitted) {
9549
0
    components.search_start -= difference;
9550
0
  }
9551
0
  if (components.hash_start != url_components::omitted) {
9552
0
    components.hash_start -= difference;
9553
0
  }
9554
0
  ada_log("url_aggregator::clear_pathname completed, running checks...");
9555
#if ADA_DEVELOPMENT_CHECKS
9556
  ADA_ASSERT_EQUAL(get_pathname(), "",
9557
                   "pathname should have been cleared on buffer=" + buffer +
9558
                       " with " + components.to_string() + "\n" + to_diagram());
9559
#endif
9560
0
  ADA_ASSERT_TRUE(validate());
9561
0
  ada_log("url_aggregator::clear_pathname completed, running checks... ok");
9562
0
}
9563
9564
0
constexpr void url_aggregator::clear_hostname() {
9565
0
  ada_log("url_aggregator::clear_hostname");
9566
0
  ADA_ASSERT_TRUE(validate());
9567
0
  if (!has_authority()) {
9568
0
    return;
9569
0
  }
9570
0
  ADA_ASSERT_TRUE(has_authority());
9571
9572
0
  uint32_t hostname_length = components.host_end - components.host_start;
9573
0
  uint32_t start = components.host_start;
9574
9575
  // If hostname starts with "@", we should not remove that character.
9576
0
  if (hostname_length > 0 && buffer[start] == '@') {
9577
0
    start++;
9578
0
    hostname_length--;
9579
0
  }
9580
0
  buffer.erase(start, hostname_length);
9581
0
  components.host_end = start;
9582
0
  components.pathname_start -= hostname_length;
9583
0
  if (components.search_start != url_components::omitted) {
9584
0
    components.search_start -= hostname_length;
9585
0
  }
9586
0
  if (components.hash_start != url_components::omitted) {
9587
0
    components.hash_start -= hostname_length;
9588
0
  }
9589
#if ADA_DEVELOPMENT_CHECKS
9590
  ADA_ASSERT_EQUAL(get_hostname(), "",
9591
                   "hostname should have been cleared on buffer=" + buffer +
9592
                       " with " + components.to_string() + "\n" + to_diagram());
9593
#endif
9594
0
  ADA_ASSERT_TRUE(has_authority());
9595
0
  ADA_ASSERT_EQUAL(has_empty_hostname(), true,
9596
0
                   "hostname should have been cleared on buffer=" + buffer +
9597
0
                       " with " + components.to_string() + "\n" + to_diagram());
9598
0
  ADA_ASSERT_TRUE(validate());
9599
0
}
9600
9601
0
[[nodiscard]] constexpr bool url_aggregator::has_hash() const noexcept {
9602
0
  ada_log("url_aggregator::has_hash");
9603
0
  return components.hash_start != url_components::omitted;
9604
0
}
9605
9606
0
[[nodiscard]] constexpr bool url_aggregator::has_search() const noexcept {
9607
0
  ada_log("url_aggregator::has_search");
9608
0
  return components.search_start != url_components::omitted;
9609
0
}
9610
9611
0
constexpr bool url_aggregator::has_credentials() const noexcept {
9612
0
  ada_log("url_aggregator::has_credentials");
9613
0
  return has_non_empty_username() || has_non_empty_password();
9614
0
}
9615
9616
0
constexpr bool url_aggregator::cannot_have_credentials_or_port() const {
9617
0
  ada_log("url_aggregator::cannot_have_credentials_or_port");
9618
0
  return type == ada::scheme::type::FILE ||
9619
0
         components.host_start == components.host_end;
9620
0
}
9621
9622
[[nodiscard]] ada_really_inline const ada::url_components&
9623
0
url_aggregator::get_components() const noexcept {
9624
0
  return components;
9625
0
}
9626
9627
[[nodiscard]] constexpr bool ada::url_aggregator::has_authority()
9628
491
    const noexcept {
9629
491
  ada_log("url_aggregator::has_authority");
9630
  // Performance: instead of doing this potentially expensive check, we could
9631
  // have a boolean in the struct.
9632
491
  return components.protocol_end + 2 <= components.host_start &&
9633
0
         buffer[components.protocol_end] == '/' &&
9634
0
         buffer[components.protocol_end + 1] == '/';
9635
491
}
9636
9637
491
inline void ada::url_aggregator::add_authority_slashes_if_needed() {
9638
491
  ada_log("url_aggregator::add_authority_slashes_if_needed");
9639
491
  ADA_ASSERT_TRUE(validate());
9640
  // Protocol setter will insert `http:` to the URL. It is up to hostname setter
9641
  // to insert
9642
  // `//` initially to the buffer, since it depends on the hostname existence.
9643
491
  if (has_authority()) {
9644
0
    return;
9645
0
  }
9646
  // Performance: the common case is components.protocol_end == buffer.size()
9647
  // Optimization opportunity: in many cases, the "//" is part of the input and
9648
  // the insert could be fused with another insert.
9649
491
  buffer.insert(components.protocol_end, "//");
9650
491
  components.username_end += 2;
9651
491
  components.host_start += 2;
9652
491
  components.host_end += 2;
9653
491
  components.pathname_start += 2;
9654
491
  if (components.search_start != url_components::omitted) {
9655
0
    components.search_start += 2;
9656
0
  }
9657
491
  if (components.hash_start != url_components::omitted) {
9658
0
    components.hash_start += 2;
9659
0
  }
9660
491
  ADA_ASSERT_TRUE(validate());
9661
491
}
9662
9663
491
constexpr void ada::url_aggregator::reserve(uint32_t capacity) {
9664
491
  buffer.reserve(capacity);
9665
491
}
9666
9667
0
constexpr bool url_aggregator::has_non_empty_username() const noexcept {
9668
0
  ada_log("url_aggregator::has_non_empty_username");
9669
0
  return components.protocol_end + 2 < components.username_end;
9670
0
}
9671
9672
0
constexpr bool url_aggregator::has_non_empty_password() const noexcept {
9673
0
  ada_log("url_aggregator::has_non_empty_password");
9674
0
  return components.host_start > components.username_end;
9675
0
}
9676
9677
0
constexpr bool url_aggregator::has_password() const noexcept {
9678
0
  ada_log("url_aggregator::has_password");
9679
  // This function does not care about the length of the password
9680
0
  return components.host_start > components.username_end &&
9681
0
         buffer[components.username_end] == ':';
9682
0
}
9683
9684
0
constexpr bool url_aggregator::has_empty_hostname() const noexcept {
9685
0
  if (!has_hostname()) {
9686
0
    return false;
9687
0
  }
9688
0
  if (components.host_start == components.host_end) {
9689
0
    return true;
9690
0
  }
9691
0
  if (components.host_end > components.host_start + 1) {
9692
0
    return false;
9693
0
  }
9694
0
  return components.username_end != components.host_start;
9695
0
}
9696
9697
0
constexpr bool url_aggregator::has_hostname() const noexcept {
9698
0
  return has_authority();
9699
0
}
9700
9701
0
constexpr bool url_aggregator::has_port() const noexcept {
9702
0
  ada_log("url_aggregator::has_port");
9703
  // A URL cannot have a username/password/port if its host is null or the empty
9704
  // string, or its scheme is "file".
9705
0
  return has_hostname() && components.pathname_start != components.host_end;
9706
0
}
9707
9708
0
[[nodiscard]] constexpr bool url_aggregator::has_dash_dot() const noexcept {
9709
  // If url's host is null, url does not have an opaque path, url's path's size
9710
  // is greater than 1, and url's path[0] is the empty string, then append
9711
  // U+002F (/) followed by U+002E (.) to output.
9712
0
  ada_log("url_aggregator::has_dash_dot");
9713
#if ADA_DEVELOPMENT_CHECKS
9714
  // If pathname_start and host_end are exactly two characters apart, then we
9715
  // either have a one-digit port such as http://test.com:5?param=1 or else we
9716
  // have a /.: sequence such as "non-spec:/.//". We test that this is the case.
9717
  if (components.pathname_start == components.host_end + 2) {
9718
    ADA_ASSERT_TRUE((buffer[components.host_end] == '/' &&
9719
                     buffer[components.host_end + 1] == '.') ||
9720
                    (buffer[components.host_end] == ':' &&
9721
                     checkers::is_digit(buffer[components.host_end + 1])));
9722
  }
9723
  if (components.pathname_start == components.host_end + 2 &&
9724
      buffer[components.host_end] == '/' &&
9725
      buffer[components.host_end + 1] == '.') {
9726
    ADA_ASSERT_TRUE(components.pathname_start + 1 < buffer.size());
9727
    ADA_ASSERT_TRUE(buffer[components.pathname_start] == '/');
9728
    ADA_ASSERT_TRUE(buffer[components.pathname_start + 1] == '/');
9729
  }
9730
#endif
9731
  // Performance: it should be uncommon for components.pathname_start ==
9732
  // components.host_end + 2 to be true. So we put this check first in the
9733
  // sequence. Most times, we do not have an opaque path. Checking for '/.' is
9734
  // more expensive, but should be uncommon.
9735
0
  return components.pathname_start == components.host_end + 2 &&
9736
0
         !has_opaque_path && buffer[components.host_end] == '/' &&
9737
0
         buffer[components.host_end + 1] == '.';
9738
0
}
9739
9740
[[nodiscard]] constexpr std::string_view url_aggregator::get_href()
9741
0
    const noexcept ada_lifetime_bound {
9742
0
  ada_log("url_aggregator::get_href");
9743
0
  return buffer;
9744
0
}
9745
9746
0
[[nodiscard]] constexpr size_t url_aggregator::get_href_size() const noexcept {
9747
0
  return buffer.size();
9748
0
}
9749
9750
ada_really_inline size_t
9751
0
url_aggregator::parse_port(std::string_view view, bool check_trailing_content) {
9752
0
  ada_log("url_aggregator::parse_port('", view, "') ", view.size());
9753
0
  if (!view.empty() && view[0] == '-') {
9754
0
    ada_log("parse_port: view[0] == '0' && view.size() > 1");
9755
0
    is_valid = false;
9756
0
    return 0;
9757
0
  }
9758
0
  uint16_t parsed_port{};
9759
0
  auto r = std::from_chars(view.data(), view.data() + view.size(), parsed_port);
9760
0
  if (r.ec == std::errc::result_out_of_range) {
9761
0
    ada_log("parse_port: r.ec == std::errc::result_out_of_range");
9762
0
    is_valid = false;
9763
0
    return 0;
9764
0
  }
9765
0
  ada_log("parse_port: ", parsed_port);
9766
0
  const size_t consumed = size_t(r.ptr - view.data());
9767
0
  ada_log("parse_port: consumed ", consumed);
9768
0
  if (check_trailing_content) {
9769
0
    is_valid &=
9770
0
        (consumed == view.size() || view[consumed] == '/' ||
9771
0
         view[consumed] == '?' || (is_special() && view[consumed] == '\\'));
9772
0
  }
9773
0
  ada_log("parse_port: is_valid = ", is_valid);
9774
0
  if (is_valid) {
9775
0
    ada_log("parse_port", r.ec == std::errc());
9776
    // scheme_default_port can return 0, and we should allow 0 as a base port.
9777
0
    auto default_port = scheme_default_port();
9778
0
    bool is_port_valid = (default_port == 0 && parsed_port == 0) ||
9779
0
                         (default_port != parsed_port);
9780
0
    if (r.ec == std::errc() && is_port_valid) {
9781
0
      update_base_port(parsed_port);
9782
0
    } else {
9783
0
      clear_port();
9784
0
    }
9785
0
  }
9786
0
  return consumed;
9787
0
}
9788
9789
0
constexpr void url_aggregator::set_protocol_as_file() {
9790
0
  ada_log("url_aggregator::set_protocol_as_file ");
9791
0
  ADA_ASSERT_TRUE(validate());
9792
0
  type = ada::scheme::type::FILE;
9793
  // next line could overflow but unsigned arithmetic has well-defined
9794
  // overflows.
9795
0
  uint32_t new_difference = 5 - components.protocol_end;
9796
9797
0
  if (buffer.empty()) {
9798
0
    buffer.append("file:");
9799
0
  } else {
9800
0
    buffer.erase(0, components.protocol_end);
9801
0
    buffer.insert(0, "file:");
9802
0
  }
9803
0
  components.protocol_end = 5;
9804
9805
  // Update the rest of the components.
9806
0
  components.username_end += new_difference;
9807
0
  components.host_start += new_difference;
9808
0
  components.host_end += new_difference;
9809
0
  components.pathname_start += new_difference;
9810
0
  if (components.search_start != url_components::omitted) {
9811
0
    components.search_start += new_difference;
9812
0
  }
9813
0
  if (components.hash_start != url_components::omitted) {
9814
0
    components.hash_start += new_difference;
9815
0
  }
9816
0
  ADA_ASSERT_TRUE(validate());
9817
0
}
9818
9819
2.93k
[[nodiscard]] constexpr bool url_aggregator::validate() const noexcept {
9820
2.93k
  if (!is_valid) {
9821
0
    return true;
9822
0
  }
9823
2.93k
  if (!components.check_offset_consistency()) {
9824
0
    ada_log("url_aggregator::validate inconsistent components \n",
9825
0
            to_diagram());
9826
0
    return false;
9827
0
  }
9828
  // We have a credible components struct, but let us investivate more
9829
  // carefully:
9830
  /**
9831
   * https://user:pass@example.com:1234/foo/bar?baz#quux
9832
   *       |     |    |          | ^^^^|       |   |
9833
   *       |     |    |          | |   |       |   `----- hash_start
9834
   *       |     |    |          | |   |       `--------- search_start
9835
   *       |     |    |          | |   `----------------- pathname_start
9836
   *       |     |    |          | `--------------------- port
9837
   *       |     |    |          `----------------------- host_end
9838
   *       |     |    `---------------------------------- host_start
9839
   *       |     `--------------------------------------- username_end
9840
   *       `--------------------------------------------- protocol_end
9841
   */
9842
2.93k
  if (components.protocol_end == url_components::omitted) {
9843
0
    ada_log("url_aggregator::validate omitted protocol_end \n", to_diagram());
9844
0
    return false;
9845
0
  }
9846
2.93k
  if (components.username_end == url_components::omitted) {
9847
0
    ada_log("url_aggregator::validate omitted username_end \n", to_diagram());
9848
0
    return false;
9849
0
  }
9850
2.93k
  if (components.host_start == url_components::omitted) {
9851
0
    ada_log("url_aggregator::validate omitted host_start \n", to_diagram());
9852
0
    return false;
9853
0
  }
9854
2.93k
  if (components.host_end == url_components::omitted) {
9855
0
    ada_log("url_aggregator::validate omitted host_end \n", to_diagram());
9856
0
    return false;
9857
0
  }
9858
2.93k
  if (components.pathname_start == url_components::omitted) {
9859
0
    ada_log("url_aggregator::validate omitted pathname_start \n", to_diagram());
9860
0
    return false;
9861
0
  }
9862
9863
2.93k
  if (components.protocol_end > buffer.size()) {
9864
0
    ada_log("url_aggregator::validate protocol_end overflow \n", to_diagram());
9865
0
    return false;
9866
0
  }
9867
2.93k
  if (components.username_end > buffer.size()) {
9868
0
    ada_log("url_aggregator::validate username_end overflow \n", to_diagram());
9869
0
    return false;
9870
0
  }
9871
2.93k
  if (components.host_start > buffer.size()) {
9872
0
    ada_log("url_aggregator::validate host_start overflow \n", to_diagram());
9873
0
    return false;
9874
0
  }
9875
2.93k
  if (components.host_end > buffer.size()) {
9876
0
    ada_log("url_aggregator::validate host_end overflow \n", to_diagram());
9877
0
    return false;
9878
0
  }
9879
2.93k
  if (components.pathname_start > buffer.size()) {
9880
0
    ada_log("url_aggregator::validate pathname_start overflow \n",
9881
0
            to_diagram());
9882
0
    return false;
9883
0
  }
9884
9885
2.93k
  if (components.protocol_end > 0) {
9886
2.93k
    if (buffer[components.protocol_end - 1] != ':') {
9887
0
      ada_log(
9888
0
          "url_aggregator::validate missing : at the end of the protocol \n",
9889
0
          to_diagram());
9890
0
      return false;
9891
0
    }
9892
2.93k
  }
9893
9894
2.93k
  if (components.username_end != buffer.size() &&
9895
2.93k
      components.username_end > components.protocol_end + 2) {
9896
0
    if (buffer[components.username_end] != ':' &&
9897
0
        buffer[components.username_end] != '@') {
9898
0
      ada_log(
9899
0
          "url_aggregator::validate missing : or @ at the end of the username "
9900
0
          "\n",
9901
0
          to_diagram());
9902
0
      return false;
9903
0
    }
9904
0
  }
9905
9906
2.93k
  if (components.host_start != buffer.size()) {
9907
2.93k
    if (components.host_start > components.username_end) {
9908
0
      if (buffer[components.host_start] != '@') {
9909
0
        ada_log(
9910
0
            "url_aggregator::validate missing @ at the end of the password \n",
9911
0
            to_diagram());
9912
0
        return false;
9913
0
      }
9914
2.93k
    } else if (components.host_start == components.username_end &&
9915
2.93k
               components.host_end > components.host_start) {
9916
2.93k
      if (components.host_start == components.protocol_end + 2) {
9917
2.93k
        if (buffer[components.protocol_end] != '/' ||
9918
2.93k
            buffer[components.protocol_end + 1] != '/') {
9919
0
          ada_log(
9920
0
              "url_aggregator::validate missing // between protocol and host "
9921
0
              "\n",
9922
0
              to_diagram());
9923
0
          return false;
9924
0
        }
9925
2.93k
      } else {
9926
0
        if (components.host_start > components.protocol_end &&
9927
0
            buffer[components.host_start] != '@') {
9928
0
          ada_log(
9929
0
              "url_aggregator::validate missing @ at the end of the username "
9930
0
              "\n",
9931
0
              to_diagram());
9932
0
          return false;
9933
0
        }
9934
0
      }
9935
2.93k
    } else {
9936
0
      if (components.host_end != components.host_start) {
9937
0
        ada_log("url_aggregator::validate expected omitted host \n",
9938
0
                to_diagram());
9939
0
        return false;
9940
0
      }
9941
0
    }
9942
2.93k
  }
9943
2.93k
  if (components.host_end != buffer.size() &&
9944
2.93k
      components.pathname_start > components.host_end) {
9945
0
    if (components.pathname_start == components.host_end + 2 &&
9946
0
        buffer[components.host_end] == '/' &&
9947
0
        buffer[components.host_end + 1] == '.') {
9948
0
      if (components.pathname_start + 1 >= buffer.size() ||
9949
0
          buffer[components.pathname_start] != '/' ||
9950
0
          buffer[components.pathname_start + 1] != '/') {
9951
0
        ada_log(
9952
0
            "url_aggregator::validate expected the path to begin with // \n",
9953
0
            to_diagram());
9954
0
        return false;
9955
0
      }
9956
0
    } else if (buffer[components.host_end] != ':') {
9957
0
      ada_log("url_aggregator::validate missing : at the port \n",
9958
0
              to_diagram());
9959
0
      return false;
9960
0
    }
9961
0
  }
9962
2.93k
  if (components.pathname_start != buffer.size() &&
9963
2.93k
      components.pathname_start < components.search_start &&
9964
2.93k
      components.pathname_start < components.hash_start && !has_opaque_path) {
9965
2.93k
    if (buffer[components.pathname_start] != '/') {
9966
0
      ada_log("url_aggregator::validate missing / at the path \n",
9967
0
              to_diagram());
9968
0
      return false;
9969
0
    }
9970
2.93k
  }
9971
2.93k
  if (components.search_start != url_components::omitted) {
9972
1.57k
    if (buffer[components.search_start] != '?') {
9973
0
      ada_log("url_aggregator::validate missing ? at the search \n",
9974
0
              to_diagram());
9975
0
      return false;
9976
0
    }
9977
1.57k
  }
9978
2.93k
  if (components.hash_start != url_components::omitted) {
9979
437
    if (buffer[components.hash_start] != '#') {
9980
0
      ada_log("url_aggregator::validate missing # at the hash \n",
9981
0
              to_diagram());
9982
0
      return false;
9983
0
    }
9984
437
  }
9985
9986
2.93k
  return true;
9987
2.93k
}
9988
9989
[[nodiscard]] constexpr std::string_view url_aggregator::get_pathname() const
9990
0
    ada_lifetime_bound {
9991
0
  ada_log("url_aggregator::get_pathname pathname_start = ",
9992
0
          components.pathname_start, " buffer.size() = ", buffer.size(),
9993
0
          " components.search_start = ", components.search_start,
9994
0
          " components.hash_start = ", components.hash_start);
9995
0
  auto ending_index = uint32_t(buffer.size());
9996
0
  if (components.search_start != url_components::omitted) {
9997
0
    ending_index = components.search_start;
9998
0
  } else if (components.hash_start != url_components::omitted) {
9999
0
    ending_index = components.hash_start;
10000
0
  }
10001
0
  return helpers::substring(buffer, components.pathname_start, ending_index);
10002
0
}
10003
10004
inline std::ostream& operator<<(std::ostream& out,
10005
0
                                const ada::url_aggregator& u) {
10006
0
  return out << u.to_string();
10007
0
}
10008
10009
0
void url_aggregator::update_host_to_base_host(const std::string_view input) {
10010
0
  ada_log("url_aggregator::update_host_to_base_host ", input);
10011
0
  ADA_ASSERT_TRUE(validate());
10012
0
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
10013
0
  if (type != ada::scheme::type::FILE) {
10014
    // Let host be the result of host parsing host_view with url is not special.
10015
0
    if (input.empty() && !is_special()) {
10016
0
      if (has_hostname()) {
10017
0
        clear_hostname();
10018
0
      } else if (has_dash_dot()) {
10019
0
        add_authority_slashes_if_needed();
10020
0
        delete_dash_dot();
10021
0
      }
10022
0
      return;
10023
0
    }
10024
0
  }
10025
0
  update_base_hostname(input);
10026
0
  ADA_ASSERT_TRUE(validate());
10027
0
  return;
10028
0
}
10029
}  // namespace ada
10030
10031
#endif  // ADA_URL_AGGREGATOR_INL_H
10032
/* end file include/ada/url_aggregator-inl.h */
10033
/* begin file include/ada/url_search_params.h */
10034
/**
10035
 * @file url_search_params.h
10036
 * @brief URL query string parameter manipulation.
10037
 *
10038
 * This file provides the `url_search_params` class for parsing, manipulating,
10039
 * and serializing URL query strings. It implements the URLSearchParams API
10040
 * from the WHATWG URL Standard.
10041
 *
10042
 * @see https://url.spec.whatwg.org/#interface-urlsearchparams
10043
 */
10044
#ifndef ADA_URL_SEARCH_PARAMS_H
10045
#define ADA_URL_SEARCH_PARAMS_H
10046
10047
#include <cstddef>
10048
#include <optional>
10049
#include <string>
10050
#include <string_view>
10051
#include <utility>
10052
#include <vector>
10053
10054
namespace ada {
10055
10056
/**
10057
 * @brief Iterator types for url_search_params iteration.
10058
 */
10059
enum class url_search_params_iter_type {
10060
  KEYS,    /**< Iterate over parameter keys only */
10061
  VALUES,  /**< Iterate over parameter values only */
10062
  ENTRIES, /**< Iterate over key-value pairs */
10063
};
10064
10065
template <typename T, url_search_params_iter_type Type>
10066
struct url_search_params_iter;
10067
10068
/** Type alias for a key-value pair of string views. */
10069
typedef std::pair<std::string_view, std::string_view> key_value_view_pair;
10070
10071
/** Iterator over search parameter keys. */
10072
using url_search_params_keys_iter =
10073
    url_search_params_iter<std::string_view, url_search_params_iter_type::KEYS>;
10074
/** Iterator over search parameter values. */
10075
using url_search_params_values_iter =
10076
    url_search_params_iter<std::string_view,
10077
                           url_search_params_iter_type::VALUES>;
10078
/** Iterator over search parameter key-value pairs. */
10079
using url_search_params_entries_iter =
10080
    url_search_params_iter<key_value_view_pair,
10081
                           url_search_params_iter_type::ENTRIES>;
10082
10083
/**
10084
 * @brief Class for parsing and manipulating URL query strings.
10085
 *
10086
 * The `url_search_params` class provides methods to parse, modify, and
10087
 * serialize URL query parameters (the part after '?' in a URL). It handles
10088
 * percent-encoding and decoding automatically.
10089
 *
10090
 * All string inputs must be valid UTF-8. The caller is responsible for
10091
 * ensuring UTF-8 validity.
10092
 *
10093
 * Construction and `reset` refuse query strings longer than
10094
 * `get_max_input_length()` (the object is left empty). Individual `append` /
10095
 * `set` calls are not length-capped.
10096
 *
10097
 * @see https://url.spec.whatwg.org/#interface-urlsearchparams
10098
 */
10099
struct url_search_params {
10100
8.79k
  url_search_params() = default;
10101
10102
  /**
10103
   * Constructs url_search_params by parsing a query string.
10104
   * @param input A query string (with or without leading '?'). Must be UTF-8.
10105
   *        If longer than `get_max_input_length()`, the object stays empty.
10106
   */
10107
14.6k
  explicit url_search_params(const std::string_view input) {
10108
14.6k
    initialize(input);
10109
14.6k
  }
10110
10111
2.93k
  url_search_params(const url_search_params& u) = default;
10112
2.93k
  url_search_params(url_search_params&& u) noexcept = default;
10113
2.93k
  url_search_params& operator=(url_search_params&& u) noexcept = default;
10114
2.93k
  url_search_params& operator=(const url_search_params& u) = default;
10115
29.3k
  ~url_search_params() = default;
10116
10117
  /**
10118
   * Returns the number of key-value pairs.
10119
   * @return The total count of parameters.
10120
   */
10121
  [[nodiscard]] inline size_t size() const noexcept;
10122
10123
  /**
10124
   * Appends a new key-value pair to the parameter list.
10125
   * @param key The parameter name (must be valid UTF-8).
10126
   * @param value The parameter value (must be valid UTF-8).
10127
   * @see https://url.spec.whatwg.org/#dom-urlsearchparams-append
10128
   */
10129
  inline void append(std::string_view key, std::string_view value);
10130
10131
  /**
10132
   * Removes all pairs with the given key.
10133
   * @param key The parameter name to remove.
10134
   * @see https://url.spec.whatwg.org/#dom-urlsearchparams-delete
10135
   */
10136
  inline void remove(std::string_view key);
10137
10138
  /**
10139
   * Removes all pairs with the given key and value.
10140
   * @param key The parameter name.
10141
   * @param value The parameter value to match.
10142
   */
10143
  inline void remove(std::string_view key, std::string_view value);
10144
10145
  /**
10146
   * Returns the value of the first pair with the given key.
10147
   * @param key The parameter name to search for.
10148
   * @return The value if found, or std::nullopt if not present.
10149
   * @see https://url.spec.whatwg.org/#dom-urlsearchparams-get
10150
   */
10151
  inline std::optional<std::string_view> get(std::string_view key);
10152
10153
  /**
10154
   * Returns all values for pairs with the given key.
10155
   * @param key The parameter name to search for.
10156
   * @return A vector of all matching values (may be empty).
10157
   * @see https://url.spec.whatwg.org/#dom-urlsearchparams-getall
10158
   */
10159
  inline std::vector<std::string> get_all(std::string_view key);
10160
10161
  /**
10162
   * Checks if any pair has the given key.
10163
   * @param key The parameter name to search for.
10164
   * @return `true` if at least one pair has this key.
10165
   * @see https://url.spec.whatwg.org/#dom-urlsearchparams-has
10166
   */
10167
  inline bool has(std::string_view key) noexcept;
10168
10169
  /**
10170
   * Checks if any pair matches the given key and value.
10171
   * @param key The parameter name to search for.
10172
   * @param value The parameter value to match.
10173
   * @return `true` if a matching pair exists.
10174
   */
10175
  inline bool has(std::string_view key, std::string_view value) noexcept;
10176
10177
  /**
10178
   * Sets a parameter value, replacing any existing pairs with the same key.
10179
   * @param key The parameter name (must be valid UTF-8).
10180
   * @param value The parameter value (must be valid UTF-8).
10181
   * @see https://url.spec.whatwg.org/#dom-urlsearchparams-set
10182
   */
10183
  inline void set(std::string_view key, std::string_view value);
10184
10185
  /**
10186
   * Sorts all key-value pairs by their keys using code unit comparison.
10187
   * @see https://url.spec.whatwg.org/#dom-urlsearchparams-sort
10188
   */
10189
  inline void sort();
10190
10191
  /**
10192
   * Serializes the parameters to a query string (without leading '?').
10193
   * @return The percent-encoded query string.
10194
   * @see https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior
10195
   */
10196
  inline std::string to_string() const;
10197
10198
  /**
10199
   * Returns an iterator over all parameter keys.
10200
   * Keys may repeat if there are duplicate parameters.
10201
   * @return An iterator yielding string_view keys.
10202
   * @note The iterator is invalidated if this object is modified.
10203
   */
10204
  inline url_search_params_keys_iter get_keys();
10205
10206
  /**
10207
   * Returns an iterator over all parameter values.
10208
   * @return An iterator yielding string_view values.
10209
   * @note The iterator is invalidated if this object is modified.
10210
   */
10211
  inline url_search_params_values_iter get_values();
10212
10213
  /**
10214
   * Returns an iterator over all key-value pairs.
10215
   * @return An iterator yielding key-value pair views.
10216
   * @note The iterator is invalidated if this object is modified.
10217
   */
10218
  inline url_search_params_entries_iter get_entries();
10219
10220
  /**
10221
   * C++ style conventional iterator support. const only because we
10222
   * do not really want the params to be modified via the iterator.
10223
   */
10224
11.7k
  inline auto begin() const { return params.begin(); }
10225
11.7k
  inline auto end() const { return params.end(); }
10226
1.15k
  inline auto front() const { return params.front(); }
10227
1.15k
  inline auto back() const { return params.back(); }
10228
1.15k
  inline auto operator[](size_t index) const { return params[index]; }
10229
10230
  /**
10231
   * @private
10232
   * Used to reset the search params to a new input.
10233
   * Used primarily for C API.
10234
   * @param input
10235
   */
10236
  void reset(std::string_view input);
10237
10238
 private:
10239
  typedef std::pair<std::string, std::string> key_value_pair;
10240
  std::vector<key_value_pair> params{};
10241
10242
  /**
10243
   * The init parameter must be valid UTF-8.
10244
   * @see https://url.spec.whatwg.org/#concept-urlencoded-parser
10245
   */
10246
  void initialize(std::string_view init);
10247
10248
  template <typename T, url_search_params_iter_type Type>
10249
  friend struct url_search_params_iter;
10250
};  // url_search_params
10251
10252
/**
10253
 * @brief JavaScript-style iterator for url_search_params.
10254
 *
10255
 * Provides a `next()` method that returns successive values until exhausted.
10256
 * This matches the iterator pattern used in the Web Platform.
10257
 *
10258
 * @tparam T The type of value returned by the iterator.
10259
 * @tparam Type The type of iteration (KEYS, VALUES, or ENTRIES).
10260
 *
10261
 * @see https://webidl.spec.whatwg.org/#idl-iterable
10262
 */
10263
template <typename T, url_search_params_iter_type Type>
10264
struct url_search_params_iter {
10265
  inline url_search_params_iter() : params(EMPTY) {}
10266
  url_search_params_iter(const url_search_params_iter& u) = default;
10267
  url_search_params_iter(url_search_params_iter&& u) noexcept = default;
10268
  url_search_params_iter& operator=(url_search_params_iter&& u) noexcept =
10269
      default;
10270
  url_search_params_iter& operator=(const url_search_params_iter& u) = default;
10271
  ~url_search_params_iter() = default;
10272
10273
  /**
10274
   * Returns the next value in the iteration sequence.
10275
   * @return The next value, or std::nullopt if iteration is complete.
10276
   */
10277
  inline std::optional<T> next();
10278
10279
  /**
10280
   * Checks if more values are available.
10281
   * @return `true` if `next()` will return a value, `false` if exhausted.
10282
   */
10283
  inline bool has_next() const;
10284
10285
 private:
10286
  static url_search_params EMPTY;
10287
8.79k
  inline url_search_params_iter(url_search_params& params_) : params(params_) {}
ada::url_search_params_iter<std::__1::basic_string_view<char, std::__1::char_traits<char> >, (ada::url_search_params_iter_type)0>::url_search_params_iter(ada::url_search_params&)
Line
Count
Source
10287
2.93k
  inline url_search_params_iter(url_search_params& params_) : params(params_) {}
ada::url_search_params_iter<std::__1::basic_string_view<char, std::__1::char_traits<char> >, (ada::url_search_params_iter_type)1>::url_search_params_iter(ada::url_search_params&)
Line
Count
Source
10287
2.93k
  inline url_search_params_iter(url_search_params& params_) : params(params_) {}
ada::url_search_params_iter<std::__1::pair<std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::basic_string_view<char, std::__1::char_traits<char> > >, (ada::url_search_params_iter_type)2>::url_search_params_iter(ada::url_search_params&)
Line
Count
Source
10287
2.93k
  inline url_search_params_iter(url_search_params& params_) : params(params_) {}
10288
10289
  url_search_params& params;
10290
  size_t pos = 0;
10291
10292
  friend struct url_search_params;
10293
};
10294
10295
}  // namespace ada
10296
#endif
10297
/* end file include/ada/url_search_params.h */
10298
/* begin file include/ada/url_search_params-inl.h */
10299
/**
10300
 * @file url_search_params-inl.h
10301
 * @brief Inline declarations for the URL Search Params
10302
 */
10303
#ifndef ADA_URL_SEARCH_PARAMS_INL_H
10304
#define ADA_URL_SEARCH_PARAMS_INL_H
10305
10306
10307
#include <algorithm>
10308
#include <cstddef>
10309
#include <cstdint>
10310
#include <iterator>
10311
#include <optional>
10312
#include <ranges>
10313
#include <string>
10314
#include <string_view>
10315
#include <vector>
10316
10317
namespace ada {
10318
10319
// Declared in implementation.h; used here as a DoS bound on untrusted query
10320
// strings (ada.h includes both headers).
10321
uint32_t get_max_input_length();
10322
10323
// A default, empty url_search_params for use with empty iterators.
10324
template <typename T, ada::url_search_params_iter_type Type>
10325
url_search_params url_search_params_iter<T, Type>::EMPTY;
10326
10327
2.93k
inline void url_search_params::reset(std::string_view input) {
10328
  // input may point into params.
10329
2.93k
  const std::string copy(input);
10330
2.93k
  params.clear();
10331
2.93k
  initialize(copy);
10332
2.93k
}
10333
10334
17.5k
inline void url_search_params::initialize(std::string_view input) {
10335
17.5k
  if (!input.empty() && input.front() == '?') {
10336
17
    input.remove_prefix(1);
10337
17
  }
10338
17.5k
  if (input.empty()) {
10339
11.2k
    return;
10340
11.2k
  }
10341
  // Refuse overlong query strings (same process-wide cap as URL parsing).
10342
6.34k
  if (input.size() > get_max_input_length()) {
10343
0
    return;
10344
0
  }
10345
10346
  // count('&')+1 is an upper bound on the pairs the loop below keeps
10347
  // (empty segments are skipped). It is one character count, which is
10348
  // the reserve the parse path already paid for. An input of only '&'
10349
  // would reserve N+1 pairs and store nothing; skip that.
10350
6.34k
  const size_t ampersands = size_t(std::count(input.begin(), input.end(), '&'));
10351
6.34k
  if (ampersands == input.size()) {
10352
68
    return;
10353
68
  }
10354
6.28k
  params.reserve(ampersands + 1);
10355
10356
35.7k
  auto process_key_value = [&](const std::string_view current) {
10357
35.7k
    const auto equal = current.find('=');
10358
35.7k
    if (equal == std::string_view::npos) {
10359
13.0k
      params.emplace_back(unicode::form_urlencoded_decode(current), "");
10360
22.7k
    } else {
10361
22.7k
      params.emplace_back(
10362
22.7k
          unicode::form_urlencoded_decode(current.substr(0, equal)),
10363
22.7k
          unicode::form_urlencoded_decode(current.substr(equal + 1)));
10364
22.7k
    }
10365
35.7k
  };
10366
10367
47.6k
  while (!input.empty()) {
10368
47.4k
    const auto ampersand_index = input.find('&');
10369
10370
47.4k
    if (ampersand_index == std::string_view::npos) {
10371
6.08k
      if (!input.empty()) {
10372
6.08k
        process_key_value(input);
10373
6.08k
      }
10374
6.08k
      break;
10375
41.3k
    } else if (ampersand_index != 0) {
10376
29.6k
      process_key_value(input.substr(0, ampersand_index));
10377
29.6k
    }
10378
10379
41.3k
    input.remove_prefix(ampersand_index + 1);
10380
41.3k
  }
10381
6.28k
}
10382
10383
inline void url_search_params::append(const std::string_view key,
10384
16.4k
                                      const std::string_view value) {
10385
16.4k
  params.emplace_back(key, value);
10386
16.4k
}
10387
10388
26.3k
inline size_t url_search_params::size() const noexcept { return params.size(); }
10389
10390
inline std::optional<std::string_view> url_search_params::get(
10391
19.5k
    const std::string_view key) {
10392
19.5k
  auto entry = std::ranges::find_if(
10393
153k
      params, [&key](const auto& param) { return param.first == key; });
10394
10395
19.5k
  if (entry == params.end()) {
10396
5.55k
    return std::nullopt;
10397
5.55k
  }
10398
10399
14.0k
  return entry->second;
10400
19.5k
}
10401
10402
inline std::vector<std::string> url_search_params::get_all(
10403
5.86k
    const std::string_view key) {
10404
5.86k
  std::vector<std::string> out{};
10405
10406
17.5k
  for (auto& param : params) {
10407
17.5k
    if (param.first == key) {
10408
6.21k
      out.emplace_back(param.second);
10409
6.21k
    }
10410
17.5k
  }
10411
10412
5.86k
  return out;
10413
5.86k
}
10414
10415
24.4k
inline bool url_search_params::has(const std::string_view key) noexcept {
10416
24.4k
  auto entry = std::ranges::find_if(
10417
286k
      params, [&key](const auto& param) { return param.first == key; });
10418
24.4k
  return entry != params.end();
10419
24.4k
}
10420
10421
inline bool url_search_params::has(std::string_view key,
10422
13.7k
                                   std::string_view value) noexcept {
10423
149k
  auto entry = std::ranges::find_if(params, [&key, &value](const auto& param) {
10424
149k
    return param.first == key && param.second == value;
10425
149k
  });
10426
13.7k
  return entry != params.end();
10427
13.7k
}
10428
10429
26.3k
inline std::string url_search_params::to_string() const {
10430
26.3k
  auto character_set = ada::character_sets::WWW_FORM_URLENCODED_PERCENT_ENCODE;
10431
26.3k
  std::string out{};
10432
87.6k
  for (size_t i = 0; i < params.size(); i++) {
10433
61.2k
    auto key = ada::unicode::percent_encode(params[i].first, character_set);
10434
61.2k
    auto value = ada::unicode::percent_encode(params[i].second, character_set);
10435
10436
    // Performance optimization: Move this inside percent_encode.
10437
61.2k
    std::ranges::replace(key, ' ', '+');
10438
61.2k
    std::ranges::replace(value, ' ', '+');
10439
10440
61.2k
    if (i != 0) {
10441
47.9k
      out += "&";
10442
47.9k
    }
10443
61.2k
    out.append(key);
10444
61.2k
    out += "=";
10445
61.2k
    out.append(value);
10446
61.2k
  }
10447
26.3k
  return out;
10448
26.3k
}
10449
10450
inline void url_search_params::set(const std::string_view key,
10451
2.93k
                                   const std::string_view value) {
10452
5.86k
  const auto find = [&key](const auto& param) { return param.first == key; };
10453
10454
2.93k
  auto it = std::ranges::find_if(params, find);
10455
10456
2.93k
  if (it == params.end()) {
10457
0
    params.emplace_back(key, value);
10458
2.93k
  } else {
10459
2.93k
    it->second = value;
10460
2.93k
    params.erase(std::remove_if(std::next(it), params.end(), find),
10461
2.93k
                 params.end());
10462
2.93k
  }
10463
2.93k
}
10464
10465
4.19k
inline void url_search_params::remove(const std::string_view key) {
10466
4.19k
  std::erase_if(params,
10467
9.32k
                [&key](const auto& param) { return param.first == key; });
10468
4.19k
}
10469
10470
inline void url_search_params::remove(const std::string_view key,
10471
4.19k
                                      const std::string_view value) {
10472
4.19k
  std::erase_if(params, [&key, &value](const auto& param) {
10473
3.37k
    return param.first == key && param.second == value;
10474
3.37k
  });
10475
4.19k
}
10476
10477
5.86k
inline void url_search_params::sort() {
10478
  // Keys are expected to be valid UTF-8, but percent_decode can produce
10479
  // arbitrary byte sequences. Handle truncated/invalid sequences gracefully.
10480
5.86k
  std::ranges::stable_sort(params, [](const key_value_pair& lhs,
10481
42.9k
                                      const key_value_pair& rhs) {
10482
42.9k
    size_t i = 0, j = 0;
10483
42.9k
    uint32_t low_surrogate1 = 0, low_surrogate2 = 0;
10484
69.3k
    while ((i < lhs.first.size() || low_surrogate1 != 0) &&
10485
46.2k
           (j < rhs.first.size() || low_surrogate2 != 0)) {
10486
44.4k
      uint32_t codePoint1 = 0, codePoint2 = 0;
10487
10488
44.4k
      if (low_surrogate1 != 0) {
10489
1.13k
        codePoint1 = low_surrogate1;
10490
1.13k
        low_surrogate1 = 0;
10491
43.3k
      } else {
10492
43.3k
        uint8_t c1 = uint8_t(lhs.first[i]);
10493
43.3k
        if (c1 > 0x7F && c1 <= 0xDF && i + 1 < lhs.first.size()) {
10494
2.40k
          codePoint1 = ((c1 & 0x1F) << 6) | (uint8_t(lhs.first[i + 1]) & 0x3F);
10495
2.40k
          i += 2;
10496
40.9k
        } else if (c1 > 0xDF && c1 <= 0xEF && i + 2 < lhs.first.size()) {
10497
1.39k
          codePoint1 = ((c1 & 0x0F) << 12) |
10498
1.39k
                       ((uint8_t(lhs.first[i + 1]) & 0x3F) << 6) |
10499
1.39k
                       (uint8_t(lhs.first[i + 2]) & 0x3F);
10500
1.39k
          i += 3;
10501
39.5k
        } else if (c1 > 0xEF && c1 <= 0xF7 && i + 3 < lhs.first.size()) {
10502
1.46k
          codePoint1 = ((c1 & 0x07) << 18) |
10503
1.46k
                       ((uint8_t(lhs.first[i + 1]) & 0x3F) << 12) |
10504
1.46k
                       ((uint8_t(lhs.first[i + 2]) & 0x3F) << 6) |
10505
1.46k
                       (uint8_t(lhs.first[i + 3]) & 0x3F);
10506
1.46k
          i += 4;
10507
10508
1.46k
          codePoint1 -= 0x10000;
10509
1.46k
          uint16_t high_surrogate = uint16_t(0xD800 + (codePoint1 >> 10));
10510
1.46k
          low_surrogate1 = uint16_t(0xDC00 + (codePoint1 & 0x3FF));
10511
1.46k
          codePoint1 = high_surrogate;
10512
38.0k
        } else {
10513
          // ASCII (c1 <= 0x7F) or truncated/invalid UTF-8: treat as raw byte
10514
38.0k
          codePoint1 = c1;
10515
38.0k
          i++;
10516
38.0k
        }
10517
43.3k
      }
10518
10519
44.4k
      if (low_surrogate2 != 0) {
10520
1.13k
        codePoint2 = low_surrogate2;
10521
1.13k
        low_surrogate2 = 0;
10522
43.3k
      } else {
10523
43.3k
        uint8_t c2 = uint8_t(rhs.first[j]);
10524
43.3k
        if (c2 > 0x7F && c2 <= 0xDF && j + 1 < rhs.first.size()) {
10525
3.37k
          codePoint2 = ((c2 & 0x1F) << 6) | (uint8_t(rhs.first[j + 1]) & 0x3F);
10526
3.37k
          j += 2;
10527
39.9k
        } else if (c2 > 0xDF && c2 <= 0xEF && j + 2 < rhs.first.size()) {
10528
1.40k
          codePoint2 = ((c2 & 0x0F) << 12) |
10529
1.40k
                       ((uint8_t(rhs.first[j + 1]) & 0x3F) << 6) |
10530
1.40k
                       (uint8_t(rhs.first[j + 2]) & 0x3F);
10531
1.40k
          j += 3;
10532
38.5k
        } else if (c2 > 0xEF && c2 <= 0xF7 && j + 3 < rhs.first.size()) {
10533
1.62k
          codePoint2 = ((c2 & 0x07) << 18) |
10534
1.62k
                       ((uint8_t(rhs.first[j + 1]) & 0x3F) << 12) |
10535
1.62k
                       ((uint8_t(rhs.first[j + 2]) & 0x3F) << 6) |
10536
1.62k
                       (uint8_t(rhs.first[j + 3]) & 0x3F);
10537
1.62k
          j += 4;
10538
1.62k
          codePoint2 -= 0x10000;
10539
1.62k
          uint16_t high_surrogate = uint16_t(0xD800 + (codePoint2 >> 10));
10540
1.62k
          low_surrogate2 = uint16_t(0xDC00 + (codePoint2 & 0x3FF));
10541
1.62k
          codePoint2 = high_surrogate;
10542
36.9k
        } else {
10543
          // ASCII (c2 <= 0x7F) or truncated/invalid UTF-8: treat as raw byte
10544
36.9k
          codePoint2 = c2;
10545
36.9k
          j++;
10546
36.9k
        }
10547
43.3k
      }
10548
10549
44.4k
      if (codePoint1 != codePoint2) {
10550
18.0k
        return (codePoint1 < codePoint2);
10551
18.0k
      }
10552
44.4k
    }
10553
24.9k
    return (j < rhs.first.size() || low_surrogate2 != 0);
10554
42.9k
  });
10555
5.86k
}
10556
10557
2.93k
inline url_search_params_keys_iter url_search_params::get_keys() {
10558
2.93k
  return url_search_params_keys_iter(*this);
10559
2.93k
}
10560
10561
/**
10562
 * @see https://url.spec.whatwg.org/#interface-urlsearchparams
10563
 */
10564
2.93k
inline url_search_params_values_iter url_search_params::get_values() {
10565
2.93k
  return url_search_params_values_iter(*this);
10566
2.93k
}
10567
10568
/**
10569
 * @see https://url.spec.whatwg.org/#interface-urlsearchparams
10570
 */
10571
2.93k
inline url_search_params_entries_iter url_search_params::get_entries() {
10572
2.93k
  return url_search_params_entries_iter(*this);
10573
2.93k
}
10574
10575
template <typename T, url_search_params_iter_type Type>
10576
66.6k
inline bool url_search_params_iter<T, Type>::has_next() const {
10577
66.6k
  return pos < params.params.size();
10578
66.6k
}
ada::url_search_params_iter<std::__1::basic_string_view<char, std::__1::char_traits<char> >, (ada::url_search_params_iter_type)0>::has_next() const
Line
Count
Source
10576
22.2k
inline bool url_search_params_iter<T, Type>::has_next() const {
10577
22.2k
  return pos < params.params.size();
10578
22.2k
}
ada::url_search_params_iter<std::__1::basic_string_view<char, std::__1::char_traits<char> >, (ada::url_search_params_iter_type)1>::has_next() const
Line
Count
Source
10576
22.2k
inline bool url_search_params_iter<T, Type>::has_next() const {
10577
22.2k
  return pos < params.params.size();
10578
22.2k
}
ada::url_search_params_iter<std::__1::pair<std::__1::basic_string_view<char, std::__1::char_traits<char> >, std::__1::basic_string_view<char, std::__1::char_traits<char> > >, (ada::url_search_params_iter_type)2>::has_next() const
Line
Count
Source
10576
22.2k
inline bool url_search_params_iter<T, Type>::has_next() const {
10577
22.2k
  return pos < params.params.size();
10578
22.2k
}
10579
10580
template <>
10581
9.64k
inline std::optional<std::string_view> url_search_params_keys_iter::next() {
10582
9.64k
  if (!has_next()) {
10583
0
    return std::nullopt;
10584
0
  }
10585
9.64k
  return params.params[pos++].first;
10586
9.64k
}
10587
10588
template <>
10589
9.64k
inline std::optional<std::string_view> url_search_params_values_iter::next() {
10590
9.64k
  if (!has_next()) {
10591
0
    return std::nullopt;
10592
0
  }
10593
9.64k
  return params.params[pos++].second;
10594
9.64k
}
10595
10596
template <>
10597
inline std::optional<key_value_view_pair>
10598
9.64k
url_search_params_entries_iter::next() {
10599
9.64k
  if (!has_next()) {
10600
0
    return std::nullopt;
10601
0
  }
10602
9.64k
  return params.params[pos++];
10603
9.64k
}
10604
10605
}  // namespace ada
10606
10607
#endif  // ADA_URL_SEARCH_PARAMS_INL_H
10608
/* end file include/ada/url_search_params-inl.h */
10609
10610
/* begin file include/ada/url_pattern-inl.h */
10611
/**
10612
 * @file url_pattern-inl.h
10613
 * @brief Declaration for the URLPattern inline functions.
10614
 */
10615
#ifndef ADA_URL_PATTERN_INL_H
10616
#define ADA_URL_PATTERN_INL_H
10617
10618
10619
#include <algorithm>
10620
#include <cstddef>
10621
#include <optional>
10622
#include <string>
10623
#include <string_view>
10624
#include <utility>
10625
#include <variant>
10626
#include <vector>
10627
10628
#if ADA_INCLUDE_URL_PATTERN
10629
namespace ada {
10630
10631
0
inline bool url_pattern_init::operator==(const url_pattern_init& other) const {
10632
0
  return protocol == other.protocol && username == other.username &&
10633
0
         password == other.password && hostname == other.hostname &&
10634
0
         port == other.port && search == other.search && hash == other.hash &&
10635
0
         pathname == other.pathname;
10636
0
}
10637
10638
inline bool url_pattern_component_result::operator==(
10639
0
    const url_pattern_component_result& other) const {
10640
0
  return input == other.input && groups == other.groups;
10641
0
}
10642
10643
inline void url_pattern_result::rebind_owned_input_views(
10644
0
    const std::pair<const char*, size_t>* from, size_t from_size) {
10645
0
  // A view the caller pushed into `inputs` does not alias `from` and
10646
0
  // is left unchanged.
10647
0
  for (auto& value : inputs) {
10648
0
    auto* sv = std::get_if<std::string_view>(&value);
10649
0
    if (sv == nullptr) {
10650
0
      continue;
10651
0
    }
10652
0
    for (size_t i = 0; i < from_size && i < owned_strings_.size(); ++i) {
10653
0
      const char* const begin = from[i].first;
10654
0
      const char* const end = begin + from[i].second;
10655
0
      if (sv->data() >= begin && sv->data() <= end &&
10656
0
          static_cast<size_t>(end - sv->data()) >= sv->size()) {
10657
0
        const size_t off = static_cast<size_t>(sv->data() - begin);
10658
0
        value = std::string_view(owned_strings_[i].data() + off, sv->size());
10659
0
        break;
10660
0
      }
10661
0
    }
10662
0
  }
10663
0
}
10664
10665
inline void url_pattern_result::take_inputs(
10666
0
    url_pattern_result& other) noexcept {
10667
0
  // SSO buffers change address when a std::string is moved, so the
10668
0
  // source addresses have to be captured first. store_inputs never
10669
0
  // owns more than two strings, which keeps this noexcept.
10670
0
  std::pair<const char*, size_t> from[2];
10671
0
  const size_t n =
10672
0
      other.owned_strings_.size() < 2 ? other.owned_strings_.size() : 2;
10673
0
  for (size_t i = 0; i < n; ++i) {
10674
0
    from[i] = {other.owned_strings_[i].data(), other.owned_strings_[i].size()};
10675
0
  }
10676
0
  inputs = std::move(other.inputs);
10677
0
  owned_strings_ = std::move(other.owned_strings_);
10678
0
  rebind_owned_input_views(from, n);
10679
0
  other.inputs.clear();
10680
0
  other.owned_strings_.clear();
10681
0
}
10682
10683
inline void url_pattern_result::store_inputs(const url_pattern_input& input,
10684
0
                                             const std::string_view* base_url) {
10685
0
  owned_strings_.clear();
10686
0
  inputs.clear();
10687
0
  // inputs[] holds views into owned_strings_, so it must not reallocate
10688
0
  // (and move SSO buffers) after the first view is taken.
10689
0
  owned_strings_.reserve(2);
10690
0
  if (std::holds_alternative<std::string_view>(input)) {
10691
0
    owned_strings_.emplace_back(std::get<std::string_view>(input));
10692
0
    inputs.emplace_back(std::string_view(owned_strings_.back()));
10693
0
  } else {
10694
0
    inputs.emplace_back(std::get<url_pattern_init>(input));
10695
0
  }
10696
0
  if (base_url != nullptr) {
10697
0
    owned_strings_.emplace_back(*base_url);
10698
0
    inputs.emplace_back(std::string_view(owned_strings_.back()));
10699
0
  }
10700
0
}
10701
10702
inline url_pattern_result::url_pattern_result(const url_pattern_result& other)
10703
    : inputs(other.inputs),
10704
      protocol(other.protocol),
10705
      username(other.username),
10706
      password(other.password),
10707
      hostname(other.hostname),
10708
      port(other.port),
10709
      pathname(other.pathname),
10710
      search(other.search),
10711
      hash(other.hash),
10712
      owned_strings_(other.owned_strings_) {
10713
  // `other` is unchanged, so its buffers are still the ones inputs
10714
  // may point at.
10715
  std::pair<const char*, size_t> from[2];
10716
  const size_t n =
10717
      other.owned_strings_.size() < 2 ? other.owned_strings_.size() : 2;
10718
  for (size_t i = 0; i < n; ++i) {
10719
    from[i] = {other.owned_strings_[i].data(), other.owned_strings_[i].size()};
10720
  }
10721
  rebind_owned_input_views(from, n);
10722
}
10723
10724
inline url_pattern_result::url_pattern_result(
10725
    url_pattern_result&& other) noexcept
10726
    : inputs(),
10727
      protocol(std::move(other.protocol)),
10728
      username(std::move(other.username)),
10729
      password(std::move(other.password)),
10730
      hostname(std::move(other.hostname)),
10731
      port(std::move(other.port)),
10732
      pathname(std::move(other.pathname)),
10733
      search(std::move(other.search)),
10734
      hash(std::move(other.hash)),
10735
      owned_strings_() {
10736
  take_inputs(other);
10737
}
10738
10739
inline url_pattern_result& url_pattern_result::operator=(
10740
0
    const url_pattern_result& other) {
10741
0
  if (this != &other) {
10742
0
    url_pattern_result tmp(other);
10743
0
    *this = std::move(tmp);
10744
0
  }
10745
0
  return *this;
10746
0
}
10747
10748
inline url_pattern_result& url_pattern_result::operator=(
10749
0
    url_pattern_result&& other) noexcept {
10750
0
  if (this != &other) {
10751
0
    protocol = std::move(other.protocol);
10752
0
    username = std::move(other.username);
10753
0
    password = std::move(other.password);
10754
0
    hostname = std::move(other.hostname);
10755
0
    port = std::move(other.port);
10756
0
    pathname = std::move(other.pathname);
10757
0
    search = std::move(other.search);
10758
0
    hash = std::move(other.hash);
10759
0
    take_inputs(other);
10760
0
  }
10761
0
  return *this;
10762
0
}
10763
10764
template <url_pattern_regex::regex_concept regex_provider>
10765
url_pattern_component_result
10766
url_pattern_component<regex_provider>::create_component_match_result(
10767
    std::string&& input,
10768
    std::vector<std::optional<std::string>>&& exec_result) {
10769
  // Let result be a new URLPatternComponentResult.
10770
  // Set result["input"] to input.
10771
  // Let groups be a record<USVString, (USVString or undefined)>.
10772
  auto result =
10773
      url_pattern_component_result{.input = std::move(input), .groups = {}};
10774
10775
  // We explicitly start iterating from 0 even though the spec
10776
  // says we should start from 1. This case is handled by the
10777
  // std_regex_provider which removes the full match from index 0.
10778
  // Use min() to guard against potential mismatches between
10779
  // exec_result size and group_name_list size.
10780
  const size_t size = std::min(exec_result.size(), group_name_list.size());
10781
  result.groups.reserve(size);
10782
  for (size_t index = 0; index < size; index++) {
10783
    result.groups.emplace(group_name_list[index],
10784
                          std::move(exec_result[index]));
10785
  }
10786
  return result;
10787
}
10788
10789
template <url_pattern_regex::regex_concept regex_provider>
10790
std::string_view url_pattern<regex_provider>::get_protocol() const
10791
    ada_lifetime_bound {
10792
  // Return this's associated URL pattern's protocol component's pattern string.
10793
  return protocol_component.pattern;
10794
}
10795
template <url_pattern_regex::regex_concept regex_provider>
10796
std::string_view url_pattern<regex_provider>::get_username() const
10797
    ada_lifetime_bound {
10798
  // Return this's associated URL pattern's username component's pattern string.
10799
  return username_component.pattern;
10800
}
10801
template <url_pattern_regex::regex_concept regex_provider>
10802
std::string_view url_pattern<regex_provider>::get_password() const
10803
    ada_lifetime_bound {
10804
  // Return this's associated URL pattern's password component's pattern string.
10805
  return password_component.pattern;
10806
}
10807
template <url_pattern_regex::regex_concept regex_provider>
10808
std::string_view url_pattern<regex_provider>::get_hostname() const
10809
    ada_lifetime_bound {
10810
  // Return this's associated URL pattern's hostname component's pattern string.
10811
  return hostname_component.pattern;
10812
}
10813
template <url_pattern_regex::regex_concept regex_provider>
10814
std::string_view url_pattern<regex_provider>::get_port() const
10815
    ada_lifetime_bound {
10816
  // Return this's associated URL pattern's port component's pattern string.
10817
  return port_component.pattern;
10818
}
10819
template <url_pattern_regex::regex_concept regex_provider>
10820
std::string_view url_pattern<regex_provider>::get_pathname() const
10821
    ada_lifetime_bound {
10822
  // Return this's associated URL pattern's pathname component's pattern string.
10823
  return pathname_component.pattern;
10824
}
10825
template <url_pattern_regex::regex_concept regex_provider>
10826
std::string_view url_pattern<regex_provider>::get_search() const
10827
    ada_lifetime_bound {
10828
  // Return this's associated URL pattern's search component's pattern string.
10829
  return search_component.pattern;
10830
}
10831
template <url_pattern_regex::regex_concept regex_provider>
10832
std::string_view url_pattern<regex_provider>::get_hash() const
10833
    ada_lifetime_bound {
10834
  // Return this's associated URL pattern's hash component's pattern string.
10835
  return hash_component.pattern;
10836
}
10837
template <url_pattern_regex::regex_concept regex_provider>
10838
bool url_pattern<regex_provider>::ignore_case() const {
10839
  return ignore_case_;
10840
}
10841
template <url_pattern_regex::regex_concept regex_provider>
10842
bool url_pattern<regex_provider>::has_regexp_groups() const {
10843
  // If this's associated URL pattern's has regexp groups, then return true.
10844
  return protocol_component.has_regexp_groups ||
10845
         username_component.has_regexp_groups ||
10846
         password_component.has_regexp_groups ||
10847
         hostname_component.has_regexp_groups ||
10848
         port_component.has_regexp_groups ||
10849
         pathname_component.has_regexp_groups ||
10850
         search_component.has_regexp_groups || hash_component.has_regexp_groups;
10851
}
10852
10853
0
inline bool url_pattern_part::is_regexp() const noexcept {
10854
0
  return type == url_pattern_part_type::REGEXP;
10855
0
}
10856
10857
inline std::string_view url_pattern_compile_component_options::get_delimiter()
10858
0
    const {
10859
0
  if (delimiter) {
10860
0
    return {&delimiter.value(), 1};
10861
0
  }
10862
0
  return {};
10863
0
}
10864
10865
inline std::string_view url_pattern_compile_component_options::get_prefix()
10866
0
    const {
10867
0
  if (prefix) {
10868
0
    return {&prefix.value(), 1};
10869
0
  }
10870
0
  return {};
10871
0
}
10872
10873
template <url_pattern_regex::regex_concept regex_provider>
10874
template <url_pattern_encoding_callback F>
10875
tl::expected<url_pattern_component<regex_provider>, errors>
10876
url_pattern_component<regex_provider>::compile(
10877
    std::string_view input, F& encoding_callback,
10878
    url_pattern_compile_component_options& options) {
10879
  ada_log("url_pattern_component::compile input: ", input);
10880
  // Let part list be the result of running parse a pattern string given input,
10881
  // options, and encoding callback.
10882
  auto part_list = url_pattern_helpers::parse_pattern_string(input, options,
10883
                                                             encoding_callback);
10884
10885
  if (!part_list) {
10886
    ada_log("parse_pattern_string failed");
10887
    return tl::unexpected(part_list.error());
10888
  }
10889
10890
  // Detect pattern type early to potentially skip expensive regex compilation
10891
  const auto has_regexp = [](const auto& part) { return part.is_regexp(); };
10892
  const bool has_regexp_groups = std::ranges::any_of(*part_list, has_regexp);
10893
10894
  url_pattern_component_type component_type =
10895
      url_pattern_component_type::REGEXP;
10896
  std::string exact_match_value{};
10897
10898
  if (part_list->empty()) {
10899
    component_type = url_pattern_component_type::EMPTY;
10900
  } else if (part_list->size() == 1) {
10901
    const auto& part = (*part_list)[0];
10902
    if (part.type == url_pattern_part_type::FIXED_TEXT &&
10903
        part.modifier == url_pattern_part_modifier::none &&
10904
        !options.ignore_case) {
10905
      component_type = url_pattern_component_type::EXACT_MATCH;
10906
      exact_match_value = part.value;
10907
    } else if (part.type == url_pattern_part_type::FULL_WILDCARD &&
10908
               part.modifier == url_pattern_part_modifier::none &&
10909
               part.prefix.empty() && part.suffix.empty()) {
10910
      component_type = url_pattern_component_type::FULL_WILDCARD;
10911
    }
10912
  }
10913
10914
  // For simple patterns, skip regex generation and compilation entirely
10915
  if (component_type != url_pattern_component_type::REGEXP) {
10916
    auto pattern_string =
10917
        url_pattern_helpers::generate_pattern_string(*part_list, options);
10918
    // For FULL_WILDCARD, we need the group name from
10919
    // generate_regular_expression
10920
    std::vector<std::string> name_list;
10921
    if (component_type == url_pattern_component_type::FULL_WILDCARD &&
10922
        !part_list->empty()) {
10923
      name_list.push_back((*part_list)[0].name);
10924
    }
10925
    return url_pattern_component<regex_provider>(
10926
        std::move(pattern_string), typename regex_provider::regex_type{},
10927
        std::move(name_list), has_regexp_groups, component_type,
10928
        std::move(exact_match_value));
10929
  }
10930
10931
  // Generate regex for complex patterns
10932
  auto [regular_expression_string, name_list] =
10933
      url_pattern_helpers::generate_regular_expression_and_name_list(*part_list,
10934
                                                                     options);
10935
  auto pattern_string =
10936
      url_pattern_helpers::generate_pattern_string(*part_list, options);
10937
10938
  std::optional<typename regex_provider::regex_type> regular_expression =
10939
      regex_provider::create_instance(regular_expression_string,
10940
                                      options.ignore_case);
10941
  if (!regular_expression) {
10942
    return tl::unexpected(errors::type_error);
10943
  }
10944
10945
  return url_pattern_component<regex_provider>(
10946
      std::move(pattern_string), std::move(*regular_expression),
10947
      std::move(name_list), has_regexp_groups, component_type,
10948
      std::move(exact_match_value));
10949
}
10950
10951
template <url_pattern_regex::regex_concept regex_provider>
10952
bool url_pattern_component<regex_provider>::fast_test(
10953
    std::string_view input) const {
10954
  // Fast path for simple patterns - avoid regex evaluation
10955
  // Using if-else for better branch prediction on common cases
10956
  if (type == url_pattern_component_type::FULL_WILDCARD) {
10957
    return true;
10958
  }
10959
  if (type == url_pattern_component_type::EXACT_MATCH) {
10960
    return input == exact_match_value;
10961
  }
10962
  if (type == url_pattern_component_type::EMPTY) {
10963
    return input.empty();
10964
  }
10965
  // type == REGEXP
10966
  return regex_provider::regex_match(input, regexp);
10967
}
10968
10969
template <url_pattern_regex::regex_concept regex_provider>
10970
std::optional<std::vector<std::optional<std::string>>>
10971
url_pattern_component<regex_provider>::fast_match(
10972
    std::string_view input) const {
10973
  // Handle each type directly without redundant checks
10974
  if (type == url_pattern_component_type::FULL_WILDCARD) {
10975
    // FULL_WILDCARD always matches - capture the input (even if empty)
10976
    // If there's no group name, return empty groups
10977
    if (group_name_list.empty()) {
10978
      return std::vector<std::optional<std::string>>{};
10979
    }
10980
    // Capture the matched input (including empty strings)
10981
    return std::vector<std::optional<std::string>>{std::string(input)};
10982
  }
10983
  if (type == url_pattern_component_type::EXACT_MATCH) {
10984
    if (input == exact_match_value) {
10985
      return std::vector<std::optional<std::string>>{};
10986
    }
10987
    return std::nullopt;
10988
  }
10989
  if (type == url_pattern_component_type::EMPTY) {
10990
    if (input.empty()) {
10991
      return std::vector<std::optional<std::string>>{};
10992
    }
10993
    return std::nullopt;
10994
  }
10995
  // type == REGEXP - use regex
10996
  return regex_provider::regex_search(input, regexp);
10997
}
10998
10999
template <url_pattern_regex::regex_concept regex_provider>
11000
result<std::optional<url_pattern_result>> url_pattern<regex_provider>::exec(
11001
    const url_pattern_input& input, const std::string_view* base_url) {
11002
  // Return the result of match given this's associated URL pattern, input, and
11003
  // baseURL if given.
11004
  return match(input, base_url);
11005
}
11006
11007
template <url_pattern_regex::regex_concept regex_provider>
11008
bool url_pattern<regex_provider>::test_components(
11009
    std::string_view protocol, std::string_view username,
11010
    std::string_view password, std::string_view hostname, std::string_view port,
11011
    std::string_view pathname, std::string_view search,
11012
    std::string_view hash) const {
11013
  return protocol_component.fast_test(protocol) &&
11014
         username_component.fast_test(username) &&
11015
         password_component.fast_test(password) &&
11016
         hostname_component.fast_test(hostname) &&
11017
         port_component.fast_test(port) &&
11018
         pathname_component.fast_test(pathname) &&
11019
         search_component.fast_test(search) && hash_component.fast_test(hash);
11020
}
11021
11022
template <url_pattern_regex::regex_concept regex_provider>
11023
result<bool> url_pattern<regex_provider>::test(
11024
    const url_pattern_input& input, const std::string_view* base_url_string) {
11025
  // If input is a URLPatternInit
11026
  if (std::holds_alternative<url_pattern_init>(input)) {
11027
    if (base_url_string) {
11028
      return tl::unexpected(errors::type_error);
11029
    }
11030
11031
    std::string protocol{}, username{}, password{}, hostname{};
11032
    std::string port{}, pathname{}, search{}, hash{};
11033
11034
    auto apply_result = url_pattern_init::process(
11035
        std::get<url_pattern_init>(input), url_pattern_init::process_type::url,
11036
        protocol, username, password, hostname, port, pathname, search, hash);
11037
11038
    if (!apply_result) {
11039
      return false;
11040
    }
11041
11042
    std::string_view search_view = *apply_result->search;
11043
    if (search_view.starts_with("?")) {
11044
      search_view.remove_prefix(1);
11045
    }
11046
11047
    return test_components(*apply_result->protocol, *apply_result->username,
11048
                           *apply_result->password, *apply_result->hostname,
11049
                           *apply_result->port, *apply_result->pathname,
11050
                           search_view, *apply_result->hash);
11051
  }
11052
11053
  // URL string input path.
11054
  // Let baseURL be null. A default-constructed result holds a value (an
11055
  // empty URL), and a relative input would then resolve against it. Start
11056
  // from an error so "no base given" means no value.
11057
  result<url_aggregator> base_url = tl::unexpected(errors::type_error);
11058
  if (base_url_string) {
11059
    base_url = ada::parse<url_aggregator>(*base_url_string, nullptr);
11060
    if (!base_url) {
11061
      return false;
11062
    }
11063
  }
11064
11065
  auto url =
11066
      ada::parse<url_aggregator>(std::get<std::string_view>(input),
11067
                                 base_url.has_value() ? &*base_url : nullptr);
11068
  if (!url) {
11069
    return false;
11070
  }
11071
11072
  // Extract components as string_view
11073
  auto protocol_view = url->get_protocol();
11074
  if (protocol_view.ends_with(":")) {
11075
    protocol_view.remove_suffix(1);
11076
  }
11077
11078
  auto search_view = url->get_search();
11079
  if (search_view.starts_with("?")) {
11080
    search_view.remove_prefix(1);
11081
  }
11082
11083
  auto hash_view = url->get_hash();
11084
  if (hash_view.starts_with("#")) {
11085
    hash_view.remove_prefix(1);
11086
  }
11087
11088
  return test_components(protocol_view, url->get_username(),
11089
                         url->get_password(), url->get_hostname(),
11090
                         url->get_port(), url->get_pathname(), search_view,
11091
                         hash_view);
11092
}
11093
11094
template <url_pattern_regex::regex_concept regex_provider>
11095
result<std::optional<url_pattern_result>> url_pattern<regex_provider>::match(
11096
    const url_pattern_input& input, const std::string_view* base_url_string) {
11097
  std::string protocol{};
11098
  std::string username{};
11099
  std::string password{};
11100
  std::string hostname{};
11101
  std::string port{};
11102
  std::string pathname{};
11103
  std::string search{};
11104
  std::string hash{};
11105
11106
  // If input is a URLPatternInit then:
11107
  if (std::holds_alternative<url_pattern_init>(input)) {
11108
    ada_log(
11109
        "url_pattern::match called with url_pattern_init and base_url_string=",
11110
        base_url_string);
11111
    // If baseURLString was given, throw a TypeError.
11112
    if (base_url_string) {
11113
      ada_log("failed to match because base_url_string was given");
11114
      return tl::unexpected(errors::type_error);
11115
    }
11116
11117
    // Let applyResult be the result of process a URLPatternInit given input,
11118
    // "url", protocol, username, password, hostname, port, pathname, search,
11119
    // and hash.
11120
    auto apply_result = url_pattern_init::process(
11121
        std::get<url_pattern_init>(input), url_pattern_init::process_type::url,
11122
        protocol, username, password, hostname, port, pathname, search, hash);
11123
11124
    // If this throws an exception, catch it, and return null.
11125
    if (!apply_result.has_value()) {
11126
      ada_log("match returned std::nullopt because process threw");
11127
      return std::nullopt;
11128
    }
11129
11130
    // Set protocol to applyResult["protocol"].
11131
    ADA_ASSERT_TRUE(apply_result->protocol.has_value());
11132
    protocol = std::move(apply_result->protocol.value());
11133
11134
    // Set username to applyResult["username"].
11135
    ADA_ASSERT_TRUE(apply_result->username.has_value());
11136
    username = std::move(apply_result->username.value());
11137
11138
    // Set password to applyResult["password"].
11139
    ADA_ASSERT_TRUE(apply_result->password.has_value());
11140
    password = std::move(apply_result->password.value());
11141
11142
    // Set hostname to applyResult["hostname"].
11143
    ADA_ASSERT_TRUE(apply_result->hostname.has_value());
11144
    hostname = std::move(apply_result->hostname.value());
11145
11146
    // Set port to applyResult["port"].
11147
    ADA_ASSERT_TRUE(apply_result->port.has_value());
11148
    port = std::move(apply_result->port.value());
11149
11150
    // Set pathname to applyResult["pathname"].
11151
    ADA_ASSERT_TRUE(apply_result->pathname.has_value());
11152
    pathname = std::move(apply_result->pathname.value());
11153
11154
    // Set search to applyResult["search"].
11155
    ADA_ASSERT_TRUE(apply_result->search.has_value());
11156
    if (apply_result->search->starts_with("?")) {
11157
      search = apply_result->search->substr(1);
11158
    } else {
11159
      search = std::move(apply_result->search.value());
11160
    }
11161
11162
    // Set hash to applyResult["hash"].
11163
    ADA_ASSERT_TRUE(apply_result->hash.has_value());
11164
    ADA_ASSERT_TRUE(!apply_result->hash->starts_with("#"));
11165
    hash = std::move(apply_result->hash.value());
11166
  } else {
11167
    ADA_ASSERT_TRUE(std::holds_alternative<std::string_view>(input));
11168
11169
    // Let baseURL be null. A default-constructed result holds a value (an
11170
    // empty URL), and a relative input would then resolve against it. Start
11171
    // from an error so "no base given" means no value.
11172
    result<url_aggregator> base_url = tl::unexpected(errors::type_error);
11173
11174
    // If baseURLString was given, then:
11175
    if (base_url_string) {
11176
      // Let baseURL be the result of parsing baseURLString.
11177
      base_url = ada::parse<url_aggregator>(*base_url_string, nullptr);
11178
11179
      // If baseURL is failure, return null.
11180
      if (!base_url) {
11181
        ada_log("match returned std::nullopt because failed to parse base_url=",
11182
                *base_url_string);
11183
        return std::nullopt;
11184
      }
11185
    }
11186
11187
    url_aggregator* base_url_value =
11188
        base_url.has_value() ? &*base_url : nullptr;
11189
11190
    // Set url to the result of parsing input given baseURL.
11191
    auto url = ada::parse<url_aggregator>(std::get<std::string_view>(input),
11192
                                          base_url_value);
11193
11194
    // If url is failure, return null.
11195
    if (!url) {
11196
      ada_log("match returned std::nullopt because url failed");
11197
      return std::nullopt;
11198
    }
11199
11200
    // Set protocol to url's scheme.
11201
    // IMPORTANT: Not documented on the URLPattern spec, but protocol suffix ':'
11202
    // is removed. Similar work was done on workerd:
11203
    // https://github.com/cloudflare/workerd/blob/8620d14012513a6ce04d079e401d3becac3c67bd/src/workerd/jsg/url.c%2B%2B#L2038
11204
    protocol = url->get_protocol().substr(0, url->get_protocol().size() - 1);
11205
    // Set username to url's username.
11206
    username = url->get_username();
11207
    // Set password to url's password.
11208
    password = url->get_password();
11209
    // Set hostname to url's host, serialized, or the empty string if the value
11210
    // is null.
11211
    hostname = url->get_hostname();
11212
    // Set port to url's port, serialized, or the empty string if the value is
11213
    // null.
11214
    port = url->get_port();
11215
    // Set pathname to the result of URL path serializing url.
11216
    pathname = url->get_pathname();
11217
    // Set search to url's query or the empty string if the value is null.
11218
    // IMPORTANT: Not documented on the URLPattern spec, but search prefix '?'
11219
    // is removed. Similar work was done on workerd:
11220
    // https://github.com/cloudflare/workerd/blob/8620d14012513a6ce04d079e401d3becac3c67bd/src/workerd/jsg/url.c%2B%2B#L2232
11221
    if (url->has_search()) {
11222
      auto view = url->get_search();
11223
      search = view.starts_with("?") ? url->get_search().substr(1) : view;
11224
    }
11225
    // Set hash to url's fragment or the empty string if the value is null.
11226
    // IMPORTANT: Not documented on the URLPattern spec, but hash prefix '#' is
11227
    // removed. Similar work was done on workerd:
11228
    // https://github.com/cloudflare/workerd/blob/8620d14012513a6ce04d079e401d3becac3c67bd/src/workerd/jsg/url.c%2B%2B#L2242
11229
    if (url->has_hash()) {
11230
      auto view = url->get_hash();
11231
      hash = view.starts_with("#") ? url->get_hash().substr(1) : view;
11232
    }
11233
  }
11234
11235
  // Use fast_match which skips regex for simple patterns (EMPTY, EXACT_MATCH,
11236
  // FULL_WILDCARD) and only falls back to regex for complex REGEXP patterns.
11237
11238
  // Let protocolExecResult be RegExpBuiltinExec(urlPattern's protocol
11239
  // component's regular expression, protocol).
11240
  auto protocol_exec_result = protocol_component.fast_match(protocol);
11241
  if (!protocol_exec_result) {
11242
    return std::nullopt;
11243
  }
11244
11245
  // Let usernameExecResult be RegExpBuiltinExec(urlPattern's username
11246
  // component's regular expression, username).
11247
  auto username_exec_result = username_component.fast_match(username);
11248
  if (!username_exec_result) {
11249
    return std::nullopt;
11250
  }
11251
11252
  // Let passwordExecResult be RegExpBuiltinExec(urlPattern's password
11253
  // component's regular expression, password).
11254
  auto password_exec_result = password_component.fast_match(password);
11255
  if (!password_exec_result) {
11256
    return std::nullopt;
11257
  }
11258
11259
  // Let hostnameExecResult be RegExpBuiltinExec(urlPattern's hostname
11260
  // component's regular expression, hostname).
11261
  auto hostname_exec_result = hostname_component.fast_match(hostname);
11262
  if (!hostname_exec_result) {
11263
    return std::nullopt;
11264
  }
11265
11266
  // Let portExecResult be RegExpBuiltinExec(urlPattern's port component's
11267
  // regular expression, port).
11268
  auto port_exec_result = port_component.fast_match(port);
11269
  if (!port_exec_result) {
11270
    return std::nullopt;
11271
  }
11272
11273
  // Let pathnameExecResult be RegExpBuiltinExec(urlPattern's pathname
11274
  // component's regular expression, pathname).
11275
  auto pathname_exec_result = pathname_component.fast_match(pathname);
11276
  if (!pathname_exec_result) {
11277
    return std::nullopt;
11278
  }
11279
11280
  // Let searchExecResult be RegExpBuiltinExec(urlPattern's search component's
11281
  // regular expression, search).
11282
  auto search_exec_result = search_component.fast_match(search);
11283
  if (!search_exec_result) {
11284
    return std::nullopt;
11285
  }
11286
11287
  // Let hashExecResult be RegExpBuiltinExec(urlPattern's hash component's
11288
  // regular expression, hash).
11289
  auto hash_exec_result = hash_component.fast_match(hash);
11290
  if (!hash_exec_result) {
11291
    return std::nullopt;
11292
  }
11293
11294
  // Let result be a new URLPatternResult.
11295
  auto result = url_pattern_result{};
11296
  // Set result["inputs"] to inputs. Copy URL / base URL text into the
11297
  // result so inputs[] string_views outlive the caller's arguments.
11298
  result.store_inputs(input, base_url_string);
11299
  // Set result["protocol"] to the result of creating a component match result
11300
  // given urlPattern's protocol component, protocol, and protocolExecResult.
11301
  result.protocol = protocol_component.create_component_match_result(
11302
      std::move(protocol), std::move(*protocol_exec_result));
11303
11304
  // Set result["username"] to the result of creating a component match result
11305
  // given urlPattern's username component, username, and usernameExecResult.
11306
  result.username = username_component.create_component_match_result(
11307
      std::move(username), std::move(*username_exec_result));
11308
11309
  // Set result["password"] to the result of creating a component match result
11310
  // given urlPattern's password component, password, and passwordExecResult.
11311
  result.password = password_component.create_component_match_result(
11312
      std::move(password), std::move(*password_exec_result));
11313
11314
  // Set result["hostname"] to the result of creating a component match result
11315
  // given urlPattern's hostname component, hostname, and hostnameExecResult.
11316
  result.hostname = hostname_component.create_component_match_result(
11317
      std::move(hostname), std::move(*hostname_exec_result));
11318
11319
  // Set result["port"] to the result of creating a component match result given
11320
  // urlPattern's port component, port, and portExecResult.
11321
  result.port = port_component.create_component_match_result(
11322
      std::move(port), std::move(*port_exec_result));
11323
11324
  // Set result["pathname"] to the result of creating a component match result
11325
  // given urlPattern's pathname component, pathname, and pathnameExecResult.
11326
  result.pathname = pathname_component.create_component_match_result(
11327
      std::move(pathname), std::move(*pathname_exec_result));
11328
11329
  // Set result["search"] to the result of creating a component match result
11330
  // given urlPattern's search component, search, and searchExecResult.
11331
  result.search = search_component.create_component_match_result(
11332
      std::move(search), std::move(*search_exec_result));
11333
11334
  // Set result["hash"] to the result of creating a component match result given
11335
  // urlPattern's hash component, hash, and hashExecResult.
11336
  result.hash = hash_component.create_component_match_result(
11337
      std::move(hash), std::move(*hash_exec_result));
11338
11339
  return result;
11340
}
11341
11342
}  // namespace ada
11343
#endif  // ADA_INCLUDE_URL_PATTERN
11344
#endif
11345
/* end file include/ada/url_pattern-inl.h */
11346
/* begin file include/ada/url_pattern_helpers-inl.h */
11347
/**
11348
 * @file url_pattern_helpers-inl.h
11349
 * @brief Declaration for the URLPattern helpers.
11350
 */
11351
#ifndef ADA_URL_PATTERN_HELPERS_INL_H
11352
#define ADA_URL_PATTERN_HELPERS_INL_H
11353
11354
#include <cstddef>
11355
#include <cstdint>
11356
#include <optional>
11357
#include <string>
11358
#include <string_view>
11359
#include <utility>
11360
#include <vector>
11361
11362
11363
#if ADA_INCLUDE_URL_PATTERN
11364
namespace ada::url_pattern_helpers {
11365
#if defined(ADA_TESTING) || defined(ADA_LOGGING)
11366
0
inline std::string to_string(token_type type) {
11367
0
  switch (type) {
11368
0
    case token_type::INVALID_CHAR:
11369
0
      return "INVALID_CHAR";
11370
0
    case token_type::OPEN:
11371
0
      return "OPEN";
11372
0
    case token_type::CLOSE:
11373
0
      return "CLOSE";
11374
0
    case token_type::REGEXP:
11375
0
      return "REGEXP";
11376
0
    case token_type::NAME:
11377
0
      return "NAME";
11378
0
    case token_type::CHAR:
11379
0
      return "CHAR";
11380
0
    case token_type::ESCAPED_CHAR:
11381
0
      return "ESCAPED_CHAR";
11382
0
    case token_type::OTHER_MODIFIER:
11383
0
      return "OTHER_MODIFIER";
11384
0
    case token_type::ASTERISK:
11385
0
      return "ASTERISK";
11386
0
    case token_type::END:
11387
0
      return "END";
11388
0
    default:
11389
0
      ada::unreachable();
11390
0
  }
11391
0
}
11392
#endif  // defined(ADA_TESTING) || defined(ADA_LOGGING)
11393
11394
template <url_pattern_regex::regex_concept regex_provider>
11395
constexpr void constructor_string_parser<regex_provider>::rewind() {
11396
  // Set parser's token index to parser's component start.
11397
  token_index = component_start;
11398
  // Set parser's token increment to 0.
11399
  token_increment = 0;
11400
}
11401
11402
template <url_pattern_regex::regex_concept regex_provider>
11403
constexpr bool constructor_string_parser<regex_provider>::is_hash_prefix() {
11404
  // Return the result of running is a non-special pattern char given parser,
11405
  // parser's token index and "#".
11406
  return is_non_special_pattern_char(token_index, '#');
11407
}
11408
11409
template <url_pattern_regex::regex_concept regex_provider>
11410
constexpr bool constructor_string_parser<regex_provider>::is_search_prefix() {
11411
  // If result of running is a non-special pattern char given parser, parser's
11412
  // token index and "?" is true, then return true.
11413
  if (is_non_special_pattern_char(token_index, '?')) {
11414
    return true;
11415
  }
11416
11417
  // If parser's token list[parser's token index]'s value is not "?", then
11418
  // return false.
11419
  if (token_list[token_index].value != "?") {
11420
    return false;
11421
  }
11422
11423
  // If previous index is less than 0, then return true.
11424
  if (token_index == 0) return true;
11425
  // Let previous index be parser's token index - 1.
11426
  auto previous_index = token_index - 1;
11427
  // Let previous token be the result of running get a safe token given parser
11428
  // and previous index.
11429
  auto previous_token = get_safe_token(previous_index);
11430
  ADA_ASSERT_TRUE(previous_token);
11431
  // If any of the following are true, then return false:
11432
  // - previous token's type is "name".
11433
  // - previous token's type is "regexp".
11434
  // - previous token's type is "close".
11435
  // - previous token's type is "asterisk".
11436
  return !(previous_token->type == token_type::NAME ||
11437
           previous_token->type == token_type::REGEXP ||
11438
           previous_token->type == token_type::CLOSE ||
11439
           previous_token->type == token_type::ASTERISK);
11440
}
11441
11442
template <url_pattern_regex::regex_concept regex_provider>
11443
constexpr bool
11444
constructor_string_parser<regex_provider>::is_non_special_pattern_char(
11445
    size_t index, uint32_t value) const {
11446
  // Let token be the result of running get a safe token given parser and index.
11447
  auto token = get_safe_token(index);
11448
  ADA_ASSERT_TRUE(token);
11449
11450
  // If token's value is not value, then return false.
11451
  // TODO: Remove this once we make sure get_safe_token returns a non-empty
11452
  // string.
11453
  if (!token->value.empty() &&
11454
      static_cast<uint32_t>(token->value[0]) != value) {
11455
    return false;
11456
  }
11457
11458
  // If any of the following are true:
11459
  // - token's type is "char";
11460
  // - token's type is "escaped-char"; or
11461
  // - token's type is "invalid-char",
11462
  // - then return true.
11463
  return token->type == token_type::CHAR ||
11464
         token->type == token_type::ESCAPED_CHAR ||
11465
         token->type == token_type::INVALID_CHAR;
11466
}
11467
11468
template <url_pattern_regex::regex_concept regex_provider>
11469
constexpr const token*
11470
constructor_string_parser<regex_provider>::get_safe_token(size_t index) const {
11471
  // If index is less than parser's token list's size, then return parser's
11472
  // token list[index].
11473
  if (index < token_list.size()) [[likely]] {
11474
    return &token_list[index];
11475
  }
11476
11477
  // Assert: parser's token list's size is greater than or equal to 1.
11478
  ADA_ASSERT_TRUE(!token_list.empty());
11479
11480
  // Let token be parser's token list[last index].
11481
  // Assert: token's type is "end".
11482
  ADA_ASSERT_TRUE(token_list.back().type == token_type::END);
11483
11484
  // Return token.
11485
  return &token_list.back();
11486
}
11487
11488
template <url_pattern_regex::regex_concept regex_provider>
11489
constexpr bool constructor_string_parser<regex_provider>::is_group_open()
11490
    const {
11491
  // If parser's token list[parser's token index]'s type is "open", then return
11492
  // true.
11493
  return token_list[token_index].type == token_type::OPEN;
11494
}
11495
11496
template <url_pattern_regex::regex_concept regex_provider>
11497
constexpr bool constructor_string_parser<regex_provider>::is_group_close()
11498
    const {
11499
  // If parser's token list[parser's token index]'s type is "close", then return
11500
  // true.
11501
  return token_list[token_index].type == token_type::CLOSE;
11502
}
11503
11504
template <url_pattern_regex::regex_concept regex_provider>
11505
constexpr bool
11506
constructor_string_parser<regex_provider>::next_is_authority_slashes() const {
11507
  // If the result of running is a non-special pattern char given parser,
11508
  // parser's token index + 1, and "/" is false, then return false.
11509
  if (!is_non_special_pattern_char(token_index + 1, '/')) {
11510
    return false;
11511
  }
11512
  // If the result of running is a non-special pattern char given parser,
11513
  // parser's token index + 2, and "/" is false, then return false.
11514
  if (!is_non_special_pattern_char(token_index + 2, '/')) {
11515
    return false;
11516
  }
11517
  return true;
11518
}
11519
11520
template <url_pattern_regex::regex_concept regex_provider>
11521
constexpr bool constructor_string_parser<regex_provider>::is_protocol_suffix()
11522
    const {
11523
  // Return the result of running is a non-special pattern char given parser,
11524
  // parser's token index, and ":".
11525
  return is_non_special_pattern_char(token_index, ':');
11526
}
11527
11528
template <url_pattern_regex::regex_concept regex_provider>
11529
void constructor_string_parser<regex_provider>::change_state(State new_state,
11530
                                                             size_t skip) {
11531
  // If parser's state is not "init", not "authority", and not "done", then set
11532
  // parser's result[parser's state] to the result of running make a component
11533
  // string given parser.
11534
  if (state != State::INIT && state != State::AUTHORITY &&
11535
      state != State::DONE) {
11536
    auto value = make_component_string();
11537
    // TODO: Simplify this.
11538
    switch (state) {
11539
      case State::PROTOCOL: {
11540
        result.protocol = value;
11541
        break;
11542
      }
11543
      case State::USERNAME: {
11544
        result.username = value;
11545
        break;
11546
      }
11547
      case State::PASSWORD: {
11548
        result.password = value;
11549
        break;
11550
      }
11551
      case State::HOSTNAME: {
11552
        result.hostname = value;
11553
        break;
11554
      }
11555
      case State::PORT: {
11556
        result.port = value;
11557
        break;
11558
      }
11559
      case State::PATHNAME: {
11560
        result.pathname = value;
11561
        break;
11562
      }
11563
      case State::SEARCH: {
11564
        result.search = value;
11565
        break;
11566
      }
11567
      case State::HASH: {
11568
        result.hash = value;
11569
        break;
11570
      }
11571
      default:
11572
        ada::unreachable();
11573
    }
11574
  }
11575
11576
  // If parser's state is not "init" and new state is not "done", then:
11577
  if (state != State::INIT && new_state != State::DONE) {
11578
    // If parser's state is "protocol", "authority", "username", or "password";
11579
    // new state is "port", "pathname", "search", or "hash"; and parser's
11580
    // result["hostname"] does not exist, then set parser's result["hostname"]
11581
    // to the empty string.
11582
    if ((state == State::PROTOCOL || state == State::AUTHORITY ||
11583
         state == State::USERNAME || state == State::PASSWORD) &&
11584
        (new_state == State::PORT || new_state == State::PATHNAME ||
11585
         new_state == State::SEARCH || new_state == State::HASH) &&
11586
        !result.hostname)
11587
      result.hostname = "";
11588
  }
11589
11590
  // If parser's state is "protocol", "authority", "username", "password",
11591
  // "hostname", or "port"; new state is "search" or "hash"; and parser's
11592
  // result["pathname"] does not exist, then:
11593
  if ((state == State::PROTOCOL || state == State::AUTHORITY ||
11594
       state == State::USERNAME || state == State::PASSWORD ||
11595
       state == State::HOSTNAME || state == State::PORT) &&
11596
      (new_state == State::SEARCH || new_state == State::HASH) &&
11597
      !result.pathname) {
11598
    if (protocol_matches_a_special_scheme_flag) {
11599
      result.pathname = "/";
11600
    } else {
11601
      // Otherwise, set parser's result["pathname"] to the empty string.
11602
      result.pathname = "";
11603
    }
11604
  }
11605
11606
  // If parser's state is "protocol", "authority", "username", "password",
11607
  // "hostname", "port", or "pathname"; new state is "hash"; and parser's
11608
  // result["search"] does not exist, then set parser's result["search"] to
11609
  // the empty string.
11610
  if ((state == State::PROTOCOL || state == State::AUTHORITY ||
11611
       state == State::USERNAME || state == State::PASSWORD ||
11612
       state == State::HOSTNAME || state == State::PORT ||
11613
       state == State::PATHNAME) &&
11614
      new_state == State::HASH && !result.search) {
11615
    result.search = "";
11616
  }
11617
11618
  // Set parser's state to new state.
11619
  state = new_state;
11620
  // Increment parser's token index by skip.
11621
  token_index += skip;
11622
  // Set parser's component start to parser's token index.
11623
  component_start = token_index;
11624
  // Set parser's token increment to 0.
11625
  token_increment = 0;
11626
}
11627
11628
template <url_pattern_regex::regex_concept regex_provider>
11629
std::string constructor_string_parser<regex_provider>::make_component_string() {
11630
  // Assert: parser's token index is less than parser's token list's size.
11631
  ADA_ASSERT_TRUE(token_index < token_list.size());
11632
11633
  // Let token be parser's token list[parser's token index].
11634
  // Let end index be token's index.
11635
  const auto end_index = token_list[token_index].index;
11636
  // Let component start token be the result of running get a safe token given
11637
  // parser and parser's component start.
11638
  const auto component_start_token = get_safe_token(component_start);
11639
  ADA_ASSERT_TRUE(component_start_token);
11640
  // Let component start input index be component start token's index.
11641
  const auto component_start_input_index = component_start_token->index;
11642
  // Return the code point substring from component start input index to end
11643
  // index within parser's input.
11644
  return std::string(input.substr(component_start_input_index,
11645
                                  end_index - component_start_input_index));
11646
}
11647
11648
template <url_pattern_regex::regex_concept regex_provider>
11649
constexpr bool
11650
constructor_string_parser<regex_provider>::is_an_identity_terminator() const {
11651
  // Return the result of running is a non-special pattern char given parser,
11652
  // parser's token index, and "@".
11653
  return is_non_special_pattern_char(token_index, '@');
11654
}
11655
11656
template <url_pattern_regex::regex_concept regex_provider>
11657
constexpr bool constructor_string_parser<regex_provider>::is_pathname_start()
11658
    const {
11659
  // Return the result of running is a non-special pattern char given parser,
11660
  // parser's token index, and "/".
11661
  return is_non_special_pattern_char(token_index, '/');
11662
}
11663
11664
template <url_pattern_regex::regex_concept regex_provider>
11665
constexpr bool constructor_string_parser<regex_provider>::is_password_prefix()
11666
    const {
11667
  // Return the result of running is a non-special pattern char given parser,
11668
  // parser's token index, and ":".
11669
  return is_non_special_pattern_char(token_index, ':');
11670
}
11671
11672
template <url_pattern_regex::regex_concept regex_provider>
11673
constexpr bool constructor_string_parser<regex_provider>::is_an_ipv6_open()
11674
    const {
11675
  // Return the result of running is a non-special pattern char given parser,
11676
  // parser's token index, and "[".
11677
  return is_non_special_pattern_char(token_index, '[');
11678
}
11679
11680
template <url_pattern_regex::regex_concept regex_provider>
11681
constexpr bool constructor_string_parser<regex_provider>::is_an_ipv6_close()
11682
    const {
11683
  // Return the result of running is a non-special pattern char given parser,
11684
  // parser's token index, and "]".
11685
  return is_non_special_pattern_char(token_index, ']');
11686
}
11687
11688
template <url_pattern_regex::regex_concept regex_provider>
11689
constexpr bool constructor_string_parser<regex_provider>::is_port_prefix()
11690
    const {
11691
  // Return the result of running is a non-special pattern char given parser,
11692
  // parser's token index, and ":".
11693
  return is_non_special_pattern_char(token_index, ':');
11694
}
11695
11696
0
constexpr void Tokenizer::get_next_code_point() {
11697
0
  ada_log("Tokenizer::get_next_code_point called with index=", next_index);
11698
0
  ADA_ASSERT_TRUE(next_index < input.size());
11699
  // Decode the next UTF-8 code point. If malformed or truncated, mark it as
11700
  // invalid, return the offending byte as the code point, and advance by one
11701
  // to guarantee forward progress.
11702
0
  invalid_code_point = false;
11703
0
  code_point = 0;
11704
0
  size_t number_bytes = 0;
11705
0
  const size_t initial_index = next_index;
11706
0
  unsigned char first_byte = input[next_index];
11707
11708
0
  if ((first_byte & 0x80) == 0) {
11709
    // 1-byte character (ASCII)
11710
0
    next_index++;
11711
0
    code_point = first_byte;
11712
0
    ada_log("Tokenizer::get_next_code_point returning ASCII code point=",
11713
0
            uint32_t(code_point));
11714
0
    ada_log("Tokenizer::get_next_code_point next_index =", next_index,
11715
0
            " input.size()=", input.size());
11716
0
    return;
11717
0
  }
11718
0
  ada_log("Tokenizer::get_next_code_point read first byte=",
11719
0
          uint32_t(first_byte));
11720
0
  if ((first_byte & 0xE0) == 0xC0) {
11721
0
    code_point = first_byte & 0x1F;
11722
0
    number_bytes = 2;
11723
0
    ada_log("Tokenizer::get_next_code_point two bytes");
11724
0
  } else if ((first_byte & 0xF0) == 0xE0) {
11725
0
    code_point = first_byte & 0x0F;
11726
0
    number_bytes = 3;
11727
0
    ada_log("Tokenizer::get_next_code_point three bytes");
11728
0
  } else if ((first_byte & 0xF8) == 0xF0) {
11729
0
    code_point = first_byte & 0x07;
11730
0
    number_bytes = 4;
11731
0
    ada_log("Tokenizer::get_next_code_point four bytes");
11732
0
  }
11733
11734
  // Invalid leading bytes that still match a multi-byte prefix.
11735
0
  if ((number_bytes == 2 && first_byte < 0xC2) ||
11736
0
      (number_bytes == 4 && first_byte > 0xF4)) {
11737
0
    invalid_code_point = true;
11738
0
    code_point = first_byte;
11739
0
    next_index = initial_index + 1;
11740
0
    return;
11741
0
  }
11742
11743
  // Invalid leading byte (e.g., continuation byte outside a sequence).
11744
0
  if (number_bytes == 0) {
11745
0
    invalid_code_point = true;
11746
0
    code_point = first_byte;
11747
0
    next_index = initial_index + 1;
11748
0
    return;
11749
0
  }
11750
11751
  // Truncated UTF-8 sequence.
11752
0
  if (number_bytes + next_index > input.size()) {
11753
0
    invalid_code_point = true;
11754
0
    code_point = first_byte;
11755
0
    next_index = initial_index + 1;
11756
0
    return;
11757
0
  }
11758
11759
0
  for (size_t i = 1 + next_index; i < number_bytes + next_index; ++i) {
11760
0
    unsigned char byte = input[i];
11761
0
    if ((byte & 0xC0) != 0x80) {
11762
0
      invalid_code_point = true;
11763
0
      code_point = first_byte;
11764
0
      next_index = initial_index + 1;
11765
0
      return;
11766
0
    }
11767
0
    ada_log("Tokenizer::get_next_code_point read byte=", uint32_t(byte));
11768
0
    code_point = (code_point << 6) | (byte & 0x3F);
11769
0
  }
11770
0
  ada_log("Tokenizer::get_next_code_point returning non-ASCII code point=",
11771
0
          uint32_t(code_point));
11772
0
  ada_log("Tokenizer::get_next_code_point next_index =", next_index,
11773
0
          " input.size()=", input.size());
11774
0
  next_index += number_bytes;
11775
0
}
11776
11777
0
constexpr void Tokenizer::seek_and_get_next_code_point(size_t new_index) {
11778
0
  ada_log("Tokenizer::seek_and_get_next_code_point called with new_index=",
11779
0
          new_index);
11780
  // Set tokenizer's next index to index.
11781
0
  next_index = new_index;
11782
  // Run get the next code point given tokenizer.
11783
0
  get_next_code_point();
11784
0
}
11785
11786
inline void Tokenizer::add_token(token_type type, size_t next_position,
11787
0
                                 size_t value_position, size_t value_length) {
11788
0
  ada_log("Tokenizer::add_token called with type=", to_string(type),
11789
0
          " next_position=", next_position, " value_position=", value_position);
11790
0
  ADA_ASSERT_TRUE(next_position >= value_position);
11791
11792
  // Let token be a new token.
11793
  // Set token's type to type.
11794
  // Set token's index to tokenizer's index.
11795
  // Set token's value to the code point substring from value position with
11796
  // length value length within tokenizer's input.
11797
  // Append token to the back of tokenizer's token list.
11798
0
  token_list.emplace_back(type, index,
11799
0
                          input.substr(value_position, value_length));
11800
  // Set tokenizer's index to next position.
11801
0
  index = next_position;
11802
0
}
11803
11804
inline void Tokenizer::add_token_with_default_length(token_type type,
11805
                                                     size_t next_position,
11806
0
                                                     size_t value_position) {
11807
  // Let computed length be next position - value position.
11808
0
  auto computed_length = next_position - value_position;
11809
  // Run add a token given tokenizer, type, next position, value position, and
11810
  // computed length.
11811
0
  add_token(type, next_position, value_position, computed_length);
11812
0
}
11813
11814
0
inline void Tokenizer::add_token_with_defaults(token_type type) {
11815
0
  ada_log("Tokenizer::add_token_with_defaults called with type=",
11816
0
          to_string(type));
11817
  // Run add a token with default length given tokenizer, type, tokenizer's next
11818
  // index, and tokenizer's index.
11819
0
  add_token_with_default_length(type, next_index, index);
11820
0
}
11821
11822
inline ada_warn_unused std::optional<errors>
11823
Tokenizer::process_tokenizing_error(size_t next_position,
11824
0
                                    size_t value_position) {
11825
  // If tokenizer's policy is "strict", then throw a TypeError.
11826
0
  if (policy == token_policy::strict) {
11827
0
    ada_log("process_tokenizing_error failed with next_position=",
11828
0
            next_position, " value_position=", value_position);
11829
0
    return errors::type_error;
11830
0
  }
11831
  // Assert: tokenizer's policy is "lenient".
11832
0
  ADA_ASSERT_TRUE(policy == token_policy::lenient);
11833
  // Run add a token with default length given tokenizer, "invalid-char", next
11834
  // position, and value position.
11835
0
  add_token_with_default_length(token_type::INVALID_CHAR, next_position,
11836
0
                                value_position);
11837
0
  return std::nullopt;
11838
0
}
11839
11840
template <url_pattern_encoding_callback F>
11841
0
token* url_pattern_parser<F>::try_consume_modifier_token() {
11842
  // Let token be the result of running try to consume a token given parser and
11843
  // "other-modifier".
11844
0
  auto token = try_consume_token(token_type::OTHER_MODIFIER);
11845
  // If token is not null, then return token.
11846
0
  if (token) return token;
11847
  // Set token to the result of running try to consume a token given parser and
11848
  // "asterisk".
11849
  // Return token.
11850
0
  return try_consume_token(token_type::ASTERISK);
11851
0
}
11852
11853
template <url_pattern_encoding_callback F>
11854
token* url_pattern_parser<F>::try_consume_regexp_or_wildcard_token(
11855
0
    const token* name_token) {
11856
  // Let token be the result of running try to consume a token given parser and
11857
  // "regexp".
11858
0
  auto token = try_consume_token(token_type::REGEXP);
11859
  // If name token is null and token is null, then set token to the result of
11860
  // running try to consume a token given parser and "asterisk".
11861
0
  if (!name_token && !token) {
11862
0
    token = try_consume_token(token_type::ASTERISK);
11863
0
  }
11864
  // Return token.
11865
0
  return token;
11866
0
}
11867
11868
template <url_pattern_encoding_callback F>
11869
0
token* url_pattern_parser<F>::try_consume_token(token_type type) {
11870
0
  ada_log("url_pattern_parser::try_consume_token called with type=",
11871
0
          to_string(type));
11872
  // Assert: parser's index is less than parser's token list size.
11873
0
  ADA_ASSERT_TRUE(index < tokens.size());
11874
  // Let next token be parser's token list[parser's index].
11875
0
  auto& next_token = tokens[index];
11876
  // If next token's type is not type return null.
11877
0
  if (next_token.type != type) return nullptr;
11878
  // Increase parser's index by 1.
11879
0
  index++;
11880
  // Return next token.
11881
0
  return &next_token;
11882
0
}
11883
11884
template <url_pattern_encoding_callback F>
11885
0
std::string url_pattern_parser<F>::consume_text() {
11886
  // Let result be the empty string.
11887
0
  std::string result{};
11888
  // While true:
11889
0
  while (true) {
11890
    // Let token be the result of running try to consume a token given parser
11891
    // and "char".
11892
0
    auto token = try_consume_token(token_type::CHAR);
11893
    // If token is null, then set token to the result of running try to consume
11894
    // a token given parser and "escaped-char".
11895
0
    if (!token) token = try_consume_token(token_type::ESCAPED_CHAR);
11896
    // If token is null, then break.
11897
0
    if (!token) break;
11898
    // Append token's value to the end of result.
11899
0
    result.append(token->value);
11900
0
  }
11901
  // Return result.
11902
0
  return result;
11903
0
}
11904
11905
template <url_pattern_encoding_callback F>
11906
0
bool url_pattern_parser<F>::consume_required_token(token_type type) {
11907
0
  ada_log("url_pattern_parser::consume_required_token called with type=",
11908
0
          to_string(type));
11909
  // Let result be the result of running try to consume a token given parser and
11910
  // type.
11911
0
  return try_consume_token(type) != nullptr;
11912
0
}
11913
11914
template <url_pattern_encoding_callback F>
11915
std::optional<errors>
11916
0
url_pattern_parser<F>::maybe_add_part_from_the_pending_fixed_value() {
11917
  // If parser's pending fixed value is the empty string, then return.
11918
0
  if (pending_fixed_value.empty()) {
11919
0
    ada_log("pending_fixed_value is empty");
11920
0
    return std::nullopt;
11921
0
  }
11922
  // Let encoded value be the result of running parser's encoding callback given
11923
  // parser's pending fixed value.
11924
0
  auto encoded_value = encoding_callback(pending_fixed_value);
11925
0
  if (!encoded_value) {
11926
0
    ada_log("failed to encode pending_fixed_value: ", pending_fixed_value);
11927
0
    return encoded_value.error();
11928
0
  }
11929
  // Set parser's pending fixed value to the empty string.
11930
0
  pending_fixed_value.clear();
11931
  // Let part be a new part whose type is "fixed-text", value is encoded value,
11932
  // and modifier is "none".
11933
  // Append part to parser's part list.
11934
0
  parts.emplace_back(url_pattern_part_type::FIXED_TEXT,
11935
0
                     std::move(*encoded_value),
11936
0
                     url_pattern_part_modifier::none);
11937
0
  return std::nullopt;
11938
0
}
11939
11940
template <url_pattern_encoding_callback F>
11941
std::optional<errors> url_pattern_parser<F>::add_part(
11942
    std::string_view prefix, token* name_token, token* regexp_or_wildcard_token,
11943
0
    std::string_view suffix, token* modifier_token) {
11944
  // Let modifier be "none".
11945
0
  auto modifier = url_pattern_part_modifier::none;
11946
  // If modifier token is not null:
11947
0
  if (modifier_token) {
11948
    // If modifier token's value is "?" then set modifier to "optional".
11949
0
    if (modifier_token->value == "?") {
11950
0
      modifier = url_pattern_part_modifier::optional;
11951
0
    } else if (modifier_token->value == "*") {
11952
      // Otherwise if modifier token's value is "*" then set modifier to
11953
      // "zero-or-more".
11954
0
      modifier = url_pattern_part_modifier::zero_or_more;
11955
0
    } else if (modifier_token->value == "+") {
11956
      // Otherwise if modifier token's value is "+" then set modifier to
11957
      // "one-or-more".
11958
0
      modifier = url_pattern_part_modifier::one_or_more;
11959
0
    }
11960
0
  }
11961
  // If name token is null and regexp or wildcard token is null and modifier
11962
  // is "none":
11963
0
  if (!name_token && !regexp_or_wildcard_token &&
11964
0
      modifier == url_pattern_part_modifier::none) {
11965
    // Append prefix to the end of parser's pending fixed value.
11966
0
    pending_fixed_value.append(prefix);
11967
0
    return std::nullopt;
11968
0
  }
11969
  // Run maybe add a part from the pending fixed value given parser.
11970
0
  if (auto error = maybe_add_part_from_the_pending_fixed_value()) {
11971
0
    return *error;
11972
0
  }
11973
  // If name token is null and regexp or wildcard token is null:
11974
0
  if (!name_token && !regexp_or_wildcard_token) {
11975
    // Assert: suffix is the empty string.
11976
0
    ADA_ASSERT_TRUE(suffix.empty());
11977
    // If prefix is the empty string, then return.
11978
0
    if (prefix.empty()) return std::nullopt;
11979
    // Let encoded value be the result of running parser's encoding callback
11980
    // given prefix.
11981
0
    auto encoded_value = encoding_callback(prefix);
11982
0
    if (!encoded_value) {
11983
0
      return encoded_value.error();
11984
0
    }
11985
    // Let part be a new part whose type is "fixed-text", value is encoded
11986
    // value, and modifier is modifier.
11987
    // Append part to parser's part list.
11988
0
    parts.emplace_back(url_pattern_part_type::FIXED_TEXT,
11989
0
                       std::move(*encoded_value), modifier);
11990
0
    return std::nullopt;
11991
0
  }
11992
  // Let regexp value be the empty string.
11993
0
  std::string regexp_value{};
11994
  // If regexp or wildcard token is null, then set regexp value to parser's
11995
  // segment wildcard regexp.
11996
0
  if (!regexp_or_wildcard_token) {
11997
0
    regexp_value = segment_wildcard_regexp;
11998
0
  } else if (regexp_or_wildcard_token->type == token_type::ASTERISK) {
11999
    // Otherwise if regexp or wildcard token's type is "asterisk", then set
12000
    // regexp value to the full wildcard regexp value.
12001
0
    regexp_value = ".*";
12002
0
  } else {
12003
    // Otherwise set regexp value to regexp or wildcard token's value.
12004
0
    regexp_value = regexp_or_wildcard_token->value;
12005
0
  }
12006
  // Let type be "regexp".
12007
0
  auto type = url_pattern_part_type::REGEXP;
12008
  // If regexp value is parser's segment wildcard regexp:
12009
0
  if (regexp_value == segment_wildcard_regexp) {
12010
    // Set type to "segment-wildcard".
12011
0
    type = url_pattern_part_type::SEGMENT_WILDCARD;
12012
    // Set regexp value to the empty string.
12013
0
    regexp_value.clear();
12014
0
  } else if (regexp_value == ".*") {
12015
    // Otherwise if regexp value is the full wildcard regexp value:
12016
    // Set type to "full-wildcard".
12017
0
    type = url_pattern_part_type::FULL_WILDCARD;
12018
    // Set regexp value to the empty string.
12019
0
    regexp_value.clear();
12020
0
  }
12021
  // Let name be the empty string.
12022
0
  std::string name{};
12023
  // If name token is not null, then set name to name token's value.
12024
0
  if (name_token) {
12025
0
    name = name_token->value;
12026
0
  } else if (regexp_or_wildcard_token != nullptr) {
12027
    // Otherwise if regexp or wildcard token is not null:
12028
    // Set name to parser's next numeric name, serialized.
12029
0
    name = std::to_string(next_numeric_name);
12030
    // Increment parser's next numeric name by 1.
12031
0
    next_numeric_name++;
12032
0
  }
12033
  // If the result of running is a duplicate name given parser and name is
12034
  // true, then throw a TypeError. Tracked in a set so this stays O(1): a
12035
  // linear scan of the part list here is O(n^2) over a pattern string with n
12036
  // named parts (e.g. "/*" repeated), an algorithmic-complexity DoS.
12037
0
  if (!name.empty() && !seen_names.insert(name).second) {
12038
0
    return errors::type_error;
12039
0
  }
12040
  // Let encoded prefix be the result of running parser's encoding callback
12041
  // given prefix.
12042
0
  auto encoded_prefix = encoding_callback(prefix);
12043
0
  if (!encoded_prefix) return encoded_prefix.error();
12044
  // Let encoded suffix be the result of running parser's encoding callback
12045
  // given suffix.
12046
0
  auto encoded_suffix = encoding_callback(suffix);
12047
0
  if (!encoded_suffix) return encoded_suffix.error();
12048
  // Let part be a new part whose type is type, value is regexp value,
12049
  // modifier is modifier, name is name, prefix is encoded prefix, and suffix
12050
  // is encoded suffix.
12051
  // Append part to parser's part list.
12052
0
  parts.emplace_back(type, std::move(regexp_value), modifier, std::move(name),
12053
0
                     std::move(*encoded_prefix), std::move(*encoded_suffix));
12054
0
  return std::nullopt;
12055
0
}
12056
12057
template <url_pattern_encoding_callback F>
12058
tl::expected<std::vector<url_pattern_part>, errors> parse_pattern_string(
12059
    std::string_view input, url_pattern_compile_component_options& options,
12060
0
    F& encoding_callback) {
12061
0
  ada_log("parse_pattern_string input=", input);
12062
  // Let parser be a new pattern parser whose encoding callback is encoding
12063
  // callback and segment wildcard regexp is the result of running generate a
12064
  // segment wildcard regexp given options.
12065
0
  auto parser = url_pattern_parser<F>(
12066
0
      encoding_callback, generate_segment_wildcard_regexp(options));
12067
  // Set parser's token list to the result of running tokenize given input and
12068
  // "strict".
12069
0
  auto tokenize_result = tokenize(input, token_policy::strict);
12070
0
  if (!tokenize_result) {
12071
0
    ada_log("parse_pattern_string tokenize failed");
12072
0
    return tl::unexpected(tokenize_result.error());
12073
0
  }
12074
0
  parser.tokens = std::move(*tokenize_result);
12075
12076
  // While parser's index is less than parser's token list's size:
12077
0
  while (parser.can_continue()) {
12078
    // Let char token be the result of running try to consume a token given
12079
    // parser and "char".
12080
0
    auto char_token = parser.try_consume_token(token_type::CHAR);
12081
    // Let name token be the result of running try to consume a token given
12082
    // parser and "name".
12083
0
    auto name_token = parser.try_consume_token(token_type::NAME);
12084
    // Let regexp or wildcard token be the result of running try to consume a
12085
    // regexp or wildcard token given parser and name token.
12086
0
    auto regexp_or_wildcard_token =
12087
0
        parser.try_consume_regexp_or_wildcard_token(name_token);
12088
    // If name token is not null or regexp or wildcard token is not null:
12089
0
    if (name_token || regexp_or_wildcard_token) {
12090
      // Let prefix be the empty string.
12091
0
      std::string prefix{};
12092
      // If char token is not null then set prefix to char token's value.
12093
0
      if (char_token) prefix = char_token->value;
12094
      // If prefix is not the empty string and not options's prefix code point:
12095
0
      if (!prefix.empty() && prefix != options.get_prefix()) {
12096
        // Append prefix to the end of parser's pending fixed value.
12097
0
        parser.pending_fixed_value.append(prefix);
12098
        // Set prefix to the empty string.
12099
0
        prefix.clear();
12100
0
      }
12101
      // Run maybe add a part from the pending fixed value given parser.
12102
0
      if (auto error = parser.maybe_add_part_from_the_pending_fixed_value()) {
12103
0
        ada_log("maybe_add_part_from_the_pending_fixed_value failed");
12104
0
        return tl::unexpected(*error);
12105
0
      }
12106
      // Let modifier token be the result of running try to consume a modifier
12107
      // token given parser.
12108
0
      auto modifier_token = parser.try_consume_modifier_token();
12109
      // Run add a part given parser, prefix, name token, regexp or wildcard
12110
      // token, the empty string, and modifier token.
12111
0
      if (auto error =
12112
0
              parser.add_part(prefix, name_token, regexp_or_wildcard_token, "",
12113
0
                              modifier_token)) {
12114
0
        ada_log("parser.add_part failed");
12115
0
        return tl::unexpected(*error);
12116
0
      }
12117
      // Continue.
12118
0
      continue;
12119
0
    }
12120
12121
    // Let fixed token be char token.
12122
0
    auto fixed_token = char_token;
12123
    // If fixed token is null, then set fixed token to the result of running try
12124
    // to consume a token given parser and "escaped-char".
12125
0
    if (!fixed_token)
12126
0
      fixed_token = parser.try_consume_token(token_type::ESCAPED_CHAR);
12127
    // If fixed token is not null:
12128
0
    if (fixed_token) {
12129
      // Append fixed token's value to parser's pending fixed value.
12130
0
      parser.pending_fixed_value.append(fixed_token->value);
12131
      // Continue.
12132
0
      continue;
12133
0
    }
12134
    // Let open token be the result of running try to consume a token given
12135
    // parser and "open".
12136
0
    auto open_token = parser.try_consume_token(token_type::OPEN);
12137
    // If open token is not null:
12138
0
    if (open_token) {
12139
      // Set prefix be the result of running consume text given parser.
12140
0
      auto prefix_ = parser.consume_text();
12141
      // Set name token to the result of running try to consume a token given
12142
      // parser and "name".
12143
0
      name_token = parser.try_consume_token(token_type::NAME);
12144
      // Set regexp or wildcard token to the result of running try to consume a
12145
      // regexp or wildcard token given parser and name token.
12146
0
      regexp_or_wildcard_token =
12147
0
          parser.try_consume_regexp_or_wildcard_token(name_token);
12148
      // Let suffix be the result of running consume text given parser.
12149
0
      auto suffix_ = parser.consume_text();
12150
      // Run consume a required token given parser and "close".
12151
0
      if (!parser.consume_required_token(token_type::CLOSE)) {
12152
0
        ada_log("parser.consume_required_token failed");
12153
0
        return tl::unexpected(errors::type_error);
12154
0
      }
12155
      // Set modifier token to the result of running try to consume a modifier
12156
      // token given parser.
12157
0
      auto modifier_token = parser.try_consume_modifier_token();
12158
      // Run add a part given parser, prefix, name token, regexp or wildcard
12159
      // token, suffix, and modifier token.
12160
0
      if (auto error =
12161
0
              parser.add_part(prefix_, name_token, regexp_or_wildcard_token,
12162
0
                              suffix_, modifier_token)) {
12163
0
        return tl::unexpected(*error);
12164
0
      }
12165
      // Continue.
12166
0
      continue;
12167
0
    }
12168
    // Run maybe add a part from the pending fixed value given parser.
12169
0
    if (auto error = parser.maybe_add_part_from_the_pending_fixed_value()) {
12170
0
      ada_log("maybe_add_part_from_the_pending_fixed_value failed on line 992");
12171
0
      return tl::unexpected(*error);
12172
0
    }
12173
    // Run consume a required token given parser and "end".
12174
0
    if (!parser.consume_required_token(token_type::END)) {
12175
0
      return tl::unexpected(errors::type_error);
12176
0
    }
12177
0
  }
12178
0
  ada_log("parser.parts size is: ", parser.parts.size());
12179
  // Return parser's part list.
12180
0
  return parser.parts;
12181
0
}
12182
12183
template <url_pattern_regex::regex_concept regex_provider>
12184
bool protocol_component_matches_special_scheme(
12185
    url_pattern_component<regex_provider>& component) {
12186
  // Optimization: Use fast_test for simple patterns to avoid regex overhead
12187
  switch (component.type) {
12188
    case url_pattern_component_type::EMPTY:
12189
      // Empty pattern can't match any special scheme
12190
      return false;
12191
    case url_pattern_component_type::EXACT_MATCH:
12192
      // Direct string comparison for exact match patterns
12193
      return component.exact_match_value == "http" ||
12194
             component.exact_match_value == "https" ||
12195
             component.exact_match_value == "ws" ||
12196
             component.exact_match_value == "wss" ||
12197
             component.exact_match_value == "ftp" ||
12198
             component.exact_match_value == "file";
12199
    case url_pattern_component_type::FULL_WILDCARD:
12200
      // Full wildcard matches everything including special schemes
12201
      return true;
12202
    case url_pattern_component_type::REGEXP:
12203
      // Fall back to regex matching for complex patterns
12204
      auto& regex = component.regexp;
12205
      return regex_provider::regex_match("http", regex) ||
12206
             regex_provider::regex_match("https", regex) ||
12207
             regex_provider::regex_match("ws", regex) ||
12208
             regex_provider::regex_match("wss", regex) ||
12209
             regex_provider::regex_match("ftp", regex) ||
12210
             regex_provider::regex_match("file", regex);
12211
  }
12212
  ada::unreachable();
12213
}
12214
12215
template <url_pattern_regex::regex_concept regex_provider>
12216
inline std::optional<errors> constructor_string_parser<
12217
    regex_provider>::compute_protocol_matches_special_scheme_flag() {
12218
  ada_log(
12219
      "constructor_string_parser::compute_protocol_matches_special_scheme_"
12220
      "flag");
12221
  // Let protocol string be the result of running make a component string given
12222
  // parser.
12223
  auto protocol_string = make_component_string();
12224
  // Let protocol component be the result of compiling a component given
12225
  // protocol string, canonicalize a protocol, and default options.
12226
  auto protocol_component = url_pattern_component<regex_provider>::compile(
12227
      protocol_string, canonicalize_protocol,
12228
      url_pattern_compile_component_options::DEFAULT);
12229
  if (!protocol_component) {
12230
    ada_log("url_pattern_component::compile failed for protocol_string ",
12231
            protocol_string);
12232
    return protocol_component.error();
12233
  }
12234
  // If the result of running protocol component matches a special scheme given
12235
  // protocol component is true, then set parser's protocol matches a special
12236
  // scheme flag to true.
12237
  if (protocol_component_matches_special_scheme(*protocol_component)) {
12238
    protocol_matches_a_special_scheme_flag = true;
12239
  }
12240
  return std::nullopt;
12241
}
12242
12243
template <url_pattern_regex::regex_concept regex_provider>
12244
tl::expected<url_pattern_init, errors>
12245
constructor_string_parser<regex_provider>::parse(std::string_view input) {
12246
  ada_log("constructor_string_parser::parse input=", input);
12247
  // Let parser be a new constructor string parser whose input is input and
12248
  // token list is the result of running tokenize given input and "lenient".
12249
  auto token_list = tokenize(input, token_policy::lenient);
12250
  if (!token_list) {
12251
    return tl::unexpected(token_list.error());
12252
  }
12253
  auto parser = constructor_string_parser(input, std::move(*token_list));
12254
12255
  // While parser's token index is less than parser's token list size:
12256
  while (parser.token_index < parser.token_list.size()) {
12257
    // Set parser's token increment to 1.
12258
    parser.token_increment = 1;
12259
12260
    // If parser's token list[parser's token index]'s type is "end" then:
12261
    if (parser.token_list[parser.token_index].type == token_type::END) {
12262
      // If parser's state is "init":
12263
      if (parser.state == State::INIT) {
12264
        // Run rewind given parser.
12265
        parser.rewind();
12266
        // If the result of running is a hash prefix given parser is true, then
12267
        // run change state given parser, "hash" and 1.
12268
        if (parser.is_hash_prefix()) {
12269
          parser.change_state(State::HASH, 1);
12270
        } else if (parser.is_search_prefix()) {
12271
          // Otherwise if the result of running is a search prefix given parser
12272
          // is true: Run change state given parser, "search" and 1.
12273
          parser.change_state(State::SEARCH, 1);
12274
        } else {
12275
          // Run change state given parser, "pathname" and 0.
12276
          parser.change_state(State::PATHNAME, 0);
12277
        }
12278
        // Increment parser's token index by parser's token increment.
12279
        parser.token_index += parser.token_increment;
12280
        // Continue.
12281
        continue;
12282
      }
12283
12284
      if (parser.state == State::AUTHORITY) {
12285
        // If parser's state is "authority":
12286
        // Run rewind and set state given parser, and "hostname".
12287
        parser.rewind();
12288
        parser.change_state(State::HOSTNAME, 0);
12289
        // Increment parser's token index by parser's token increment.
12290
        parser.token_index += parser.token_increment;
12291
        // Continue.
12292
        continue;
12293
      }
12294
12295
      // Run change state given parser, "done" and 0.
12296
      parser.change_state(State::DONE, 0);
12297
      // Break.
12298
      break;
12299
    }
12300
12301
    // If the result of running is a group open given parser is true:
12302
    if (parser.is_group_open()) {
12303
      // Increment parser's group depth by 1.
12304
      parser.group_depth += 1;
12305
      // Increment parser's token index by parser's token increment.
12306
      parser.token_index += parser.token_increment;
12307
      // Continue.
12308
      continue;
12309
    }
12310
12311
    // If parser's group depth is greater than 0:
12312
    if (parser.group_depth > 0) {
12313
      // If the result of running is a group close given parser is true, then
12314
      // decrement parser's group depth by 1.
12315
      if (parser.is_group_close()) {
12316
        parser.group_depth -= 1;
12317
      } else {
12318
        // Increment parser's token index by parser's token increment.
12319
        parser.token_index += parser.token_increment;
12320
        continue;
12321
      }
12322
    }
12323
12324
    // Switch on parser's state and run the associated steps:
12325
    switch (parser.state) {
12326
      case State::INIT: {
12327
        // If the result of running is a protocol suffix given parser is true:
12328
        if (parser.is_protocol_suffix()) {
12329
          // Run rewind and set state given parser and "protocol".
12330
          parser.rewind();
12331
          parser.change_state(State::PROTOCOL, 0);
12332
        }
12333
        break;
12334
      }
12335
      case State::PROTOCOL: {
12336
        // If the result of running is a protocol suffix given parser is true:
12337
        if (parser.is_protocol_suffix()) {
12338
          // Run compute protocol matches a special scheme flag given parser.
12339
          if (const auto error =
12340
                  parser.compute_protocol_matches_special_scheme_flag()) {
12341
            ada_log("compute_protocol_matches_special_scheme_flag failed");
12342
            return tl::unexpected(*error);
12343
          }
12344
          // Let next state be "pathname".
12345
          auto next_state = State::PATHNAME;
12346
          // Let skip be 1.
12347
          auto skip = 1;
12348
          // If the result of running next is authority slashes given parser is
12349
          // true:
12350
          if (parser.next_is_authority_slashes()) {
12351
            // Set next state to "authority".
12352
            next_state = State::AUTHORITY;
12353
            // Set skip to 3.
12354
            skip = 3;
12355
          } else if (parser.protocol_matches_a_special_scheme_flag) {
12356
            // Otherwise if parser's protocol matches a special scheme flag is
12357
            // true, then set next state to "authority".
12358
            next_state = State::AUTHORITY;
12359
          }
12360
12361
          // Run change state given parser, next state, and skip.
12362
          parser.change_state(next_state, skip);
12363
        }
12364
        break;
12365
      }
12366
      case State::AUTHORITY: {
12367
        // If the result of running is an identity terminator given parser is
12368
        // true, then run rewind and set state given parser and "username".
12369
        if (parser.is_an_identity_terminator()) {
12370
          parser.rewind();
12371
          parser.change_state(State::USERNAME, 0);
12372
        } else if (parser.is_pathname_start() || parser.is_search_prefix() ||
12373
                   parser.is_hash_prefix()) {
12374
          // Otherwise if any of the following are true:
12375
          // - the result of running is a pathname start given parser;
12376
          // - the result of running is a search prefix given parser; or
12377
          // - the result of running is a hash prefix given parser,
12378
          // then run rewind and set state given parser and "hostname".
12379
          parser.rewind();
12380
          parser.change_state(State::HOSTNAME, 0);
12381
        }
12382
        break;
12383
      }
12384
      case State::USERNAME: {
12385
        // If the result of running is a password prefix given parser is true,
12386
        // then run change state given parser, "password", and 1.
12387
        if (parser.is_password_prefix()) {
12388
          parser.change_state(State::PASSWORD, 1);
12389
        } else if (parser.is_an_identity_terminator()) {
12390
          // Otherwise if the result of running is an identity terminator given
12391
          // parser is true, then run change state given parser, "hostname",
12392
          // and 1.
12393
          parser.change_state(State::HOSTNAME, 1);
12394
        }
12395
        break;
12396
      }
12397
      case State::PASSWORD: {
12398
        // If the result of running is an identity terminator given parser is
12399
        // true, then run change state given parser, "hostname", and 1.
12400
        if (parser.is_an_identity_terminator()) {
12401
          parser.change_state(State::HOSTNAME, 1);
12402
        }
12403
        break;
12404
      }
12405
      case State::HOSTNAME: {
12406
        // If the result of running is an IPv6 open given parser is true, then
12407
        // increment parser's hostname IPv6 bracket depth by 1.
12408
        if (parser.is_an_ipv6_open()) {
12409
          parser.hostname_ipv6_bracket_depth += 1;
12410
        } else if (parser.is_an_ipv6_close()) {
12411
          // Otherwise if the result of running is an IPv6 close given parser is
12412
          // true, then decrement parser's hostname IPv6 bracket depth by 1.
12413
          parser.hostname_ipv6_bracket_depth -= 1;
12414
        } else if (parser.is_port_prefix() &&
12415
                   parser.hostname_ipv6_bracket_depth == 0) {
12416
          // Otherwise if the result of running is a port prefix given parser is
12417
          // true and parser's hostname IPv6 bracket depth is zero, then run
12418
          // change state given parser, "port", and 1.
12419
          parser.change_state(State::PORT, 1);
12420
        } else if (parser.is_pathname_start()) {
12421
          // Otherwise if the result of running is a pathname start given parser
12422
          // is true, then run change state given parser, "pathname", and 0.
12423
          parser.change_state(State::PATHNAME, 0);
12424
        } else if (parser.is_search_prefix()) {
12425
          // Otherwise if the result of running is a search prefix given parser
12426
          // is true, then run change state given parser, "search", and 1.
12427
          parser.change_state(State::SEARCH, 1);
12428
        } else if (parser.is_hash_prefix()) {
12429
          // Otherwise if the result of running is a hash prefix given parser is
12430
          // true, then run change state given parser, "hash", and 1.
12431
          parser.change_state(State::HASH, 1);
12432
        }
12433
12434
        break;
12435
      }
12436
      case State::PORT: {
12437
        // If the result of running is a pathname start given parser is true,
12438
        // then run change state given parser, "pathname", and 0.
12439
        if (parser.is_pathname_start()) {
12440
          parser.change_state(State::PATHNAME, 0);
12441
        } else if (parser.is_search_prefix()) {
12442
          // Otherwise if the result of running is a search prefix given parser
12443
          // is true, then run change state given parser, "search", and 1.
12444
          parser.change_state(State::SEARCH, 1);
12445
        } else if (parser.is_hash_prefix()) {
12446
          // Otherwise if the result of running is a hash prefix given parser is
12447
          // true, then run change state given parser, "hash", and 1.
12448
          parser.change_state(State::HASH, 1);
12449
        }
12450
        break;
12451
      }
12452
      case State::PATHNAME: {
12453
        // If the result of running is a search prefix given parser is true,
12454
        // then run change state given parser, "search", and 1.
12455
        if (parser.is_search_prefix()) {
12456
          parser.change_state(State::SEARCH, 1);
12457
        } else if (parser.is_hash_prefix()) {
12458
          // Otherwise if the result of running is a hash prefix given parser is
12459
          // true, then run change state given parser, "hash", and 1.
12460
          parser.change_state(State::HASH, 1);
12461
        }
12462
        break;
12463
      }
12464
      case State::SEARCH: {
12465
        // If the result of running is a hash prefix given parser is true, then
12466
        // run change state given parser, "hash", and 1.
12467
        if (parser.is_hash_prefix()) {
12468
          parser.change_state(State::HASH, 1);
12469
        }
12470
        break;
12471
      }
12472
      case State::HASH: {
12473
        // Do nothing
12474
        break;
12475
      }
12476
      default: {
12477
        // Assert: This step is never reached.
12478
        unreachable();
12479
      }
12480
    }
12481
12482
    // Increment parser's token index by parser's token increment.
12483
    parser.token_index += parser.token_increment;
12484
  }
12485
12486
  // If parser's result contains "hostname" and not "port", then set parser's
12487
  // result["port"] to the empty string.
12488
  if (parser.result.hostname && !parser.result.port) {
12489
    parser.result.port = "";
12490
  }
12491
12492
  // Return parser's result.
12493
  return parser.result;
12494
}
12495
12496
}  // namespace ada::url_pattern_helpers
12497
#endif  // ADA_INCLUDE_URL_PATTERN
12498
#endif
12499
/* end file include/ada/url_pattern_helpers-inl.h */
12500
/* begin file include/ada/url_pattern_list.h */
12501
/**
12502
 * @file url_pattern_list.h
12503
 * @brief Compiled set-level matching over URLPattern pathname patterns.
12504
 *
12505
 * `ada::url_pattern_list` answers the question "which of my N routes matches
12506
 * this pathname, and what are the parameter values?" in a single walk
12507
 * instead of a loop of N `url_pattern::exec` calls. The whole route set is
12508
 * compiled once, by ada::parse_url_pattern_list, into a segment trie with
12509
 * per-node dispatch (direct compares for small fanouts, a first-byte index
12510
 * at the root, perfect-hash projection for wide nodes). Matching a pathname
12511
 * against the compiled set is allocation-free and does not execute any
12512
 * regular expression for routes written in the common static / ":param" /
12513
 * "*" subset; other routes are matched through the regex provider, exactly
12514
 * as ada::url_pattern does.
12515
 *
12516
 * This implements the route-set ("URLPatternList") use case discussed in
12517
 * https://github.com/whatwg/urlpattern/issues/166 for the pathname component.
12518
 *
12519
 * Correctness does not depend on the fast path: inputs or routes that exceed
12520
 * the fast-path limits (documented on the constants in
12521
 * `ada::url_pattern_list_limits`) are matched by a sequential fallback with
12522
 * identical priority semantics, never rejected and never answered wrongly.
12523
 *
12524
 * @see https://urlpattern.spec.whatwg.org/
12525
 */
12526
#ifndef ADA_URL_PATTERN_LIST_H
12527
#define ADA_URL_PATTERN_LIST_H
12528
12529
12530
#include <array>
12531
#include <cstddef>
12532
#include <cstdint>
12533
#include <optional>
12534
#include <span>
12535
#include <string>
12536
#include <string_view>
12537
#include <vector>
12538
12539
#if ADA_INCLUDE_URL_PATTERN
12540
namespace ada {
12541
12542
/**
12543
 * The limits of the url_pattern_list fast path. None of them changes what a
12544
 * list matches: routes and inputs beyond a limit are matched by a sequential
12545
 * fallback with identical semantics.
12546
 * @namespace ada::url_pattern_list_limits
12547
 */
12548
namespace url_pattern_list_limits {
12549
12550
/**
12551
 * Maximum number of captures (":param" groups plus one trailing "*" group)
12552
 * a route may declare and still be compiled into the fast path. Routes with
12553
 * more groups are matched by the sequential fallback; their match is still
12554
 * correct, but only the first `max_captures_per_route` captures are reported
12555
 * (see url_pattern_list_match_result::captures_truncated).
12556
 */
12557
inline constexpr uint32_t max_captures_per_route = 8;
12558
12559
/**
12560
 * Maximum number of '/'-separated segments an input pathname may have and
12561
 * still be matched by the fast path. Longer inputs fall back to the
12562
 * sequential matcher and are still matched correctly.
12563
 */
12564
inline constexpr uint32_t max_fast_path_segments = 24;
12565
12566
/**
12567
 * Maximum input pathname length (bytes) accepted by the fast path; segment
12568
 * offsets are tracked in 16-bit integers internally. Longer inputs fall back
12569
 * to the sequential matcher and are still matched correctly.
12570
 */
12571
inline constexpr uint32_t max_fast_path_pathname_length = 4096;
12572
12573
/**
12574
 * Maximum number of pattern segments a route may have and still be compiled
12575
 * into the trie fast path. Deeper routes are matched by the sequential
12576
 * fallback with identical semantics.
12577
 */
12578
inline constexpr uint32_t max_trie_pattern_segments = 16;
12579
12580
/**
12581
 * Maximum number of routes in a url_pattern_list (a node's static child
12582
 * count is a uint16_t).
12583
 */
12584
inline constexpr size_t max_routes = 65535;
12585
12586
/**
12587
 * Maximum number of challenger table entries. The table grows with the
12588
 * product of overlapping auxiliary and trie routes.
12589
 */
12590
inline constexpr size_t max_aux_entries = 1u << 20;
12591
12592
}  // namespace url_pattern_list_limits
12593
12594
/**
12595
 * The result of url_pattern_list::match. A winning route reports its group
12596
 * values in one of two forms, mirroring url_pattern_list::group_names():
12597
 *
12598
 * - Routes in the static / ":param" / "*" subset report zero-allocation
12599
 *   captures: (offset, length) slices of the pathname passed to match, in
12600
 *   capture order (":param" groups left to right, then the "*" group).
12601
 *   `regexp_route` is false and `regexp_groups` is empty.
12602
 * - Routes matched through the regex provider (patterns with custom regexp
12603
 *   groups or "?" / "+" / "*" modifiers) report the group values the
12604
 *   provider's regex_search returned, exactly as url_pattern::exec would for
12605
 *   the pathname component: `regexp_route` is true, `regexp_groups[i]` is the
12606
 *   value of group_names(route_index)[i] (nullopt for a group that did not
12607
 *   participate), and capture_count is 0.
12608
 *
12609
 * Routes with more than url_pattern_list_limits::max_captures_per_route
12610
 * groups report only the first max_captures_per_route slices and set
12611
 * captures_truncated.
12612
 */
12613
struct url_pattern_list_match_result {
12614
  /** One capture: an (offset, length) slice of the matched pathname. */
12615
  struct capture {
12616
    uint32_t offset = 0;
12617
    uint32_t length = 0;
12618
  };
12619
  /** Index of the winning route in the creation order, or -1 for no match. */
12620
  int32_t route_index = -1;
12621
  /** Number of valid entries in captures. */
12622
  uint32_t capture_count = 0;
12623
  /** True when the route has more groups than could be reported as slices. */
12624
  bool captures_truncated = false;
12625
  /** True when the winning route was matched through the regex provider; its
12626
   * group values are in regexp_groups. */
12627
  bool regexp_route = false;
12628
  std::array<capture, url_pattern_list_limits::max_captures_per_route>
12629
      captures{};
12630
  /** Group values of a regexp route, as returned by the provider. */
12631
  std::vector<std::optional<std::string>> regexp_groups{};
12632
12633
0
  [[nodiscard]] bool has_match() const noexcept { return route_index >= 0; }
12634
};
12635
12636
/**
12637
 * @private
12638
 * The compiled tables url_pattern_list::match walks, and the inline matcher
12639
 * over them (url_pattern_list-inl.h). Nothing here is part of the supported
12640
 * API. The route-set compiler that produces these tables is not part of the
12641
 * public headers at all (src/url_pattern_list_compiler.h).
12642
 * @namespace ada::url_pattern_list_detail
12643
 */
12644
namespace url_pattern_list_detail {
12645
12646
/** @private One trie node. Nodes with a projection dispatch keep their hash
12647
 * payload in a separate hash_record, so the common 0/1/direct nodes stay at
12648
 * 24 bytes. */
12649
struct node_record {
12650
  // First static edge (edges are laid out per node, contiguously).
12651
  int32_t first_child = 0;
12652
  // Child node index, -2 - route (pure-leaf shortcut), or -1.
12653
  int32_t param_child = -1;
12654
  // Route index of a "*" ending at this prefix, or -1.
12655
  int32_t wild_route = -1;
12656
  // Route ending exactly here, or -1.
12657
  int32_t terminal_route = -1;
12658
  uint16_t n_static = 0;
12659
  // 0 none, 1 direct compares, 2 projection, 3 linear scan, 4 first-byte
12660
  // index (root only).
12661
  uint8_t dispatch = 0;
12662
  // 1 if the node still has a param/wildcard alternative to backtrack to.
12663
  uint8_t has_alternative = 0;
12664
  // Index of the node's hash_record (dispatch == 2 only).
12665
  uint32_t hash_index = 0;
12666
};
12667
12668
/** @private Projection-dispatch payload of a hashed node. */
12669
struct hash_record {
12670
  uint64_t multiplier = 0;
12671
  uint32_t slot_base = 0;
12672
  // Witness plan: 3 nibble ids | count << 12 | use_len << 14.
12673
  uint16_t witness_plan = 0;
12674
  // Slot table size == 1 << slot_bits.
12675
  uint8_t slot_bits = 0;
12676
  uint8_t reserved = 0;
12677
};
12678
12679
/** @private One static edge; keys <= 16 bytes verify from the packed
12680
 * windows alone. */
12681
struct edge_record {
12682
  // Key bytes [0, min(8, len)), little-endian, zero-padded.
12683
  uint64_t prefix = 0;
12684
  // Key bytes [max(0, len - 8), len), little-endian, zero-padded.
12685
  uint64_t suffix = 0;
12686
  // Child node index; negative values encode -2 - route pure-leaf shortcuts.
12687
  int32_t node = -1;
12688
  // Full key in the blob (read only when key_length > 16).
12689
  uint32_t key_offset = 0;
12690
  uint16_t key_length = 0;
12691
};
12692
12693
/** @private How one route of the set is matched. */
12694
enum class route_mode : uint8_t {
12695
  // Compiled into the trie fast path.
12696
  trie = 0,
12697
  // Safe static/":param"/"*" syntax beyond a fast-path build limit: matched
12698
  // by the sequential segment matcher.
12699
  sequential = 1,
12700
  // Needs URLPattern regexp semantics: matched through the regex provider.
12701
  regexp = 2,
12702
};
12703
12704
/** @private Everything the matcher knows about one route after a hit. */
12705
struct route_record {
12706
  // Packed per-segment kinds, two bits per segment, most significant first;
12707
  // (kind_sequence, kind_length, route index) compared as a tuple is the
12708
  // specificity order.
12709
  uint64_t kind_sequence = 0;
12710
  // Sequential-mode routes: their segments in the segment table.
12711
  uint32_t segment_first = 0;
12712
  uint32_t segment_count = 0;
12713
  // Auxiliary routes that can outrank this route when it wins the fast
12714
  // path: a range of the aux table (usually empty).
12715
  uint32_t challenger_first = 0;
12716
  uint32_t challenger_count = 0;
12717
  // Ordinal among the regexp-mode routes, or -1.
12718
  int32_t regexp_component = -1;
12719
  uint8_t kind_length = 0;
12720
  route_mode mode = route_mode::sequential;
12721
  // Trie-mode routes: capture positions.
12722
  uint8_t n_params = 0;
12723
  uint8_t wild = 0;
12724
  std::array<uint8_t, url_pattern_list_limits::max_captures_per_route>
12725
      param_positions{};
12726
};
12727
12728
/** @private One pattern segment of a sequential-mode route. */
12729
struct segment_record {
12730
  uint32_t text_offset = 0;
12731
  uint32_t text_length = 0;
12732
  // 0 literal, 1 ":param", 2 "*".
12733
  uint8_t kind = 0;
12734
};
12735
12736
/**
12737
 * @private
12738
 * The compiled route set: one arena holding every table, addressed by
12739
 * section offsets, plus the per-route group names. Sections are 8-byte
12740
 * aligned; the blob is zero-padded by 8 bytes so short key windows can be
12741
 * loaded whole.
12742
 */
12743
struct compiled_routes {
12744
  std::vector<uint8_t> arena{};
12745
  std::vector<std::vector<std::string>> group_names{};
12746
  uint32_t nodes_offset = 0;
12747
  uint32_t hashes_offset = 0;
12748
  uint32_t edges_offset = 0;
12749
  uint32_t slots_offset = 0;
12750
  uint32_t blob_offset = 0;
12751
  uint32_t routes_offset = 0;
12752
  uint32_t segments_offset = 0;
12753
  uint32_t aux_offset = 0;
12754
  uint32_t root_index_offset = 0;
12755
  uint32_t n_routes = 0;
12756
  // All auxiliary routes (regexp mode and sequential mode) in insertion
12757
  // order: the aux table's first n_aux_all entries; challenger ranges
12758
  // follow.
12759
  uint32_t n_aux_all = 0;
12760
  uint8_t ignore_case = 0;
12761
12762
  template <typename T>
12763
0
  [[nodiscard]] const T* section(uint32_t offset) const noexcept {
12764
0
    return reinterpret_cast<const T*>(arena.data() + offset);
12765
0
  }
Unexecuted instantiation: char const* ada::url_pattern_list_detail::compiled_routes::section<char>(unsigned int) const
Unexecuted instantiation: ada::url_pattern_list_detail::route_record const* ada::url_pattern_list_detail::compiled_routes::section<ada::url_pattern_list_detail::route_record>(unsigned int) const
Unexecuted instantiation: ada::url_pattern_list_detail::segment_record const* ada::url_pattern_list_detail::compiled_routes::section<ada::url_pattern_list_detail::segment_record>(unsigned int) const
Unexecuted instantiation: ada::url_pattern_list_detail::node_record const* ada::url_pattern_list_detail::compiled_routes::section<ada::url_pattern_list_detail::node_record>(unsigned int) const
Unexecuted instantiation: ada::url_pattern_list_detail::hash_record const* ada::url_pattern_list_detail::compiled_routes::section<ada::url_pattern_list_detail::hash_record>(unsigned int) const
Unexecuted instantiation: ada::url_pattern_list_detail::edge_record const* ada::url_pattern_list_detail::compiled_routes::section<ada::url_pattern_list_detail::edge_record>(unsigned int) const
Unexecuted instantiation: unsigned char const* ada::url_pattern_list_detail::compiled_routes::section<unsigned char>(unsigned int) const
Unexecuted instantiation: unsigned short const* ada::url_pattern_list_detail::compiled_routes::section<unsigned short>(unsigned int) const
12766
};
12767
12768
/** @private Result of the fast-path engine or of the sequential matcher. */
12769
struct engine_result {
12770
  using capture = url_pattern_list_match_result::capture;
12771
  int32_t route = -1;
12772
  uint32_t capture_count = 0;
12773
  // False when the input exceeded a fast-path limit and the caller must run
12774
  // the sequential fallback over the whole route set.
12775
  bool within_fast_path = true;
12776
  bool captures_truncated = false;
12777
  std::array<capture, url_pattern_list_limits::max_captures_per_route>
12778
      captures{};
12779
};
12780
12781
/**
12782
 * @private
12783
 * Parses and compiles a set of pathname patterns (already base-URL
12784
 * processed). Routes that need the regex provider come back with
12785
 * route_record::regexp_component set to their ordinal in insertion order;
12786
 * the caller compiles those components and fills their group names.
12787
 */
12788
tl::expected<compiled_routes, errors> compile_pathname_patterns(
12789
    std::span<const std::string> patterns, bool ignore_case);
12790
12791
/**
12792
 * @private
12793
 * Sequential reference matcher for one non-regexp route of the compiled set;
12794
 * matches any input (no fast-path limits) with the same semantics as the
12795
 * compiled engine. With `fold_input`, input bytes are ASCII case-folded on
12796
 * the fly (the compiled literals are already folded). On a match, fills
12797
 * `result` (route index is NOT set) and returns true.
12798
 */
12799
bool match_route_sequential(const compiled_routes& tables, uint32_t route,
12800
                            std::string_view pathname, bool fold_input,
12801
                            engine_result& result) noexcept;
12802
12803
/**
12804
 * @private
12805
 * True when the bytes [p, p + n) hold no line terminator. A "*" segment
12806
 * compiles to "(.*)" in the URLPattern regexp, and "." in an ECMAScript
12807
 * regular expression does not match LF or CR, so a wildcard may not capture
12808
 * past one. Deliberately not inlined into the walk (it costs the static and
12809
 * ":param" paths, which never run it), and deliberately defined in
12810
 * url_pattern_list.cpp rather than here: MSVC's ada_never_inline carries no
12811
 * inline linkage, so a definition in this header is emitted in every
12812
 * translation unit.
12813
 */
12814
bool wildcard_tail_ok(const char* p, uint32_t n) noexcept;
12815
12816
/**
12817
 * @private
12818
 * Cheap pre-check for a regexp-mode route before running the provider: the
12819
 * part of the route's segment shape that is certain (see the compiler's
12820
 * approximate_kind_sequence) must fit the pathname -- its anchored literal
12821
 * segments, and its exact segment count when every group is a ":name"
12822
 * segment wildcard. False proves the regular expression cannot match.
12823
 */
12824
bool match_regexp_shape(const compiled_routes& tables, uint32_t route,
12825
                        std::string_view pathname, bool fold_input) noexcept;
12826
12827
/**
12828
 * @private
12829
 * True when route `a` (at insertion index `a_index`) outranks route `b` (at
12830
 * `b_index`): lexicographically smaller kind sequence, insertion order as the
12831
 * tiebreak.
12832
 */
12833
constexpr bool outranks(uint64_t a_sequence, uint32_t a_length, size_t a_index,
12834
                        uint64_t b_sequence, uint32_t b_length,
12835
0
                        size_t b_index) noexcept {
12836
0
  if (a_sequence != b_sequence) {
12837
0
    return a_sequence < b_sequence;
12838
0
  }
12839
0
  if (a_length != b_length) {
12840
0
    return a_length < b_length;
12841
0
  }
12842
0
  return a_index < b_index;
12843
0
}
12844
12845
}  // namespace url_pattern_list_detail
12846
12847
template <url_pattern_regex::regex_concept regex_provider>
12848
class url_pattern_list;
12849
12850
/**
12851
 * @private
12852
 * url_pattern_list befriends these two specializations, so they have to be
12853
 * declared before it: a friend declaration that redeclares the function
12854
 * template instead is not matched by every compiler we support (Apple clang
12855
 * 15 rejects the resulting member access). The documented declarations are
12856
 * in implementation.h, next to parse_url_pattern, and carry the default
12857
 * arguments: this header includes url_pattern.h, which includes
12858
 * implementation.h, so those declarations are always seen first, and a
12859
 * function template may not gain default arguments in a later declaration.
12860
 */
12861
template <url_pattern_regex::regex_concept regex_provider>
12862
ada_warn_unused tl::expected<url_pattern_list<regex_provider>, errors>
12863
parse_url_pattern_list(std::span<const std::string_view> pathname_patterns,
12864
                       const std::string_view* base_url,
12865
                       const url_pattern_options* options);
12866
12867
/** @private See above. */
12868
template <url_pattern_regex::regex_concept regex_provider>
12869
ada_warn_unused tl::expected<url_pattern_list<regex_provider>, errors>
12870
parse_url_pattern_list(std::span<const url_pattern<regex_provider>> patterns);
12871
12872
/**
12873
 * @brief A compiled set of URLPattern pathname patterns with one-shot
12874
 * matching.
12875
 *
12876
 * Build once with ada::parse_url_pattern_list, then call match() per
12877
 * request. Matching within the fast-path limits is allocation-free and
12878
 * regex-free for routes written in the static / ":param" / "*" subset; other
12879
 * routes are matched through the regex provider (the same regex_search call
12880
 * url_pattern::exec makes) and still participate in the priority order.
12881
 *
12882
 * Match priority is specificity order, not registration order: routes are
12883
 * compared by their per-segment kind sequence (literal < ":param" < "*",
12884
 * lexicographically from the first segment), with insertion order breaking
12885
 * ties. This is the priority scheme of find-my-way (Fastify) and Express-
12886
 * style routers. Whether a standardized URLPatternList should instead use
12887
 * pure first-match-in-insertion-order semantics is an open question; the
12888
 * compiled representation supports either, and the priority rule is
12889
 * deliberately centralized in url_pattern_list_detail::outranks.
12890
 *
12891
 * Scope (v1): the pathname component only. Other URL components are treated
12892
 * as fully wildcarded; match() takes an already-extracted pathname (for
12893
 * example ada::url_aggregator::get_pathname()). Inputs are matched as given
12894
 * and are expected to be in canonical (percent-encoded) form; the pattern
12895
 * side is canonicalized by the URLPattern pattern parser at creation. The
12896
 * subset follows the URLPattern regexp it stands for: a ":param" segment
12897
 * ("[^/]+?") is one non-empty segment, and a "*" tail ("(.*)") matches any
12898
 * bytes except the line terminators LF and CR, which "." never matches.
12899
 *
12900
 * With url_pattern_options::ignore_case, regexp routes are compiled through
12901
 * the provider with the flag set (as url_pattern does), and the static /
12902
 * ":param" / "*" subset compares literal segments with ASCII case folding,
12903
 * which is what a case-insensitive regular expression does over the ASCII
12904
 * text of a canonical pathname.
12905
 *
12906
 * @tparam regex_provider The regex implementation used only for routes that
12907
 *         need URLPattern regexp semantics. Must satisfy
12908
 *         url_pattern_regex::regex_concept.
12909
 */
12910
template <url_pattern_regex::regex_concept regex_provider>
12911
class url_pattern_list {
12912
 public:
12913
  url_pattern_list() = default;
12914
12915
  /**
12916
   * Matches a pathname against the set and returns the winning route with
12917
   * its captures (see url_pattern_list_match_result). The fast path is
12918
   * allocation-free; inputs beyond the fast-path limits are matched by the
12919
   * sequential fallback with identical semantics.
12920
   */
12921
  [[nodiscard]] url_pattern_list_match_result match(
12922
      std::string_view pathname) const;
12923
12924
  /** Number of routes in the set. */
12925
  [[nodiscard]] size_t size() const noexcept { return patterns_.size(); }
12926
12927
  /** The pathname pattern string the route at `route_index` was created
12928
   * from (after base URL processing, if a base URL was given). */
12929
  [[nodiscard]] std::string_view pattern(size_t route_index) const
12930
      ada_lifetime_bound {
12931
    return patterns_[route_index];
12932
  }
12933
12934
  /**
12935
   * Capture group names of the route at `route_index`, in the order of
12936
   * url_pattern_list_match_result::captures / regexp_groups ("*" groups have
12937
   * numeric names, per URLPattern).
12938
   */
12939
  [[nodiscard]] const std::vector<std::string>& group_names(
12940
      size_t route_index) const ada_lifetime_bound {
12941
    return compiled_.group_names[route_index];
12942
  }
12943
12944
  /** The ignore_case option the set was created with. */
12945
  [[nodiscard]] bool ignore_case() const noexcept {
12946
    return compiled_.ignore_case != 0;
12947
  }
12948
12949
  friend tl::expected<url_pattern_list, errors>
12950
  parse_url_pattern_list<regex_provider>(
12951
      std::span<const std::string_view> pathname_patterns,
12952
      const std::string_view* base_url, const url_pattern_options* options);
12953
12954
  friend tl::expected<url_pattern_list, errors> parse_url_pattern_list<
12955
      regex_provider>(std::span<const url_pattern<regex_provider>> patterns);
12956
12957
 private:
12958
  /** @private Compiles the (already processed) pattern strings; the regexp
12959
   * components are then supplied by the caller in insertion order. */
12960
  static tl::expected<url_pattern_list, errors> create(
12961
      std::vector<std::string>&& pathname_patterns, bool ignore_case);
12962
12963
  /** @private Tests one auxiliary route (sequential or regexp mode) and,
12964
   * when it matches and outranks `best`, replaces `best` with it. `probe`
12965
   * is the (possibly case-folded) pathname for the sequential matcher,
12966
   * `pathname` the original for the provider. */
12967
  void consider_route(
12968
      uint32_t route_index, std::string_view pathname, std::string_view probe,
12969
      bool fold_input, url_pattern_list_detail::engine_result& best,
12970
      std::vector<std::optional<std::string>>& best_groups) const;
12971
12972
  /** @private The pattern strings, by route index. */
12973
  std::vector<std::string> patterns_{};
12974
  /** @private The compiled tables. */
12975
  url_pattern_list_detail::compiled_routes compiled_{};
12976
  /** @private Compiled pathname components of the regexp-mode routes, in
12977
   * insertion order. */
12978
  std::vector<url_pattern_component<regex_provider>> regexp_components_{};
12979
};
12980
12981
}  // namespace ada
12982
#endif  // ADA_INCLUDE_URL_PATTERN
12983
#endif  // ADA_URL_PATTERN_LIST_H
12984
/* end file include/ada/url_pattern_list.h */
12985
/* begin file include/ada/url_pattern_list-inl.h */
12986
/**
12987
 * @file url_pattern_list-inl.h
12988
 * @brief The url_pattern_list matcher (inline) and the class template's
12989
 * member definitions.
12990
 *
12991
 * The walk over the compiled tables lives here, as ada_really_inline
12992
 * functions, so that it inlines into url_pattern_list::match; the route-set
12993
 * compiler that builds the tables is in its own translation unit
12994
 * (src/url_pattern_list.cpp) and is not part of the public headers.
12995
 */
12996
#ifndef ADA_URL_PATTERN_LIST_INL_H
12997
#define ADA_URL_PATTERN_LIST_INL_H
12998
12999
13000
#include <bit>
13001
#include <cstdint>
13002
#include <cstring>
13003
#include <optional>
13004
#include <string>
13005
#include <string_view>
13006
#include <utility>
13007
#include <vector>
13008
13009
#if ADA_NEON
13010
#include <arm_neon.h>
13011
#endif
13012
13013
#if ADA_INCLUDE_URL_PATTERN
13014
namespace ada::url_pattern_list_detail {
13015
13016
// ---- byte helpers ----------------------------------------------------------
13017
13018
// Unaligned 8-byte little-endian load; all 8 bytes must be readable. The
13019
// byte-assembly fallback keeps big-endian targets correct (the compiler
13020
// lowers it to a single load plus byte swap).
13021
0
ada_really_inline uint64_t load8_le(const char* p) noexcept {
13022
0
  if constexpr (std::endian::native == std::endian::little) {
13023
0
    uint64_t x;
13024
0
    std::memcpy(&x, p, 8);
13025
0
    return x;
13026
  } else {
13027
    uint64_t x = 0;
13028
    for (uint32_t j = 0; j < 8; j++) {
13029
      x |= static_cast<uint64_t>(static_cast<uint8_t>(p[j])) << (8 * j);
13030
    }
13031
    return x;
13032
  }
13033
0
}
13034
13035
// Bytes [0, n) of p packed little-endian, zero-padded; reads exactly n
13036
// bytes (n < 8). This is the byte-compare path for short tails.
13037
0
ada_really_inline uint64_t gather_le(const char* p, uint32_t n) noexcept {
13038
0
  uint64_t x = 0;
13039
0
  for (uint32_t j = 0; j < n; j++) {
13040
0
    x |= static_cast<uint64_t>(static_cast<uint8_t>(p[j])) << (8 * j);
13041
0
  }
13042
0
  return x;
13043
0
}
13044
13045
// Mask selecting the low n bytes, 1 <= n <= 7.
13046
0
constexpr uint64_t low_bytes_mask(uint32_t n) noexcept {
13047
0
  return ~0ull >> (64 - 8 * n);
13048
0
}
13049
13050
// ASCII case folding of n bytes from src into dst (the compiler vectorizes
13051
// this loop). Only ASCII letters change: canonical pathnames are ASCII, and
13052
// this is what a case-insensitive regular expression does over them.
13053
0
inline void ascii_fold(const char* src, uint32_t n, char* dst) noexcept {
13054
0
  for (uint32_t i = 0; i < n; i++) {
13055
0
    const uint8_t c = static_cast<uint8_t>(src[i]);
13056
0
    dst[i] = static_cast<char>(c | ((c >= 'A' && c <= 'Z') ? 0x20u : 0u));
13057
0
  }
13058
0
}
13059
13060
// ---- witness machinery -----------------------------------------------------
13061
// Projection dispatch for wide trie nodes. A witness id names a feature of a
13062
// byte string:
13063
//   0..7   the byte at absolute offset id           (0 when out of range)
13064
//   8..15  the byte at offset id-8 counted from the end
13065
// A projection is three witness bytes plus the length packed into one
13066
// uint64; a perfect multiplier turns it into a slot index. Builder and
13067
// matcher call the same accessors and the same packing, so a slot table
13068
// cannot disagree with the gather that reads it.
13069
13070
0
constexpr uint8_t length_byte(uint32_t len) noexcept {
13071
0
  return len < 255u ? static_cast<uint8_t>(len) : static_cast<uint8_t>(255);
13072
0
}
13073
13074
constexpr uint8_t witness_byte(const char* p, uint32_t len,
13075
0
                               uint8_t id) noexcept {  // ids 0..15
13076
0
  uint32_t o = id & 7u;
13077
0
  bool in = o < len;
13078
0
  uint32_t pos = (id & 8u) ? len - 1u - o : o;  // wraps when !in; masked then
13079
0
  pos = in ? pos : 0u;
13080
0
  uint8_t v = len ? static_cast<uint8_t>(p[pos]) : static_cast<uint8_t>(0);
13081
0
  return in ? v : static_cast<uint8_t>(0);
13082
0
}
13083
13084
constexpr uint64_t pack_projection(uint8_t f0, uint8_t f1, uint8_t f2,
13085
0
                                   uint8_t f3) noexcept {
13086
0
  return (static_cast<uint64_t>(f0) << 24) | (static_cast<uint64_t>(f1) << 16) |
13087
0
         (static_cast<uint64_t>(f2) << 8) | static_cast<uint64_t>(f3);
13088
0
}
13089
13090
// Perfect-multiplier slot index; b <= 12 everywhere, so the shift is in
13091
// range and the product needs no modulus.
13092
constexpr uint64_t slot_of(uint64_t proj, uint64_t multiplier,
13093
0
                           uint8_t b) noexcept {
13094
0
  return (proj * multiplier) >> (64 - b);
13095
0
}
13096
13097
// Fixed-shape projection of one string: always 3 witness bytes plus the
13098
// length. Duplicated ids add no information but keep the gather uniform.
13099
constexpr uint64_t project(const char* p, uint32_t len,
13100
0
                           uint16_t plan) noexcept {
13101
0
  return pack_projection(
13102
0
      witness_byte(p, len, static_cast<uint8_t>(plan & 15u)),
13103
0
      witness_byte(p, len, static_cast<uint8_t>((plan >> 4) & 15u)),
13104
0
      witness_byte(p, len, static_cast<uint8_t>((plan >> 8) & 15u)),
13105
0
      length_byte(len));
13106
0
}
13107
13108
// ---- segment scan ----------------------------------------------------------
13109
13110
// Splits the pathname into segments in one pass, in place: only segment
13111
// starts are recorded, with a sentinel soff[nseg] = ulen + 1 so that
13112
// seg_len(i) == soff[i + 1] - soff[i] - 1. Returns the segment count, or 0
13113
// when the input has more than max_fast_path_segments segments (the caller
13114
// falls back to the sequential matcher). Requires ulen >= 1 and
13115
// url[0] == '/'.
13116
//
13117
// Two implementations with the same contract: the portable SWAR scan (8
13118
// bytes per step, an exact zero-byte test on x ^ '/'-fill with no false
13119
// positives, bytes >= 0x80 included, and a byte-exact partial load for the
13120
// tail, so the input is never over-read), and on AArch64 a NEON scan for
13121
// inputs of 16 bytes or more (16 bytes per step, the '/' compare narrowed
13122
// to one nibble per byte, the last block overlapping the previous one so
13123
// the input is never over-read). The 1k+ pathname benchmark in the PR
13124
// discussion is what keeps the NEON scan: it is faster at every length and
13125
// 3-4x faster past 1 KB.
13126
struct segment_emitter {
13127
  uint16_t* soff;
13128
  uint32_t nseg = 0;
13129
  uint32_t start = 1;
13130
  // One segment start per set bit of `lanes`; a lane is 1 << shift bits
13131
  // wide (8 for the SWAR masks, 4 for the NEON nibble masks).
13132
  ada_really_inline bool emit(uint64_t lanes, uint32_t base,
13133
0
                              unsigned shift) noexcept {
13134
0
    using url_pattern_list_limits::max_fast_path_segments;
13135
0
    while (lanes) {
13136
0
      const uint32_t pos =
13137
0
          base + (static_cast<uint32_t>(std::countr_zero(lanes)) >> shift);
13138
0
      if (nseg >= max_fast_path_segments) {
13139
0
        return false;
13140
0
      }
13141
0
      soff[nseg++] = static_cast<uint16_t>(start);
13142
0
      start = pos + 1;
13143
0
      lanes &= lanes - 1;
13144
0
    }
13145
0
    return true;
13146
0
  }
13147
0
  ada_really_inline uint32_t finish(uint32_t ulen) noexcept {
13148
0
    using url_pattern_list_limits::max_fast_path_segments;
13149
0
    if (nseg >= max_fast_path_segments) {
13150
0
      return 0;
13151
0
    }
13152
0
    soff[nseg++] = static_cast<uint16_t>(start);
13153
0
    soff[nseg] = static_cast<uint16_t>(ulen + 1);  // sentinel
13154
0
    return nseg;
13155
0
  }
13156
};
13157
13158
ada_really_inline uint32_t scan_segments_swar(const char* url, uint32_t ulen,
13159
0
                                              uint16_t* soff) noexcept {
13160
0
  constexpr uint64_t slashes = 0x2F2F2F2F2F2F2F2Full;
13161
0
  constexpr uint64_t low7 = 0x7F7F7F7F7F7F7F7Full;
13162
0
  // Bit 7 of every byte of x that is zero, exactly: (b & 0x7F) + 0x7F has
13163
0
  // bit 7 set iff the low bits are non-zero, b itself has it set iff b is
13164
0
  // >= 0x80, and no lane can carry into its neighbour.
13165
0
  const auto zero_lanes = [](uint64_t x) noexcept {
13166
0
    return ~(((x & low7) + low7) | x | low7);
13167
0
  };
13168
0
  segment_emitter out{soff};
13169
0
  uint32_t i = 1;
13170
0
  for (; i + 8 <= ulen; i += 8) {
13171
0
    const uint64_t lanes = zero_lanes(load8_le(url + i) ^ slashes);
13172
0
    if (lanes != 0 && !out.emit(lanes, i, 3)) {
13173
0
      return 0;
13174
0
    }
13175
0
  }
13176
0
  if (i < ulen) {  // tail of 1..7 bytes: zero padding is never a '/'
13177
0
    const uint64_t lanes = zero_lanes(gather_le(url + i, ulen - i) ^ slashes);
13178
0
    if (lanes != 0 && !out.emit(lanes, i, 3)) {
13179
0
      return 0;
13180
0
    }
13181
0
  }
13182
0
  return out.finish(ulen);
13183
0
}
13184
13185
#if ADA_NEON
13186
ada_really_inline uint32_t scan_segments_neon(const char* url, uint32_t ulen,
13187
                                              uint16_t* soff) noexcept {
13188
  // Requires ulen >= 16.
13189
  const uint8x16_t slash = vdupq_n_u8('/');
13190
  // One bit per byte lane that holds a '/': compare, narrow each 16-bit
13191
  // pair to its high nibble, keep bit 0 of every nibble.
13192
  const auto slash_lanes = [&](const char* p) noexcept {
13193
    const uint8x16_t v = vld1q_u8(reinterpret_cast<const uint8_t*>(p));
13194
    const uint64_t nibbles =
13195
        vget_lane_u64(vreinterpret_u64_u8(vshrn_n_u16(
13196
                          vreinterpretq_u16_u8(vceqq_u8(v, slash)), 4)),
13197
                      0);
13198
    return nibbles & 0x1111111111111111ull;
13199
  };
13200
  segment_emitter out{soff};
13201
  uint32_t i = 0;
13202
  for (; i + 16 <= ulen; i += 16) {
13203
    uint64_t lanes = slash_lanes(url + i);
13204
    if (i == 0) {
13205
      lanes &= ~0xFull;  // the leading '/' is not a separator
13206
    }
13207
    if (lanes != 0 && !out.emit(lanes, i, 2)) {
13208
      return 0;
13209
    }
13210
  }
13211
  if (i < ulen) {  // overlapped last block: drop the lanes already scanned
13212
    const uint32_t off = ulen - 16;
13213
    const uint64_t lanes = slash_lanes(url + off) & (~0ull << ((i - off) * 4));
13214
    if (lanes != 0 && !out.emit(lanes, off, 2)) {
13215
      return 0;
13216
    }
13217
  }
13218
  return out.finish(ulen);
13219
}
13220
#endif  // ADA_NEON
13221
13222
ada_really_inline uint32_t scan_segments(const char* url, uint32_t ulen,
13223
0
                                         uint16_t* soff) noexcept {
13224
0
#if ADA_NEON
13225
0
  if (ulen >= 16) {
13226
0
    return scan_segments_neon(url, ulen, soff);
13227
0
  }
13228
0
#endif
13229
0
  return scan_segments_swar(url, ulen, soff);
13230
0
}
13231
13232
// ---- verify / dispatch -----------------------------------------------------
13233
13234
// One input segment prepared for dispatch: its bytes, its length, and how
13235
// many bytes are readable from p (to the end of the pathname).
13236
struct segment_ref {
13237
  const char* p;
13238
  uint32_t len;
13239
  uint32_t avail;
13240
};
13241
13242
// Segment-vs-edge compare. Keys of 8..16 bytes verify from two whole-word
13243
// loads inside the segment; shorter keys from one masked load when the
13244
// input has 8 readable bytes, else from a byte gather (short tails such as
13245
// "42" or "me"); longer keys through memcmp against the blob. An empty key
13246
// (a pattern such as "/users/") matches exactly the empty segment.
13247
ada_really_inline bool verify_edge(const edge_record& e, const segment_ref& s,
13248
0
                                   const char* blob) noexcept {
13249
0
  const uint32_t len = s.len;
13250
0
  if (len != e.key_length) {
13251
0
    return false;
13252
0
  }
13253
0
  if (len == 0) {
13254
0
    return true;
13255
0
  }
13256
0
  if (len > 16) {
13257
0
    return std::memcmp(s.p, blob + e.key_offset, len) == 0;
13258
0
  }
13259
0
  if (len >= 8) {
13260
0
    return ((load8_le(s.p) ^ e.prefix) |
13261
0
            (load8_le(s.p + len - 8) ^ e.suffix)) == 0;
13262
0
  }
13263
0
  const uint64_t x = s.avail >= 8 ? (load8_le(s.p) & low_bytes_mask(len))
13264
0
                                  : gather_le(s.p, len);
13265
0
  return x == e.prefix;
13266
0
}
13267
13268
// The typed view of the arena the walk reads; derived once per match.
13269
struct table_view {
13270
  const node_record* nodes;
13271
  const hash_record* hashes;
13272
  const edge_record* edges;
13273
  const uint8_t* slots;
13274
  const char* blob;
13275
  const uint16_t* root_index;
13276
};
13277
13278
0
ada_really_inline table_view view_of(const compiled_routes& r) noexcept {
13279
0
  return table_view{r.section<node_record>(r.nodes_offset),
13280
0
                    r.section<hash_record>(r.hashes_offset),
13281
0
                    r.section<edge_record>(r.edges_offset),
13282
0
                    r.section<uint8_t>(r.slots_offset),
13283
0
                    r.section<char>(r.blob_offset),
13284
0
                    r.section<uint16_t>(r.root_index_offset)};
13285
0
}
13286
13287
// Static-child dispatch: returns the child ordinal within the node or -1.
13288
// Correctness never depends on the projection or the index: the candidate
13289
// is always confirmed by a full segment compare, so a bad table can only
13290
// cost time, never change an answer.
13291
ada_really_inline int32_t dispatch_static(const table_view& t,
13292
                                          const node_record& nd,
13293
0
                                          const segment_ref& s) noexcept {
13294
0
  const edge_record* e = t.edges + nd.first_child;
13295
0
  switch (nd.dispatch) {
13296
0
    case 0:
13297
0
      return -1;
13298
0
    case 1: {  // direct: up to 8 compares, each gated by the key length
13299
0
      for (uint32_t j = 0; j < nd.n_static; j++) {
13300
0
        if (verify_edge(e[j], s, t.blob)) {
13301
0
          return static_cast<int32_t>(j);
13302
0
        }
13303
0
      }
13304
0
      return -1;
13305
0
    }
13306
0
    case 2: {  // projection: gather -> multiply -> slot -> verify
13307
0
      const hash_record& h = t.hashes[nd.hash_index];
13308
0
      const uint64_t proj = project(s.p, s.len, h.witness_plan);
13309
0
      const uint8_t ord =
13310
0
          t.slots[h.slot_base + slot_of(proj, h.multiplier, h.slot_bits)];
13311
0
      if (ord == 0xFF) {
13312
0
        return -1;
13313
0
      }
13314
0
      return verify_edge(e[ord], s, t.blob) ? static_cast<int32_t>(ord) : -1;
13315
0
    }
13316
0
    case 4: {  // root first-byte index: jump to the run of children that
13317
0
               // share the segment's first byte (children are sorted by it)
13318
0
      if (s.len == 0) {
13319
0
        return -1;  // no first byte; an indexed root has no empty key
13320
0
      }
13321
0
      const uint8_t b = static_cast<uint8_t>(s.p[0]);
13322
0
      uint32_t j = t.root_index[b];
13323
0
      if (j == 0xFFFF) {
13324
0
        return -1;
13325
0
      }
13326
0
      for (; j < nd.n_static && static_cast<uint8_t>(e[j].prefix & 0xFFu) == b;
13327
0
           j++) {
13328
0
        if (verify_edge(e[j], s, t.blob)) {
13329
0
          return static_cast<int32_t>(j);
13330
0
        }
13331
0
      }
13332
0
      return -1;
13333
0
    }
13334
0
    default: {  // linear demotion rung (also carries fanout > 254)
13335
0
      for (uint32_t j = 0; j < nd.n_static; j++) {
13336
0
        if (verify_edge(e[j], s, t.blob)) {
13337
0
          return static_cast<int32_t>(j);
13338
0
        }
13339
0
      }
13340
0
      return -1;
13341
0
    }
13342
0
  }
13343
0
}
13344
13345
// ---- the match residual ----------------------------------------------------
13346
13347
// Matches `pathname` against the compiled tables. When the input is out of
13348
// the fast-path contract, returns with within_fast_path == false and no
13349
// answer; the caller falls back to the sequential matcher.
13350
ada_really_inline void match_compiled(const compiled_routes& r, const char* url,
13351
                                      uint32_t ulen,
13352
0
                                      engine_result& out) noexcept {
13353
0
  using url_pattern_list_limits::max_fast_path_pathname_length;
13354
0
  using url_pattern_list_limits::max_fast_path_segments;
13355
0
  out = engine_result{};
13356
0
  if (ulen == 0 || url[0] != '/' || ulen > max_fast_path_pathname_length) {
13357
0
    out.within_fast_path = false;  // the sequential fallback decides
13358
0
    return;
13359
0
  }
13360
0
  const table_view t = view_of(r);
13361
0
  const route_record* routes = r.section<route_record>(r.routes_offset);
13362
0
13363
0
  // Segment scan; overflow means the input is beyond the fast path.
13364
0
  uint16_t soff[max_fast_path_segments + 1];
13365
0
  const uint32_t nseg = scan_segments(url, ulen, soff);
13366
0
  if (nseg == 0) {
13367
0
    out.within_fast_path = false;
13368
0
    return;
13369
0
  }
13370
0
  const auto seg_len = [&](uint32_t i) {
13371
0
    return static_cast<uint32_t>(soff[i + 1]) - soff[i] - 1u;
13372
0
  };
13373
0
  const auto seg_ref = [&](uint32_t i) {
13374
0
    const uint32_t off = soff[i];
13375
0
    return segment_ref{url + off, seg_len(i), ulen - off};
13376
0
  };
13377
0
13378
0
  // Trie walk with an explicit bounded backtrack stack. Every node offers
13379
0
  // the same three alternatives in the compiled priority order (static
13380
0
  // child, param child, wildcard); a backtrack record stores the resume
13381
0
  // point, and a record is pushed only when the node still has an untried
13382
0
  // alternative, so the stack never exceeds the walk depth. Edges encoded
13383
0
  // as -2 - route are pure-leaf shortcuts.
13384
0
  enum alternative : uint16_t {
13385
0
    alt_static = 0,
13386
0
    alt_param = 1,
13387
0
    alt_wild = 2,
13388
0
    alt_none = 3
13389
0
  };
13390
0
  struct backtrack {
13391
0
    int32_t node;
13392
0
    uint16_t i;
13393
0
    uint16_t resume;
13394
0
  };
13395
0
  backtrack stack[max_fast_path_segments + 1];
13396
0
  uint32_t sp = 0;
13397
0
  int32_t node = 0;
13398
0
  uint32_t i = 0;
13399
0
  uint32_t alt = alt_static;
13400
0
  int32_t route = -1;
13401
0
  uint32_t wild_from = 0;
13402
0
  bool wild = false;
13403
0
  for (;;) {
13404
0
    const node_record& nd = t.nodes[static_cast<size_t>(node)];
13405
0
    if (alt == alt_static) {
13406
0
      if (i == nseg) {
13407
0
        if (nd.terminal_route >= 0) {
13408
0
          route = nd.terminal_route;
13409
0
          break;
13410
0
        }
13411
0
        alt = alt_none;
13412
0
      } else {
13413
0
        const int32_t ord = dispatch_static(t, nd, seg_ref(i));
13414
0
        if (ord >= 0) {
13415
0
          const int32_t nxt = t.edges[static_cast<size_t>(nd.first_child) +
13416
0
                                      static_cast<size_t>(ord)]
13417
0
                                  .node;
13418
0
          if (nxt >= 0) {
13419
0
            if (nd.has_alternative) {
13420
0
              stack[sp++] = {node, static_cast<uint16_t>(i), alt_param};
13421
0
            }
13422
0
            node = nxt;
13423
0
            i++;
13424
0
            continue;
13425
0
          }
13426
0
          // Pure-leaf shortcut.
13427
0
          if (i + 1 == nseg) {
13428
0
            route = -2 - nxt;
13429
0
            break;
13430
0
          }
13431
0
          alt = alt_param;  // dead end: fall through to this node's fallbacks
13432
0
        } else {
13433
0
          alt = alt_param;
13434
0
        }
13435
0
      }
13436
0
    }
13437
0
    if (alt == alt_param) {
13438
0
      const int32_t pc = nd.param_child;
13439
0
      if (pc != -1 && seg_len(i) > 0) {
13440
0
        if (pc >= 0) {
13441
0
          if (nd.wild_route >= 0) {
13442
0
            stack[sp++] = {node, static_cast<uint16_t>(i), alt_wild};
13443
0
          }
13444
0
          node = pc;
13445
0
          i++;
13446
0
          alt = alt_static;
13447
0
          continue;
13448
0
        }
13449
0
        // Pure-leaf param shortcut.
13450
0
        if (i + 1 == nseg) {
13451
0
          route = -2 - pc;
13452
0
          break;
13453
0
        }
13454
0
        alt = alt_wild;  // only the wildcard remains here
13455
0
      } else {
13456
0
        alt = alt_wild;
13457
0
      }
13458
0
    }
13459
0
    if (alt == alt_wild) {
13460
0
      if (nd.wild_route >= 0 &&
13461
0
          wildcard_tail_ok(url + soff[i], ulen - soff[i])) {
13462
0
        route = nd.wild_route;
13463
0
        wild_from = i;
13464
0
        wild = true;
13465
0
        break;
13466
0
      }
13467
0
      // No alternative left at this node: resume from the backtrack stack
13468
0
      // (alt is overwritten by the popped record).
13469
0
    }
13470
0
    if (sp == 0) {
13471
0
      break;  // nothing to resume: miss
13472
0
    }
13473
0
    --sp;
13474
0
    node = stack[sp].node;
13475
0
    i = stack[sp].i;
13476
0
    alt = stack[sp].resume;
13477
0
  }
13478
0
13479
0
  out.route = route;
13480
0
  if (route >= 0) {  // capture extraction: params first, wildcard tail last
13481
0
    const route_record& rm = routes[static_cast<size_t>(route)];
13482
0
    uint32_t nc = 0;
13483
0
    for (uint32_t k = 0; k < rm.n_params; k++) {
13484
0
      const uint32_t p = rm.param_positions[k];
13485
0
      out.captures[nc++] = {soff[p], seg_len(p)};
13486
0
    }
13487
0
    if (wild) {
13488
0
      out.captures[nc++] = {soff[wild_from], ulen - soff[wild_from]};
13489
0
    }
13490
0
    out.capture_count = nc;
13491
0
  }
13492
0
}
13493
13494
}  // namespace ada::url_pattern_list_detail
13495
13496
namespace ada {
13497
13498
template <url_pattern_regex::regex_concept regex_provider>
13499
tl::expected<url_pattern_list<regex_provider>, errors>
13500
url_pattern_list<regex_provider>::create(
13501
    std::vector<std::string>&& pathname_patterns, bool ignore_case) {
13502
  url_pattern_list list{};
13503
  list.patterns_ = std::move(pathname_patterns);
13504
  auto compiled = url_pattern_list_detail::compile_pathname_patterns(
13505
      list.patterns_, ignore_case);
13506
  if (!compiled) {
13507
    return tl::unexpected(compiled.error());
13508
  }
13509
  list.compiled_ = std::move(*compiled);
13510
  return list;
13511
}
13512
13513
template <url_pattern_regex::regex_concept regex_provider>
13514
void url_pattern_list<regex_provider>::consider_route(
13515
    uint32_t route_index, std::string_view pathname, std::string_view probe,
13516
    bool fold_input, url_pattern_list_detail::engine_result& best,
13517
    std::vector<std::optional<std::string>>& best_groups) const {
13518
  namespace detail = url_pattern_list_detail;
13519
  const detail::route_record* routes =
13520
      compiled_.section<detail::route_record>(compiled_.routes_offset);
13521
  const detail::route_record& candidate = routes[route_index];
13522
  // Only test candidates that would outrank the current best.
13523
  if (best.route >= 0) {
13524
    const detail::route_record& current =
13525
        routes[static_cast<size_t>(best.route)];
13526
    if (!detail::outranks(candidate.kind_sequence, candidate.kind_length,
13527
                          route_index, current.kind_sequence,
13528
                          current.kind_length,
13529
                          static_cast<size_t>(best.route))) {
13530
      return;
13531
    }
13532
  }
13533
  if (candidate.mode == detail::route_mode::regexp) {
13534
    // A route whose certain segment shape does not fit the input cannot
13535
    // match at all: skip the provider.
13536
    if (!detail::match_regexp_shape(compiled_, route_index, probe,
13537
                                    fold_input)) {
13538
      return;
13539
    }
13540
    // URLPattern's own test/exec split: regex_match answers yes/no (this is
13541
    // what rejects a non-matching route cheaply; a regex_search miss can
13542
    // cost a scan over every start position), and regex_search then
13543
    // produces the group values exactly as url_pattern::exec does.
13544
    const url_pattern_component<regex_provider>& component =
13545
        regexp_components_[static_cast<size_t>(candidate.regexp_component)];
13546
    if (!component.fast_test(pathname)) {
13547
      return;
13548
    }
13549
    auto groups = component.fast_match(pathname);
13550
    if (groups) {
13551
      best = detail::engine_result{};
13552
      best.route = static_cast<int32_t>(route_index);
13553
      best_groups = std::move(*groups);
13554
    }
13555
  } else {
13556
    detail::engine_result scratch{};
13557
    if (detail::match_route_sequential(compiled_, route_index, probe,
13558
                                       fold_input, scratch)) {
13559
      scratch.route = static_cast<int32_t>(route_index);
13560
      best = scratch;
13561
      best_groups.clear();
13562
    }
13563
  }
13564
}
13565
13566
template <url_pattern_regex::regex_concept regex_provider>
13567
url_pattern_list_match_result url_pattern_list<regex_provider>::match(
13568
    std::string_view pathname) const {
13569
  namespace detail = url_pattern_list_detail;
13570
  using url_pattern_list_limits::max_fast_path_pathname_length;
13571
  // A default-constructed list (or one compiled from no routes) has no
13572
  // tables. Walking them would dereference section pointers into an empty
13573
  // arena.
13574
  if (patterns_.empty() || compiled_.arena.empty()) {
13575
    return {};
13576
  }
13577
  // With ignore_case the compiled literals are ASCII-folded, so the fast
13578
  // path probes a folded copy of the input (offsets are unchanged, so the
13579
  // captures still slice the original). Inputs beyond the fast-path length
13580
  // are folded on the fly by the sequential matcher instead.
13581
  char folded[max_fast_path_pathname_length];
13582
  std::string_view probe = pathname;
13583
  bool fold_input = false;
13584
  if (compiled_.ignore_case) {
13585
    if (pathname.size() <= max_fast_path_pathname_length) {
13586
      detail::ascii_fold(pathname.data(),
13587
                         static_cast<uint32_t>(pathname.size()), folded);
13588
      probe = std::string_view(folded, pathname.size());
13589
    } else {
13590
      fold_input = true;
13591
    }
13592
  }
13593
  detail::engine_result best{};
13594
  std::vector<std::optional<std::string>> best_groups{};
13595
  detail::match_compiled(compiled_, probe.data(),
13596
                         static_cast<uint32_t>(probe.size()), best);
13597
  const uint32_t* aux = compiled_.section<uint32_t>(compiled_.aux_offset);
13598
  if (!best.within_fast_path) {
13599
    // The input exceeds a fast-path limit (length, segment count, or no
13600
    // leading '/'): the sequential fallback matches every route with
13601
    // identical priority semantics.
13602
    best = detail::engine_result{};
13603
    for (size_t i = 0; i < patterns_.size(); i++) {
13604
      consider_route(static_cast<uint32_t>(i), pathname, probe, fold_input,
13605
                     best, best_groups);
13606
    }
13607
  } else if (best.route >= 0) {
13608
    // A fast-path winner is final except for the auxiliary routes recorded
13609
    // at creation as able to outrank it (usually none).
13610
    const detail::route_record& winner =
13611
        compiled_.section<detail::route_record>(
13612
            compiled_.routes_offset)[static_cast<size_t>(best.route)];
13613
    for (uint32_t k = 0; k < winner.challenger_count; k++) {
13614
      consider_route(aux[winner.challenger_first + k], pathname, probe,
13615
                     fold_input, best, best_groups);
13616
    }
13617
  } else {
13618
    // A fast-path miss: any auxiliary route may still match.
13619
    for (uint32_t k = 0; k < compiled_.n_aux_all; k++) {
13620
      consider_route(aux[k], pathname, probe, fold_input, best, best_groups);
13621
    }
13622
  }
13623
  url_pattern_list_match_result result{};
13624
  result.route_index = best.route;
13625
  if (best.route >= 0) {
13626
    const detail::route_record& winner =
13627
        compiled_.section<detail::route_record>(
13628
            compiled_.routes_offset)[static_cast<size_t>(best.route)];
13629
    if (winner.mode == detail::route_mode::regexp) {
13630
      result.regexp_route = true;
13631
      result.regexp_groups = std::move(best_groups);
13632
    } else {
13633
      result.capture_count = best.capture_count;
13634
      result.captures_truncated = best.captures_truncated;
13635
      result.captures = best.captures;
13636
    }
13637
  }
13638
  return result;
13639
}
13640
13641
}  // namespace ada
13642
#endif  // ADA_INCLUDE_URL_PATTERN
13643
#endif  // ADA_URL_PATTERN_LIST_INL_H
13644
/* end file include/ada/url_pattern_list-inl.h */
13645
13646
// Public API
13647
/* begin file include/ada/ada_version.h */
13648
/**
13649
 * @file ada_version.h
13650
 * @brief Definitions for Ada's version number.
13651
 */
13652
#ifndef ADA_ADA_VERSION_H
13653
#define ADA_ADA_VERSION_H
13654
13655
0
#define ADA_VERSION "4.1.1"
13656
13657
namespace ada {
13658
13659
enum {
13660
  ADA_VERSION_MAJOR = 4,
13661
  ADA_VERSION_MINOR = 1,
13662
  ADA_VERSION_REVISION = 1,
13663
};
13664
13665
}  // namespace ada
13666
13667
#endif  // ADA_ADA_VERSION_H
13668
/* end file include/ada/ada_version.h */
13669
/* begin file include/ada/implementation-inl.h */
13670
/**
13671
 * @file implementation-inl.h
13672
 */
13673
#ifndef ADA_IMPLEMENTATION_INL_H
13674
#define ADA_IMPLEMENTATION_INL_H
13675
13676
13677
13678
#include <cstddef>
13679
#include <span>
13680
#include <string>
13681
#include <string_view>
13682
#include <utility>
13683
#include <variant>
13684
#include <vector>
13685
13686
namespace ada {
13687
13688
#if ADA_INCLUDE_URL_PATTERN
13689
template <url_pattern_regex::regex_concept regex_provider>
13690
ada_warn_unused tl::expected<url_pattern<regex_provider>, errors>
13691
parse_url_pattern(std::variant<std::string_view, url_pattern_init>&& input,
13692
                  const std::string_view* base_url,
13693
                  const url_pattern_options* options) {
13694
  return parser::parse_url_pattern_impl<regex_provider>(std::move(input),
13695
                                                        base_url, options);
13696
}
13697
13698
template <url_pattern_regex::regex_concept regex_provider>
13699
ada_warn_unused tl::expected<url_pattern_list<regex_provider>, errors>
13700
parse_url_pattern_list(std::span<const std::string_view> pathname_patterns,
13701
                       const std::string_view* base_url,
13702
                       const url_pattern_options* options) {
13703
  std::vector<std::string> processed;
13704
  processed.reserve(pathname_patterns.size());
13705
  for (const std::string_view pattern : pathname_patterns) {
13706
    if (base_url == nullptr) {
13707
      processed.emplace_back(pattern);
13708
      continue;
13709
    }
13710
    // With a base URL, each pattern is processed exactly as the pathname of
13711
    // a URLPatternInit would be: a relative pattern is resolved against the
13712
    // base URL's path (and an unparsable base URL is a type error).
13713
    url_pattern_init init{};
13714
    init.pathname = std::string(pattern);
13715
    init.base_url = std::string(*base_url);
13716
    auto result = url_pattern_init::process(
13717
        init, url_pattern_init::process_type::pattern);
13718
    if (!result) {
13719
      return tl::unexpected(result.error());
13720
    }
13721
    processed.push_back(std::move(result->pathname).value_or(std::string{}));
13722
  }
13723
  const bool ignore_case = options != nullptr && options->ignore_case;
13724
  auto list = url_pattern_list<regex_provider>::create(std::move(processed),
13725
                                                       ignore_case);
13726
  if (!list) {
13727
    return list;
13728
  }
13729
  // Routes outside the static/":param"/"*" subset are compiled as a
13730
  // URLPattern pathname component through the provider, with the same
13731
  // options parse_url_pattern would use (ignore_case included).
13732
  auto compile_options = url_pattern_compile_component_options::PATHNAME;
13733
  compile_options.ignore_case = ignore_case;
13734
  const url_pattern_list_detail::route_record* routes =
13735
      list->compiled_.template section<url_pattern_list_detail::route_record>(
13736
          list->compiled_.routes_offset);
13737
  for (size_t i = 0; i < list->patterns_.size(); i++) {
13738
    if (routes[i].regexp_component < 0) {
13739
      continue;
13740
    }
13741
    auto component = url_pattern_component<regex_provider>::compile(
13742
        list->patterns_[i], url_pattern_helpers::canonicalize_pathname,
13743
        compile_options);
13744
    if (!component) {
13745
      return tl::unexpected(component.error());
13746
    }
13747
    list->compiled_.group_names[i] = component->group_name_list;
13748
    list->regexp_components_.push_back(std::move(*component));
13749
  }
13750
  return list;
13751
}
13752
13753
template <url_pattern_regex::regex_concept regex_provider>
13754
ada_warn_unused tl::expected<url_pattern_list<regex_provider>, errors>
13755
parse_url_pattern_list(std::span<const url_pattern<regex_provider>> patterns) {
13756
  std::vector<std::string> texts;
13757
  texts.reserve(patterns.size());
13758
  const bool ignore_case = !patterns.empty() && patterns[0].ignore_case();
13759
  for (const url_pattern<regex_provider>& pattern : patterns) {
13760
    if (pattern.ignore_case() != ignore_case) {
13761
      return tl::unexpected(errors::type_error);  // one flag per list
13762
    }
13763
    texts.emplace_back(pattern.get_pathname());
13764
  }
13765
  auto list =
13766
      url_pattern_list<regex_provider>::create(std::move(texts), ignore_case);
13767
  if (!list) {
13768
    return list;
13769
  }
13770
  // Routes outside the subset reuse the pattern's already compiled pathname
13771
  // component: no second create_instance through the provider.
13772
  const url_pattern_list_detail::route_record* routes =
13773
      list->compiled_.template section<url_pattern_list_detail::route_record>(
13774
          list->compiled_.routes_offset);
13775
  for (size_t i = 0; i < patterns.size(); i++) {
13776
    if (routes[i].regexp_component < 0) {
13777
      continue;
13778
    }
13779
    list->compiled_.group_names[i] =
13780
        patterns[i].pathname_component.group_name_list;
13781
    list->regexp_components_.push_back(patterns[i].pathname_component);
13782
  }
13783
  return list;
13784
}
13785
#endif  // ADA_INCLUDE_URL_PATTERN
13786
13787
}  // namespace ada
13788
13789
#endif  // ADA_IMPLEMENTATION_INL_H
13790
/* end file include/ada/implementation-inl.h */
13791
13792
#endif  // ADA_H
13793
/* end file include/ada.h */