Coverage Report

Created: 2026-10-10 06:50

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-10-09 20:22:24 -0400. 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-07-12 20:34:08 -0400. 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 to_ascii / to_unicode.
154
// Bounds heap growth under untrusted input (DoS resistance). DNS wire limits
155
// are smaller; this allows long Unicode labels used in URL tests/fixtures.
156
inline constexpr size_t max_domain_input_bytes = 16384;
157
158
}  // namespace ada::idna
159
160
#endif  // ADA_IDNA_LIMITS_H
161
/* end file include/ada/idna/limits.h */
162
163
namespace ada::idna {
164
165
// Converts a domain (e.g., www.google.com) possibly containing international
166
// characters to an ascii domain (with punycode). It will not do percent
167
// decoding: percent decoding should be done prior to calling this function. We
168
// do not remove tabs and spaces, they should have been removed prior to calling
169
// this function. We also do not trim control characters. We also assume that
170
// the input is not empty. We return "" on error. Inputs longer than
171
// max_domain_input_bytes are rejected.
172
//
173
// This function may accept or even produce invalid domains (WHATWG carve-outs).
174
std::string to_ascii(std::string_view ut8_string);
175
176
// Same as to_ascii, but writes into `out` and returns false on error without
177
// relying on empty-string ambiguity.
178
[[nodiscard]] bool to_ascii(std::string_view ut8_string, std::string& out);
179
180
// Returns true if the string contains a forbidden code point according to the
181
// WHATGL URL specification:
182
// https://url.spec.whatwg.org/#forbidden-domain-code-point
183
bool contains_forbidden_domain_code_point(std::string_view ascii_string);
184
185
bool constexpr is_ascii(std::u32string_view view);
186
bool constexpr is_ascii(std::string_view view);
187
188
}  // namespace ada::idna
189
190
#endif  // ADA_IDNA_TO_ASCII_H
191
/* end file include/ada/idna/to_ascii.h */
192
/* begin file include/ada/idna/to_unicode.h */
193
#ifndef ADA_IDNA_TO_UNICODE_H
194
#define ADA_IDNA_TO_UNICODE_H
195
196
#include <string>
197
#include <string_view>
198
199
namespace ada::idna {
200
201
// UTS #46 ToUnicode. Never fails per the standard: on step failure the original
202
// label is kept. Inputs longer than max_domain_input_bytes are returned
203
// unchanged as a safety measure under untrusted input.
204
std::string to_unicode(std::string_view input);
205
206
// Writes into `out`. Returns false only if the input exceeds
207
// max_domain_input_bytes (out is left empty). Otherwise always returns true
208
// (ToUnicode does not fail).
209
[[nodiscard]] bool to_unicode(std::string_view input, std::string& out);
210
211
}  // namespace ada::idna
212
213
#endif  // ADA_IDNA_TO_UNICODE_H
214
/* end file include/ada/idna/to_unicode.h */
215
/* begin file include/ada/idna/identifier.h */
216
#ifndef ADA_IDNA_IDENTIFIER_H
217
#define ADA_IDNA_IDENTIFIER_H
218
219
#include <string>
220
#include <string_view>
221
222
namespace ada::idna {
223
224
// Verify if it is valid name code point given a Unicode code point and a
225
// boolean first: If first is true return the result of checking if code point
226
// is contained in the IdentifierStart set of code points. Otherwise return the
227
// result of checking if code point is contained in the IdentifierPart set of
228
// code points. Returns false if the input is empty or the code point is not
229
// valid. There is minimal Unicode error handling: the input should be valid
230
// UTF-8. https://urlpattern.spec.whatwg.org/#is-a-valid-name-code-point
231
bool valid_name_code_point(char32_t code_point, bool first);
232
233
}  // namespace ada::idna
234
235
#endif
236
/* end file include/ada/idna/identifier.h */
237
238
#endif
239
/* end file include/idna.h */
240
/* end file include/ada/ada_idna.h */
241
/* begin file include/ada/character_sets.h */
242
/**
243
 * @file character_sets.h
244
 * @brief Declaration of the character sets used by unicode functions.
245
 * @author Node.js
246
 * @see https://github.com/nodejs/node/blob/main/src/node_url_tables.cc
247
 */
248
#ifndef ADA_CHARACTER_SETS_H
249
#define ADA_CHARACTER_SETS_H
250
251
/* begin file include/ada/common_defs.h */
252
/**
253
 * @file common_defs.h
254
 * @brief Cross-platform compiler macros and common definitions.
255
 *
256
 * This header provides compiler-specific macros for optimization hints,
257
 * platform detection, SIMD support detection, and development/debug utilities.
258
 * It ensures consistent behavior across different compilers (GCC, Clang, MSVC).
259
 */
260
#ifndef ADA_COMMON_DEFS_H
261
#define ADA_COMMON_DEFS_H
262
263
// https://en.cppreference.com/w/cpp/feature_test#Library_features
264
// detect C++20 features
265
#include <version>
266
267
#ifdef _MSC_VER
268
#define ADA_VISUAL_STUDIO 1
269
/**
270
 * We want to differentiate carefully between
271
 * clang under visual studio and regular visual
272
 * studio.
273
 */
274
#ifdef __clang__
275
// clang under visual studio
276
#define ADA_CLANG_VISUAL_STUDIO 1
277
#else
278
// just regular visual studio (best guess)
279
#define ADA_REGULAR_VISUAL_STUDIO 1
280
#endif  // __clang__
281
#endif  // _MSC_VER
282
283
#if defined(__GNUC__)
284
// Marks a block with a name so that MCA analysis can see it.
285
#define ADA_BEGIN_DEBUG_BLOCK(name) __asm volatile("# LLVM-MCA-BEGIN " #name);
286
#define ADA_END_DEBUG_BLOCK(name) __asm volatile("# LLVM-MCA-END " #name);
287
#define ADA_DEBUG_BLOCK(name, block) \
288
  BEGIN_DEBUG_BLOCK(name);           \
289
  block;                             \
290
  END_DEBUG_BLOCK(name);
291
#else
292
#define ADA_BEGIN_DEBUG_BLOCK(name)
293
#define ADA_END_DEBUG_BLOCK(name)
294
#define ADA_DEBUG_BLOCK(name, block)
295
#endif
296
297
// Align to N-byte boundary
298
#define ADA_ROUNDUP_N(a, n) (((a) + ((n) - 1)) & ~((n) - 1))
299
#define ADA_ROUNDDOWN_N(a, n) ((a) & ~((n) - 1))
300
301
#define ADA_ISALIGNED_N(ptr, n) (((uintptr_t)(ptr) & ((n) - 1)) == 0)
302
303
#if defined(ADA_REGULAR_VISUAL_STUDIO)
304
305
#define ada_really_inline __forceinline
306
#define ada_never_inline __declspec(noinline)
307
308
#define ada_unused
309
#define ada_warn_unused
310
311
#define ADA_PUSH_DISABLE_WARNINGS __pragma(warning(push))
312
#define ADA_PUSH_DISABLE_ALL_WARNINGS __pragma(warning(push, 0))
313
#define ADA_DISABLE_VS_WARNING(WARNING_NUMBER) \
314
  __pragma(warning(disable : WARNING_NUMBER))
315
// Get rid of Intellisense-only warnings (Code Analysis)
316
// Though __has_include is C++17, it is supported in Visual Studio 2017 or
317
// better (_MSC_VER>=1910).
318
#ifdef __has_include
319
#if __has_include(<CppCoreCheck\Warnings.h>)
320
#include <CppCoreCheck\Warnings.h>
321
#define ADA_DISABLE_UNDESIRED_WARNINGS \
322
  ADA_DISABLE_VS_WARNING(ALL_CPPCORECHECK_WARNINGS)
323
#endif
324
#endif
325
326
#ifndef ADA_DISABLE_UNDESIRED_WARNINGS
327
#define ADA_DISABLE_UNDESIRED_WARNINGS
328
#endif
329
330
#define ADA_DISABLE_DEPRECATED_WARNING ADA_DISABLE_VS_WARNING(4996)
331
#define ADA_DISABLE_STRICT_OVERFLOW_WARNING
332
#define ADA_POP_DISABLE_WARNINGS __pragma(warning(pop))
333
334
#else  // ADA_REGULAR_VISUAL_STUDIO
335
336
#define ada_really_inline inline __attribute__((always_inline))
337
#define ada_never_inline inline __attribute__((noinline))
338
339
#define ada_unused __attribute__((unused))
340
#define ada_warn_unused __attribute__((warn_unused_result))
341
342
#define ADA_PUSH_DISABLE_WARNINGS _Pragma("GCC diagnostic push")
343
// gcc doesn't seem to disable all warnings with all and extra, add warnings
344
// here as necessary
345
#define ADA_PUSH_DISABLE_ALL_WARNINGS               \
346
  ADA_PUSH_DISABLE_WARNINGS                         \
347
  ADA_DISABLE_GCC_WARNING("-Weffc++")               \
348
  ADA_DISABLE_GCC_WARNING("-Wall")                  \
349
  ADA_DISABLE_GCC_WARNING("-Wconversion")           \
350
  ADA_DISABLE_GCC_WARNING("-Wextra")                \
351
  ADA_DISABLE_GCC_WARNING("-Wattributes")           \
352
  ADA_DISABLE_GCC_WARNING("-Wimplicit-fallthrough") \
353
  ADA_DISABLE_GCC_WARNING("-Wnon-virtual-dtor")     \
354
  ADA_DISABLE_GCC_WARNING("-Wreturn-type")          \
355
  ADA_DISABLE_GCC_WARNING("-Wshadow")               \
356
  ADA_DISABLE_GCC_WARNING("-Wunused-parameter")     \
357
  ADA_DISABLE_GCC_WARNING("-Wunused-variable")      \
358
  ADA_DISABLE_GCC_WARNING("-Wsign-compare")
359
#define ADA_PRAGMA(P) _Pragma(#P)
360
#define ADA_DISABLE_GCC_WARNING(WARNING) \
361
  ADA_PRAGMA(GCC diagnostic ignored WARNING)
362
#if defined(ADA_CLANG_VISUAL_STUDIO)
363
#define ADA_DISABLE_UNDESIRED_WARNINGS \
364
  ADA_DISABLE_GCC_WARNING("-Wmicrosoft-include")
365
#else
366
#define ADA_DISABLE_UNDESIRED_WARNINGS
367
#endif
368
#define ADA_DISABLE_DEPRECATED_WARNING \
369
  ADA_DISABLE_GCC_WARNING("-Wdeprecated-declarations")
370
#define ADA_DISABLE_STRICT_OVERFLOW_WARNING \
371
  ADA_DISABLE_GCC_WARNING("-Wstrict-overflow")
372
#define ADA_POP_DISABLE_WARNINGS _Pragma("GCC diagnostic pop")
373
374
#endif  // MSC_VER
375
376
#if defined(ADA_VISUAL_STUDIO)
377
/**
378
 * It does not matter here whether you are using
379
 * the regular visual studio or clang under visual
380
 * studio.
381
 */
382
#if ADA_USING_LIBRARY
383
#define ADA_DLLIMPORTEXPORT __declspec(dllimport)
384
#else
385
#define ADA_DLLIMPORTEXPORT __declspec(dllexport)
386
#endif
387
#else
388
#define ADA_DLLIMPORTEXPORT
389
#endif
390
391
/// If EXPR is an error, returns it.
392
#define ADA_TRY(EXPR)   \
393
  {                     \
394
    auto _err = (EXPR); \
395
    if (_err) {         \
396
      return _err;      \
397
    }                   \
398
  }
399
400
// __has_cpp_attribute is part of C++20
401
#if !defined(__has_cpp_attribute)
402
#define __has_cpp_attribute(x) 0
403
#endif
404
405
#if __has_cpp_attribute(gnu::noinline)
406
#define ADA_ATTRIBUTE_NOINLINE [[gnu::noinline]]
407
#else
408
#define ADA_ATTRIBUTE_NOINLINE
409
#endif
410
411
namespace ada {
412
0
[[noreturn]] inline void unreachable() {
413
0
#ifdef __GNUC__
414
0
  __builtin_unreachable();
415
#elif defined(_MSC_VER)
416
  __assume(false);
417
#else
418
#endif
419
0
}
420
}  // namespace ada
421
422
// Unless the programmer has already set ADA_DEVELOPMENT_CHECKS,
423
// we want to set it under debug builds. We detect a debug build
424
// under Visual Studio when the _DEBUG macro is set. Under the other
425
// compilers, we use the fact that they define __OPTIMIZE__ whenever
426
// they allow optimizations.
427
// It is possible that this could miss some cases where ADA_DEVELOPMENT_CHECKS
428
// is helpful, but the programmer can set the macro ADA_DEVELOPMENT_CHECKS.
429
// It could also wrongly set ADA_DEVELOPMENT_CHECKS (e.g., if the programmer
430
// sets _DEBUG in a release build under Visual Studio, or if some compiler fails
431
// to set the __OPTIMIZE__ macro).
432
#if !defined(ADA_DEVELOPMENT_CHECKS) && !defined(NDEBUG)
433
#ifdef _MSC_VER
434
// Visual Studio seems to set _DEBUG for debug builds.
435
#ifdef _DEBUG
436
#define ADA_DEVELOPMENT_CHECKS 1
437
#endif  // _DEBUG
438
#else   // _MSC_VER
439
// All other compilers appear to set __OPTIMIZE__ to a positive integer
440
// when the compiler is optimizing.
441
#ifndef __OPTIMIZE__
442
#define ADA_DEVELOPMENT_CHECKS 1
443
#endif  // __OPTIMIZE__
444
#endif  // _MSC_VER
445
#endif  // ADA_DEVELOPMENT_CHECKS
446
447
#define ADA_STR(x) #x
448
449
#if ADA_DEVELOPMENT_CHECKS
450
#define ADA_REQUIRE(EXPR) \
451
  {                       \
452
    if (!(EXPR) { abort(); }) }
453
454
#define ADA_FAIL(MESSAGE)                            \
455
  do {                                               \
456
    std::cerr << "FAIL: " << (MESSAGE) << std::endl; \
457
    abort();                                         \
458
  } while (0);
459
#define ADA_ASSERT_EQUAL(LHS, RHS, MESSAGE)                                    \
460
  do {                                                                         \
461
    if (LHS != RHS) {                                                          \
462
      std::cerr << "Mismatch: '" << LHS << "' - '" << RHS << "'" << std::endl; \
463
      ADA_FAIL(MESSAGE);                                                       \
464
    }                                                                          \
465
  } while (0);
466
#define ADA_ASSERT_TRUE(COND)                                               \
467
  do {                                                                      \
468
    if (!(COND)) {                                                          \
469
      std::cerr << "Assert at line " << __LINE__ << " of file " << __FILE__ \
470
                << std::endl;                                               \
471
      ADA_FAIL(ADA_STR(COND));                                              \
472
    }                                                                       \
473
  } while (0);
474
#else
475
#define ADA_FAIL(MESSAGE)
476
#define ADA_ASSERT_EQUAL(LHS, RHS, MESSAGE)
477
#define ADA_ASSERT_TRUE(COND)
478
#endif
479
480
#ifdef ADA_VISUAL_STUDIO
481
#define ADA_ASSUME(COND) __assume(COND)
482
#else
483
#define ADA_ASSUME(COND)       \
484
  do {                         \
485
    if (!(COND)) {             \
486
      __builtin_unreachable(); \
487
    }                          \
488
  } while (0)
489
#endif
490
491
#if defined(__SSSE3__)
492
#define ADA_SSSE3 1
493
#endif
494
495
#if defined(__SSE2__) || defined(__x86_64__) || defined(__x86_64) || \
496
    (defined(_M_AMD64) || defined(_M_X64) ||                         \
497
     (defined(_M_IX86_FP) && _M_IX86_FP == 2))
498
#define ADA_SSE2 1
499
#endif
500
501
// AVX-512 byte/word ops + 128/256-bit vectors of AVX-512 instructions.
502
// Used for optional high-performance IP address parsing kernels.
503
#if defined(__AVX512BW__) && defined(__AVX512VL__)
504
#define ADA_AVX512 1
505
#endif
506
507
#if defined(__aarch64__) || defined(_M_ARM64)
508
#define ADA_NEON 1
509
#endif
510
511
#if defined(__loongarch_sx)
512
#define ADA_LSX 1
513
#endif
514
515
#if defined(__riscv_v) && __riscv_v_intrinsic >= 11000
516
// Support RVV intrinsics v0.11 and above
517
#define ADA_RVV 1
518
#endif
519
520
#ifndef __has_cpp_attribute
521
#define ada_lifetime_bound
522
#elif __has_cpp_attribute(msvc::lifetimebound)
523
#define ada_lifetime_bound [[msvc::lifetimebound]]
524
#elif __has_cpp_attribute(clang::lifetimebound)
525
#define ada_lifetime_bound [[clang::lifetimebound]]
526
#elif __has_cpp_attribute(lifetimebound)
527
#define ada_lifetime_bound [[lifetimebound]]
528
#else
529
#define ada_lifetime_bound
530
#endif
531
532
#ifdef __cpp_lib_format
533
#if __cpp_lib_format >= 202110L
534
#include <format>
535
#define ADA_HAS_FORMAT 1
536
#endif
537
#endif
538
539
#ifndef ADA_INCLUDE_URL_PATTERN
540
#define ADA_INCLUDE_URL_PATTERN 1
541
#endif  // ADA_INCLUDE_URL_PATTERN
542
543
// When set, NEON all-zero tests use an integer compare instead of
544
// reinterpreting the bits as a double. The double compare is faster (no
545
// GPR transfer) but is incorrect if flush-to-zero is enabled.
546
#ifndef ADA_NEON_SAFE_ZERO_CHECK
547
#define ADA_NEON_SAFE_ZERO_CHECK 0
548
#endif  // ADA_NEON_SAFE_ZERO_CHECK
549
550
#endif  // ADA_COMMON_DEFS_H
551
/* end file include/ada/common_defs.h */
552
#include <cstdint>
553
554
/**
555
 * These functions are not part of our public API and may
556
 * change at any time.
557
 * @private
558
 * @namespace ada::character_sets
559
 * @brief Includes the definitions for unicode character sets.
560
 */
561
namespace ada::character_sets {
562
ada_really_inline constexpr bool bit_at(const uint8_t a[], uint8_t i);
563
}  // namespace ada::character_sets
564
565
#endif  // ADA_CHARACTER_SETS_H
566
/* end file include/ada/character_sets.h */
567
/* begin file include/ada/character_sets-inl.h */
568
/**
569
 * @file character_sets-inl.h
570
 * @brief Definitions of the character sets used by unicode functions.
571
 * @author Node.js
572
 * @see https://github.com/nodejs/node/blob/main/src/node_url_tables.cc
573
 */
574
#ifndef ADA_CHARACTER_SETS_INL_H
575
#define ADA_CHARACTER_SETS_INL_H
576
577
578
/**
579
 * These functions are not part of our public API and may
580
 * change at any time.
581
 * @private
582
 */
583
namespace ada::character_sets {
584
585
constexpr char hex[1024] =
586
    "%00\0%01\0%02\0%03\0%04\0%05\0%06\0%07\0"
587
    "%08\0%09\0%0A\0%0B\0%0C\0%0D\0%0E\0%0F\0"
588
    "%10\0%11\0%12\0%13\0%14\0%15\0%16\0%17\0"
589
    "%18\0%19\0%1A\0%1B\0%1C\0%1D\0%1E\0%1F\0"
590
    "%20\0%21\0%22\0%23\0%24\0%25\0%26\0%27\0"
591
    "%28\0%29\0%2A\0%2B\0%2C\0%2D\0%2E\0%2F\0"
592
    "%30\0%31\0%32\0%33\0%34\0%35\0%36\0%37\0"
593
    "%38\0%39\0%3A\0%3B\0%3C\0%3D\0%3E\0%3F\0"
594
    "%40\0%41\0%42\0%43\0%44\0%45\0%46\0%47\0"
595
    "%48\0%49\0%4A\0%4B\0%4C\0%4D\0%4E\0%4F\0"
596
    "%50\0%51\0%52\0%53\0%54\0%55\0%56\0%57\0"
597
    "%58\0%59\0%5A\0%5B\0%5C\0%5D\0%5E\0%5F\0"
598
    "%60\0%61\0%62\0%63\0%64\0%65\0%66\0%67\0"
599
    "%68\0%69\0%6A\0%6B\0%6C\0%6D\0%6E\0%6F\0"
600
    "%70\0%71\0%72\0%73\0%74\0%75\0%76\0%77\0"
601
    "%78\0%79\0%7A\0%7B\0%7C\0%7D\0%7E\0%7F\0"
602
    "%80\0%81\0%82\0%83\0%84\0%85\0%86\0%87\0"
603
    "%88\0%89\0%8A\0%8B\0%8C\0%8D\0%8E\0%8F\0"
604
    "%90\0%91\0%92\0%93\0%94\0%95\0%96\0%97\0"
605
    "%98\0%99\0%9A\0%9B\0%9C\0%9D\0%9E\0%9F\0"
606
    "%A0\0%A1\0%A2\0%A3\0%A4\0%A5\0%A6\0%A7\0"
607
    "%A8\0%A9\0%AA\0%AB\0%AC\0%AD\0%AE\0%AF\0"
608
    "%B0\0%B1\0%B2\0%B3\0%B4\0%B5\0%B6\0%B7\0"
609
    "%B8\0%B9\0%BA\0%BB\0%BC\0%BD\0%BE\0%BF\0"
610
    "%C0\0%C1\0%C2\0%C3\0%C4\0%C5\0%C6\0%C7\0"
611
    "%C8\0%C9\0%CA\0%CB\0%CC\0%CD\0%CE\0%CF\0"
612
    "%D0\0%D1\0%D2\0%D3\0%D4\0%D5\0%D6\0%D7\0"
613
    "%D8\0%D9\0%DA\0%DB\0%DC\0%DD\0%DE\0%DF\0"
614
    "%E0\0%E1\0%E2\0%E3\0%E4\0%E5\0%E6\0%E7\0"
615
    "%E8\0%E9\0%EA\0%EB\0%EC\0%ED\0%EE\0%EF\0"
616
    "%F0\0%F1\0%F2\0%F3\0%F4\0%F5\0%F6\0%F7\0"
617
    "%F8\0%F9\0%FA\0%FB\0%FC\0%FD\0%FE\0%FF";
618
619
constexpr uint8_t C0_CONTROL_PERCENT_ENCODE[32] = {
620
    // 00     01     02     03     04     05     06     07
621
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
622
    // 08     09     0A     0B     0C     0D     0E     0F
623
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
624
    // 10     11     12     13     14     15     16     17
625
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
626
    // 18     19     1A     1B     1C     1D     1E     1F
627
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
628
    // 20     21     22     23     24     25     26     27
629
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
630
    // 28     29     2A     2B     2C     2D     2E     2F
631
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
632
    // 30     31     32     33     34     35     36     37
633
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
634
    // 38     39     3A     3B     3C     3D     3E     3F
635
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
636
    // 40     41     42     43     44     45     46     47
637
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
638
    // 48     49     4A     4B     4C     4D     4E     4F
639
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
640
    // 50     51     52     53     54     55     56     57
641
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
642
    // 58     59     5A     5B     5C     5D     5E     5F
643
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
644
    // 60     61     62     63     64     65     66     67
645
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
646
    // 68     69     6A     6B     6C     6D     6E     6F
647
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
648
    // 70     71     72     73     74     75     76     77
649
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
650
    // 78     79     7A     7B     7C     7D     7E     7F
651
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x80,
652
    // 80     81     82     83     84     85     86     87
653
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
654
    // 88     89     8A     8B     8C     8D     8E     8F
655
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
656
    // 90     91     92     93     94     95     96     97
657
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
658
    // 98     99     9A     9B     9C     9D     9E     9F
659
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
660
    // A0     A1     A2     A3     A4     A5     A6     A7
661
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
662
    // A8     A9     AA     AB     AC     AD     AE     AF
663
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
664
    // B0     B1     B2     B3     B4     B5     B6     B7
665
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
666
    // B8     B9     BA     BB     BC     BD     BE     BF
667
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
668
    // C0     C1     C2     C3     C4     C5     C6     C7
669
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
670
    // C8     C9     CA     CB     CC     CD     CE     CF
671
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
672
    // D0     D1     D2     D3     D4     D5     D6     D7
673
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
674
    // D8     D9     DA     DB     DC     DD     DE     DF
675
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
676
    // E0     E1     E2     E3     E4     E5     E6     E7
677
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
678
    // E8     E9     EA     EB     EC     ED     EE     EF
679
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
680
    // F0     F1     F2     F3     F4     F5     F6     F7
681
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
682
    // F8     F9     FA     FB     FC     FD     FE     FF
683
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80};
684
685
constexpr uint8_t SPECIAL_QUERY_PERCENT_ENCODE[32] = {
686
    // 00     01     02     03     04     05     06     07
687
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
688
    // 08     09     0A     0B     0C     0D     0E     0F
689
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
690
    // 10     11     12     13     14     15     16     17
691
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
692
    // 18     19     1A     1B     1C     1D     1E     1F
693
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
694
    // 20     21     22     23     24     25     26     27
695
    0x01 | 0x00 | 0x04 | 0x08 | 0x00 | 0x00 | 0x00 | 0x80,
696
    // 28     29     2A     2B     2C     2D     2E     2F
697
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
698
    // 30     31     32     33     34     35     36     37
699
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
700
    // 38     39     3A     3B     3C     3D     3E     3F
701
    0x00 | 0x00 | 0x00 | 0x00 | 0x10 | 0x00 | 0x40 | 0x00,
702
    // 40     41     42     43     44     45     46     47
703
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
704
    // 48     49     4A     4B     4C     4D     4E     4F
705
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
706
    // 50     51     52     53     54     55     56     57
707
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
708
    // 58     59     5A     5B     5C     5D     5E     5F
709
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
710
    // 60     61     62     63     64     65     66     67
711
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
712
    // 68     69     6A     6B     6C     6D     6E     6F
713
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
714
    // 70     71     72     73     74     75     76     77
715
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
716
    // 78     79     7A     7B     7C     7D     7E     7F
717
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x80,
718
    // 80     81     82     83     84     85     86     87
719
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
720
    // 88     89     8A     8B     8C     8D     8E     8F
721
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
722
    // 90     91     92     93     94     95     96     97
723
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
724
    // 98     99     9A     9B     9C     9D     9E     9F
725
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
726
    // A0     A1     A2     A3     A4     A5     A6     A7
727
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
728
    // A8     A9     AA     AB     AC     AD     AE     AF
729
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
730
    // B0     B1     B2     B3     B4     B5     B6     B7
731
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
732
    // B8     B9     BA     BB     BC     BD     BE     BF
733
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
734
    // C0     C1     C2     C3     C4     C5     C6     C7
735
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
736
    // C8     C9     CA     CB     CC     CD     CE     CF
737
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
738
    // D0     D1     D2     D3     D4     D5     D6     D7
739
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
740
    // D8     D9     DA     DB     DC     DD     DE     DF
741
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
742
    // E0     E1     E2     E3     E4     E5     E6     E7
743
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
744
    // E8     E9     EA     EB     EC     ED     EE     EF
745
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
746
    // F0     F1     F2     F3     F4     F5     F6     F7
747
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
748
    // F8     F9     FA     FB     FC     FD     FE     FF
749
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80};
750
751
constexpr uint8_t QUERY_PERCENT_ENCODE[32] = {
752
    // 00     01     02     03     04     05     06     07
753
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
754
    // 08     09     0A     0B     0C     0D     0E     0F
755
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
756
    // 10     11     12     13     14     15     16     17
757
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
758
    // 18     19     1A     1B     1C     1D     1E     1F
759
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
760
    // 20     21     22     23     24     25     26     27
761
    0x01 | 0x00 | 0x04 | 0x08 | 0x00 | 0x00 | 0x00 | 0x00,
762
    // 28     29     2A     2B     2C     2D     2E     2F
763
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
764
    // 30     31     32     33     34     35     36     37
765
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
766
    // 38     39     3A     3B     3C     3D     3E     3F
767
    0x00 | 0x00 | 0x00 | 0x00 | 0x10 | 0x00 | 0x40 | 0x00,
768
    // 40     41     42     43     44     45     46     47
769
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
770
    // 48     49     4A     4B     4C     4D     4E     4F
771
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
772
    // 50     51     52     53     54     55     56     57
773
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
774
    // 58     59     5A     5B     5C     5D     5E     5F
775
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
776
    // 60     61     62     63     64     65     66     67
777
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
778
    // 68     69     6A     6B     6C     6D     6E     6F
779
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
780
    // 70     71     72     73     74     75     76     77
781
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
782
    // 78     79     7A     7B     7C     7D     7E     7F
783
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x80,
784
    // 80     81     82     83     84     85     86     87
785
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
786
    // 88     89     8A     8B     8C     8D     8E     8F
787
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
788
    // 90     91     92     93     94     95     96     97
789
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
790
    // 98     99     9A     9B     9C     9D     9E     9F
791
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
792
    // A0     A1     A2     A3     A4     A5     A6     A7
793
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
794
    // A8     A9     AA     AB     AC     AD     AE     AF
795
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
796
    // B0     B1     B2     B3     B4     B5     B6     B7
797
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
798
    // B8     B9     BA     BB     BC     BD     BE     BF
799
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
800
    // C0     C1     C2     C3     C4     C5     C6     C7
801
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
802
    // C8     C9     CA     CB     CC     CD     CE     CF
803
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
804
    // D0     D1     D2     D3     D4     D5     D6     D7
805
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
806
    // D8     D9     DA     DB     DC     DD     DE     DF
807
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
808
    // E0     E1     E2     E3     E4     E5     E6     E7
809
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
810
    // E8     E9     EA     EB     EC     ED     EE     EF
811
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
812
    // F0     F1     F2     F3     F4     F5     F6     F7
813
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
814
    // F8     F9     FA     FB     FC     FD     FE     FF
815
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80};
816
817
constexpr uint8_t FRAGMENT_PERCENT_ENCODE[32] = {
818
    // 00     01     02     03     04     05     06     07
819
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
820
    // 08     09     0A     0B     0C     0D     0E     0F
821
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
822
    // 10     11     12     13     14     15     16     17
823
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
824
    // 18     19     1A     1B     1C     1D     1E     1F
825
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
826
    // 20     21     22     23     24     25     26     27
827
    0x01 | 0x00 | 0x04 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
828
    // 28     29     2A     2B     2C     2D     2E     2F
829
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
830
    // 30     31     32     33     34     35     36     37
831
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
832
    // 38     39     3A     3B     3C     3D     3E     3F
833
    0x00 | 0x00 | 0x00 | 0x00 | 0x10 | 0x00 | 0x40 | 0x00,
834
    // 40     41     42     43     44     45     46     47
835
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
836
    // 48     49     4A     4B     4C     4D     4E     4F
837
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
838
    // 50     51     52     53     54     55     56     57
839
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
840
    // 58     59     5A     5B     5C     5D     5E     5F
841
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
842
    // 60     61     62     63     64     65     66     67
843
    0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
844
    // 68     69     6A     6B     6C     6D     6E     6F
845
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
846
    // 70     71     72     73     74     75     76     77
847
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
848
    // 78     79     7A     7B     7C     7D     7E     7F
849
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x80,
850
    // 80     81     82     83     84     85     86     87
851
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
852
    // 88     89     8A     8B     8C     8D     8E     8F
853
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
854
    // 90     91     92     93     94     95     96     97
855
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
856
    // 98     99     9A     9B     9C     9D     9E     9F
857
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
858
    // A0     A1     A2     A3     A4     A5     A6     A7
859
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
860
    // A8     A9     AA     AB     AC     AD     AE     AF
861
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
862
    // B0     B1     B2     B3     B4     B5     B6     B7
863
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
864
    // B8     B9     BA     BB     BC     BD     BE     BF
865
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
866
    // C0     C1     C2     C3     C4     C5     C6     C7
867
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
868
    // C8     C9     CA     CB     CC     CD     CE     CF
869
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
870
    // D0     D1     D2     D3     D4     D5     D6     D7
871
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
872
    // D8     D9     DA     DB     DC     DD     DE     DF
873
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
874
    // E0     E1     E2     E3     E4     E5     E6     E7
875
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
876
    // E8     E9     EA     EB     EC     ED     EE     EF
877
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
878
    // F0     F1     F2     F3     F4     F5     F6     F7
879
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
880
    // F8     F9     FA     FB     FC     FD     FE     FF
881
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80};
882
883
constexpr uint8_t USERINFO_PERCENT_ENCODE[32] = {
884
    // 00     01     02     03     04     05     06     07
885
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
886
    // 08     09     0A     0B     0C     0D     0E     0F
887
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
888
    // 10     11     12     13     14     15     16     17
889
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
890
    // 18     19     1A     1B     1C     1D     1E     1F
891
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
892
    // 20     21     22     23     24     25     26     27
893
    0x01 | 0x00 | 0x04 | 0x08 | 0x00 | 0x00 | 0x00 | 0x00,
894
    // 28     29     2A     2B     2C     2D     2E     2F
895
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x80,
896
    // 30     31     32     33     34     35     36     37
897
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
898
    // 38     39     3A     3B     3C     3D     3E     3F
899
    0x00 | 0x00 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
900
    // 40     41     42     43     44     45     46     47
901
    0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
902
    // 48     49     4A     4B     4C     4D     4E     4F
903
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
904
    // 50     51     52     53     54     55     56     57
905
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
906
    // 58     59     5A     5B     5C     5D     5E     5F
907
    0x00 | 0x00 | 0x00 | 0x08 | 0x10 | 0x20 | 0x40 | 0x00,
908
    // 60     61     62     63     64     65     66     67
909
    0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
910
    // 68     69     6A     6B     6C     6D     6E     6F
911
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
912
    // 70     71     72     73     74     75     76     77
913
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
914
    // 78     79     7A     7B     7C     7D     7E     7F
915
    0x00 | 0x00 | 0x00 | 0x08 | 0x10 | 0x20 | 0x00 | 0x80,
916
    // 80     81     82     83     84     85     86     87
917
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
918
    // 88     89     8A     8B     8C     8D     8E     8F
919
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
920
    // 90     91     92     93     94     95     96     97
921
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
922
    // 98     99     9A     9B     9C     9D     9E     9F
923
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
924
    // A0     A1     A2     A3     A4     A5     A6     A7
925
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
926
    // A8     A9     AA     AB     AC     AD     AE     AF
927
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
928
    // B0     B1     B2     B3     B4     B5     B6     B7
929
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
930
    // B8     B9     BA     BB     BC     BD     BE     BF
931
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
932
    // C0     C1     C2     C3     C4     C5     C6     C7
933
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
934
    // C8     C9     CA     CB     CC     CD     CE     CF
935
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
936
    // D0     D1     D2     D3     D4     D5     D6     D7
937
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
938
    // D8     D9     DA     DB     DC     DD     DE     DF
939
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
940
    // E0     E1     E2     E3     E4     E5     E6     E7
941
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
942
    // E8     E9     EA     EB     EC     ED     EE     EF
943
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
944
    // F0     F1     F2     F3     F4     F5     F6     F7
945
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
946
    // F8     F9     FA     FB     FC     FD     FE     FF
947
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80};
948
949
constexpr uint8_t PATH_PERCENT_ENCODE[32] = {
950
    // 00     01     02     03     04     05     06     07
951
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
952
    // 08     09     0A     0B     0C     0D     0E     0F
953
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
954
    // 10     11     12     13     14     15     16     17
955
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
956
    // 18     19     1A     1B     1C     1D     1E     1F
957
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
958
    // 20     21     22     23     24     25     26     27
959
    0x01 | 0x00 | 0x04 | 0x08 | 0x00 | 0x00 | 0x00 | 0x00,
960
    // 28     29     2A     2B     2C     2D     2E     2F
961
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
962
    // 30     31     32     33     34     35     36     37
963
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
964
    // 38     39     3A     3B     3C     3D     3E     3F
965
    0x00 | 0x00 | 0x00 | 0x00 | 0x10 | 0x00 | 0x40 | 0x80,
966
    // 40     41     42     43     44     45     46     47
967
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
968
    // 48     49     4A     4B     4C     4D     4E     4F
969
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
970
    // 50     51     52     53     54     55     56     57
971
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
972
    // 58     59     5A     5B     5C     5D     5E     5F
973
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x40 | 0x00,
974
    // 60     61     62     63     64     65     66     67
975
    0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
976
    // 68     69     6A     6B     6C     6D     6E     6F
977
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
978
    // 70     71     72     73     74     75     76     77
979
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
980
    // 78     79     7A     7B     7C     7D     7E     7F
981
    0x00 | 0x00 | 0x00 | 0x08 | 0x00 | 0x20 | 0x00 | 0x80,
982
    // 80     81     82     83     84     85     86     87
983
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
984
    // 88     89     8A     8B     8C     8D     8E     8F
985
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
986
    // 90     91     92     93     94     95     96     97
987
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
988
    // 98     99     9A     9B     9C     9D     9E     9F
989
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
990
    // A0     A1     A2     A3     A4     A5     A6     A7
991
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
992
    // A8     A9     AA     AB     AC     AD     AE     AF
993
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
994
    // B0     B1     B2     B3     B4     B5     B6     B7
995
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
996
    // B8     B9     BA     BB     BC     BD     BE     BF
997
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
998
    // C0     C1     C2     C3     C4     C5     C6     C7
999
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1000
    // C8     C9     CA     CB     CC     CD     CE     CF
1001
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1002
    // D0     D1     D2     D3     D4     D5     D6     D7
1003
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1004
    // D8     D9     DA     DB     DC     DD     DE     DF
1005
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1006
    // E0     E1     E2     E3     E4     E5     E6     E7
1007
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1008
    // E8     E9     EA     EB     EC     ED     EE     EF
1009
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1010
    // F0     F1     F2     F3     F4     F5     F6     F7
1011
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1012
    // F8     F9     FA     FB     FC     FD     FE     FF
1013
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80};
1014
1015
constexpr uint8_t WWW_FORM_URLENCODED_PERCENT_ENCODE[32] = {
1016
    // 00     01     02     03     04     05     06     07
1017
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1018
    // 08     09     0A     0B     0C     0D     0E     0F
1019
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1020
    // 10     11     12     13     14     15     16     17
1021
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1022
    // 18     19     1A     1B     1C     1D     1E     1F
1023
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1024
    // 20     21     22     23     24     25     26     27
1025
    0x00 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1026
    // 28     29     2A     2B     2C     2D     2E     2F
1027
    0x01 | 0x02 | 0x00 | 0x08 | 0x10 | 0x00 | 0x00 | 0x80,
1028
    // 30     31     32     33     34     35     36     37
1029
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
1030
    // 38     39     3A     3B     3C     3D     3E     3F
1031
    0x00 | 0x00 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1032
    // 40     41     42     43     44     45     46     47
1033
    0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
1034
    // 48     49     4A     4B     4C     4D     4E     4F
1035
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
1036
    // 50     51     52     53     54     55     56     57
1037
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
1038
    // 58     59     5A     5B     5C     5D     5E     5F
1039
    0x00 | 0x00 | 0x00 | 0x08 | 0x10 | 0x20 | 0x40 | 0x00,
1040
    // 60     61     62     63     64     65     66     67
1041
    0x01 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
1042
    // 68     69     6A     6B     6C     6D     6E     6F
1043
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
1044
    // 70     71     72     73     74     75     76     77
1045
    0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00 | 0x00,
1046
    // 78     79     7A     7B     7C     7D     7E     7F
1047
    0x00 | 0x00 | 0x00 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1048
    // 80     81     82     83     84     85     86     87
1049
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1050
    // 88     89     8A     8B     8C     8D     8E     8F
1051
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1052
    // 90     91     92     93     94     95     96     97
1053
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1054
    // 98     99     9A     9B     9C     9D     9E     9F
1055
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1056
    // A0     A1     A2     A3     A4     A5     A6     A7
1057
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1058
    // A8     A9     AA     AB     AC     AD     AE     AF
1059
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1060
    // B0     B1     B2     B3     B4     B5     B6     B7
1061
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1062
    // B8     B9     BA     BB     BC     BD     BE     BF
1063
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1064
    // C0     C1     C2     C3     C4     C5     C6     C7
1065
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1066
    // C8     C9     CA     CB     CC     CD     CE     CF
1067
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1068
    // D0     D1     D2     D3     D4     D5     D6     D7
1069
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1070
    // D8     D9     DA     DB     DC     DD     DE     DF
1071
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1072
    // E0     E1     E2     E3     E4     E5     E6     E7
1073
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1074
    // E8     E9     EA     EB     EC     ED     EE     EF
1075
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1076
    // F0     F1     F2     F3     F4     F5     F6     F7
1077
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80,
1078
    // F8     F9     FA     FB     FC     FD     FE     FF
1079
    0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80};
1080
1081
18.8M
ada_really_inline constexpr bool bit_at(const uint8_t a[], const uint8_t i) {
1082
18.8M
  return !!(a[i >> 3] & (1 << (i & 7)));
1083
18.8M
}
1084
1085
}  // namespace ada::character_sets
1086
1087
#endif  // ADA_CHARACTER_SETS_INL_H
1088
/* end file include/ada/character_sets-inl.h */
1089
/* begin file include/ada/checkers-inl.h */
1090
/**
1091
 * @file checkers-inl.h
1092
 * @brief Definitions for URL specific checkers used within Ada.
1093
 */
1094
#ifndef ADA_CHECKERS_INL_H
1095
#define ADA_CHECKERS_INL_H
1096
1097
#include <bit>
1098
#include <cstdint>
1099
#include <string_view>
1100
/* begin file include/ada/checkers.h */
1101
/**
1102
 * @file checkers.h
1103
 * @brief Declarations for URL specific checkers used within Ada.
1104
 */
1105
#ifndef ADA_CHECKERS_H
1106
#define ADA_CHECKERS_H
1107
1108
1109
#include <cstring>
1110
#include <string_view>
1111
1112
/**
1113
 * These functions are not part of our public API and may
1114
 * change at any time.
1115
 * @private
1116
 * @namespace ada::checkers
1117
 * @brief Includes the definitions for validation functions
1118
 */
1119
namespace ada::checkers {
1120
1121
/**
1122
 * @private
1123
 * Assuming that x is an ASCII letter, this function returns the lower case
1124
 * equivalent.
1125
 * @details More likely to be inlined by the compiler and constexpr.
1126
 */
1127
constexpr char to_lower(char x) noexcept;
1128
1129
/**
1130
 * @private
1131
 * Returns true if the character is an ASCII letter. Equivalent to std::isalpha
1132
 * but more likely to be inlined by the compiler.
1133
 *
1134
 * @attention std::isalpha is not constexpr generally.
1135
 */
1136
constexpr bool is_alpha(char x) noexcept;
1137
1138
/**
1139
 * @private
1140
 * Check whether x is an ASCII digit. More likely to be inlined than
1141
 * std::isdigit.
1142
 */
1143
constexpr bool is_digit(char x) noexcept;
1144
1145
/**
1146
 * @private
1147
 * @details A string starts with a Windows drive letter if all of the following
1148
 * are true:
1149
 *
1150
 *   - its length is greater than or equal to 2
1151
 *   - its first two code points are a Windows drive letter
1152
 *   - its length is 2 or its third code point is U+002F (/), U+005C (\), U+003F
1153
 * (?), or U+0023 (#).
1154
 *
1155
 * https://url.spec.whatwg.org/#start-with-a-windows-drive-letter
1156
 */
1157
inline constexpr bool is_windows_drive_letter(std::string_view input) noexcept;
1158
1159
/**
1160
 * @private
1161
 * @details A normalized Windows drive letter is a Windows drive letter of which
1162
 * the second code point is U+003A (:).
1163
 */
1164
inline constexpr bool is_normalized_windows_drive_letter(
1165
    std::string_view input) noexcept;
1166
1167
/**
1168
 * @private
1169
 * Returns true if an input is an ipv4 address. It is assumed that the string
1170
 * does not contain uppercase ASCII characters (the input should have been
1171
 * lowered cased before calling this function) and is not empty.
1172
 */
1173
ada_really_inline constexpr bool is_ipv4(std::string_view view) noexcept;
1174
1175
/**
1176
 * @private
1177
 * Cheap pre-check for the WHATWG "ends in a number" / IPv4-host cases.
1178
 * False means the host cannot be IPv4: the last label is empty, does not
1179
 * start with an ASCII digit, or contains a character other than a hex
1180
 * digit or x/X. True means the slower IPv4 parsers should run.
1181
 *
1182
 * Safe on mixed-case input (unlike is_ipv4, which expects a lowercased
1183
 * host).
1184
 */
1185
ada_really_inline constexpr bool last_label_may_be_a_number(
1186
    std::string_view view) noexcept;
1187
1188
/**
1189
 * @private
1190
 * Returns a bitset. If the first bit is set, then at least one character needs
1191
 * percent encoding. If the second bit is set, a \\ is found. If the third bit
1192
 * is set then we have a dot. If the fourth bit is set, then we have a percent
1193
 * character.
1194
 */
1195
ada_really_inline constexpr uint8_t path_signature(
1196
    std::string_view input) noexcept;
1197
1198
/**
1199
 * @private
1200
 * Returns true if the length of the domain name and its labels are according to
1201
 * the specifications. The length of the domain must be 255 octets (253
1202
 * characters not including the last 2 which are the empty label reserved at the
1203
 * end). When the empty label is included (a dot at the end), the domain name
1204
 * can have 254 characters. The length of a label must be at least 1 and at most
1205
 * 63 characters.
1206
 * @see section 3.1. of https://www.rfc-editor.org/rfc/rfc1034
1207
 * @see https://www.unicode.org/reports/tr46/#ToASCII
1208
 */
1209
ada_really_inline constexpr bool verify_dns_length(
1210
    std::string_view input) noexcept;
1211
1212
/**
1213
 * @private
1214
 * Fast-path parser for pure decimal IPv4 addresses (e.g., "192.168.1.1").
1215
 * Returns the packed 32-bit IPv4 address on success, or a value > 0xFFFFFFFF
1216
 * to indicate failure (caller should fall back to general parser).
1217
 * This is optimized for the common case where the input is a well-formed
1218
 * decimal IPv4 address with exactly 4 octets.
1219
 */
1220
ada_really_inline uint64_t try_parse_ipv4_fast(std::string_view input) noexcept;
1221
1222
/**
1223
 * Sentinel value indicating try_parse_ipv4_fast() did not succeed.
1224
 * Any value > 0xFFFFFFFF indicates the fast path should not be used.
1225
 */
1226
constexpr uint64_t ipv4_fast_fail = uint64_t(1) << 32;
1227
1228
}  // namespace ada::checkers
1229
1230
#endif  // ADA_CHECKERS_H
1231
/* end file include/ada/checkers.h */
1232
1233
#if defined(ADA_AVX512) && defined(__AVX512VBMI2__)
1234
#include <immintrin.h>
1235
#endif
1236
1237
namespace ada::checkers {
1238
1239
1.04M
constexpr bool is_digit(char x) noexcept { return (x >= '0') & (x <= '9'); }
1240
1241
4.77M
constexpr bool is_ipv4_number_char(char x) noexcept {
1242
4.77M
  const unsigned char c = static_cast<unsigned char>(x);
1243
4.77M
  return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
1244
2.70M
         (c >= 'A' && c <= 'F') || c == 'x' || c == 'X';
1245
4.77M
}
1246
1247
2.36M
constexpr bool last_label_may_be_a_number(std::string_view view) noexcept {
1248
2.36M
  if (view.empty()) {
1249
0
    return false;
1250
0
  }
1251
2.36M
  const char* start = view.data();
1252
2.36M
  const char* end = start + view.size();
1253
2.36M
  if (end[-1] == '.') {
1254
96.0k
    --end;
1255
96.0k
    if (end == start) {
1256
24.9k
      return false;
1257
24.9k
    }
1258
96.0k
  }
1259
2.34M
  if (!is_ipv4_number_char(end[-1])) {
1260
1.68M
    return false;
1261
1.68M
  }
1262
658k
  const char* label = end;
1263
2.73M
  while (label != start && is_ipv4_number_char(label[-1])) {
1264
2.07M
    --label;
1265
2.07M
  }
1266
658k
  if (label != start && label[-1] != '.') {
1267
172k
    return false;
1268
172k
  }
1269
486k
  return label != end && is_digit(*label);
1270
658k
}
1271
1272
4.84M
constexpr char to_lower(char x) noexcept { return (x | 0x20); }
1273
1274
2.48M
constexpr bool is_alpha(char x) noexcept {
1275
2.48M
  return (to_lower(x) >= 'a') && (to_lower(x) <= 'z');
1276
2.48M
}
1277
1278
214k
constexpr bool is_windows_drive_letter(std::string_view input) noexcept {
1279
214k
  return input.size() >= 2 &&
1280
112k
         (is_alpha(input[0]) && ((input[1] == ':') || (input[1] == '|'))) &&
1281
11.5k
         ((input.size() == 2) || (input[2] == '/' || input[2] == '\\' ||
1282
6.11k
                                  input[2] == '?' || input[2] == '#'));
1283
214k
}
1284
1285
constexpr bool is_normalized_windows_drive_letter(
1286
27.4k
    std::string_view input) noexcept {
1287
27.4k
  return input.size() == 2 && (is_alpha(input[0]) && (input[1] == ':'));
1288
27.4k
}
1289
1290
namespace detail {
1291
1292
// Unrolled pure-decimal IPv4. The common portable path for 7-16 byte hosts.
1293
ada_really_inline uint64_t
1294
737k
parse_ipv4_decimal_scalar(const char* p, const char* pend) noexcept {
1295
737k
  uint32_t ipv4 = 0;
1296
1.94M
  for (int i = 0; i < 4; ++i) {
1297
1.64M
    if (p == pend) [[unlikely]] {
1298
246
      return ipv4_fast_fail;
1299
246
    }
1300
1.64M
    uint32_t val;
1301
1.64M
    char c = *p;
1302
1.64M
    if (c >= '0' && c <= '9') [[likely]] {
1303
1.32M
      val = static_cast<uint32_t>(c - '0');
1304
1.32M
      ++p;
1305
1.32M
    } else {
1306
321k
      return ipv4_fast_fail;
1307
321k
    }
1308
1.32M
    if (p < pend) {
1309
1.18M
      c = *p;
1310
1.18M
      if (c >= '0' && c <= '9') {
1311
747k
        if (val == 0) [[unlikely]] {
1312
7.60k
          return ipv4_fast_fail;
1313
7.60k
        }
1314
739k
        val = val * 10u + static_cast<uint32_t>(c - '0');
1315
739k
        ++p;
1316
739k
        if (p < pend) {
1317
628k
          c = *p;
1318
628k
          if (c >= '0' && c <= '9') {
1319
367k
            val = val * 10u + static_cast<uint32_t>(c - '0');
1320
367k
            ++p;
1321
367k
            if (val > 255u) [[unlikely]] {
1322
11.1k
              return ipv4_fast_fail;
1323
11.1k
            }
1324
367k
          }
1325
628k
        }
1326
739k
      }
1327
1.18M
    }
1328
1.30M
    ipv4 = (ipv4 << 8) | val;
1329
1.30M
    if (i < 3) {
1330
1.00M
      if (p == pend || *p != '.') [[unlikely]] {
1331
99.3k
        return ipv4_fast_fail;
1332
99.3k
      }
1333
910k
      ++p;
1334
910k
    }
1335
1.30M
  }
1336
298k
  if (p != pend) {
1337
6.12k
    if (p == pend - 1 && *p == '.') {
1338
755
      return ipv4;
1339
755
    }
1340
5.37k
    return ipv4_fast_fail;
1341
6.12k
  }
1342
292k
  return ipv4;
1343
298k
}
1344
1345
#if defined(ADA_AVX512) && defined(__AVX512VBMI2__)
1346
// Table-free AVX-512VL IPv4 parse (simdip parse_ipv4_avx512vl_notab5).
1347
// Needs VBMI2 for vpcompressb; ADA_AVX512 stays BW+VL (IPv6 does not use
1348
// VBMI2). Masked load of exactly `len` bytes (no over-read). Digit
1349
// placement is computed from compressed delimiter positions; octet > 255
1350
// is a dword compare on the zero-padded reversed digit group, in parallel
1351
// with the convert. Unusual-but-valid forms (octal, hex, leading zeros,
1352
// fewer than four parts) return ipv4_fast_fail so the general parser runs.
1353
ada_really_inline uint64_t try_parse_ipv4_avx512(const char* data,
1354
                                                 size_t len) noexcept {
1355
  // One trailing dot is WHATWG-legal ("1.2.3.4."); the SIMD kernel is
1356
  // strict four-group dotted-decimal.
1357
  if (data[len - 1] == '.') {
1358
    --len;
1359
  }
1360
  if (len > 15) [[unlikely]] {
1361
    return ipv4_fast_fail;
1362
  }
1363
1364
#if defined(__BMI2__)
1365
  const uint32_t len_mask = _bzhi_u32(0xFFFFFFFFu, static_cast<unsigned>(len));
1366
#else
1367
  const uint32_t len_mask = (1u << static_cast<unsigned>(len)) - 1u;
1368
#endif
1369
  const __mmask16 len_k = static_cast<__mmask16>(len_mask);
1370
  const __m128i dot = _mm_set1_epi8('.');
1371
  const __m128i v =
1372
      _mm_mask_loadu_epi8(dot, len_k, reinterpret_cast<const void*>(data));
1373
1374
  const __mmask16 delim = _mm_cmpeq_epi8_mask(v, dot);
1375
  const uint32_t dots = static_cast<uint32_t>(delim) & len_mask;
1376
  const uint32_t keep = len_mask & ~dots;
1377
1378
  const __m128i zero = _mm_set1_epi8('0');
1379
  const __m128i digits = _mm_sub_epi8(v, zero);
1380
  const __mmask16 is_digit = _mm_cmple_epu8_mask(digits, _mm_set1_epi8(9));
1381
  // Junk in a digit slot: inside [0, len) yet neither a digit nor a dot.
1382
  const __mmask16 hole = _kandn_mask16(_kor_mask16(delim, is_digit), len_k);
1383
  const __m128i v0 = _mm_maskz_mov_epi8(is_digit, digits);
1384
1385
  const __m128i iota =
1386
      _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
1387
  const __m128i c = _mm_maskz_compress_epi8(delim, iota);
1388
  const __m128i k_rep =
1389
      _mm_setr_epi8(0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3);
1390
  const __m128i qi = _mm_shuffle_epi8(c, k_rep);
1391
  const __m128i prev =
1392
      _mm_shuffle_epi8(_mm_alignr_epi8(c, _mm_set1_epi8(-1), 15), k_rep);
1393
  // Reversed group order: lane 4i+j fetches q_i-(j+1), so the dword is
1394
  // ones | tens<<8 | hundreds<<16, monotone in the decimal value.
1395
  const __m128i offr = _mm_setr_epi8(-1, -2, -3, -4, -1, -2, -3, -4, -1, -2, -3,
1396
                                     -4, -1, -2, -3, -4);
1397
  const __m128i idx = _mm_max_epi8(_mm_add_epi8(qi, offr), prev);
1398
  const __m128i padded = _mm_shuffle_epi8(v0, idx);
1399
1400
  const __m128i lim =
1401
      _mm_setr_epi8(5, 5, 2, 0, 5, 5, 2, 0, 5, 5, 2, 0, 5, 5, 2, 0);
1402
  const __mmask8 over = _mm_cmpgt_epu32_mask(padded, lim);
1403
  const __m128i wtsr =
1404
      _mm_setr_epi8(1, 10, 100, 0, 1, 10, 100, 0, 1, 10, 100, 0, 1, 10, 100, 0);
1405
#if defined(__AVX512VNNI__)
1406
  const __m128i res = _mm_dpbusd_epi32(_mm_setzero_si128(), padded, wtsr);
1407
#else
1408
  const __m128i res =
1409
      _mm_madd_epi16(_mm_maddubs_epi16(padded, wtsr), _mm_set1_epi16(1));
1410
#endif
1411
1412
  const __m128i gmin =
1413
      _mm_setr_epi8(1, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1414
  const __m128i gmax =
1415
      _mm_setr_epi8(2, 2, 2, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
1416
  const __m128i gap = _mm_sub_epi8(c, _mm_slli_si128(c, 1));
1417
  const __mmask16 bad_gap = _mm_cmpgt_epu8_mask(_mm_sub_epi8(gap, gmin), gmax);
1418
1419
  const uint32_t zero_bits =
1420
      static_cast<uint32_t>(_mm_cmpeq_epi8_mask(v, zero));
1421
  const uint32_t start_bits = (dots << 1) | 1u;
1422
1423
  const __mmask16 kerr =
1424
      _kor_mask16(_kor_mask16(hole, static_cast<__mmask16>(over)), bad_gap);
1425
  const uint32_t gerr = static_cast<uint32_t>(_mm_popcnt_u32(dots) ^ 3u) |
1426
                        (zero_bits & start_bits & (keep >> 1));
1427
1428
  if ((gerr | static_cast<uint32_t>(kerr)) == 0) [[likely]] {
1429
    const uint32_t packed =
1430
        static_cast<uint32_t>(_mm_cvtsi128_si32(_mm_cvtepi32_epi8(res)));
1431
#if defined(__GNUC__) || defined(__clang__)
1432
    return static_cast<uint64_t>(__builtin_bswap32(packed));
1433
#else
1434
    return static_cast<uint64_t>(_byteswap_ulong(packed));
1435
#endif
1436
  }
1437
  return ipv4_fast_fail;
1438
}
1439
#endif  // ADA_AVX512 && __AVX512VBMI2__
1440
1441
}  // namespace detail
1442
1443
/**
1444
 * Fast pure-decimal IPv4 parse. Returns packed address or ipv4_fast_fail.
1445
 * Accepts an optional single trailing dot.
1446
 *
1447
 * On AVX-512BW+VL+VBMI2 targets, uses a table-free SIMD parse (masked
1448
 * load, no source over-read) based on parse_ipv4_avx512vl_notab5.
1449
 * Otherwise uses an unrolled scalar path (typically faster than SSE2/NEON
1450
 * pre-validation for these 7-16 byte hosts).
1451
 */
1452
ada_really_inline uint64_t
1453
1.47M
try_parse_ipv4_fast(std::string_view input) noexcept {
1454
1.47M
  const size_t len = input.size();
1455
  // Shortest pure decimal: "0.0.0.0" (7). Longest + trailing dot: 16.
1456
1.47M
  if (len < 7 || len > 16) [[unlikely]] {
1457
735k
    return ipv4_fast_fail;
1458
735k
  }
1459
737k
  const char* data = input.data();
1460
1461
#if defined(ADA_AVX512) && defined(__AVX512VBMI2__)
1462
  return detail::try_parse_ipv4_avx512(data, len);
1463
#else
1464
737k
  return detail::parse_ipv4_decimal_scalar(data, data + len);
1465
1.47M
#endif
1466
1.47M
}
1467
1468
}  // namespace ada::checkers
1469
1470
#endif  // ADA_CHECKERS_INL_H
1471
/* end file include/ada/checkers-inl.h */
1472
/* begin file include/ada/log.h */
1473
/**
1474
 * @file log.h
1475
 * @brief Includes the definitions for logging.
1476
 * @private Excluded from docs through the doxygen file.
1477
 */
1478
#ifndef ADA_LOG_H
1479
#define ADA_LOG_H
1480
1481
// To enable logging, set ADA_LOGGING to 1:
1482
#ifndef ADA_LOGGING
1483
#define ADA_LOGGING 0
1484
#endif
1485
1486
#if ADA_LOGGING
1487
#include <iostream>
1488
#endif  // ADA_LOGGING
1489
1490
namespace ada {
1491
1492
/**
1493
 * Log a message. If you want to have no overhead when logging is disabled, use
1494
 * the ada_log macro.
1495
 * @private
1496
 */
1497
template <typename... Args>
1498
constexpr ada_really_inline void log([[maybe_unused]] Args... args) {
1499
#if ADA_LOGGING
1500
  ((std::cout << "ADA_LOG: ") << ... << args) << std::endl;
1501
#endif  // ADA_LOGGING
1502
}
1503
}  // namespace ada
1504
1505
#if ADA_LOGGING
1506
#ifndef ada_log
1507
#define ada_log(...)       \
1508
  do {                     \
1509
    ada::log(__VA_ARGS__); \
1510
  } while (0)
1511
#endif  // ada_log
1512
#else
1513
#define ada_log(...)
1514
#endif  // ADA_LOGGING
1515
1516
#endif  // ADA_LOG_H
1517
/* end file include/ada/log.h */
1518
/* begin file include/ada/encoding_type.h */
1519
/**
1520
 * @file encoding_type.h
1521
 * @brief Character encoding type definitions.
1522
 *
1523
 * Defines the encoding types supported for URL processing.
1524
 *
1525
 * @see https://encoding.spec.whatwg.org/
1526
 */
1527
#ifndef ADA_ENCODING_TYPE_H
1528
#define ADA_ENCODING_TYPE_H
1529
1530
#include <string>
1531
1532
namespace ada {
1533
1534
/**
1535
 * @brief Character encoding types for URL processing.
1536
 *
1537
 * Specifies the character encoding used for percent-decoding and other
1538
 * string operations. UTF-8 is the most commonly used encoding for URLs.
1539
 *
1540
 * @see https://encoding.spec.whatwg.org/#encodings
1541
 */
1542
enum class encoding_type {
1543
  UTF8,     /**< UTF-8 encoding (default for URLs) */
1544
  UTF_16LE, /**< UTF-16 Little Endian encoding */
1545
  UTF_16BE, /**< UTF-16 Big Endian encoding */
1546
};
1547
1548
/**
1549
 * Converts an encoding_type to its string representation.
1550
 * @param type The encoding type to convert.
1551
 * @return A string view of the encoding name.
1552
 */
1553
ada_warn_unused std::string_view to_string(encoding_type type);
1554
1555
}  // namespace ada
1556
1557
#endif  // ADA_ENCODING_TYPE_H
1558
/* end file include/ada/encoding_type.h */
1559
/* begin file include/ada/helpers.h */
1560
/**
1561
 * @file helpers.h
1562
 * @brief Definitions for helper functions used within Ada.
1563
 */
1564
#ifndef ADA_HELPERS_H
1565
#define ADA_HELPERS_H
1566
1567
/* begin file include/ada/url_base.h */
1568
/**
1569
 * @file url_base.h
1570
 * @brief Base class and common definitions for URL types.
1571
 *
1572
 * This file defines the `url_base` abstract base class from which both
1573
 * `ada::url` and `ada::url_aggregator` inherit. It also defines common
1574
 * enumerations like `url_host_type`.
1575
 */
1576
#ifndef ADA_URL_BASE_H
1577
#define ADA_URL_BASE_H
1578
1579
/* begin file include/ada/scheme.h */
1580
/**
1581
 * @file scheme.h
1582
 * @brief URL scheme type definitions and utilities.
1583
 *
1584
 * This header defines the URL scheme types (http, https, etc.) and provides
1585
 * functions to identify special schemes and their default ports according
1586
 * to the WHATWG URL Standard.
1587
 *
1588
 * @see https://url.spec.whatwg.org/#special-scheme
1589
 */
1590
#ifndef ADA_SCHEME_H
1591
#define ADA_SCHEME_H
1592
1593
1594
#include <string>
1595
1596
/**
1597
 * @namespace ada::scheme
1598
 * @brief URL scheme utilities and constants.
1599
 *
1600
 * Provides functions for working with URL schemes, including identification
1601
 * of special schemes and retrieval of default port numbers.
1602
 */
1603
namespace ada::scheme {
1604
1605
/**
1606
 * @brief Enumeration of URL scheme types.
1607
 *
1608
 * Special schemes have specific parsing rules and default ports.
1609
 * Using an enum allows efficient scheme comparisons without string operations.
1610
 *
1611
 * Default ports:
1612
 * - HTTP: 80
1613
 * - HTTPS: 443
1614
 * - WS: 80
1615
 * - WSS: 443
1616
 * - FTP: 21
1617
 * - FILE: (none)
1618
 */
1619
enum type : uint8_t {
1620
  HTTP = 0,        /**< http:// scheme (port 80) */
1621
  NOT_SPECIAL = 1, /**< Non-special scheme (no default port) */
1622
  HTTPS = 2,       /**< https:// scheme (port 443) */
1623
  WS = 3,          /**< ws:// WebSocket scheme (port 80) */
1624
  FTP = 4,         /**< ftp:// scheme (port 21) */
1625
  WSS = 5,         /**< wss:// secure WebSocket scheme (port 443) */
1626
  FILE = 6         /**< file:// scheme (no default port) */
1627
};
1628
1629
/**
1630
 * Checks if a scheme string is a special scheme.
1631
 * @param scheme The scheme string to check (e.g., "http", "https").
1632
 * @return `true` if the scheme is special, `false` otherwise.
1633
 * @see https://url.spec.whatwg.org/#special-scheme
1634
 */
1635
ada_really_inline constexpr bool is_special(std::string_view scheme);
1636
1637
/**
1638
 * Returns the default port for a special scheme string.
1639
 * @param scheme The scheme string (e.g., "http", "https").
1640
 * @return The default port number, or 0 if not a special scheme.
1641
 * @see https://url.spec.whatwg.org/#special-scheme
1642
 */
1643
constexpr uint16_t get_special_port(std::string_view scheme) noexcept;
1644
1645
/**
1646
 * Returns the default port for a scheme type.
1647
 * @param type The scheme type enum value.
1648
 * @return The default port number, or 0 if not applicable.
1649
 * @see https://url.spec.whatwg.org/#special-scheme
1650
 */
1651
constexpr uint16_t get_special_port(ada::scheme::type type) noexcept;
1652
1653
/**
1654
 * Converts a scheme string to its type enum.
1655
 * @param scheme The scheme string to convert.
1656
 * @return The corresponding scheme type, or NOT_SPECIAL if not recognized.
1657
 */
1658
constexpr ada::scheme::type get_scheme_type(std::string_view scheme) noexcept;
1659
1660
}  // namespace ada::scheme
1661
1662
#endif  // ADA_SCHEME_H
1663
/* end file include/ada/scheme.h */
1664
1665
#include <string>
1666
#include <string_view>
1667
1668
namespace ada {
1669
1670
/**
1671
 * @brief Enum representing the type of host in a URL.
1672
 *
1673
 * Used to distinguish between regular domain names, IPv4 addresses,
1674
 * and IPv6 addresses for proper parsing and serialization.
1675
 */
1676
enum url_host_type : uint8_t {
1677
  /** Regular domain name (e.g., "www.example.com") */
1678
  DEFAULT = 0,
1679
  /** IPv4 address (e.g., "127.0.0.1") */
1680
  IPV4 = 1,
1681
  /** IPv6 address (e.g., "[::1]" or "[2001:db8::1]") */
1682
  IPV6 = 2,
1683
};
1684
1685
/**
1686
 * @brief Abstract base class for URL representations.
1687
 *
1688
 * The `url_base` class provides the common interface and state shared by
1689
 * both `ada::url` and `ada::url_aggregator`. It contains basic URL attributes
1690
 * like validity status and scheme type, but delegates component storage and
1691
 * access to derived classes.
1692
 *
1693
 * @note This is an abstract class and cannot be instantiated directly.
1694
 *       Use `ada::url` or `ada::url_aggregator` instead.
1695
 *
1696
 * @see url
1697
 * @see url_aggregator
1698
 */
1699
struct url_base {
1700
7.25M
  virtual ~url_base() = default;
1701
1702
  /**
1703
   * Indicates whether the URL was successfully parsed.
1704
   * Set to `false` if parsing failed (e.g., invalid URL syntax).
1705
   */
1706
  bool is_valid{true};
1707
1708
  /**
1709
   * Indicates whether the URL has an opaque path (non-hierarchical).
1710
   * Opaque paths occur in non-special URLs like `mailto:` or `javascript:`.
1711
   */
1712
  bool has_opaque_path{false};
1713
1714
  /**
1715
   * The type of the URL's host (domain, IPv4, or IPv6).
1716
   */
1717
  url_host_type host_type = url_host_type::DEFAULT;
1718
1719
  /**
1720
   * @private
1721
   * Internal representation of the URL's scheme type.
1722
   */
1723
  ada::scheme::type type{ada::scheme::type::NOT_SPECIAL};
1724
1725
  /**
1726
   * Checks if the URL has a special scheme (http, https, ws, wss, ftp, file).
1727
   * Special schemes have specific parsing rules and default ports.
1728
   * @return `true` if the scheme is special, `false` otherwise.
1729
   */
1730
  [[nodiscard]] ada_really_inline constexpr bool is_special() const noexcept;
1731
1732
  /**
1733
   * Returns the URL's origin (scheme + host + port for special URLs).
1734
   * @return A newly allocated string containing the serialized origin.
1735
   * @see https://url.spec.whatwg.org/#concept-url-origin
1736
   */
1737
  [[nodiscard]] virtual std::string get_origin() const = 0;
1738
1739
  /**
1740
   * Validates whether the hostname is a valid domain according to RFC 1034.
1741
   * Checks that the domain and its labels have valid lengths.
1742
   * @return `true` if the domain is valid, `false` otherwise.
1743
   */
1744
  [[nodiscard]] virtual bool has_valid_domain() const noexcept = 0;
1745
1746
  /**
1747
   * @private
1748
   * Returns the default port for special schemes (e.g., 443 for https).
1749
   * Returns 0 for file:// URLs or non-special schemes.
1750
   */
1751
  [[nodiscard]] inline uint16_t get_special_port() const noexcept;
1752
1753
  /**
1754
   * @private
1755
   * Returns the default port for the URL's scheme, or 0 if none.
1756
   */
1757
  [[nodiscard]] ada_really_inline uint16_t scheme_default_port() const noexcept;
1758
1759
  /**
1760
   * @private
1761
   * Parses a port number from the input string.
1762
   * @param view The string containing the port to parse.
1763
   * @param check_trailing_content Whether to validate no trailing characters.
1764
   * @return Number of bytes consumed on success, 0 on failure.
1765
   */
1766
  virtual size_t parse_port(std::string_view view,
1767
                            bool check_trailing_content) = 0;
1768
1769
  /** @private */
1770
0
  virtual ada_really_inline size_t parse_port(std::string_view view) {
1771
0
    return this->parse_port(view, false);
1772
0
  }
1773
1774
  /**
1775
   * Returns a JSON string representation of this URL for debugging.
1776
   * @return A JSON-formatted string with URL information.
1777
   */
1778
  [[nodiscard]] virtual std::string to_string() const = 0;
1779
1780
  /** @private */
1781
  virtual inline void clear_pathname() = 0;
1782
1783
  /** @private */
1784
  virtual inline void clear_search() = 0;
1785
1786
  /** @private */
1787
  [[nodiscard]] virtual inline bool has_hash() const noexcept = 0;
1788
1789
  /** @private */
1790
  [[nodiscard]] virtual inline bool has_search() const noexcept = 0;
1791
1792
};  // url_base
1793
1794
}  // namespace ada
1795
1796
#endif
1797
/* end file include/ada/url_base.h */
1798
1799
#include <string>
1800
#include <string_view>
1801
#include <optional>
1802
1803
#if ADA_DEVELOPMENT_CHECKS
1804
#include <iostream>
1805
#endif  // ADA_DEVELOPMENT_CHECKS
1806
1807
/**
1808
 * These functions are not part of our public API and may
1809
 * change at any time.
1810
 *
1811
 * @private
1812
 * @namespace ada::helpers
1813
 * @brief Includes the definitions for helper functions
1814
 */
1815
namespace ada::helpers {
1816
1817
/**
1818
 * @private
1819
 */
1820
template <typename out_iter>
1821
void encode_json(std::string_view view, out_iter out);
1822
1823
/**
1824
 * @private
1825
 * This function is used to prune a fragment from a url, and returning the
1826
 * removed string if input has fragment.
1827
 *
1828
 * @details prune_hash seeks the first '#' and returns everything after it
1829
 * as a string_view, and modifies (in place) the input so that it points at
1830
 * everything before the '#'. If no '#' is found, the input is left unchanged
1831
 * and std::nullopt is returned.
1832
 *
1833
 * @attention The function is non-allocating and it does not throw.
1834
 * @returns Note that the returned string_view might be empty!
1835
 */
1836
ada_really_inline std::optional<std::string_view> prune_hash(
1837
    std::string_view& input) noexcept;
1838
1839
/**
1840
 * @private
1841
 * Defined by the URL specification, shorten a URLs paths.
1842
 * @see https://url.spec.whatwg.org/#shorten-a-urls-path
1843
 * @returns Returns true if path is shortened.
1844
 */
1845
ada_really_inline bool shorten_path(std::string& path, ada::scheme::type type);
1846
1847
/**
1848
 * @private
1849
 * Defined by the URL specification, shorten a URLs paths.
1850
 * @see https://url.spec.whatwg.org/#shorten-a-urls-path
1851
 * @returns Returns true if path is shortened.
1852
 */
1853
ada_really_inline bool shorten_path(std::string_view& path,
1854
                                    ada::scheme::type type);
1855
1856
/**
1857
 * @private
1858
 *
1859
 * Parse the path from the provided input and append to the existing
1860
 * (possibly empty) path. The input cannot contain tabs and spaces: it
1861
 * is the user's responsibility to check.
1862
 *
1863
 * The input is expected to be UTF-8.
1864
 *
1865
 * @see https://url.spec.whatwg.org/
1866
 */
1867
ada_really_inline void parse_prepared_path(std::string_view input,
1868
                                           ada::scheme::type type,
1869
                                           std::string& path);
1870
1871
/**
1872
 * @private
1873
 * Remove and mutate all ASCII tab or newline characters from an input.
1874
 */
1875
ada_really_inline void remove_ascii_tab_or_newline(std::string& input);
1876
1877
/**
1878
 * @private
1879
 * Return the substring from input going from index pos to the end.
1880
 */
1881
ada_really_inline constexpr std::string_view substring(std::string_view input,
1882
                                                       size_t pos);
1883
1884
/**
1885
 * @private
1886
 * Returns true if the string_view points within the string.
1887
 */
1888
bool overlaps(std::string_view input1, const std::string& input2) noexcept;
1889
1890
/**
1891
 * @private
1892
 * Return the substring from input going from index pos1 to the pos2 (non
1893
 * included). The length of the substring is pos2 - pos1.
1894
 */
1895
ada_really_inline constexpr std::string_view substring(std::string_view input,
1896
                                                       size_t pos1,
1897
4.51M
                                                       size_t pos2) {
1898
#if ADA_DEVELOPMENT_CHECKS
1899
  if (pos2 < pos1) {
1900
    std::cerr << "Negative-length substring: [" << pos1 << " to " << pos2 << ")"
1901
              << std::endl;
1902
    abort();
1903
  }
1904
#endif
1905
4.51M
  return input.substr(pos1, pos2 - pos1);
1906
4.51M
}
1907
1908
/**
1909
 * @private
1910
 * Modify the string_view so that it has the new size pos, assuming that pos <=
1911
 * input.size(). This function cannot throw.
1912
 */
1913
ada_really_inline void resize(std::string_view& input, size_t pos) noexcept;
1914
1915
/**
1916
 * @private
1917
 * Returns a host's delimiter location depending on the state of the instance,
1918
 * and whether a colon was found outside brackets. Used by the host parser.
1919
 */
1920
ada_really_inline std::pair<size_t, bool> get_host_delimiter_location(
1921
    bool is_special, std::string_view& view) noexcept;
1922
1923
/**
1924
 * @private
1925
 * Removes leading and trailing C0 control and whitespace characters from
1926
 * string.
1927
 */
1928
void trim_c0_whitespace(std::string_view& input) noexcept;
1929
1930
/**
1931
 * @private
1932
 * @see
1933
 * https://url.spec.whatwg.org/#potentially-strip-trailing-spaces-from-an-opaque-path
1934
 */
1935
template <class url_type>
1936
ada_really_inline void strip_trailing_spaces_from_opaque_path(url_type& url);
1937
1938
/**
1939
 * @private
1940
 * Finds the delimiter of a view in authority state.
1941
 */
1942
ada_really_inline size_t
1943
find_authority_delimiter_special(std::string_view view) noexcept;
1944
1945
/**
1946
 * @private
1947
 * Finds the delimiter of a view in authority state.
1948
 */
1949
ada_really_inline size_t
1950
find_authority_delimiter(std::string_view view) noexcept;
1951
1952
/**
1953
 * @private
1954
 */
1955
template <typename T, typename... Args>
1956
1.04M
inline void inner_concat(std::string& buffer, T t) {
1957
1.04M
  buffer.append(t);
1958
1.04M
}
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> >)
Line
Count
Source
1956
112k
inline void inner_concat(std::string& buffer, T t) {
1957
112k
  buffer.append(t);
1958
112k
}
void ada::helpers::inner_concat<char const*>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&, char const*)
Line
Count
Source
1956
835k
inline void inner_concat(std::string& buffer, T t) {
1957
835k
  buffer.append(t);
1958
835k
}
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> >)
Line
Count
Source
1956
95.8k
inline void inner_concat(std::string& buffer, T t) {
1957
95.8k
  buffer.append(t);
1958
95.8k
}
1959
1960
/**
1961
 * @private
1962
 */
1963
template <typename T, typename... Args>
1964
1.17M
inline void inner_concat(std::string& buffer, T t, Args... args) {
1965
1.17M
  buffer.append(t);
1966
1.17M
  return inner_concat(buffer, args...);
1967
1.17M
}
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> >)
Line
Count
Source
1964
112k
inline void inner_concat(std::string& buffer, T t, Args... args) {
1965
112k
  buffer.append(t);
1966
112k
  return inner_concat(buffer, args...);
1967
112k
}
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> >)
Line
Count
Source
1964
31.2k
inline void inner_concat(std::string& buffer, T t, Args... args) {
1965
31.2k
  buffer.append(t);
1966
31.2k
  return inner_concat(buffer, args...);
1967
31.2k
}
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*)
Line
Count
Source
1964
820k
inline void inner_concat(std::string& buffer, T t, Args... args) {
1965
820k
  buffer.append(t);
1966
820k
  return inner_concat(buffer, args...);
1967
820k
}
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*)
Line
Count
Source
1964
15.6k
inline void inner_concat(std::string& buffer, T t, Args... args) {
1965
15.6k
  buffer.append(t);
1966
15.6k
  return inner_concat(buffer, args...);
1967
15.6k
}
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> >)
Line
Count
Source
1964
95.8k
inline void inner_concat(std::string& buffer, T t, Args... args) {
1965
95.8k
  buffer.append(t);
1966
95.8k
  return inner_concat(buffer, args...);
1967
95.8k
}
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> >)
Line
Count
Source
1964
95.8k
inline void inner_concat(std::string& buffer, T t, Args... args) {
1965
95.8k
  buffer.append(t);
1966
95.8k
  return inner_concat(buffer, args...);
1967
95.8k
}
1968
1969
/**
1970
 * @private
1971
 * Concatenate the arguments and return a string.
1972
 * @returns a string
1973
 */
1974
template <typename... Args>
1975
1.04M
std::string concat(Args... args) {
1976
1.04M
  std::string answer;
1977
1.04M
  inner_concat(answer, args...);
1978
1.04M
  return answer;
1979
1.04M
}
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> >)
Line
Count
Source
1975
80.8k
std::string concat(Args... args) {
1976
80.8k
  std::string answer;
1977
80.8k
  inner_concat(answer, args...);
1978
80.8k
  return answer;
1979
80.8k
}
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> >)
Line
Count
Source
1975
31.2k
std::string concat(Args... args) {
1976
31.2k
  std::string answer;
1977
31.2k
  inner_concat(answer, args...);
1978
31.2k
  return answer;
1979
31.2k
}
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*)
Line
Count
Source
1975
820k
std::string concat(Args... args) {
1976
820k
  std::string answer;
1977
820k
  inner_concat(answer, args...);
1978
820k
  return answer;
1979
820k
}
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*)
Line
Count
Source
1975
15.6k
std::string concat(Args... args) {
1976
15.6k
  std::string answer;
1977
15.6k
  inner_concat(answer, args...);
1978
15.6k
  return answer;
1979
15.6k
}
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> >)
Line
Count
Source
1975
33
std::string concat(Args... args) {
1976
33
  std::string answer;
1977
33
  inner_concat(answer, args...);
1978
33
  return answer;
1979
33
}
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> >)
Line
Count
Source
1975
95.8k
std::string concat(Args... args) {
1976
95.8k
  std::string answer;
1977
95.8k
  inner_concat(answer, args...);
1978
95.8k
  return answer;
1979
95.8k
}
1980
1981
/**
1982
 * @private
1983
 * @return Number of leading zeroes.
1984
 */
1985
1.91M
inline int leading_zeroes(uint32_t input_num) noexcept {
1986
#if ADA_REGULAR_VISUAL_STUDIO
1987
  unsigned long leading_zero(0);
1988
  unsigned long in(input_num);
1989
  return _BitScanReverse(&leading_zero, in) ? int(31 - leading_zero) : 32;
1990
#else
1991
1.91M
  return __builtin_clz(input_num);
1992
1.91M
#endif  // ADA_REGULAR_VISUAL_STUDIO
1993
1.91M
}
1994
1995
/**
1996
 * @private
1997
 * Counts the number of decimal digits necessary to represent x.
1998
 * faster than std::to_string(x).size().
1999
 * @return digit count
2000
 */
2001
60.7k
inline int fast_digit_count(uint32_t x) noexcept {
2002
60.7k
  auto int_log2 = [](uint32_t z) -> int {
2003
60.7k
    return 31 - ada::helpers::leading_zeroes(z | 1);
2004
60.7k
  };
2005
  // Compiles to very few instructions. Note that the
2006
  // table is static and thus effectively a constant.
2007
  // We leave it inside the function because it is meaningless
2008
  // outside of it (this comes at no performance cost).
2009
60.7k
  const static uint64_t table[] = {
2010
60.7k
      4294967296,  8589934582,  8589934582,  8589934582,  12884901788,
2011
60.7k
      12884901788, 12884901788, 17179868184, 17179868184, 17179868184,
2012
60.7k
      21474826480, 21474826480, 21474826480, 21474826480, 25769703776,
2013
60.7k
      25769703776, 25769703776, 30063771072, 30063771072, 30063771072,
2014
60.7k
      34349738368, 34349738368, 34349738368, 34349738368, 38554705664,
2015
60.7k
      38554705664, 38554705664, 41949672960, 41949672960, 41949672960,
2016
60.7k
      42949672960, 42949672960};
2017
60.7k
  return int((x + table[int_log2(x)]) >> 32);
2018
60.7k
}
2019
}  // namespace ada::helpers
2020
2021
#endif  // ADA_HELPERS_H
2022
/* end file include/ada/helpers.h */
2023
/* begin file include/ada/parser.h */
2024
/**
2025
 * @file parser.h
2026
 * @brief Low-level URL parsing functions.
2027
 *
2028
 * This header provides the internal URL parsing implementation. Most users
2029
 * should use `ada::parse()` from implementation.h instead of these functions
2030
 * directly.
2031
 *
2032
 * @see implementation.h for the recommended public API
2033
 */
2034
#ifndef ADA_PARSER_H
2035
#define ADA_PARSER_H
2036
2037
#include <string_view>
2038
#include <variant>
2039
2040
/* begin file include/ada/expected.h */
2041
/**
2042
 * @file expected.h
2043
 * @brief Definitions for std::expected
2044
 * @private Excluded from docs through the doxygen file.
2045
 */
2046
///
2047
// expected - An implementation of std::expected with extensions
2048
// Written in 2017 by Sy Brand (tartanllama@gmail.com, @TartanLlama)
2049
//
2050
// Documentation available at http://tl.tartanllama.xyz/
2051
//
2052
// To the extent possible under law, the author(s) have dedicated all
2053
// copyright and related and neighboring rights to this software to the
2054
// public domain worldwide. This software is distributed without any warranty.
2055
//
2056
// You should have received a copy of the CC0 Public Domain Dedication
2057
// along with this software. If not, see
2058
// <http://creativecommons.org/publicdomain/zero/1.0/>.
2059
///
2060
2061
#ifndef TL_EXPECTED_HPP
2062
#define TL_EXPECTED_HPP
2063
2064
#define TL_EXPECTED_VERSION_MAJOR 1
2065
#define TL_EXPECTED_VERSION_MINOR 1
2066
#define TL_EXPECTED_VERSION_PATCH 0
2067
2068
#include <exception>
2069
#include <functional>
2070
#include <type_traits>
2071
#include <utility>
2072
2073
#if defined(__EXCEPTIONS) || defined(_CPPUNWIND)
2074
#define TL_EXPECTED_EXCEPTIONS_ENABLED
2075
#endif
2076
2077
#if (defined(_MSC_VER) && _MSC_VER == 1900)
2078
#define TL_EXPECTED_MSVC2015
2079
#define TL_EXPECTED_MSVC2015_CONSTEXPR
2080
#else
2081
#define TL_EXPECTED_MSVC2015_CONSTEXPR constexpr
2082
#endif
2083
2084
#if (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ <= 9 && \
2085
     !defined(__clang__))
2086
#define TL_EXPECTED_GCC49
2087
#endif
2088
2089
#if (defined(__GNUC__) && __GNUC__ == 5 && __GNUC_MINOR__ <= 4 && \
2090
     !defined(__clang__))
2091
#define TL_EXPECTED_GCC54
2092
#endif
2093
2094
#if (defined(__GNUC__) && __GNUC__ == 5 && __GNUC_MINOR__ <= 5 && \
2095
     !defined(__clang__))
2096
#define TL_EXPECTED_GCC55
2097
#endif
2098
2099
#if !defined(TL_ASSERT)
2100
// can't have assert in constexpr in C++11 and GCC 4.9 has a compiler bug
2101
#if (__cplusplus > 201103L) && !defined(TL_EXPECTED_GCC49)
2102
#include <cassert>
2103
53.2M
#define TL_ASSERT(x) assert(x)
2104
#else
2105
#define TL_ASSERT(x)
2106
#endif
2107
#endif
2108
2109
#if (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ <= 9 && \
2110
     !defined(__clang__))
2111
// GCC < 5 doesn't support overloading on const&& for member functions
2112
2113
#define TL_EXPECTED_NO_CONSTRR
2114
// GCC < 5 doesn't support some standard C++11 type traits
2115
#define TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T) \
2116
  std::has_trivial_copy_constructor<T>
2117
#define TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T) \
2118
  std::has_trivial_copy_assign<T>
2119
2120
// This one will be different for GCC 5.7 if it's ever supported
2121
#define TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T) \
2122
  std::is_trivially_destructible<T>
2123
2124
// GCC 5 < v < 8 has a bug in is_trivially_copy_constructible which breaks
2125
// std::vector for non-copyable types
2126
#elif (defined(__GNUC__) && __GNUC__ < 8 && !defined(__clang__))
2127
#ifndef TL_GCC_LESS_8_TRIVIALLY_COPY_CONSTRUCTIBLE_MUTEX
2128
#define TL_GCC_LESS_8_TRIVIALLY_COPY_CONSTRUCTIBLE_MUTEX
2129
namespace tl {
2130
namespace detail {
2131
template <class T>
2132
struct is_trivially_copy_constructible
2133
    : std::is_trivially_copy_constructible<T> {};
2134
#ifdef _GLIBCXX_VECTOR
2135
template <class T, class A>
2136
struct is_trivially_copy_constructible<std::vector<T, A>> : std::false_type {};
2137
#endif
2138
}  // namespace detail
2139
}  // namespace tl
2140
#endif
2141
2142
#define TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T) \
2143
  tl::detail::is_trivially_copy_constructible<T>
2144
#define TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T) \
2145
  std::is_trivially_copy_assignable<T>
2146
#define TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T) \
2147
  std::is_trivially_destructible<T>
2148
#else
2149
#define TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T) \
2150
  std::is_trivially_copy_constructible<T>
2151
#define TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T) \
2152
  std::is_trivially_copy_assignable<T>
2153
#define TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T) \
2154
  std::is_trivially_destructible<T>
2155
#endif
2156
2157
#if __cplusplus > 201103L
2158
#define TL_EXPECTED_CXX14
2159
#endif
2160
2161
#ifdef TL_EXPECTED_GCC49
2162
#define TL_EXPECTED_GCC49_CONSTEXPR
2163
#else
2164
#define TL_EXPECTED_GCC49_CONSTEXPR constexpr
2165
#endif
2166
2167
#if (__cplusplus == 201103L || defined(TL_EXPECTED_MSVC2015) || \
2168
     defined(TL_EXPECTED_GCC49))
2169
#define TL_EXPECTED_11_CONSTEXPR
2170
#else
2171
#define TL_EXPECTED_11_CONSTEXPR constexpr
2172
#endif
2173
2174
namespace tl {
2175
template <class T, class E>
2176
class expected;
2177
2178
#ifndef TL_MONOSTATE_INPLACE_MUTEX
2179
#define TL_MONOSTATE_INPLACE_MUTEX
2180
class monostate {};
2181
2182
struct in_place_t {
2183
  explicit in_place_t() = default;
2184
};
2185
static constexpr in_place_t in_place{};
2186
#endif
2187
2188
template <class E>
2189
class unexpected {
2190
 public:
2191
  static_assert(!std::is_same<E, void>::value, "E must not be void");
2192
2193
  unexpected() = delete;
2194
1.40k
  constexpr explicit unexpected(const E& e) : m_val(e) {}
2195
2196
1.86M
  constexpr explicit unexpected(E&& e) : m_val(std::move(e)) {}
2197
2198
  template <class... Args, typename std::enable_if<std::is_constructible<
2199
                               E, Args&&...>::value>::type* = nullptr>
2200
  constexpr explicit unexpected(Args&&... args)
2201
85.0k
      : m_val(std::forward<Args>(args)...) {}
2202
  template <
2203
      class U, class... Args,
2204
      typename std::enable_if<std::is_constructible<
2205
          E, std::initializer_list<U>&, Args&&...>::value>::type* = nullptr>
2206
  constexpr explicit unexpected(std::initializer_list<U> l, Args&&... args)
2207
      : m_val(l, std::forward<Args>(args)...) {}
2208
2209
  constexpr const E& value() const& { return m_val; }
2210
1.06M
  TL_EXPECTED_11_CONSTEXPR E& value() & { return m_val; }
2211
  TL_EXPECTED_11_CONSTEXPR E&& value() && { return std::move(m_val); }
2212
  constexpr const E&& value() const&& { return std::move(m_val); }
2213
2214
 private:
2215
  E m_val;
2216
};
2217
2218
#ifdef __cpp_deduction_guides
2219
template <class E>
2220
unexpected(E) -> unexpected<E>;
2221
#endif
2222
2223
template <class E>
2224
constexpr bool operator==(const unexpected<E>& lhs, const unexpected<E>& rhs) {
2225
  return lhs.value() == rhs.value();
2226
}
2227
template <class E>
2228
constexpr bool operator!=(const unexpected<E>& lhs, const unexpected<E>& rhs) {
2229
  return lhs.value() != rhs.value();
2230
}
2231
template <class E>
2232
constexpr bool operator<(const unexpected<E>& lhs, const unexpected<E>& rhs) {
2233
  return lhs.value() < rhs.value();
2234
}
2235
template <class E>
2236
constexpr bool operator<=(const unexpected<E>& lhs, const unexpected<E>& rhs) {
2237
  return lhs.value() <= rhs.value();
2238
}
2239
template <class E>
2240
constexpr bool operator>(const unexpected<E>& lhs, const unexpected<E>& rhs) {
2241
  return lhs.value() > rhs.value();
2242
}
2243
template <class E>
2244
constexpr bool operator>=(const unexpected<E>& lhs, const unexpected<E>& rhs) {
2245
  return lhs.value() >= rhs.value();
2246
}
2247
2248
template <class E>
2249
unexpected<typename std::decay<E>::type> make_unexpected(E&& e) {
2250
  return unexpected<typename std::decay<E>::type>(std::forward<E>(e));
2251
}
2252
2253
struct unexpect_t {
2254
  unexpect_t() = default;
2255
};
2256
static constexpr unexpect_t unexpect{};
2257
2258
namespace detail {
2259
template <typename E>
2260
0
[[noreturn]] TL_EXPECTED_11_CONSTEXPR void throw_exception(E&& e) {
2261
0
#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED
2262
0
  throw std::forward<E>(e);
2263
#else
2264
  (void)e;
2265
#ifdef _MSC_VER
2266
  __assume(0);
2267
#else
2268
  __builtin_unreachable();
2269
#endif
2270
#endif
2271
0
}
2272
2273
#ifndef TL_TRAITS_MUTEX
2274
#define TL_TRAITS_MUTEX
2275
// C++14-style aliases for brevity
2276
template <class T>
2277
using remove_const_t = typename std::remove_const<T>::type;
2278
template <class T>
2279
using remove_reference_t = typename std::remove_reference<T>::type;
2280
template <class T>
2281
using decay_t = typename std::decay<T>::type;
2282
template <bool E, class T = void>
2283
using enable_if_t = typename std::enable_if<E, T>::type;
2284
template <bool B, class T, class F>
2285
using conditional_t = typename std::conditional<B, T, F>::type;
2286
2287
// std::conjunction from C++17
2288
template <class...>
2289
struct conjunction : std::true_type {};
2290
template <class B>
2291
struct conjunction<B> : B {};
2292
template <class B, class... Bs>
2293
struct conjunction<B, Bs...>
2294
    : std::conditional<bool(B::value), conjunction<Bs...>, B>::type {};
2295
2296
#if defined(_LIBCPP_VERSION) && __cplusplus == 201103L
2297
#define TL_TRAITS_LIBCXX_MEM_FN_WORKAROUND
2298
#endif
2299
2300
// In C++11 mode, there's an issue in libc++'s std::mem_fn
2301
// which results in a hard-error when using it in a noexcept expression
2302
// in some cases. This is a check to workaround the common failing case.
2303
#ifdef TL_TRAITS_LIBCXX_MEM_FN_WORKAROUND
2304
template <class T>
2305
struct is_pointer_to_non_const_member_func : std::false_type {};
2306
template <class T, class Ret, class... Args>
2307
struct is_pointer_to_non_const_member_func<Ret (T::*)(Args...)>
2308
    : std::true_type {};
2309
template <class T, class Ret, class... Args>
2310
struct is_pointer_to_non_const_member_func<Ret (T::*)(Args...) &>
2311
    : std::true_type {};
2312
template <class T, class Ret, class... Args>
2313
struct is_pointer_to_non_const_member_func<Ret (T::*)(Args...) &&>
2314
    : std::true_type {};
2315
template <class T, class Ret, class... Args>
2316
struct is_pointer_to_non_const_member_func<Ret (T::*)(Args...) volatile>
2317
    : std::true_type {};
2318
template <class T, class Ret, class... Args>
2319
struct is_pointer_to_non_const_member_func<Ret (T::*)(Args...) volatile&>
2320
    : std::true_type {};
2321
template <class T, class Ret, class... Args>
2322
struct is_pointer_to_non_const_member_func<Ret (T::*)(Args...) volatile&&>
2323
    : std::true_type {};
2324
2325
template <class T>
2326
struct is_const_or_const_ref : std::false_type {};
2327
template <class T>
2328
struct is_const_or_const_ref<T const&> : std::true_type {};
2329
template <class T>
2330
struct is_const_or_const_ref<T const> : std::true_type {};
2331
#endif
2332
2333
// std::invoke from C++17
2334
// https://stackoverflow.com/questions/38288042/c11-14-invoke-workaround
2335
template <
2336
    typename Fn, typename... Args,
2337
#ifdef TL_TRAITS_LIBCXX_MEM_FN_WORKAROUND
2338
    typename = enable_if_t<!(is_pointer_to_non_const_member_func<Fn>::value &&
2339
                             is_const_or_const_ref<Args...>::value)>,
2340
#endif
2341
    typename = enable_if_t<std::is_member_pointer<decay_t<Fn>>::value>, int = 0>
2342
constexpr auto invoke(Fn&& f, Args&&... args) noexcept(
2343
    noexcept(std::mem_fn(f)(std::forward<Args>(args)...)))
2344
    -> decltype(std::mem_fn(f)(std::forward<Args>(args)...)) {
2345
  return std::mem_fn(f)(std::forward<Args>(args)...);
2346
}
2347
2348
template <typename Fn, typename... Args,
2349
          typename = enable_if_t<!std::is_member_pointer<decay_t<Fn>>::value>>
2350
constexpr auto invoke(Fn&& f, Args&&... args) noexcept(
2351
    noexcept(std::forward<Fn>(f)(std::forward<Args>(args)...)))
2352
    -> decltype(std::forward<Fn>(f)(std::forward<Args>(args)...)) {
2353
  return std::forward<Fn>(f)(std::forward<Args>(args)...);
2354
}
2355
2356
// std::invoke_result from C++17
2357
template <class F, class, class... Us>
2358
struct invoke_result_impl;
2359
2360
template <class F, class... Us>
2361
struct invoke_result_impl<
2362
    F,
2363
    decltype(detail::invoke(std::declval<F>(), std::declval<Us>()...), void()),
2364
    Us...> {
2365
  using type =
2366
      decltype(detail::invoke(std::declval<F>(), std::declval<Us>()...));
2367
};
2368
2369
template <class F, class... Us>
2370
using invoke_result = invoke_result_impl<F, void, Us...>;
2371
2372
template <class F, class... Us>
2373
using invoke_result_t = typename invoke_result<F, Us...>::type;
2374
2375
#if defined(_MSC_VER) && _MSC_VER <= 1900
2376
// TODO make a version which works with MSVC 2015
2377
template <class T, class U = T>
2378
struct is_swappable : std::true_type {};
2379
2380
template <class T, class U = T>
2381
struct is_nothrow_swappable : std::true_type {};
2382
#else
2383
// https://stackoverflow.com/questions/26744589/what-is-a-proper-way-to-implement-is-swappable-to-test-for-the-swappable-concept
2384
namespace swap_adl_tests {
2385
// if swap ADL finds this then it would call std::swap otherwise (same
2386
// signature)
2387
struct tag {};
2388
2389
template <class T>
2390
tag swap(T&, T&);
2391
template <class T, std::size_t N>
2392
tag swap(T (&a)[N], T (&b)[N]);
2393
2394
// helper functions to test if an unqualified swap is possible, and if it
2395
// becomes std::swap
2396
template <class, class>
2397
std::false_type can_swap(...) noexcept(false);
2398
template <class T, class U,
2399
          class = decltype(swap(std::declval<T&>(), std::declval<U&>()))>
2400
std::true_type can_swap(int) noexcept(noexcept(swap(std::declval<T&>(),
2401
                                                    std::declval<U&>())));
2402
2403
template <class, class>
2404
std::false_type uses_std(...);
2405
template <class T, class U>
2406
std::is_same<decltype(swap(std::declval<T&>(), std::declval<U&>())), tag>
2407
uses_std(int);
2408
2409
template <class T>
2410
struct is_std_swap_noexcept
2411
    : std::integral_constant<bool,
2412
                             std::is_nothrow_move_constructible<T>::value &&
2413
                                 std::is_nothrow_move_assignable<T>::value> {};
2414
2415
template <class T, std::size_t N>
2416
struct is_std_swap_noexcept<T[N]> : is_std_swap_noexcept<T> {};
2417
2418
template <class T, class U>
2419
struct is_adl_swap_noexcept
2420
    : std::integral_constant<bool, noexcept(can_swap<T, U>(0))> {};
2421
}  // namespace swap_adl_tests
2422
2423
template <class T, class U = T>
2424
struct is_swappable
2425
    : std::integral_constant<
2426
          bool,
2427
          decltype(detail::swap_adl_tests::can_swap<T, U>(0))::value &&
2428
              (!decltype(detail::swap_adl_tests::uses_std<T, U>(0))::value ||
2429
               (std::is_move_assignable<T>::value &&
2430
                std::is_move_constructible<T>::value))> {};
2431
2432
template <class T, std::size_t N>
2433
struct is_swappable<T[N], T[N]>
2434
    : std::integral_constant<
2435
          bool,
2436
          decltype(detail::swap_adl_tests::can_swap<T[N], T[N]>(0))::value &&
2437
              (!decltype(detail::swap_adl_tests::uses_std<T[N], T[N]>(
2438
                   0))::value ||
2439
               is_swappable<T, T>::value)> {};
2440
2441
template <class T, class U = T>
2442
struct is_nothrow_swappable
2443
    : std::integral_constant<
2444
          bool,
2445
          is_swappable<T, U>::value &&
2446
              ((decltype(detail::swap_adl_tests::uses_std<T, U>(0))::value &&
2447
                detail::swap_adl_tests::is_std_swap_noexcept<T>::value) ||
2448
               (!decltype(detail::swap_adl_tests::uses_std<T, U>(0))::value &&
2449
                detail::swap_adl_tests::is_adl_swap_noexcept<T, U>::value))> {};
2450
#endif
2451
#endif
2452
2453
// Trait for checking if a type is a tl::expected
2454
template <class T>
2455
struct is_expected_impl : std::false_type {};
2456
template <class T, class E>
2457
struct is_expected_impl<expected<T, E>> : std::true_type {};
2458
template <class T>
2459
using is_expected = is_expected_impl<decay_t<T>>;
2460
2461
template <class T, class E, class U>
2462
using expected_enable_forward_value = detail::enable_if_t<
2463
    std::is_constructible<T, U&&>::value &&
2464
    !std::is_same<detail::decay_t<U>, in_place_t>::value &&
2465
    !std::is_same<expected<T, E>, detail::decay_t<U>>::value &&
2466
    !std::is_same<unexpected<E>, detail::decay_t<U>>::value>;
2467
2468
template <class T, class E, class U, class G, class UR, class GR>
2469
using expected_enable_from_other = detail::enable_if_t<
2470
    std::is_constructible<T, UR>::value &&
2471
    std::is_constructible<E, GR>::value &&
2472
    !std::is_constructible<T, expected<U, G>&>::value &&
2473
    !std::is_constructible<T, expected<U, G>&&>::value &&
2474
    !std::is_constructible<T, const expected<U, G>&>::value &&
2475
    !std::is_constructible<T, const expected<U, G>&&>::value &&
2476
    !std::is_convertible<expected<U, G>&, T>::value &&
2477
    !std::is_convertible<expected<U, G>&&, T>::value &&
2478
    !std::is_convertible<const expected<U, G>&, T>::value &&
2479
    !std::is_convertible<const expected<U, G>&&, T>::value>;
2480
2481
template <class T, class U>
2482
using is_void_or = conditional_t<std::is_void<T>::value, std::true_type, U>;
2483
2484
template <class T>
2485
using is_copy_constructible_or_void =
2486
    is_void_or<T, std::is_copy_constructible<T>>;
2487
2488
template <class T>
2489
using is_move_constructible_or_void =
2490
    is_void_or<T, std::is_move_constructible<T>>;
2491
2492
template <class T>
2493
using is_copy_assignable_or_void = is_void_or<T, std::is_copy_assignable<T>>;
2494
2495
template <class T>
2496
using is_move_assignable_or_void = is_void_or<T, std::is_move_assignable<T>>;
2497
2498
}  // namespace detail
2499
2500
namespace detail {
2501
struct no_init_t {};
2502
static constexpr no_init_t no_init{};
2503
2504
// Implements the storage of the values, and ensures that the destructor is
2505
// trivial if it can be.
2506
//
2507
// This specialization is for where neither `T` or `E` is trivially
2508
// destructible, so the destructors must be called on destruction of the
2509
// `expected`
2510
template <class T, class E, bool = std::is_trivially_destructible<T>::value,
2511
          bool = std::is_trivially_destructible<E>::value>
2512
struct expected_storage_base {
2513
  constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {}
2514
  constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {}
2515
2516
  template <class... Args,
2517
            detail::enable_if_t<std::is_constructible<T, Args&&...>::value>* =
2518
                nullptr>
2519
  constexpr expected_storage_base(in_place_t, Args&&... args)
2520
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
2521
2522
  template <class U, class... Args,
2523
            detail::enable_if_t<std::is_constructible<
2524
                T, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
2525
  constexpr expected_storage_base(in_place_t, std::initializer_list<U> il,
2526
                                  Args&&... args)
2527
      : m_val(il, std::forward<Args>(args)...), m_has_val(true) {}
2528
  template <class... Args,
2529
            detail::enable_if_t<std::is_constructible<E, Args&&...>::value>* =
2530
                nullptr>
2531
  constexpr explicit expected_storage_base(unexpect_t, Args&&... args)
2532
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
2533
2534
  template <class U, class... Args,
2535
            detail::enable_if_t<std::is_constructible<
2536
                E, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
2537
  constexpr explicit expected_storage_base(unexpect_t,
2538
                                           std::initializer_list<U> il,
2539
                                           Args&&... args)
2540
      : m_unexpect(il, std::forward<Args>(args)...), m_has_val(false) {}
2541
2542
  ~expected_storage_base() {
2543
    if (m_has_val) {
2544
      m_val.~T();
2545
    } else {
2546
      m_unexpect.~unexpected<E>();
2547
    }
2548
  }
2549
  union {
2550
    T m_val;
2551
    unexpected<E> m_unexpect;
2552
    char m_no_init;
2553
  };
2554
  bool m_has_val;
2555
};
2556
2557
// This specialization is for when both `T` and `E` are trivially-destructible,
2558
// so the destructor of the `expected` can be trivial.
2559
template <class T, class E>
2560
struct expected_storage_base<T, E, true, true> {
2561
  constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {}
2562
  constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {}
2563
2564
  template <class... Args,
2565
            detail::enable_if_t<std::is_constructible<T, Args&&...>::value>* =
2566
                nullptr>
2567
  constexpr expected_storage_base(in_place_t, Args&&... args)
2568
424k
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseIN3ada22url_search_params_iterINSt3__117basic_string_viewIcNS4_11char_traitsIcEEEELNS2_27url_search_params_iter_typeE0EEENS2_6errorsELb1ELb1EEC2IJSA_ETnPNS4_9enable_ifIXsr3std16is_constructibleISA_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESH_
Line
Count
Source
2568
13.7k
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseIN3ada22url_search_params_iterINSt3__117basic_string_viewIcNS4_11char_traitsIcEEEELNS2_27url_search_params_iter_typeE1EEENS2_6errorsELb1ELb1EEC2IJSA_ETnPNS4_9enable_ifIXsr3std16is_constructibleISA_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESH_
Line
Count
Source
2568
13.7k
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseIN3ada22url_search_params_iterINSt3__14pairINS4_17basic_string_viewIcNS4_11char_traitsIcEEEES9_EELNS2_27url_search_params_iter_typeE2EEENS2_6errorsELb1ELb1EEC2IJSC_ETnPNS4_9enable_ifIXsr3std16is_constructibleISC_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESJ_
Line
Count
Source
2568
13.7k
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
2569
2570
  template <class U, class... Args,
2571
            detail::enable_if_t<std::is_constructible<
2572
                T, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
2573
  constexpr expected_storage_base(in_place_t, std::initializer_list<U> il,
2574
                                  Args&&... args)
2575
      : m_val(il, std::forward<Args>(args)...), m_has_val(true) {}
2576
  template <class... Args,
2577
            detail::enable_if_t<std::is_constructible<E, Args&&...>::value>* =
2578
                nullptr>
2579
  constexpr explicit expected_storage_base(unexpect_t, Args&&... args)
2580
0
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
2581
2582
  template <class U, class... Args,
2583
            detail::enable_if_t<std::is_constructible<
2584
                E, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
2585
  constexpr explicit expected_storage_base(unexpect_t,
2586
                                           std::initializer_list<U> il,
2587
                                           Args&&... args)
2588
      : m_unexpect(il, std::forward<Args>(args)...), m_has_val(false) {}
2589
2590
  ~expected_storage_base() = default;
2591
  union {
2592
    T m_val;
2593
    unexpected<E> m_unexpect;
2594
    char m_no_init;
2595
  };
2596
  bool m_has_val;
2597
};
2598
2599
// T is trivial, E is not.
2600
template <class T, class E>
2601
struct expected_storage_base<T, E, true, false> {
2602
  constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {}
2603
  TL_EXPECTED_MSVC2015_CONSTEXPR expected_storage_base(no_init_t)
2604
      : m_no_init(), m_has_val(false) {}
2605
2606
  template <class... Args,
2607
            detail::enable_if_t<std::is_constructible<T, Args&&...>::value>* =
2608
                nullptr>
2609
  constexpr expected_storage_base(in_place_t, Args&&... args)
2610
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
2611
2612
  template <class U, class... Args,
2613
            detail::enable_if_t<std::is_constructible<
2614
                T, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
2615
  constexpr expected_storage_base(in_place_t, std::initializer_list<U> il,
2616
                                  Args&&... args)
2617
      : m_val(il, std::forward<Args>(args)...), m_has_val(true) {}
2618
  template <class... Args,
2619
            detail::enable_if_t<std::is_constructible<E, Args&&...>::value>* =
2620
                nullptr>
2621
  constexpr explicit expected_storage_base(unexpect_t, Args&&... args)
2622
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
2623
2624
  template <class U, class... Args,
2625
            detail::enable_if_t<std::is_constructible<
2626
                E, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
2627
  constexpr explicit expected_storage_base(unexpect_t,
2628
                                           std::initializer_list<U> il,
2629
                                           Args&&... args)
2630
      : m_unexpect(il, std::forward<Args>(args)...), m_has_val(false) {}
2631
2632
  ~expected_storage_base() {
2633
    if (!m_has_val) {
2634
      m_unexpect.~unexpected<E>();
2635
    }
2636
  }
2637
2638
  union {
2639
    T m_val;
2640
    unexpected<E> m_unexpect;
2641
    char m_no_init;
2642
  };
2643
  bool m_has_val;
2644
};
2645
2646
// E is trivial, T is not.
2647
template <class T, class E>
2648
struct expected_storage_base<T, E, false, true> {
2649
639k
  constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {}
2650
80.9k
  constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {}
tl::detail::expected_storage_base<ada::url_aggregator, ada::errors, false, true>::expected_storage_base(tl::detail::no_init_t)
Line
Count
Source
2650
72.3k
  constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {}
tl::detail::expected_storage_base<ada::url_pattern_list<ada::url_pattern_regex::std_regex_provider>, ada::errors, false, true>::expected_storage_base(tl::detail::no_init_t)
Line
Count
Source
2650
8.57k
  constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {}
2651
2652
  template <class... Args,
2653
            detail::enable_if_t<std::is_constructible<T, Args&&...>::value>* =
2654
                nullptr>
2655
  constexpr expected_storage_base(in_place_t, Args&&... args)
2656
19.0M
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseIN3ada3urlENS2_6errorsELb0ELb1EEC2IJS3_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS3_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESB_
Line
Count
Source
2656
683k
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseIN3ada14url_aggregatorENS2_6errorsELb0ELb1EEC2IJS3_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS3_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESB_
Line
Count
Source
2656
1.95M
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseIN3ada16url_pattern_initENS2_6errorsELb0ELb1EEC2IJS3_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS3_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESB_
Line
Count
Source
2656
574k
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseINSt3__112basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEEN3ada6errorsELb0ELb1EEC2IJS8_ETnPNS2_9enable_ifIXsr3std16is_constructibleIS8_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESG_
Line
Count
Source
2656
2.13M
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseINSt3__112basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEEN3ada6errorsELb0ELb1EEC2IJRA1_KcETnPNS2_9enable_ifIXsr3std16is_constructibleIS8_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESJ_
Line
Count
Source
2656
4.12M
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseINSt3__112basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEEN3ada6errorsELb0ELb1EEC2IJRA2_KcETnPNS2_9enable_ifIXsr3std16is_constructibleIS8_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESJ_
Line
Count
Source
2656
54
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseINSt3__16vectorIN3ada19url_pattern_helpers5tokenENS2_9allocatorIS6_EEEENS4_6errorsELb0ELb1EEC2IJRS9_ETnPNS2_9enable_ifIXsr3std16is_constructibleIS9_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESH_
Line
Count
Source
2656
3.07M
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseIN3ada23url_pattern_list_detail15compiled_routesENS2_6errorsELb0ELb1EEC2IJS4_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS4_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESC_
Line
Count
Source
2656
8.63k
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseIN3ada17url_search_paramsENS2_6errorsELb0ELb1EEC2IJS3_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS3_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESB_
Line
Count
Source
2656
13.7k
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseINSt3__16vectorINS2_12basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEENS7_IS9_EEEEN3ada6errorsELb0ELb1EEC2IJSB_ETnPNS2_9enable_ifIXsr3std16is_constructibleISB_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESJ_
Line
Count
Source
2656
13.7k
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseINSt3__16vectorIN3ada16url_pattern_partENS2_9allocatorIS5_EEEENS4_6errorsELb0ELb1EEC2IJRS8_ETnPNS2_9enable_ifIXsr3std16is_constructibleIS8_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESG_
Line
Count
Source
2656
2.98M
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseIN3ada16url_pattern_initENS2_6errorsELb0ELb1EEC2IJRS3_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS3_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESC_
Line
Count
Source
2656
87.5k
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseIN3ada21url_pattern_componentINS2_17url_pattern_regex18std_regex_providerEEENS2_6errorsELb0ELb1EEC2IJS6_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS6_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESE_
Line
Count
Source
2656
2.58M
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseIN3ada11url_patternINS2_17url_pattern_regex18std_regex_providerEEENS2_6errorsELb0ELb1EEC2IJS6_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS6_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESE_
Line
Count
Source
2656
311k
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseIN3ada16url_pattern_listINS2_17url_pattern_regex18std_regex_providerEEENS2_6errorsELb0ELb1EEC2IJS6_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS6_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESE_
Line
Count
Source
2656
8.63k
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseINSt3__18optionalIN3ada18url_pattern_resultEEENS4_6errorsELb0ELb1EEC2IJRKNS2_9nullopt_tEETnPNS2_9enable_ifIXsr3std16is_constructibleIS6_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESG_
Line
Count
Source
2656
457k
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
_ZN2tl6detail21expected_storage_baseINSt3__18optionalIN3ada18url_pattern_resultEEENS4_6errorsELb0ELb1EEC2IJS5_ETnPNS2_9enable_ifIXsr3std16is_constructibleIS6_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESD_
Line
Count
Source
2656
54.2k
      : m_val(std::forward<Args>(args)...), m_has_val(true) {}
2657
2658
  template <class U, class... Args,
2659
            detail::enable_if_t<std::is_constructible<
2660
                T, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
2661
  constexpr expected_storage_base(in_place_t, std::initializer_list<U> il,
2662
                                  Args&&... args)
2663
      : m_val(il, std::forward<Args>(args)...), m_has_val(true) {}
2664
  template <class... Args,
2665
            detail::enable_if_t<std::is_constructible<E, Args&&...>::value>* =
2666
                nullptr>
2667
  constexpr explicit expected_storage_base(unexpect_t, Args&&... args)
2668
977k
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
_ZN2tl6detail21expected_storage_baseIN3ada3urlENS2_6errorsELb0ELb1EEC2IJS4_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS4_DpOT_EE5valueEvE4typeELPv0EEENS_10unexpect_tESB_
Line
Count
Source
2668
76.1k
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
_ZN2tl6detail21expected_storage_baseIN3ada14url_aggregatorENS2_6errorsELb0ELb1EEC2IJS4_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS4_DpOT_EE5valueEvE4typeELPv0EEENS_10unexpect_tESB_
Line
Count
Source
2668
703k
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
_ZN2tl6detail21expected_storage_baseIN3ada16url_pattern_initENS2_6errorsELb0ELb1EEC2IJS4_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS4_DpOT_EE5valueEvE4typeELPv0EEENS_10unexpect_tESB_
Line
Count
Source
2668
58.8k
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
_ZN2tl6detail21expected_storage_baseINSt3__112basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEEN3ada6errorsELb0ELb1EEC2IJSA_ETnPNS2_9enable_ifIXsr3std16is_constructibleISA_DpOT_EE5valueEvE4typeELPv0EEENS_10unexpect_tESG_
Line
Count
Source
2668
5.06k
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
_ZN2tl6detail21expected_storage_baseINSt3__16vectorIN3ada19url_pattern_helpers5tokenENS2_9allocatorIS6_EEEENS4_6errorsELb0ELb1EEC2IJSA_ETnPNS2_9enable_ifIXsr3std16is_constructibleISA_DpOT_EE5valueEvE4typeELPv0EEENS_10unexpect_tESG_
Line
Count
Source
2668
2.07k
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
_ZN2tl6detail21expected_storage_baseIN3ada23url_pattern_list_detail15compiled_routesENS2_6errorsELb0ELb1EEC2IJS5_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS5_DpOT_EE5valueEvE4typeELPv0EEENS_10unexpect_tESC_
Line
Count
Source
2668
760
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
_ZN2tl6detail21expected_storage_baseINSt3__16vectorIN3ada16url_pattern_partENS2_9allocatorIS5_EEEENS4_6errorsELb0ELb1EEC2IJS9_ETnPNS2_9enable_ifIXsr3std16is_constructibleIS9_DpOT_EE5valueEvE4typeELPv0EEENS_10unexpect_tESF_
Line
Count
Source
2668
8.47k
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
_ZN2tl6detail21expected_storage_baseIN3ada11url_patternINS2_17url_pattern_regex18std_regex_providerEEENS2_6errorsELb0ELb1EEC2IJS7_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS7_DpOT_EE5valueEvE4typeELPv0EEENS_10unexpect_tESE_
Line
Count
Source
2668
110k
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
_ZN2tl6detail21expected_storage_baseIN3ada21url_pattern_componentINS2_17url_pattern_regex18std_regex_providerEEENS2_6errorsELb0ELb1EEC2IJS7_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS7_DpOT_EE5valueEvE4typeELPv0EEENS_10unexpect_tESE_
Line
Count
Source
2668
10.2k
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
_ZN2tl6detail21expected_storage_baseIN3ada16url_pattern_listINS2_17url_pattern_regex18std_regex_providerEEENS2_6errorsELb0ELb1EEC2IJS7_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS7_DpOT_EE5valueEvE4typeELPv0EEENS_10unexpect_tESE_
Line
Count
Source
2668
1.57k
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
Unexecuted instantiation: _ZN2tl6detail21expected_storage_baseINSt3__18optionalIN3ada18url_pattern_resultEEENS4_6errorsELb0ELb1EEC2IJS7_ETnPNS2_9enable_ifIXsr3std16is_constructibleIS7_DpOT_EE5valueEvE4typeELPv0EEENS_10unexpect_tESD_
2669
2670
  template <class U, class... Args,
2671
            detail::enable_if_t<std::is_constructible<
2672
                E, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
2673
  constexpr explicit expected_storage_base(unexpect_t,
2674
                                           std::initializer_list<U> il,
2675
                                           Args&&... args)
2676
      : m_unexpect(il, std::forward<Args>(args)...), m_has_val(false) {}
2677
2678
20.7M
  ~expected_storage_base() {
2679
20.7M
    if (m_has_val) {
2680
19.7M
      m_val.~T();
2681
19.7M
    }
2682
20.7M
  }
tl::detail::expected_storage_base<ada::url, ada::errors, false, true>::~expected_storage_base()
Line
Count
Source
2678
759k
  ~expected_storage_base() {
2679
759k
    if (m_has_val) {
2680
683k
      m_val.~T();
2681
683k
    }
2682
759k
  }
tl::detail::expected_storage_base<ada::url_aggregator, ada::errors, false, true>::~expected_storage_base()
Line
Count
Source
2678
3.36M
  ~expected_storage_base() {
2679
3.36M
    if (m_has_val) {
2680
2.65M
      m_val.~T();
2681
2.65M
    }
2682
3.36M
  }
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()
Line
Count
Source
2678
6.26M
  ~expected_storage_base() {
2679
6.26M
    if (m_has_val) {
2680
6.25M
      m_val.~T();
2681
6.25M
    }
2682
6.26M
  }
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()
Line
Count
Source
2678
2.99M
  ~expected_storage_base() {
2679
2.99M
    if (m_has_val) {
2680
2.98M
      m_val.~T();
2681
2.98M
    }
2682
2.99M
  }
tl::detail::expected_storage_base<ada::url_search_params, ada::errors, false, true>::~expected_storage_base()
Line
Count
Source
2678
13.7k
  ~expected_storage_base() {
2679
13.7k
    if (m_has_val) {
2680
13.7k
      m_val.~T();
2681
13.7k
    }
2682
13.7k
  }
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()
Line
Count
Source
2678
13.7k
  ~expected_storage_base() {
2679
13.7k
    if (m_has_val) {
2680
13.7k
      m_val.~T();
2681
13.7k
    }
2682
13.7k
  }
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()
Line
Count
Source
2678
3.07M
  ~expected_storage_base() {
2679
3.07M
    if (m_has_val) {
2680
3.07M
      m_val.~T();
2681
3.07M
    }
2682
3.07M
  }
tl::detail::expected_storage_base<ada::url_pattern_init, ada::errors, false, true>::~expected_storage_base()
Line
Count
Source
2678
721k
  ~expected_storage_base() {
2679
721k
    if (m_has_val) {
2680
662k
      m_val.~T();
2681
662k
    }
2682
721k
  }
tl::detail::expected_storage_base<ada::url_pattern_component<ada::url_pattern_regex::std_regex_provider>, ada::errors, false, true>::~expected_storage_base()
Line
Count
Source
2678
2.59M
  ~expected_storage_base() {
2679
2.59M
    if (m_has_val) {
2680
2.58M
      m_val.~T();
2681
2.58M
    }
2682
2.59M
  }
tl::detail::expected_storage_base<ada::url_pattern<ada::url_pattern_regex::std_regex_provider>, ada::errors, false, true>::~expected_storage_base()
Line
Count
Source
2678
421k
  ~expected_storage_base() {
2679
421k
    if (m_has_val) {
2680
311k
      m_val.~T();
2681
311k
    }
2682
421k
  }
tl::detail::expected_storage_base<ada::url_pattern_list<ada::url_pattern_regex::std_regex_provider>, ada::errors, false, true>::~expected_storage_base()
Line
Count
Source
2678
18.7k
  ~expected_storage_base() {
2679
18.7k
    if (m_has_val) {
2680
16.4k
      m_val.~T();
2681
16.4k
    }
2682
18.7k
  }
tl::detail::expected_storage_base<ada::url_pattern_list_detail::compiled_routes, ada::errors, false, true>::~expected_storage_base()
Line
Count
Source
2678
9.39k
  ~expected_storage_base() {
2679
9.39k
    if (m_has_val) {
2680
8.63k
      m_val.~T();
2681
8.63k
    }
2682
9.39k
  }
tl::detail::expected_storage_base<std::__1::optional<ada::url_pattern_result>, ada::errors, false, true>::~expected_storage_base()
Line
Count
Source
2678
511k
  ~expected_storage_base() {
2679
511k
    if (m_has_val) {
2680
511k
      m_val.~T();
2681
511k
    }
2682
511k
  }
2683
  union {
2684
    T m_val;
2685
    unexpected<E> m_unexpect;
2686
    char m_no_init;
2687
  };
2688
  bool m_has_val;
2689
};
2690
2691
// `T` is `void`, `E` is trivially-destructible
2692
template <class E>
2693
struct expected_storage_base<void, E, false, true> {
2694
#if __GNUC__ <= 5
2695
// no constexpr for GCC 4/5 bug
2696
#else
2697
  TL_EXPECTED_MSVC2015_CONSTEXPR
2698
#endif
2699
  expected_storage_base() : m_has_val(true) {}
2700
2701
  constexpr expected_storage_base(no_init_t) : m_val(), m_has_val(false) {}
2702
2703
  constexpr expected_storage_base(in_place_t) : m_has_val(true) {}
2704
2705
  template <class... Args,
2706
            detail::enable_if_t<std::is_constructible<E, Args&&...>::value>* =
2707
                nullptr>
2708
  constexpr explicit expected_storage_base(unexpect_t, Args&&... args)
2709
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
2710
2711
  template <class U, class... Args,
2712
            detail::enable_if_t<std::is_constructible<
2713
                E, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
2714
  constexpr explicit expected_storage_base(unexpect_t,
2715
                                           std::initializer_list<U> il,
2716
                                           Args&&... args)
2717
      : m_unexpect(il, std::forward<Args>(args)...), m_has_val(false) {}
2718
2719
  ~expected_storage_base() = default;
2720
  struct dummy {};
2721
  union {
2722
    unexpected<E> m_unexpect;
2723
    dummy m_val;
2724
  };
2725
  bool m_has_val;
2726
};
2727
2728
// `T` is `void`, `E` is not trivially-destructible
2729
template <class E>
2730
struct expected_storage_base<void, E, false, false> {
2731
  constexpr expected_storage_base() : m_dummy(), m_has_val(true) {}
2732
  constexpr expected_storage_base(no_init_t) : m_dummy(), m_has_val(false) {}
2733
2734
  constexpr expected_storage_base(in_place_t) : m_dummy(), m_has_val(true) {}
2735
2736
  template <class... Args,
2737
            detail::enable_if_t<std::is_constructible<E, Args&&...>::value>* =
2738
                nullptr>
2739
  constexpr explicit expected_storage_base(unexpect_t, Args&&... args)
2740
      : m_unexpect(std::forward<Args>(args)...), m_has_val(false) {}
2741
2742
  template <class U, class... Args,
2743
            detail::enable_if_t<std::is_constructible<
2744
                E, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
2745
  constexpr explicit expected_storage_base(unexpect_t,
2746
                                           std::initializer_list<U> il,
2747
                                           Args&&... args)
2748
      : m_unexpect(il, std::forward<Args>(args)...), m_has_val(false) {}
2749
2750
  ~expected_storage_base() {
2751
    if (!m_has_val) {
2752
      m_unexpect.~unexpected<E>();
2753
    }
2754
  }
2755
2756
  union {
2757
    unexpected<E> m_unexpect;
2758
    char m_dummy;
2759
  };
2760
  bool m_has_val;
2761
};
2762
2763
// This base class provides some handy member functions which can be used in
2764
// further derived classes
2765
template <class T, class E>
2766
struct expected_operations_base : expected_storage_base<T, E> {
2767
  using expected_storage_base<T, E>::expected_storage_base;
2768
2769
  template <class... Args>
2770
0
  void construct(Args&&... args) noexcept {
2771
0
    new (std::addressof(this->m_val)) T(std::forward<Args>(args)...);
2772
0
    this->m_has_val = true;
2773
0
  }
2774
2775
  template <class Rhs>
2776
  // NOLINTNEXTLINE(bugprone-exception-escape)
2777
70.9k
  void construct_with(Rhs&& rhs) noexcept {
2778
70.9k
    new (std::addressof(this->m_val)) T(std::forward<Rhs>(rhs).get());
2779
70.9k
    this->m_has_val = true;
2780
70.9k
  }
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&)
Line
Count
Source
2777
63.1k
  void construct_with(Rhs&& rhs) noexcept {
2778
63.1k
    new (std::addressof(this->m_val)) T(std::forward<Rhs>(rhs).get());
2779
63.1k
    this->m_has_val = true;
2780
63.1k
  }
void tl::detail::expected_operations_base<ada::url_pattern_list<ada::url_pattern_regex::std_regex_provider>, ada::errors>::construct_with<tl::detail::expected_move_base<ada::url_pattern_list<ada::url_pattern_regex::std_regex_provider>, ada::errors, false> >(tl::detail::expected_move_base<ada::url_pattern_list<ada::url_pattern_regex::std_regex_provider>, ada::errors, false>&&)
Line
Count
Source
2777
7.81k
  void construct_with(Rhs&& rhs) noexcept {
2778
7.81k
    new (std::addressof(this->m_val)) T(std::forward<Rhs>(rhs).get());
2779
7.81k
    this->m_has_val = true;
2780
7.81k
  }
2781
2782
  template <class... Args>
2783
9.96k
  void construct_error(Args&&... args) noexcept {
2784
9.96k
    new (std::addressof(this->m_unexpect))
2785
9.96k
        unexpected<E>(std::forward<Args>(args)...);
2786
9.96k
    this->m_has_val = false;
2787
9.96k
  }
void tl::detail::expected_operations_base<ada::url_aggregator, ada::errors>::construct_error<tl::unexpected<ada::errors> const&>(tl::unexpected<ada::errors> const&)
Line
Count
Source
2783
9.20k
  void construct_error(Args&&... args) noexcept {
2784
9.20k
    new (std::addressof(this->m_unexpect))
2785
9.20k
        unexpected<E>(std::forward<Args>(args)...);
2786
9.20k
    this->m_has_val = false;
2787
9.20k
  }
void tl::detail::expected_operations_base<ada::url_pattern_list<ada::url_pattern_regex::std_regex_provider>, ada::errors>::construct_error<tl::unexpected<ada::errors> >(tl::unexpected<ada::errors>&&)
Line
Count
Source
2783
760
  void construct_error(Args&&... args) noexcept {
2784
760
    new (std::addressof(this->m_unexpect))
2785
760
        unexpected<E>(std::forward<Args>(args)...);
2786
760
    this->m_has_val = false;
2787
760
  }
Unexecuted instantiation: void tl::detail::expected_operations_base<ada::url_aggregator, ada::errors>::construct_error<tl::unexpected<ada::errors> >(tl::unexpected<ada::errors>&&)
2788
2789
#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED
2790
2791
  // These assign overloads ensure that the most efficient assignment
2792
  // implementation is used while maintaining the strong exception guarantee.
2793
  // The problematic case is where rhs has a value, but *this does not.
2794
  //
2795
  // This overload handles the case where we can just copy-construct `T`
2796
  // directly into place without throwing.
2797
  template <class U = T,
2798
            detail::enable_if_t<std::is_nothrow_copy_constructible<U>::value>* =
2799
                nullptr>
2800
  void assign(const expected_operations_base& rhs) noexcept {
2801
    if (!this->m_has_val && rhs.m_has_val) {
2802
      geterr().~unexpected<E>();
2803
      construct(rhs.get());
2804
    } else {
2805
      assign_common(rhs);
2806
    }
2807
  }
2808
2809
  // This overload handles the case where we can attempt to create a copy of
2810
  // `T`, then no-throw move it into place if the copy was successful.
2811
  template <class U = T,
2812
            detail::enable_if_t<!std::is_nothrow_copy_constructible<U>::value &&
2813
                                std::is_nothrow_move_constructible<U>::value>* =
2814
                nullptr>
2815
  void assign(const expected_operations_base& rhs) noexcept {
2816
    if (!this->m_has_val && rhs.m_has_val) {
2817
      T tmp = rhs.get();
2818
      geterr().~unexpected<E>();
2819
      construct(std::move(tmp));
2820
    } else {
2821
      assign_common(rhs);
2822
    }
2823
  }
2824
2825
  // This overload is the worst-case, where we have to move-construct the
2826
  // unexpected value into temporary storage, then try to copy the T into place.
2827
  // If the construction succeeds, then everything is fine, but if it throws,
2828
  // then we move the old unexpected value back into place before rethrowing the
2829
  // exception.
2830
  template <class U = T,
2831
            detail::enable_if_t<
2832
                !std::is_nothrow_copy_constructible<U>::value &&
2833
                !std::is_nothrow_move_constructible<U>::value>* = nullptr>
2834
  void assign(const expected_operations_base& rhs) {
2835
    if (!this->m_has_val && rhs.m_has_val) {
2836
      auto tmp = std::move(geterr());
2837
      geterr().~unexpected<E>();
2838
2839
#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED
2840
      try {
2841
        construct(rhs.get());
2842
      } catch (...) {
2843
        geterr() = std::move(tmp);
2844
        throw;
2845
      }
2846
#else
2847
      construct(rhs.get());
2848
#endif
2849
    } else {
2850
      assign_common(rhs);
2851
    }
2852
  }
2853
2854
  // These overloads do the same as above, but for rvalues
2855
  template <class U = T,
2856
            detail::enable_if_t<std::is_nothrow_move_constructible<U>::value>* =
2857
                nullptr>
2858
255k
  void assign(expected_operations_base&& rhs) noexcept {
2859
255k
    if (!this->m_has_val && rhs.m_has_val) {
2860
0
      geterr().~unexpected<E>();
2861
0
      construct(std::move(rhs).get());
2862
255k
    } else {
2863
255k
      assign_common(std::move(rhs));
2864
255k
    }
2865
255k
  }
2866
2867
  template <class U = T,
2868
            detail::enable_if_t<
2869
                !std::is_nothrow_move_constructible<U>::value>* = nullptr>
2870
  void assign(expected_operations_base&& rhs) {
2871
    if (!this->m_has_val && rhs.m_has_val) {
2872
      auto tmp = std::move(geterr());
2873
      geterr().~unexpected<E>();
2874
#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED
2875
      try {
2876
        construct(std::move(rhs).get());
2877
      } catch (...) {
2878
        geterr() = std::move(tmp);
2879
        throw;
2880
      }
2881
#else
2882
      construct(std::move(rhs).get());
2883
#endif
2884
    } else {
2885
      assign_common(std::move(rhs));
2886
    }
2887
  }
2888
2889
#else
2890
2891
  // If exceptions are disabled then we can just copy-construct
2892
  void assign(const expected_operations_base& rhs) noexcept {
2893
    if (!this->m_has_val && rhs.m_has_val) {
2894
      geterr().~unexpected<E>();
2895
      construct(rhs.get());
2896
    } else {
2897
      assign_common(rhs);
2898
    }
2899
  }
2900
2901
  void assign(expected_operations_base&& rhs) noexcept {
2902
    if (!this->m_has_val && rhs.m_has_val) {
2903
      geterr().~unexpected<E>();
2904
      construct(std::move(rhs).get());
2905
    } else {
2906
      assign_common(std::move(rhs));
2907
    }
2908
  }
2909
2910
#endif
2911
2912
  // The common part of move/copy assigning
2913
  template <class Rhs>
2914
255k
  void assign_common(Rhs&& rhs) {
2915
255k
    if (this->m_has_val) {
2916
255k
      if (rhs.m_has_val) {
2917
255k
        get() = std::forward<Rhs>(rhs).get();
2918
255k
      } else {
2919
0
        destroy_val();
2920
0
        construct_error(std::forward<Rhs>(rhs).geterr());
2921
0
      }
2922
255k
    } else {
2923
0
      if (!rhs.m_has_val) {
2924
0
        geterr() = std::forward<Rhs>(rhs).geterr();
2925
0
      }
2926
0
    }
2927
255k
  }
2928
2929
80.9k
  bool has_value() const { return this->m_has_val; }
tl::detail::expected_operations_base<ada::url_aggregator, ada::errors>::has_value() const
Line
Count
Source
2929
72.3k
  bool has_value() const { return this->m_has_val; }
tl::detail::expected_operations_base<ada::url_pattern_list<ada::url_pattern_regex::std_regex_provider>, ada::errors>::has_value() const
Line
Count
Source
2929
8.57k
  bool has_value() const { return this->m_has_val; }
2930
2931
255k
  TL_EXPECTED_11_CONSTEXPR T& get() & { return this->m_val; }
2932
63.1k
  constexpr const T& get() const& { return this->m_val; }
2933
263k
  TL_EXPECTED_11_CONSTEXPR T&& get() && { return std::move(this->m_val); }
tl::detail::expected_operations_base<ada::url_pattern_list<ada::url_pattern_regex::std_regex_provider>, ada::errors>::get() &&
Line
Count
Source
2933
7.81k
  TL_EXPECTED_11_CONSTEXPR T&& get() && { return std::move(this->m_val); }
tl::detail::expected_operations_base<ada::url_aggregator, ada::errors>::get() &&
Line
Count
Source
2933
255k
  TL_EXPECTED_11_CONSTEXPR T&& get() && { return std::move(this->m_val); }
2934
#ifndef TL_EXPECTED_NO_CONSTRR
2935
  constexpr const T&& get() const&& { return std::move(this->m_val); }
2936
#endif
2937
2938
760
  TL_EXPECTED_11_CONSTEXPR unexpected<E>& geterr() & {
2939
760
    return this->m_unexpect;
2940
760
  }
tl::detail::expected_operations_base<ada::url_pattern_list<ada::url_pattern_regex::std_regex_provider>, ada::errors>::geterr() &
Line
Count
Source
2938
760
  TL_EXPECTED_11_CONSTEXPR unexpected<E>& geterr() & {
2939
760
    return this->m_unexpect;
2940
760
  }
Unexecuted instantiation: tl::detail::expected_operations_base<ada::url_aggregator, ada::errors>::geterr() &
2941
9.20k
  constexpr const unexpected<E>& geterr() const& { return this->m_unexpect; }
2942
0
  TL_EXPECTED_11_CONSTEXPR unexpected<E>&& geterr() && {
2943
0
    return std::move(this->m_unexpect);
2944
0
  }
2945
#ifndef TL_EXPECTED_NO_CONSTRR
2946
  constexpr const unexpected<E>&& geterr() const&& {
2947
    return std::move(this->m_unexpect);
2948
  }
2949
#endif
2950
2951
0
  TL_EXPECTED_11_CONSTEXPR void destroy_val() { get().~T(); }
2952
};
2953
2954
// This base class provides some handy member functions which can be used in
2955
// further derived classes
2956
template <class E>
2957
struct expected_operations_base<void, E> : expected_storage_base<void, E> {
2958
  using expected_storage_base<void, E>::expected_storage_base;
2959
2960
  template <class... Args>
2961
  void construct() noexcept {
2962
    this->m_has_val = true;
2963
  }
2964
2965
  // This function doesn't use its argument, but needs it so that code in
2966
  // levels above this can work independently of whether T is void
2967
  template <class Rhs>
2968
  void construct_with(Rhs&&) noexcept {
2969
    this->m_has_val = true;
2970
  }
2971
2972
  template <class... Args>
2973
  void construct_error(Args&&... args) noexcept {
2974
    new (std::addressof(this->m_unexpect))
2975
        unexpected<E>(std::forward<Args>(args)...);
2976
    this->m_has_val = false;
2977
  }
2978
2979
  template <class Rhs>
2980
  void assign(Rhs&& rhs) noexcept {
2981
    if (!this->m_has_val) {
2982
      if (rhs.m_has_val) {
2983
        geterr().~unexpected<E>();
2984
        construct();
2985
      } else {
2986
        geterr() = std::forward<Rhs>(rhs).geterr();
2987
      }
2988
    } else {
2989
      if (!rhs.m_has_val) {
2990
        construct_error(std::forward<Rhs>(rhs).geterr());
2991
      }
2992
    }
2993
  }
2994
2995
  bool has_value() const { return this->m_has_val; }
2996
2997
  TL_EXPECTED_11_CONSTEXPR unexpected<E>& geterr() & {
2998
    return this->m_unexpect;
2999
  }
3000
  constexpr const unexpected<E>& geterr() const& { return this->m_unexpect; }
3001
  TL_EXPECTED_11_CONSTEXPR unexpected<E>&& geterr() && {
3002
    return std::move(this->m_unexpect);
3003
  }
3004
#ifndef TL_EXPECTED_NO_CONSTRR
3005
  constexpr const unexpected<E>&& geterr() const&& {
3006
    return std::move(this->m_unexpect);
3007
  }
3008
#endif
3009
3010
  TL_EXPECTED_11_CONSTEXPR void destroy_val() {
3011
    // no-op
3012
  }
3013
};
3014
3015
// This class manages conditionally having a trivial copy constructor
3016
// This specialization is for when T and E are trivially copy constructible
3017
template <class T, class E,
3018
          bool = is_void_or<T, TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(
3019
                                   T)>::value &&
3020
                 TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(E)::value>
3021
struct expected_copy_base : expected_operations_base<T, E> {
3022
  using expected_operations_base<T, E>::expected_operations_base;
3023
};
3024
3025
// This specialization is for when T or E are not trivially copy constructible
3026
template <class T, class E>
3027
struct expected_copy_base<T, E, false> : expected_operations_base<T, E> {
3028
  using expected_operations_base<T, E>::expected_operations_base;
3029
3030
639k
  expected_copy_base() = default;
3031
  expected_copy_base(const expected_copy_base& rhs)
3032
72.3k
      : expected_operations_base<T, E>(no_init) {
3033
72.3k
    if (rhs.has_value()) {
3034
63.1k
      this->construct_with(rhs);
3035
63.1k
    } else {
3036
9.20k
      this->construct_error(rhs.geterr());
3037
9.20k
    }
3038
72.3k
  }
3039
3040
  expected_copy_base(expected_copy_base&& rhs) = default;
3041
  expected_copy_base& operator=(const expected_copy_base& rhs) = default;
3042
  expected_copy_base& operator=(expected_copy_base&& rhs) = default;
3043
};
3044
3045
// This class manages conditionally having a trivial move constructor
3046
// Unfortunately there's no way to achieve this in GCC < 5 AFAIK, since it
3047
// doesn't implement an analogue to std::is_trivially_move_constructible. We
3048
// have to make do with a non-trivial move constructor even if T is trivially
3049
// move constructible
3050
#ifndef TL_EXPECTED_GCC49
3051
template <class T, class E,
3052
          bool =
3053
              is_void_or<T, std::is_trivially_move_constructible<T>>::value &&
3054
              std::is_trivially_move_constructible<E>::value>
3055
struct expected_move_base : expected_copy_base<T, E> {
3056
  using expected_copy_base<T, E>::expected_copy_base;
3057
};
3058
#else
3059
template <class T, class E, bool = false>
3060
struct expected_move_base;
3061
#endif
3062
template <class T, class E>
3063
struct expected_move_base<T, E, false> : expected_copy_base<T, E> {
3064
  using expected_copy_base<T, E>::expected_copy_base;
3065
3066
639k
  expected_move_base() = default;
3067
72.3k
  expected_move_base(const expected_move_base& rhs) = default;
3068
3069
  expected_move_base(expected_move_base&& rhs) noexcept(
3070
      std::is_nothrow_move_constructible<T>::value)
3071
8.57k
      : expected_copy_base<T, E>(no_init) {
3072
8.57k
    if (rhs.has_value()) {
3073
7.81k
      this->construct_with(std::move(rhs));
3074
7.81k
    } else {
3075
760
      this->construct_error(std::move(rhs.geterr()));
3076
760
    }
3077
8.57k
  }
3078
  expected_move_base& operator=(const expected_move_base& rhs) = default;
3079
  expected_move_base& operator=(expected_move_base&& rhs) = default;
3080
};
3081
3082
// This class manages conditionally having a trivial copy assignment operator
3083
template <
3084
    class T, class E,
3085
    bool =
3086
        is_void_or<
3087
            T, conjunction<TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T),
3088
                           TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T),
3089
                           TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T)>>::value &&
3090
        TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(E)::value &&
3091
        TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(E)::value &&
3092
        TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(E)::value>
3093
struct expected_copy_assign_base : expected_move_base<T, E> {
3094
  using expected_move_base<T, E>::expected_move_base;
3095
};
3096
3097
template <class T, class E>
3098
struct expected_copy_assign_base<T, E, false> : expected_move_base<T, E> {
3099
  using expected_move_base<T, E>::expected_move_base;
3100
3101
639k
  expected_copy_assign_base() = default;
3102
72.3k
  expected_copy_assign_base(const expected_copy_assign_base& rhs) = default;
3103
3104
8.57k
  expected_copy_assign_base(expected_copy_assign_base&& rhs) = default;
3105
  expected_copy_assign_base& operator=(const expected_copy_assign_base& rhs) {
3106
    this->assign(rhs);
3107
    return *this;
3108
  }
3109
  expected_copy_assign_base& operator=(expected_copy_assign_base&& rhs) =
3110
      default;
3111
};
3112
3113
// This class manages conditionally having a trivial move assignment operator
3114
// Unfortunately there's no way to achieve this in GCC < 5 AFAIK, since it
3115
// doesn't implement an analogue to std::is_trivially_move_assignable. We have
3116
// to make do with a non-trivial move assignment operator even if T is trivially
3117
// move assignable
3118
#ifndef TL_EXPECTED_GCC49
3119
template <
3120
    class T, class E,
3121
    bool = is_void_or<
3122
               T, conjunction<std::is_trivially_destructible<T>,
3123
                              std::is_trivially_move_constructible<T>,
3124
                              std::is_trivially_move_assignable<T>>>::value &&
3125
           std::is_trivially_destructible<E>::value &&
3126
           std::is_trivially_move_constructible<E>::value &&
3127
           std::is_trivially_move_assignable<E>::value>
3128
struct expected_move_assign_base : expected_copy_assign_base<T, E> {
3129
  using expected_copy_assign_base<T, E>::expected_copy_assign_base;
3130
};
3131
#else
3132
template <class T, class E, bool = false>
3133
struct expected_move_assign_base;
3134
#endif
3135
3136
template <class T, class E>
3137
struct expected_move_assign_base<T, E, false>
3138
    : expected_copy_assign_base<T, E> {
3139
  using expected_copy_assign_base<T, E>::expected_copy_assign_base;
3140
3141
639k
  expected_move_assign_base() = default;
3142
72.3k
  expected_move_assign_base(const expected_move_assign_base& rhs) = default;
3143
3144
8.57k
  expected_move_assign_base(expected_move_assign_base&& rhs) = default;
3145
3146
  expected_move_assign_base& operator=(const expected_move_assign_base& rhs) =
3147
      default;
3148
3149
  expected_move_assign_base&
3150
  operator=(expected_move_assign_base&& rhs) noexcept(
3151
      std::is_nothrow_move_constructible<T>::value &&
3152
255k
      std::is_nothrow_move_assignable<T>::value) {
3153
255k
    this->assign(std::move(rhs));
3154
255k
    return *this;
3155
255k
  }
3156
};
3157
3158
// expected_delete_ctor_base will conditionally delete copy and move
3159
// constructors depending on whether T is copy/move constructible
3160
template <class T, class E,
3161
          bool EnableCopy = (is_copy_constructible_or_void<T>::value &&
3162
                             std::is_copy_constructible<E>::value),
3163
          bool EnableMove = (is_move_constructible_or_void<T>::value &&
3164
                             std::is_move_constructible<E>::value)>
3165
struct expected_delete_ctor_base {
3166
  expected_delete_ctor_base() = default;
3167
  expected_delete_ctor_base(const expected_delete_ctor_base&) = default;
3168
  expected_delete_ctor_base(expected_delete_ctor_base&&) noexcept = default;
3169
  expected_delete_ctor_base& operator=(const expected_delete_ctor_base&) =
3170
      default;
3171
  expected_delete_ctor_base& operator=(expected_delete_ctor_base&&) noexcept =
3172
      default;
3173
};
3174
3175
template <class T, class E>
3176
struct expected_delete_ctor_base<T, E, true, false> {
3177
  expected_delete_ctor_base() = default;
3178
  expected_delete_ctor_base(const expected_delete_ctor_base&) = default;
3179
  expected_delete_ctor_base(expected_delete_ctor_base&&) noexcept = delete;
3180
  expected_delete_ctor_base& operator=(const expected_delete_ctor_base&) =
3181
      default;
3182
  expected_delete_ctor_base& operator=(expected_delete_ctor_base&&) noexcept =
3183
      default;
3184
};
3185
3186
template <class T, class E>
3187
struct expected_delete_ctor_base<T, E, false, true> {
3188
  expected_delete_ctor_base() = default;
3189
  expected_delete_ctor_base(const expected_delete_ctor_base&) = delete;
3190
  expected_delete_ctor_base(expected_delete_ctor_base&&) noexcept = default;
3191
  expected_delete_ctor_base& operator=(const expected_delete_ctor_base&) =
3192
      default;
3193
  expected_delete_ctor_base& operator=(expected_delete_ctor_base&&) noexcept =
3194
      default;
3195
};
3196
3197
template <class T, class E>
3198
struct expected_delete_ctor_base<T, E, false, false> {
3199
  expected_delete_ctor_base() = default;
3200
  expected_delete_ctor_base(const expected_delete_ctor_base&) = delete;
3201
  expected_delete_ctor_base(expected_delete_ctor_base&&) noexcept = delete;
3202
  expected_delete_ctor_base& operator=(const expected_delete_ctor_base&) =
3203
      default;
3204
  expected_delete_ctor_base& operator=(expected_delete_ctor_base&&) noexcept =
3205
      default;
3206
};
3207
3208
// expected_delete_assign_base will conditionally delete copy and move
3209
// constructors depending on whether T and E are copy/move constructible +
3210
// assignable
3211
template <class T, class E,
3212
          bool EnableCopy = (is_copy_constructible_or_void<T>::value &&
3213
                             std::is_copy_constructible<E>::value &&
3214
                             is_copy_assignable_or_void<T>::value &&
3215
                             std::is_copy_assignable<E>::value),
3216
          bool EnableMove = (is_move_constructible_or_void<T>::value &&
3217
                             std::is_move_constructible<E>::value &&
3218
                             is_move_assignable_or_void<T>::value &&
3219
                             std::is_move_assignable<E>::value)>
3220
struct expected_delete_assign_base {
3221
  expected_delete_assign_base() = default;
3222
  expected_delete_assign_base(const expected_delete_assign_base&) = default;
3223
  expected_delete_assign_base(expected_delete_assign_base&&) noexcept = default;
3224
  expected_delete_assign_base& operator=(const expected_delete_assign_base&) =
3225
      default;
3226
  expected_delete_assign_base& operator=(
3227
      expected_delete_assign_base&&) noexcept = default;
3228
};
3229
3230
template <class T, class E>
3231
struct expected_delete_assign_base<T, E, true, false> {
3232
  expected_delete_assign_base() = default;
3233
  expected_delete_assign_base(const expected_delete_assign_base&) = default;
3234
  expected_delete_assign_base(expected_delete_assign_base&&) noexcept = default;
3235
  expected_delete_assign_base& operator=(const expected_delete_assign_base&) =
3236
      default;
3237
  expected_delete_assign_base& operator=(
3238
      expected_delete_assign_base&&) noexcept = delete;
3239
};
3240
3241
template <class T, class E>
3242
struct expected_delete_assign_base<T, E, false, true> {
3243
  expected_delete_assign_base() = default;
3244
  expected_delete_assign_base(const expected_delete_assign_base&) = default;
3245
  expected_delete_assign_base(expected_delete_assign_base&&) noexcept = default;
3246
  expected_delete_assign_base& operator=(const expected_delete_assign_base&) =
3247
      delete;
3248
  expected_delete_assign_base& operator=(
3249
      expected_delete_assign_base&&) noexcept = default;
3250
};
3251
3252
template <class T, class E>
3253
struct expected_delete_assign_base<T, E, false, false> {
3254
  expected_delete_assign_base() = default;
3255
  expected_delete_assign_base(const expected_delete_assign_base&) = default;
3256
  expected_delete_assign_base(expected_delete_assign_base&&) noexcept = default;
3257
  expected_delete_assign_base& operator=(const expected_delete_assign_base&) =
3258
      delete;
3259
  expected_delete_assign_base& operator=(
3260
      expected_delete_assign_base&&) noexcept = delete;
3261
};
3262
3263
// This is needed to be able to construct the expected_default_ctor_base which
3264
// follows, while still conditionally deleting the default constructor.
3265
struct default_constructor_tag {
3266
  explicit constexpr default_constructor_tag() = default;
3267
};
3268
3269
// expected_default_ctor_base will ensure that expected has a deleted default
3270
// consturctor if T is not default constructible.
3271
// This specialization is for when T is default constructible
3272
template <class T, class E,
3273
          bool Enable =
3274
              std::is_default_constructible<T>::value || std::is_void<T>::value>
3275
struct expected_default_ctor_base {
3276
  constexpr expected_default_ctor_base() noexcept = default;
3277
  constexpr expected_default_ctor_base(
3278
      expected_default_ctor_base const&) noexcept = default;
3279
  constexpr expected_default_ctor_base(expected_default_ctor_base&&) noexcept =
3280
      default;
3281
  expected_default_ctor_base& operator=(
3282
      expected_default_ctor_base const&) noexcept = default;
3283
  expected_default_ctor_base& operator=(expected_default_ctor_base&&) noexcept =
3284
      default;
3285
3286
20.4M
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
tl::detail::expected_default_ctor_base<ada::url, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
Line
Count
Source
3286
759k
  constexpr explicit expected_default_ctor_base(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
3286
2.65M
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
tl::detail::expected_default_ctor_base<ada::url_pattern_init, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
Line
Count
Source
3286
721k
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
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)
Line
Count
Source
3286
6.26M
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
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)
Line
Count
Source
3286
3.07M
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
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)
Line
Count
Source
3286
9.39k
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
tl::detail::expected_default_ctor_base<ada::url_search_params, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
Line
Count
Source
3286
13.7k
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
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)
Line
Count
Source
3286
13.7k
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
tl::detail::expected_default_ctor_base<ada::url_search_params_iter<std::__1::basic_string_view<char, std::__1::char_traits<char> >, (ada::url_search_params_iter_type)0>, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
Line
Count
Source
3286
13.7k
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
tl::detail::expected_default_ctor_base<ada::url_search_params_iter<std::__1::basic_string_view<char, std::__1::char_traits<char> >, (ada::url_search_params_iter_type)1>, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
Line
Count
Source
3286
13.7k
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
tl::detail::expected_default_ctor_base<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>, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
Line
Count
Source
3286
13.7k
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
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)
Line
Count
Source
3286
2.99M
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
tl::detail::expected_default_ctor_base<ada::url_pattern<ada::url_pattern_regex::std_regex_provider>, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
Line
Count
Source
3286
421k
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
tl::detail::expected_default_ctor_base<ada::url_pattern_component<ada::url_pattern_regex::std_regex_provider>, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
Line
Count
Source
3286
2.59M
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
tl::detail::expected_default_ctor_base<ada::url_pattern_list<ada::url_pattern_regex::std_regex_provider>, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
Line
Count
Source
3286
10.2k
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
tl::detail::expected_default_ctor_base<bool, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
Line
Count
Source
3286
383k
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
tl::detail::expected_default_ctor_base<std::__1::optional<ada::url_pattern_result>, ada::errors, true>::expected_default_ctor_base(tl::detail::default_constructor_tag)
Line
Count
Source
3286
511k
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
3287
};
3288
3289
// This specialization is for when T is not default constructible
3290
template <class T, class E>
3291
struct expected_default_ctor_base<T, E, false> {
3292
  constexpr expected_default_ctor_base() noexcept = delete;
3293
  constexpr expected_default_ctor_base(
3294
      expected_default_ctor_base const&) noexcept = default;
3295
  constexpr expected_default_ctor_base(expected_default_ctor_base&&) noexcept =
3296
      default;
3297
  expected_default_ctor_base& operator=(
3298
      expected_default_ctor_base const&) noexcept = default;
3299
  expected_default_ctor_base& operator=(expected_default_ctor_base&&) noexcept =
3300
      default;
3301
3302
  constexpr explicit expected_default_ctor_base(default_constructor_tag) {}
3303
};
3304
}  // namespace detail
3305
3306
template <class E>
3307
class bad_expected_access : public std::exception {
3308
 public:
3309
0
  explicit bad_expected_access(E e) : m_val(std::move(e)) {}
3310
3311
0
  virtual const char* what() const noexcept override {
3312
0
    return "Bad expected access";
3313
0
  }
3314
3315
  const E& error() const& { return m_val; }
3316
  E& error() & { return m_val; }
3317
  const E&& error() const&& { return std::move(m_val); }
3318
  E&& error() && { return std::move(m_val); }
3319
3320
 private:
3321
  E m_val;
3322
};
3323
3324
/// An `expected<T, E>` object is an object that contains the storage for
3325
/// another object and manages the lifetime of this contained object `T`.
3326
/// Alternatively it could contain the storage for another unexpected object
3327
/// `E`. The contained object may not be initialized after the expected object
3328
/// has been initialized, and may not be destroyed before the expected object
3329
/// has been destroyed. The initialization state of the contained object is
3330
/// tracked by the expected object.
3331
template <class T, class E>
3332
class expected : private detail::expected_move_assign_base<T, E>,
3333
                 private detail::expected_delete_ctor_base<T, E>,
3334
                 private detail::expected_delete_assign_base<T, E>,
3335
                 private detail::expected_default_ctor_base<T, E> {
3336
  static_assert(!std::is_reference<T>::value, "T must not be a reference");
3337
  static_assert(!std::is_same<T, std::remove_cv<in_place_t>::type>::value,
3338
                "T must not be in_place_t");
3339
  static_assert(!std::is_same<T, std::remove_cv<unexpect_t>::type>::value,
3340
                "T must not be unexpect_t");
3341
  static_assert(
3342
      !std::is_same<T, typename std::remove_cv<unexpected<E>>::type>::value,
3343
      "T must not be unexpected<E>");
3344
  static_assert(!std::is_reference<E>::value, "E must not be a reference");
3345
3346
27.6M
  T* valptr() { return std::addressof(this->m_val); }
tl::expected<ada::url, ada::errors>::valptr()
Line
Count
Source
3346
1.83M
  T* valptr() { return std::addressof(this->m_val); }
tl::expected<ada::url_aggregator, ada::errors>::valptr()
Line
Count
Source
3346
7.69M
  T* valptr() { return std::addressof(this->m_val); }
tl::expected<ada::url_search_params, ada::errors>::valptr()
Line
Count
Source
3346
205k
  T* valptr() { return std::addressof(this->m_val); }
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()
Line
Count
Source
3346
27.4k
  T* valptr() { return std::addressof(this->m_val); }
tl::expected<ada::url_search_params_iter<std::__1::basic_string_view<char, std::__1::char_traits<char> >, (ada::url_search_params_iter_type)0>, ada::errors>::valptr()
Line
Count
Source
3346
60.6k
  T* valptr() { return std::addressof(this->m_val); }
tl::expected<ada::url_search_params_iter<std::__1::basic_string_view<char, std::__1::char_traits<char> >, (ada::url_search_params_iter_type)1>, ada::errors>::valptr()
Line
Count
Source
3346
60.6k
  T* valptr() { return std::addressof(this->m_val); }
tl::expected<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>, ada::errors>::valptr()
Line
Count
Source
3346
60.6k
  T* valptr() { return std::addressof(this->m_val); }
tl::expected<ada::url_pattern_init, ada::errors>::valptr()
Line
Count
Source
3346
9.86M
  T* valptr() { return std::addressof(this->m_val); }
tl::expected<std::__1::vector<ada::url_pattern_part, std::__1::allocator<ada::url_pattern_part> >, ada::errors>::valptr()
Line
Count
Source
3346
6.73M
  T* valptr() { return std::addressof(this->m_val); }
tl::expected<ada::url_pattern_list<ada::url_pattern_regex::std_regex_provider>, ada::errors>::valptr()
Line
Count
Source
3346
279k
  T* valptr() { return std::addressof(this->m_val); }
tl::expected<ada::url_pattern_component<ada::url_pattern_regex::std_regex_provider>, ada::errors>::valptr()
Line
Count
Source
3346
23.2k
  T* valptr() { return std::addressof(this->m_val); }
tl::expected<std::__1::optional<ada::url_pattern_result>, ada::errors>::valptr()
Line
Count
Source
3346
767k
  T* valptr() { return std::addressof(this->m_val); }
3347
  const T* valptr() const { return std::addressof(this->m_val); }
3348
  unexpected<E>* errptr() { return std::addressof(this->m_unexpect); }
3349
  const unexpected<E>* errptr() const {
3350
    return std::addressof(this->m_unexpect);
3351
  }
3352
3353
  template <class U = T,
3354
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
3355
25.5M
  TL_EXPECTED_11_CONSTEXPR U& val() {
3356
25.5M
    return this->m_val;
3357
25.5M
  }
_ZN2tl8expectedIN3ada3urlENS1_6errorsEE3valIS2_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERS8_v
Line
Count
Source
3355
1.02M
  TL_EXPECTED_11_CONSTEXPR U& val() {
3356
1.02M
    return this->m_val;
3357
1.02M
  }
_ZN2tl8expectedIN3ada14url_aggregatorENS1_6errorsEE3valIS2_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERS8_v
Line
Count
Source
3355
1.84M
  TL_EXPECTED_11_CONSTEXPR U& val() {
3356
1.84M
    return this->m_val;
3357
1.84M
  }
_ZN2tl8expectedINSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEN3ada6errorsEE3valIS7_TnPNS1_9enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSD_v
Line
Count
Source
3355
6.25M
  TL_EXPECTED_11_CONSTEXPR U& val() {
3356
6.25M
    return this->m_val;
3357
6.25M
  }
_ZN2tl8expectedINSt3__16vectorIN3ada16url_pattern_partENS1_9allocatorIS4_EEEENS3_6errorsEE3valIS7_TnPNS1_9enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSC_v
Line
Count
Source
3355
9.83M
  TL_EXPECTED_11_CONSTEXPR U& val() {
3356
9.83M
    return this->m_val;
3357
9.83M
  }
_ZN2tl8expectedINSt3__16vectorIN3ada19url_pattern_helpers5tokenENS1_9allocatorIS5_EEEENS3_6errorsEE3valIS8_TnPNS1_9enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSD_v
Line
Count
Source
3355
3.07M
  TL_EXPECTED_11_CONSTEXPR U& val() {
3356
3.07M
    return this->m_val;
3357
3.07M
  }
_ZN2tl8expectedIN3ada16url_pattern_initENS1_6errorsEE3valIS2_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERS8_v
Line
Count
Source
3355
87.5k
  TL_EXPECTED_11_CONSTEXPR U& val() {
3356
87.5k
    return this->m_val;
3357
87.5k
  }
_ZN2tl8expectedIN3ada21url_pattern_componentINS1_17url_pattern_regex18std_regex_providerEEENS1_6errorsEE3valIS5_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSB_v
Line
Count
Source
3355
2.58M
  TL_EXPECTED_11_CONSTEXPR U& val() {
3356
2.58M
    return this->m_val;
3357
2.58M
  }
_ZN2tl8expectedIN3ada11url_patternINS1_17url_pattern_regex18std_regex_providerEEENS1_6errorsEE3valIS5_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSB_v
Line
Count
Source
3355
439k
  TL_EXPECTED_11_CONSTEXPR U& val() {
3356
439k
    return this->m_val;
3357
439k
  }
_ZN2tl8expectedIN3ada16url_pattern_listINS1_17url_pattern_regex18std_regex_providerEEENS1_6errorsEE3valIS5_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSB_v
Line
Count
Source
3355
7.81k
  TL_EXPECTED_11_CONSTEXPR U& val() {
3356
7.81k
    return this->m_val;
3357
7.81k
  }
_ZN2tl8expectedIN3ada23url_pattern_list_detail15compiled_routesENS1_6errorsEE3valIS3_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERS9_v
Line
Count
Source
3355
8.63k
  TL_EXPECTED_11_CONSTEXPR U& val() {
3356
8.63k
    return this->m_val;
3357
8.63k
  }
_ZN2tl8expectedIbN3ada6errorsEE3valIbTnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERS7_v
Line
Count
Source
3355
383k
  TL_EXPECTED_11_CONSTEXPR U& val() {
3356
383k
    return this->m_val;
3357
383k
  }
_ZN2tl8expectedINSt3__18optionalIN3ada18url_pattern_resultEEENS3_6errorsEE3valIS5_TnPNS1_9enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSA_v
Line
Count
Source
3355
45.3k
  TL_EXPECTED_11_CONSTEXPR U& val() {
3356
45.3k
    return this->m_val;
3357
45.3k
  }
3358
84.3k
  TL_EXPECTED_11_CONSTEXPR unexpected<E>& err() { return this->m_unexpect; }
tl::expected<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, ada::errors>::err()
Line
Count
Source
3358
5.06k
  TL_EXPECTED_11_CONSTEXPR unexpected<E>& err() { return this->m_unexpect; }
tl::expected<std::__1::vector<ada::url_pattern_part, std::__1::allocator<ada::url_pattern_part> >, ada::errors>::err()
Line
Count
Source
3358
7.93k
  TL_EXPECTED_11_CONSTEXPR unexpected<E>& err() { return this->m_unexpect; }
Unexecuted instantiation: tl::expected<ada::url_aggregator, ada::errors>::err()
tl::expected<std::__1::vector<ada::url_pattern_helpers::token, std::__1::allocator<ada::url_pattern_helpers::token> >, ada::errors>::err()
Line
Count
Source
3358
2.07k
  TL_EXPECTED_11_CONSTEXPR unexpected<E>& err() { return this->m_unexpect; }
tl::expected<ada::url_pattern_init, ada::errors>::err()
Line
Count
Source
3358
58.3k
  TL_EXPECTED_11_CONSTEXPR unexpected<E>& err() { return this->m_unexpect; }
tl::expected<ada::url_pattern_component<ada::url_pattern_regex::std_regex_provider>, ada::errors>::err()
Line
Count
Source
3358
10.2k
  TL_EXPECTED_11_CONSTEXPR unexpected<E>& err() { return this->m_unexpect; }
tl::expected<ada::url_pattern_list_detail::compiled_routes, ada::errors>::err()
Line
Count
Source
3358
760
  TL_EXPECTED_11_CONSTEXPR unexpected<E>& err() { return this->m_unexpect; }
3359
3360
  template <class U = T,
3361
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
3362
  constexpr const U& val() const {
3363
    return this->m_val;
3364
  }
3365
  constexpr const unexpected<E>& err() const { return this->m_unexpect; }
3366
3367
  using impl_base = detail::expected_move_assign_base<T, E>;
3368
  using ctor_base = detail::expected_default_ctor_base<T, E>;
3369
3370
 public:
3371
  typedef T value_type;
3372
  typedef E error_type;
3373
  typedef unexpected<E> unexpected_type;
3374
3375
#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \
3376
    !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55)
3377
  template <class F>
3378
  TL_EXPECTED_11_CONSTEXPR auto and_then(F&& f) & {
3379
    return and_then_impl(*this, std::forward<F>(f));
3380
  }
3381
  template <class F>
3382
  TL_EXPECTED_11_CONSTEXPR auto and_then(F&& f) && {
3383
    return and_then_impl(std::move(*this), std::forward<F>(f));
3384
  }
3385
  template <class F>
3386
  constexpr auto and_then(F&& f) const& {
3387
    return and_then_impl(*this, std::forward<F>(f));
3388
  }
3389
3390
#ifndef TL_EXPECTED_NO_CONSTRR
3391
  template <class F>
3392
  constexpr auto and_then(F&& f) const&& {
3393
    return and_then_impl(std::move(*this), std::forward<F>(f));
3394
  }
3395
#endif
3396
3397
#else
3398
  template <class F>
3399
  TL_EXPECTED_11_CONSTEXPR auto and_then(F&& f) & -> decltype(and_then_impl(
3400
      std::declval<expected&>(), std::forward<F>(f))) {
3401
    return and_then_impl(*this, std::forward<F>(f));
3402
  }
3403
  template <class F>
3404
  TL_EXPECTED_11_CONSTEXPR auto and_then(F&& f) && -> decltype(and_then_impl(
3405
      std::declval<expected&&>(), std::forward<F>(f))) {
3406
    return and_then_impl(std::move(*this), std::forward<F>(f));
3407
  }
3408
  template <class F>
3409
  constexpr auto and_then(F&& f) const& -> decltype(and_then_impl(
3410
      std::declval<expected const&>(), std::forward<F>(f))) {
3411
    return and_then_impl(*this, std::forward<F>(f));
3412
  }
3413
3414
#ifndef TL_EXPECTED_NO_CONSTRR
3415
  template <class F>
3416
  constexpr auto and_then(F&& f) const&& -> decltype(and_then_impl(
3417
      std::declval<expected const&&>(), std::forward<F>(f))) {
3418
    return and_then_impl(std::move(*this), std::forward<F>(f));
3419
  }
3420
#endif
3421
#endif
3422
3423
#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \
3424
    !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55)
3425
  template <class F>
3426
  TL_EXPECTED_11_CONSTEXPR auto map(F&& f) & {
3427
    return expected_map_impl(*this, std::forward<F>(f));
3428
  }
3429
  template <class F>
3430
  TL_EXPECTED_11_CONSTEXPR auto map(F&& f) && {
3431
    return expected_map_impl(std::move(*this), std::forward<F>(f));
3432
  }
3433
  template <class F>
3434
  constexpr auto map(F&& f) const& {
3435
    return expected_map_impl(*this, std::forward<F>(f));
3436
  }
3437
  template <class F>
3438
  constexpr auto map(F&& f) const&& {
3439
    return expected_map_impl(std::move(*this), std::forward<F>(f));
3440
  }
3441
#else
3442
  template <class F>
3443
  TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl(
3444
      std::declval<expected&>(), std::declval<F&&>())) map(F&& f) & {
3445
    return expected_map_impl(*this, std::forward<F>(f));
3446
  }
3447
  template <class F>
3448
  TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl(std::declval<expected>(),
3449
                                                      std::declval<F&&>()))
3450
  map(F&& f) && {
3451
    return expected_map_impl(std::move(*this), std::forward<F>(f));
3452
  }
3453
  template <class F>
3454
  constexpr decltype(expected_map_impl(std::declval<const expected&>(),
3455
                                       std::declval<F&&>()))
3456
  map(F&& f) const& {
3457
    return expected_map_impl(*this, std::forward<F>(f));
3458
  }
3459
3460
#ifndef TL_EXPECTED_NO_CONSTRR
3461
  template <class F>
3462
  constexpr decltype(expected_map_impl(std::declval<const expected&&>(),
3463
                                       std::declval<F&&>())) map(F&& f)
3464
      const&& {
3465
    return expected_map_impl(std::move(*this), std::forward<F>(f));
3466
  }
3467
#endif
3468
#endif
3469
3470
#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \
3471
    !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55)
3472
  template <class F>
3473
  TL_EXPECTED_11_CONSTEXPR auto transform(F&& f) & {
3474
    return expected_map_impl(*this, std::forward<F>(f));
3475
  }
3476
  template <class F>
3477
  TL_EXPECTED_11_CONSTEXPR auto transform(F&& f) && {
3478
    return expected_map_impl(std::move(*this), std::forward<F>(f));
3479
  }
3480
  template <class F>
3481
  constexpr auto transform(F&& f) const& {
3482
    return expected_map_impl(*this, std::forward<F>(f));
3483
  }
3484
  template <class F>
3485
  constexpr auto transform(F&& f) const&& {
3486
    return expected_map_impl(std::move(*this), std::forward<F>(f));
3487
  }
3488
#else
3489
  template <class F>
3490
  TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl(
3491
      std::declval<expected&>(), std::declval<F&&>())) transform(F&& f) & {
3492
    return expected_map_impl(*this, std::forward<F>(f));
3493
  }
3494
  template <class F>
3495
  TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl(std::declval<expected>(),
3496
                                                      std::declval<F&&>()))
3497
  transform(F&& f) && {
3498
    return expected_map_impl(std::move(*this), std::forward<F>(f));
3499
  }
3500
  template <class F>
3501
  constexpr decltype(expected_map_impl(std::declval<const expected&>(),
3502
                                       std::declval<F&&>()))
3503
  transform(F&& f) const& {
3504
    return expected_map_impl(*this, std::forward<F>(f));
3505
  }
3506
3507
#ifndef TL_EXPECTED_NO_CONSTRR
3508
  template <class F>
3509
  constexpr decltype(expected_map_impl(std::declval<const expected&&>(),
3510
                                       std::declval<F&&>())) transform(F&& f)
3511
      const&& {
3512
    return expected_map_impl(std::move(*this), std::forward<F>(f));
3513
  }
3514
#endif
3515
#endif
3516
3517
#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \
3518
    !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55)
3519
  template <class F>
3520
  TL_EXPECTED_11_CONSTEXPR auto map_error(F&& f) & {
3521
    return map_error_impl(*this, std::forward<F>(f));
3522
  }
3523
  template <class F>
3524
  TL_EXPECTED_11_CONSTEXPR auto map_error(F&& f) && {
3525
    return map_error_impl(std::move(*this), std::forward<F>(f));
3526
  }
3527
  template <class F>
3528
  constexpr auto map_error(F&& f) const& {
3529
    return map_error_impl(*this, std::forward<F>(f));
3530
  }
3531
  template <class F>
3532
  constexpr auto map_error(F&& f) const&& {
3533
    return map_error_impl(std::move(*this), std::forward<F>(f));
3534
  }
3535
#else
3536
  template <class F>
3537
  TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(
3538
      std::declval<expected&>(), std::declval<F&&>())) map_error(F&& f) & {
3539
    return map_error_impl(*this, std::forward<F>(f));
3540
  }
3541
  template <class F>
3542
  TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(std::declval<expected&&>(),
3543
                                                   std::declval<F&&>()))
3544
  map_error(F&& f) && {
3545
    return map_error_impl(std::move(*this), std::forward<F>(f));
3546
  }
3547
  template <class F>
3548
  constexpr decltype(map_error_impl(std::declval<const expected&>(),
3549
                                    std::declval<F&&>()))
3550
  map_error(F&& f) const& {
3551
    return map_error_impl(*this, std::forward<F>(f));
3552
  }
3553
3554
#ifndef TL_EXPECTED_NO_CONSTRR
3555
  template <class F>
3556
  constexpr decltype(map_error_impl(std::declval<const expected&&>(),
3557
                                    std::declval<F&&>())) map_error(F&& f)
3558
      const&& {
3559
    return map_error_impl(std::move(*this), std::forward<F>(f));
3560
  }
3561
#endif
3562
#endif
3563
#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \
3564
    !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55)
3565
  template <class F>
3566
  TL_EXPECTED_11_CONSTEXPR auto transform_error(F&& f) & {
3567
    return map_error_impl(*this, std::forward<F>(f));
3568
  }
3569
  template <class F>
3570
  TL_EXPECTED_11_CONSTEXPR auto transform_error(F&& f) && {
3571
    return map_error_impl(std::move(*this), std::forward<F>(f));
3572
  }
3573
  template <class F>
3574
  constexpr auto transform_error(F&& f) const& {
3575
    return map_error_impl(*this, std::forward<F>(f));
3576
  }
3577
  template <class F>
3578
  constexpr auto transform_error(F&& f) const&& {
3579
    return map_error_impl(std::move(*this), std::forward<F>(f));
3580
  }
3581
#else
3582
  template <class F>
3583
  TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(
3584
      std::declval<expected&>(),
3585
      std::declval<F&&>())) transform_error(F&& f) & {
3586
    return map_error_impl(*this, std::forward<F>(f));
3587
  }
3588
  template <class F>
3589
  TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(std::declval<expected&&>(),
3590
                                                   std::declval<F&&>()))
3591
  transform_error(F&& f) && {
3592
    return map_error_impl(std::move(*this), std::forward<F>(f));
3593
  }
3594
  template <class F>
3595
  constexpr decltype(map_error_impl(std::declval<const expected&>(),
3596
                                    std::declval<F&&>()))
3597
  transform_error(F&& f) const& {
3598
    return map_error_impl(*this, std::forward<F>(f));
3599
  }
3600
3601
#ifndef TL_EXPECTED_NO_CONSTRR
3602
  template <class F>
3603
  constexpr decltype(map_error_impl(std::declval<const expected&&>(),
3604
                                    std::declval<F&&>())) transform_error(F&& f)
3605
      const&& {
3606
    return map_error_impl(std::move(*this), std::forward<F>(f));
3607
  }
3608
#endif
3609
#endif
3610
  template <class F>
3611
  expected TL_EXPECTED_11_CONSTEXPR or_else(F&& f) & {
3612
    return or_else_impl(*this, std::forward<F>(f));
3613
  }
3614
3615
  template <class F>
3616
  expected TL_EXPECTED_11_CONSTEXPR or_else(F&& f) && {
3617
    return or_else_impl(std::move(*this), std::forward<F>(f));
3618
  }
3619
3620
  template <class F>
3621
  expected constexpr or_else(F&& f) const& {
3622
    return or_else_impl(*this, std::forward<F>(f));
3623
  }
3624
3625
#ifndef TL_EXPECTED_NO_CONSTRR
3626
  template <class F>
3627
  expected constexpr or_else(F&& f) const&& {
3628
    return or_else_impl(std::move(*this), std::forward<F>(f));
3629
  }
3630
#endif
3631
639k
  constexpr expected() = default;
3632
72.3k
  constexpr expected(const expected& rhs) = default;
3633
8.57k
  constexpr expected(expected&& rhs) = default;
3634
  expected& operator=(const expected& rhs) = default;
3635
255k
  expected& operator=(expected&& rhs) = default;
3636
3637
  template <class... Args,
3638
            detail::enable_if_t<std::is_constructible<T, Args&&...>::value>* =
3639
                nullptr>
3640
  constexpr expected(in_place_t, Args&&... args)
3641
19.4M
      : impl_base(in_place, std::forward<Args>(args)...),
3642
19.4M
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIN3ada3urlENS1_6errorsEEC2IJS2_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS2_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESA_
Line
Count
Source
3641
683k
      : impl_base(in_place, std::forward<Args>(args)...),
3642
683k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIN3ada14url_aggregatorENS1_6errorsEEC2IJS2_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS2_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESA_
Line
Count
Source
3641
1.95M
      : impl_base(in_place, std::forward<Args>(args)...),
3642
1.95M
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIN3ada16url_pattern_initENS1_6errorsEEC2IJS2_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS2_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESA_
Line
Count
Source
3641
574k
      : impl_base(in_place, std::forward<Args>(args)...),
3642
574k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedINSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEN3ada6errorsEEC2IJS7_ETnPNS1_9enable_ifIXsr3std16is_constructibleIS7_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESF_
Line
Count
Source
3641
2.13M
      : impl_base(in_place, std::forward<Args>(args)...),
3642
2.13M
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedINSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEN3ada6errorsEEC2IJRA1_KcETnPNS1_9enable_ifIXsr3std16is_constructibleIS7_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESI_
Line
Count
Source
3641
4.12M
      : impl_base(in_place, std::forward<Args>(args)...),
3642
4.12M
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedINSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEN3ada6errorsEEC2IJRA2_KcETnPNS1_9enable_ifIXsr3std16is_constructibleIS7_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESI_
Line
Count
Source
3641
54
      : impl_base(in_place, std::forward<Args>(args)...),
3642
54
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedINSt3__16vectorIN3ada19url_pattern_helpers5tokenENS1_9allocatorIS5_EEEENS3_6errorsEEC2IJRS8_ETnPNS1_9enable_ifIXsr3std16is_constructibleIS8_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESG_
Line
Count
Source
3641
3.07M
      : impl_base(in_place, std::forward<Args>(args)...),
3642
3.07M
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIN3ada23url_pattern_list_detail15compiled_routesENS1_6errorsEEC2IJS3_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS3_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESB_
Line
Count
Source
3641
8.63k
      : impl_base(in_place, std::forward<Args>(args)...),
3642
8.63k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIN3ada17url_search_paramsENS1_6errorsEEC2IJS2_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS2_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESA_
Line
Count
Source
3641
13.7k
      : impl_base(in_place, std::forward<Args>(args)...),
3642
13.7k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedINSt3__16vectorINS1_12basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEENS6_IS8_EEEEN3ada6errorsEEC2IJSA_ETnPNS1_9enable_ifIXsr3std16is_constructibleISA_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESI_
Line
Count
Source
3641
13.7k
      : impl_base(in_place, std::forward<Args>(args)...),
3642
13.7k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIN3ada22url_search_params_iterINSt3__117basic_string_viewIcNS3_11char_traitsIcEEEELNS1_27url_search_params_iter_typeE0EEENS1_6errorsEEC2IJS9_ETnPNS3_9enable_ifIXsr3std16is_constructibleIS9_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESG_
Line
Count
Source
3641
13.7k
      : impl_base(in_place, std::forward<Args>(args)...),
3642
13.7k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIN3ada22url_search_params_iterINSt3__117basic_string_viewIcNS3_11char_traitsIcEEEELNS1_27url_search_params_iter_typeE1EEENS1_6errorsEEC2IJS9_ETnPNS3_9enable_ifIXsr3std16is_constructibleIS9_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESG_
Line
Count
Source
3641
13.7k
      : impl_base(in_place, std::forward<Args>(args)...),
3642
13.7k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIN3ada22url_search_params_iterINSt3__14pairINS3_17basic_string_viewIcNS3_11char_traitsIcEEEES8_EELNS1_27url_search_params_iter_typeE2EEENS1_6errorsEEC2IJSB_ETnPNS3_9enable_ifIXsr3std16is_constructibleISB_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESI_
Line
Count
Source
3641
13.7k
      : impl_base(in_place, std::forward<Args>(args)...),
3642
13.7k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedINSt3__16vectorIN3ada16url_pattern_partENS1_9allocatorIS4_EEEENS3_6errorsEEC2IJRS7_ETnPNS1_9enable_ifIXsr3std16is_constructibleIS7_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESF_
Line
Count
Source
3641
2.98M
      : impl_base(in_place, std::forward<Args>(args)...),
3642
2.98M
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIN3ada16url_pattern_initENS1_6errorsEEC2IJRS2_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS2_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESB_
Line
Count
Source
3641
87.5k
      : impl_base(in_place, std::forward<Args>(args)...),
3642
87.5k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIN3ada21url_pattern_componentINS1_17url_pattern_regex18std_regex_providerEEENS1_6errorsEEC2IJS5_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS5_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESD_
Line
Count
Source
3641
2.58M
      : impl_base(in_place, std::forward<Args>(args)...),
3642
2.58M
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIN3ada11url_patternINS1_17url_pattern_regex18std_regex_providerEEENS1_6errorsEEC2IJS5_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS5_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESD_
Line
Count
Source
3641
311k
      : impl_base(in_place, std::forward<Args>(args)...),
3642
311k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIN3ada16url_pattern_listINS1_17url_pattern_regex18std_regex_providerEEENS1_6errorsEEC2IJS5_ETnPNSt3__19enable_ifIXsr3std16is_constructibleIS5_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESD_
Line
Count
Source
3641
8.63k
      : impl_base(in_place, std::forward<Args>(args)...),
3642
8.63k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIbN3ada6errorsEEC2IJbETnPNSt3__19enable_ifIXsr3std16is_constructibleIbDpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tES9_
Line
Count
Source
3641
383k
      : impl_base(in_place, std::forward<Args>(args)...),
3642
383k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedINSt3__18optionalIN3ada18url_pattern_resultEEENS3_6errorsEEC2IJRKNS1_9nullopt_tEETnPNS1_9enable_ifIXsr3std16is_constructibleIS5_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESF_
Line
Count
Source
3641
457k
      : impl_base(in_place, std::forward<Args>(args)...),
3642
457k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedINSt3__18optionalIN3ada18url_pattern_resultEEENS3_6errorsEEC2IJS4_ETnPNS1_9enable_ifIXsr3std16is_constructibleIS5_DpOT_EE5valueEvE4typeELPv0EEENS_10in_place_tESC_
Line
Count
Source
3641
54.2k
      : impl_base(in_place, std::forward<Args>(args)...),
3642
54.2k
        ctor_base(detail::default_constructor_tag{}) {}
3643
3644
  template <class U, class... Args,
3645
            detail::enable_if_t<std::is_constructible<
3646
                T, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
3647
  constexpr expected(in_place_t, std::initializer_list<U> il, Args&&... args)
3648
      : impl_base(in_place, il, std::forward<Args>(args)...),
3649
        ctor_base(detail::default_constructor_tag{}) {}
3650
3651
  template <
3652
      class G = E,
3653
      detail::enable_if_t<std::is_constructible<E, const G&>::value>* = nullptr,
3654
      detail::enable_if_t<!std::is_convertible<const G&, E>::value>* = nullptr>
3655
  explicit constexpr expected(const unexpected<G>& e)
3656
      : impl_base(unexpect, e.value()),
3657
        ctor_base(detail::default_constructor_tag{}) {}
3658
3659
  template <
3660
      class G = E,
3661
      detail::enable_if_t<std::is_constructible<E, const G&>::value>* = nullptr,
3662
      detail::enable_if_t<std::is_convertible<const G&, E>::value>* = nullptr>
3663
  constexpr expected(unexpected<G> const& e)
3664
      : impl_base(unexpect, e.value()),
3665
        ctor_base(detail::default_constructor_tag{}) {}
3666
3667
  template <
3668
      class G = E,
3669
      detail::enable_if_t<std::is_constructible<E, G&&>::value>* = nullptr,
3670
      detail::enable_if_t<!std::is_convertible<G&&, E>::value>* = nullptr>
3671
  explicit constexpr expected(unexpected<G>&& e) noexcept(
3672
      std::is_nothrow_constructible<E, G&&>::value)
3673
      : impl_base(unexpect, std::move(e.value())),
3674
        ctor_base(detail::default_constructor_tag{}) {}
3675
3676
  template <
3677
      class G = E,
3678
      detail::enable_if_t<std::is_constructible<E, G&&>::value>* = nullptr,
3679
      detail::enable_if_t<std::is_convertible<G&&, E>::value>* = nullptr>
3680
  constexpr expected(unexpected<G>&& e) noexcept(
3681
      std::is_nothrow_constructible<E, G&&>::value)
3682
977k
      : impl_base(unexpect, std::move(e.value())),
3683
977k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIN3ada3urlENS1_6errorsEEC2IS3_TnPNSt3__19enable_ifIXsr3std16is_constructibleIS3_OT_EE5valueEvE4typeELPv0ETnPNS7_IXsr3std14is_convertibleIS9_S3_EE5valueEvE4typeELSD_0EEEONS_10unexpectedIS8_EE
Line
Count
Source
3682
76.1k
      : impl_base(unexpect, std::move(e.value())),
3683
76.1k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIN3ada14url_aggregatorENS1_6errorsEEC2IS3_TnPNSt3__19enable_ifIXsr3std16is_constructibleIS3_OT_EE5valueEvE4typeELPv0ETnPNS7_IXsr3std14is_convertibleIS9_S3_EE5valueEvE4typeELSD_0EEEONS_10unexpectedIS8_EE
Line
Count
Source
3682
703k
      : impl_base(unexpect, std::move(e.value())),
3683
703k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIN3ada16url_pattern_initENS1_6errorsEEC2IS3_TnPNSt3__19enable_ifIXsr3std16is_constructibleIS3_OT_EE5valueEvE4typeELPv0ETnPNS7_IXsr3std14is_convertibleIS9_S3_EE5valueEvE4typeELSD_0EEEONS_10unexpectedIS8_EE
Line
Count
Source
3682
58.8k
      : impl_base(unexpect, std::move(e.value())),
3683
58.8k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedINSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEN3ada6errorsEEC2IS9_TnPNS1_9enable_ifIXsr3std16is_constructibleIS9_OT_EE5valueEvE4typeELPv0ETnPNSC_IXsr3std14is_convertibleISE_S9_EE5valueEvE4typeELSI_0EEEONS_10unexpectedISD_EE
Line
Count
Source
3682
5.06k
      : impl_base(unexpect, std::move(e.value())),
3683
5.06k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedINSt3__16vectorIN3ada19url_pattern_helpers5tokenENS1_9allocatorIS5_EEEENS3_6errorsEEC2IS9_TnPNS1_9enable_ifIXsr3std16is_constructibleIS9_OT_EE5valueEvE4typeELPv0ETnPNSC_IXsr3std14is_convertibleISE_S9_EE5valueEvE4typeELSI_0EEEONS_10unexpectedISD_EE
Line
Count
Source
3682
2.07k
      : impl_base(unexpect, std::move(e.value())),
3683
2.07k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIN3ada23url_pattern_list_detail15compiled_routesENS1_6errorsEEC2IS4_TnPNSt3__19enable_ifIXsr3std16is_constructibleIS4_OT_EE5valueEvE4typeELPv0ETnPNS8_IXsr3std14is_convertibleISA_S4_EE5valueEvE4typeELSE_0EEEONS_10unexpectedIS9_EE
Line
Count
Source
3682
760
      : impl_base(unexpect, std::move(e.value())),
3683
760
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedINSt3__16vectorIN3ada16url_pattern_partENS1_9allocatorIS4_EEEENS3_6errorsEEC2IS8_TnPNS1_9enable_ifIXsr3std16is_constructibleIS8_OT_EE5valueEvE4typeELPv0ETnPNSB_IXsr3std14is_convertibleISD_S8_EE5valueEvE4typeELSH_0EEEONS_10unexpectedISC_EE
Line
Count
Source
3682
8.47k
      : impl_base(unexpect, std::move(e.value())),
3683
8.47k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIN3ada11url_patternINS1_17url_pattern_regex18std_regex_providerEEENS1_6errorsEEC2IS6_TnPNSt3__19enable_ifIXsr3std16is_constructibleIS6_OT_EE5valueEvE4typeELPv0ETnPNSA_IXsr3std14is_convertibleISC_S6_EE5valueEvE4typeELSG_0EEEONS_10unexpectedISB_EE
Line
Count
Source
3682
110k
      : impl_base(unexpect, std::move(e.value())),
3683
110k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIN3ada21url_pattern_componentINS1_17url_pattern_regex18std_regex_providerEEENS1_6errorsEEC2IS6_TnPNSt3__19enable_ifIXsr3std16is_constructibleIS6_OT_EE5valueEvE4typeELPv0ETnPNSA_IXsr3std14is_convertibleISC_S6_EE5valueEvE4typeELSG_0EEEONS_10unexpectedISB_EE
Line
Count
Source
3682
10.2k
      : impl_base(unexpect, std::move(e.value())),
3683
10.2k
        ctor_base(detail::default_constructor_tag{}) {}
_ZN2tl8expectedIN3ada16url_pattern_listINS1_17url_pattern_regex18std_regex_providerEEENS1_6errorsEEC2IS6_TnPNSt3__19enable_ifIXsr3std16is_constructibleIS6_OT_EE5valueEvE4typeELPv0ETnPNSA_IXsr3std14is_convertibleISC_S6_EE5valueEvE4typeELSG_0EEEONS_10unexpectedISB_EE
Line
Count
Source
3682
1.57k
      : impl_base(unexpect, std::move(e.value())),
3683
1.57k
        ctor_base(detail::default_constructor_tag{}) {}
Unexecuted instantiation: _ZN2tl8expectedIbN3ada6errorsEEC2IS2_TnPNSt3__19enable_ifIXsr3std16is_constructibleIS2_OT_EE5valueEvE4typeELPv0ETnPNS6_IXsr3std14is_convertibleIS8_S2_EE5valueEvE4typeELSC_0EEEONS_10unexpectedIS7_EE
Unexecuted instantiation: _ZN2tl8expectedINSt3__18optionalIN3ada18url_pattern_resultEEENS3_6errorsEEC2IS6_TnPNS1_9enable_ifIXsr3std16is_constructibleIS6_OT_EE5valueEvE4typeELPv0ETnPNS9_IXsr3std14is_convertibleISB_S6_EE5valueEvE4typeELSF_0EEEONS_10unexpectedISA_EE
3684
3685
  template <class... Args,
3686
            detail::enable_if_t<std::is_constructible<E, Args&&...>::value>* =
3687
                nullptr>
3688
  constexpr explicit expected(unexpect_t, Args&&... args)
3689
      : impl_base(unexpect, std::forward<Args>(args)...),
3690
        ctor_base(detail::default_constructor_tag{}) {}
3691
3692
  template <class U, class... Args,
3693
            detail::enable_if_t<std::is_constructible<
3694
                E, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
3695
  constexpr explicit expected(unexpect_t, std::initializer_list<U> il,
3696
                              Args&&... args)
3697
      : impl_base(unexpect, il, std::forward<Args>(args)...),
3698
        ctor_base(detail::default_constructor_tag{}) {}
3699
3700
  template <class U, class G,
3701
            detail::enable_if_t<!(std::is_convertible<U const&, T>::value &&
3702
                                  std::is_convertible<G const&, E>::value)>* =
3703
                nullptr,
3704
            detail::expected_enable_from_other<T, E, U, G, const U&,
3705
                                               const G&>* = nullptr>
3706
  explicit TL_EXPECTED_11_CONSTEXPR expected(const expected<U, G>& rhs)
3707
      : ctor_base(detail::default_constructor_tag{}) {
3708
    if (rhs.has_value()) {
3709
      this->construct(*rhs);
3710
    } else {
3711
      this->construct_error(rhs.error());
3712
    }
3713
  }
3714
3715
  template <
3716
      class U, class G,
3717
      detail::enable_if_t<(std::is_convertible<U const&, T>::value &&
3718
                           std::is_convertible<G const&, E>::value)>* = nullptr,
3719
      detail::expected_enable_from_other<T, E, U, G, const U&, const G&>* =
3720
          nullptr>
3721
  TL_EXPECTED_11_CONSTEXPR expected(const expected<U, G>& rhs)
3722
      : ctor_base(detail::default_constructor_tag{}) {
3723
    if (rhs.has_value()) {
3724
      this->construct(*rhs);
3725
    } else {
3726
      this->construct_error(rhs.error());
3727
    }
3728
  }
3729
3730
  template <
3731
      class U, class G,
3732
      detail::enable_if_t<!(std::is_convertible<U&&, T>::value &&
3733
                            std::is_convertible<G&&, E>::value)>* = nullptr,
3734
      detail::expected_enable_from_other<T, E, U, G, U&&, G&&>* = nullptr>
3735
  explicit TL_EXPECTED_11_CONSTEXPR expected(expected<U, G>&& rhs)
3736
      : ctor_base(detail::default_constructor_tag{}) {
3737
    if (rhs.has_value()) {
3738
      this->construct(std::move(*rhs));
3739
    } else {
3740
      this->construct_error(std::move(rhs.error()));
3741
    }
3742
  }
3743
3744
  template <
3745
      class U, class G,
3746
      detail::enable_if_t<(std::is_convertible<U&&, T>::value &&
3747
                           std::is_convertible<G&&, E>::value)>* = nullptr,
3748
      detail::expected_enable_from_other<T, E, U, G, U&&, G&&>* = nullptr>
3749
  TL_EXPECTED_11_CONSTEXPR expected(expected<U, G>&& rhs)
3750
      : ctor_base(detail::default_constructor_tag{}) {
3751
    if (rhs.has_value()) {
3752
      this->construct(std::move(*rhs));
3753
    } else {
3754
      this->construct_error(std::move(rhs.error()));
3755
    }
3756
  }
3757
3758
  template <class U = T,
3759
            detail::enable_if_t<!std::is_convertible<U&&, T>::value>* = nullptr,
3760
            detail::expected_enable_forward_value<T, E, U>* = nullptr>
3761
  explicit TL_EXPECTED_MSVC2015_CONSTEXPR expected(U&& v)
3762
      : expected(in_place, std::forward<U>(v)) {}
3763
3764
  template <class U = T,
3765
            detail::enable_if_t<std::is_convertible<U&&, T>::value>* = nullptr,
3766
            detail::expected_enable_forward_value<T, E, U>* = nullptr>
3767
  TL_EXPECTED_MSVC2015_CONSTEXPR expected(U&& v)
3768
19.4M
      : expected(in_place, std::forward<U>(v)) {}
_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_
Line
Count
Source
3768
683k
      : expected(in_place, std::forward<U>(v)) {}
_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
3768
1.95M
      : expected(in_place, std::forward<U>(v)) {}
_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_
Line
Count
Source
3768
574k
      : expected(in_place, std::forward<U>(v)) {}
_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_
Line
Count
Source
3768
2.13M
      : expected(in_place, std::forward<U>(v)) {}
_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_
Line
Count
Source
3768
4.12M
      : expected(in_place, std::forward<U>(v)) {}
_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_
Line
Count
Source
3768
54
      : expected(in_place, std::forward<U>(v)) {}
_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_
Line
Count
Source
3768
3.07M
      : expected(in_place, std::forward<U>(v)) {}
_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_
Line
Count
Source
3768
8.63k
      : expected(in_place, std::forward<U>(v)) {}
_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_
Line
Count
Source
3768
13.7k
      : expected(in_place, std::forward<U>(v)) {}
_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_
Line
Count
Source
3768
13.7k
      : expected(in_place, std::forward<U>(v)) {}
_ZN2tl8expectedIN3ada22url_search_params_iterINSt3__117basic_string_viewIcNS3_11char_traitsIcEEEELNS1_27url_search_params_iter_typeE0EEENS1_6errorsEEC2IS9_TnPNS3_9enable_ifIXsr3std14is_convertibleIOT_S9_EE5valueEvE4typeELPv0ETnPNSD_IXaaaaaasr3std16is_constructibleIS9_SF_EE5valuentsr3std7is_sameINS3_5decayISE_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameISB_SM_EE5valuentsr3std7is_sameINS_10unexpectedISA_EESM_EE5valueEvE4typeELSJ_0EEESF_
Line
Count
Source
3768
13.7k
      : expected(in_place, std::forward<U>(v)) {}
_ZN2tl8expectedIN3ada22url_search_params_iterINSt3__117basic_string_viewIcNS3_11char_traitsIcEEEELNS1_27url_search_params_iter_typeE1EEENS1_6errorsEEC2IS9_TnPNS3_9enable_ifIXsr3std14is_convertibleIOT_S9_EE5valueEvE4typeELPv0ETnPNSD_IXaaaaaasr3std16is_constructibleIS9_SF_EE5valuentsr3std7is_sameINS3_5decayISE_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameISB_SM_EE5valuentsr3std7is_sameINS_10unexpectedISA_EESM_EE5valueEvE4typeELSJ_0EEESF_
Line
Count
Source
3768
13.7k
      : expected(in_place, std::forward<U>(v)) {}
_ZN2tl8expectedIN3ada22url_search_params_iterINSt3__14pairINS3_17basic_string_viewIcNS3_11char_traitsIcEEEES8_EELNS1_27url_search_params_iter_typeE2EEENS1_6errorsEEC2ISB_TnPNS3_9enable_ifIXsr3std14is_convertibleIOT_SB_EE5valueEvE4typeELPv0ETnPNSF_IXaaaaaasr3std16is_constructibleISB_SH_EE5valuentsr3std7is_sameINS3_5decayISG_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameISD_SO_EE5valuentsr3std7is_sameINS_10unexpectedISC_EESO_EE5valueEvE4typeELSL_0EEESH_
Line
Count
Source
3768
13.7k
      : expected(in_place, std::forward<U>(v)) {}
_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_
Line
Count
Source
3768
2.98M
      : expected(in_place, std::forward<U>(v)) {}
_ZN2tl8expectedIN3ada16url_pattern_initENS1_6errorsEEC2IRS2_TnPNSt3__19enable_ifIXsr3std14is_convertibleIOT_S2_EE5valueEvE4typeELPv0ETnPNS8_IXaaaaaasr3std16is_constructibleIS2_SA_EE5valuentsr3std7is_sameINS7_5decayIS9_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameIS4_SH_EE5valuentsr3std7is_sameINS_10unexpectedIS3_EESH_EE5valueEvE4typeELSE_0EEESA_
Line
Count
Source
3768
87.5k
      : expected(in_place, std::forward<U>(v)) {}
_ZN2tl8expectedIN3ada21url_pattern_componentINS1_17url_pattern_regex18std_regex_providerEEENS1_6errorsEEC2IS5_TnPNSt3__19enable_ifIXsr3std14is_convertibleIOT_S5_EE5valueEvE4typeELPv0ETnPNSA_IXaaaaaasr3std16is_constructibleIS5_SC_EE5valuentsr3std7is_sameINS9_5decayISB_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameIS7_SJ_EE5valuentsr3std7is_sameINS_10unexpectedIS6_EESJ_EE5valueEvE4typeELSG_0EEESC_
Line
Count
Source
3768
2.58M
      : expected(in_place, std::forward<U>(v)) {}
_ZN2tl8expectedIN3ada11url_patternINS1_17url_pattern_regex18std_regex_providerEEENS1_6errorsEEC2IS5_TnPNSt3__19enable_ifIXsr3std14is_convertibleIOT_S5_EE5valueEvE4typeELPv0ETnPNSA_IXaaaaaasr3std16is_constructibleIS5_SC_EE5valuentsr3std7is_sameINS9_5decayISB_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameIS7_SJ_EE5valuentsr3std7is_sameINS_10unexpectedIS6_EESJ_EE5valueEvE4typeELSG_0EEESC_
Line
Count
Source
3768
311k
      : expected(in_place, std::forward<U>(v)) {}
_ZN2tl8expectedIN3ada16url_pattern_listINS1_17url_pattern_regex18std_regex_providerEEENS1_6errorsEEC2IS5_TnPNSt3__19enable_ifIXsr3std14is_convertibleIOT_S5_EE5valueEvE4typeELPv0ETnPNSA_IXaaaaaasr3std16is_constructibleIS5_SC_EE5valuentsr3std7is_sameINS9_5decayISB_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameIS7_SJ_EE5valuentsr3std7is_sameINS_10unexpectedIS6_EESJ_EE5valueEvE4typeELSG_0EEESC_
Line
Count
Source
3768
8.63k
      : expected(in_place, std::forward<U>(v)) {}
_ZN2tl8expectedIbN3ada6errorsEEC2IbTnPNSt3__19enable_ifIXsr3std14is_convertibleIOT_bEE5valueEvE4typeELPv0ETnPNS6_IXaaaaaasr3std16is_constructibleIbS8_EE5valuentsr3std7is_sameINS5_5decayIS7_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameIS3_SF_EE5valuentsr3std7is_sameINS_10unexpectedIS2_EESF_EE5valueEvE4typeELSC_0EEES8_
Line
Count
Source
3768
383k
      : expected(in_place, std::forward<U>(v)) {}
_ZN2tl8expectedINSt3__18optionalIN3ada18url_pattern_resultEEENS3_6errorsEEC2IRKNS1_9nullopt_tETnPNS1_9enable_ifIXsr3std14is_convertibleIOT_S5_EE5valueEvE4typeELPv0ETnPNSC_IXaaaaaasr3std16is_constructibleIS5_SE_EE5valuentsr3std7is_sameINS1_5decayISD_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameIS7_SL_EE5valuentsr3std7is_sameINS_10unexpectedIS6_EESL_EE5valueEvE4typeELSI_0EEESE_
Line
Count
Source
3768
457k
      : expected(in_place, std::forward<U>(v)) {}
_ZN2tl8expectedINSt3__18optionalIN3ada18url_pattern_resultEEENS3_6errorsEEC2IS4_TnPNS1_9enable_ifIXsr3std14is_convertibleIOT_S5_EE5valueEvE4typeELPv0ETnPNS9_IXaaaaaasr3std16is_constructibleIS5_SB_EE5valuentsr3std7is_sameINS1_5decayISA_E4typeENS_10in_place_tEEE5valuentsr3std7is_sameIS7_SI_EE5valuentsr3std7is_sameINS_10unexpectedIS6_EESI_EE5valueEvE4typeELSF_0EEESB_
Line
Count
Source
3768
54.2k
      : expected(in_place, std::forward<U>(v)) {}
3769
3770
  template <
3771
      class U = T, class G = T,
3772
      detail::enable_if_t<std::is_nothrow_constructible<T, U&&>::value>* =
3773
          nullptr,
3774
      detail::enable_if_t<!std::is_void<G>::value>* = nullptr,
3775
      detail::enable_if_t<
3776
          (!std::is_same<expected<T, E>, detail::decay_t<U>>::value &&
3777
           !detail::conjunction<std::is_scalar<T>,
3778
                                std::is_same<T, detail::decay_t<U>>>::value &&
3779
           std::is_constructible<T, U>::value &&
3780
           std::is_assignable<G&, U>::value &&
3781
           std::is_nothrow_move_constructible<E>::value)>* = nullptr>
3782
  expected& operator=(U&& v) {
3783
    if (has_value()) {
3784
      val() = std::forward<U>(v);
3785
    } else {
3786
      err().~unexpected<E>();
3787
      ::new (valptr()) T(std::forward<U>(v));
3788
      this->m_has_val = true;
3789
    }
3790
3791
    return *this;
3792
  }
3793
3794
  template <
3795
      class U = T, class G = T,
3796
      detail::enable_if_t<!std::is_nothrow_constructible<T, U&&>::value>* =
3797
          nullptr,
3798
      detail::enable_if_t<!std::is_void<U>::value>* = nullptr,
3799
      detail::enable_if_t<
3800
          (!std::is_same<expected<T, E>, detail::decay_t<U>>::value &&
3801
           !detail::conjunction<std::is_scalar<T>,
3802
                                std::is_same<T, detail::decay_t<U>>>::value &&
3803
           std::is_constructible<T, U>::value &&
3804
           std::is_assignable<G&, U>::value &&
3805
           std::is_nothrow_move_constructible<E>::value)>* = nullptr>
3806
  expected& operator=(U&& v) {
3807
    if (has_value()) {
3808
      val() = std::forward<U>(v);
3809
    } else {
3810
      auto tmp = std::move(err());
3811
      err().~unexpected<E>();
3812
3813
#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED
3814
      try {
3815
        ::new (valptr()) T(std::forward<U>(v));
3816
        this->m_has_val = true;
3817
      } catch (...) {
3818
        err() = std::move(tmp);
3819
        throw;
3820
      }
3821
#else
3822
      ::new (valptr()) T(std::forward<U>(v));
3823
      this->m_has_val = true;
3824
#endif
3825
    }
3826
3827
    return *this;
3828
  }
3829
3830
  template <class G = E,
3831
            detail::enable_if_t<std::is_nothrow_copy_constructible<G>::value &&
3832
                                std::is_assignable<G&, G>::value>* = nullptr>
3833
  expected& operator=(const unexpected<G>& rhs) {
3834
    if (!has_value()) {
3835
      err() = rhs;
3836
    } else {
3837
      this->destroy_val();
3838
      ::new (errptr()) unexpected<E>(rhs);
3839
      this->m_has_val = false;
3840
    }
3841
3842
    return *this;
3843
  }
3844
3845
  template <class G = E,
3846
            detail::enable_if_t<std::is_nothrow_move_constructible<G>::value &&
3847
                                std::is_move_assignable<G>::value>* = nullptr>
3848
  expected& operator=(unexpected<G>&& rhs) noexcept {
3849
    if (!has_value()) {
3850
      err() = std::move(rhs);
3851
    } else {
3852
      this->destroy_val();
3853
      ::new (errptr()) unexpected<E>(std::move(rhs));
3854
      this->m_has_val = false;
3855
    }
3856
3857
    return *this;
3858
  }
3859
3860
  template <class... Args, detail::enable_if_t<std::is_nothrow_constructible<
3861
                               T, Args&&...>::value>* = nullptr>
3862
  void emplace(Args&&... args) {
3863
    if (has_value()) {
3864
      val().~T();
3865
    } else {
3866
      err().~unexpected<E>();
3867
      this->m_has_val = true;
3868
    }
3869
    ::new (valptr()) T(std::forward<Args>(args)...);
3870
  }
3871
3872
  template <class... Args, detail::enable_if_t<!std::is_nothrow_constructible<
3873
                               T, Args&&...>::value>* = nullptr>
3874
  void emplace(Args&&... args) {
3875
    if (has_value()) {
3876
      val().~T();
3877
      ::new (valptr()) T(std::forward<Args>(args)...);
3878
    } else {
3879
      auto tmp = std::move(err());
3880
      err().~unexpected<E>();
3881
3882
#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED
3883
      try {
3884
        ::new (valptr()) T(std::forward<Args>(args)...);
3885
        this->m_has_val = true;
3886
      } catch (...) {
3887
        err() = std::move(tmp);
3888
        throw;
3889
      }
3890
#else
3891
      ::new (valptr()) T(std::forward<Args>(args)...);
3892
      this->m_has_val = true;
3893
#endif
3894
    }
3895
  }
3896
3897
  template <class U, class... Args,
3898
            detail::enable_if_t<std::is_nothrow_constructible<
3899
                T, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
3900
  void emplace(std::initializer_list<U> il, Args&&... args) {
3901
    if (has_value()) {
3902
      T t(il, std::forward<Args>(args)...);
3903
      val() = std::move(t);
3904
    } else {
3905
      err().~unexpected<E>();
3906
      ::new (valptr()) T(il, std::forward<Args>(args)...);
3907
      this->m_has_val = true;
3908
    }
3909
  }
3910
3911
  template <class U, class... Args,
3912
            detail::enable_if_t<!std::is_nothrow_constructible<
3913
                T, std::initializer_list<U>&, Args&&...>::value>* = nullptr>
3914
  void emplace(std::initializer_list<U> il, Args&&... args) {
3915
    if (has_value()) {
3916
      T t(il, std::forward<Args>(args)...);
3917
      val() = std::move(t);
3918
    } else {
3919
      auto tmp = std::move(err());
3920
      err().~unexpected<E>();
3921
3922
#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED
3923
      try {
3924
        ::new (valptr()) T(il, std::forward<Args>(args)...);
3925
        this->m_has_val = true;
3926
      } catch (...) {
3927
        err() = std::move(tmp);
3928
        throw;
3929
      }
3930
#else
3931
      ::new (valptr()) T(il, std::forward<Args>(args)...);
3932
      this->m_has_val = true;
3933
#endif
3934
    }
3935
  }
3936
3937
 private:
3938
  using t_is_void = std::true_type;
3939
  using t_is_not_void = std::false_type;
3940
  using t_is_nothrow_move_constructible = std::true_type;
3941
  using move_constructing_t_can_throw = std::false_type;
3942
  using e_is_nothrow_move_constructible = std::true_type;
3943
  using move_constructing_e_can_throw = std::false_type;
3944
3945
  void swap_where_both_have_value(expected& /*rhs*/, t_is_void) noexcept {
3946
    // swapping void is a no-op
3947
  }
3948
3949
  void swap_where_both_have_value(expected& rhs, t_is_not_void) {
3950
    using std::swap;
3951
    swap(val(), rhs.val());
3952
  }
3953
3954
  void swap_where_only_one_has_value(expected& rhs, t_is_void) noexcept(
3955
      std::is_nothrow_move_constructible<E>::value) {
3956
    ::new (errptr()) unexpected_type(std::move(rhs.err()));
3957
    rhs.err().~unexpected_type();
3958
    std::swap(this->m_has_val, rhs.m_has_val);
3959
  }
3960
3961
  void swap_where_only_one_has_value(expected& rhs, t_is_not_void) {
3962
    swap_where_only_one_has_value_and_t_is_not_void(
3963
        rhs, typename std::is_nothrow_move_constructible<T>::type{},
3964
        typename std::is_nothrow_move_constructible<E>::type{});
3965
  }
3966
3967
  void swap_where_only_one_has_value_and_t_is_not_void(
3968
      expected& rhs, t_is_nothrow_move_constructible,
3969
      e_is_nothrow_move_constructible) noexcept {
3970
    auto temp = std::move(val());
3971
    val().~T();
3972
    ::new (errptr()) unexpected_type(std::move(rhs.err()));
3973
    rhs.err().~unexpected_type();
3974
    ::new (rhs.valptr()) T(std::move(temp));
3975
    std::swap(this->m_has_val, rhs.m_has_val);
3976
  }
3977
3978
  void swap_where_only_one_has_value_and_t_is_not_void(
3979
      expected& rhs, t_is_nothrow_move_constructible,
3980
      move_constructing_e_can_throw) {
3981
    auto temp = std::move(val());
3982
    val().~T();
3983
#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED
3984
    try {
3985
      ::new (errptr()) unexpected_type(std::move(rhs.err()));
3986
      rhs.err().~unexpected_type();
3987
      ::new (rhs.valptr()) T(std::move(temp));
3988
      std::swap(this->m_has_val, rhs.m_has_val);
3989
    } catch (...) {
3990
      val() = std::move(temp);
3991
      throw;
3992
    }
3993
#else
3994
    ::new (errptr()) unexpected_type(std::move(rhs.err()));
3995
    rhs.err().~unexpected_type();
3996
    ::new (rhs.valptr()) T(std::move(temp));
3997
    std::swap(this->m_has_val, rhs.m_has_val);
3998
#endif
3999
  }
4000
4001
  void swap_where_only_one_has_value_and_t_is_not_void(
4002
      expected& rhs, move_constructing_t_can_throw,
4003
      e_is_nothrow_move_constructible) {
4004
    auto temp = std::move(rhs.err());
4005
    rhs.err().~unexpected_type();
4006
#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED
4007
    try {
4008
      ::new (rhs.valptr()) T(std::move(val()));
4009
      val().~T();
4010
      ::new (errptr()) unexpected_type(std::move(temp));
4011
      std::swap(this->m_has_val, rhs.m_has_val);
4012
    } catch (...) {
4013
      rhs.err() = std::move(temp);
4014
      throw;
4015
    }
4016
#else
4017
    ::new (rhs.valptr()) T(std::move(val()));
4018
    val().~T();
4019
    ::new (errptr()) unexpected_type(std::move(temp));
4020
    std::swap(this->m_has_val, rhs.m_has_val);
4021
#endif
4022
  }
4023
4024
 public:
4025
  template <class OT = T, class OE = E>
4026
  detail::enable_if_t<detail::is_swappable<OT>::value &&
4027
                      detail::is_swappable<OE>::value &&
4028
                      (std::is_nothrow_move_constructible<OT>::value ||
4029
                       std::is_nothrow_move_constructible<OE>::value)>
4030
  swap(expected& rhs) noexcept(std::is_nothrow_move_constructible<T>::value &&
4031
                               detail::is_nothrow_swappable<T>::value &&
4032
                               std::is_nothrow_move_constructible<E>::value &&
4033
                               detail::is_nothrow_swappable<E>::value) {
4034
    if (has_value() && rhs.has_value()) {
4035
      swap_where_both_have_value(rhs, typename std::is_void<T>::type{});
4036
    } else if (!has_value() && rhs.has_value()) {
4037
      rhs.swap(*this);
4038
    } else if (has_value()) {
4039
      swap_where_only_one_has_value(rhs, typename std::is_void<T>::type{});
4040
    } else {
4041
      using std::swap;
4042
      swap(err(), rhs.err());
4043
    }
4044
  }
4045
4046
  constexpr const T* operator->() const {
4047
    TL_ASSERT(has_value());
4048
    return valptr();
4049
  }
4050
27.6M
  TL_EXPECTED_11_CONSTEXPR T* operator->() {
4051
27.6M
    TL_ASSERT(has_value());
4052
27.6M
    return valptr();
4053
27.6M
  }
tl::expected<ada::url, ada::errors>::operator->()
Line
Count
Source
4050
1.83M
  TL_EXPECTED_11_CONSTEXPR T* operator->() {
4051
1.83M
    TL_ASSERT(has_value());
4052
1.83M
    return valptr();
4053
1.83M
  }
tl::expected<ada::url_aggregator, ada::errors>::operator->()
Line
Count
Source
4050
7.69M
  TL_EXPECTED_11_CONSTEXPR T* operator->() {
4051
7.69M
    TL_ASSERT(has_value());
4052
7.69M
    return valptr();
4053
7.69M
  }
tl::expected<ada::url_search_params, ada::errors>::operator->()
Line
Count
Source
4050
205k
  TL_EXPECTED_11_CONSTEXPR T* operator->() {
4051
205k
    TL_ASSERT(has_value());
4052
205k
    return valptr();
4053
205k
  }
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->()
Line
Count
Source
4050
27.4k
  TL_EXPECTED_11_CONSTEXPR T* operator->() {
4051
27.4k
    TL_ASSERT(has_value());
4052
27.4k
    return valptr();
4053
27.4k
  }
tl::expected<ada::url_search_params_iter<std::__1::basic_string_view<char, std::__1::char_traits<char> >, (ada::url_search_params_iter_type)0>, ada::errors>::operator->()
Line
Count
Source
4050
60.6k
  TL_EXPECTED_11_CONSTEXPR T* operator->() {
4051
60.6k
    TL_ASSERT(has_value());
4052
60.6k
    return valptr();
4053
60.6k
  }
tl::expected<ada::url_search_params_iter<std::__1::basic_string_view<char, std::__1::char_traits<char> >, (ada::url_search_params_iter_type)1>, ada::errors>::operator->()
Line
Count
Source
4050
60.6k
  TL_EXPECTED_11_CONSTEXPR T* operator->() {
4051
60.6k
    TL_ASSERT(has_value());
4052
60.6k
    return valptr();
4053
60.6k
  }
tl::expected<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>, ada::errors>::operator->()
Line
Count
Source
4050
60.6k
  TL_EXPECTED_11_CONSTEXPR T* operator->() {
4051
60.6k
    TL_ASSERT(has_value());
4052
60.6k
    return valptr();
4053
60.6k
  }
tl::expected<ada::url_pattern_init, ada::errors>::operator->()
Line
Count
Source
4050
9.86M
  TL_EXPECTED_11_CONSTEXPR T* operator->() {
4051
9.86M
    TL_ASSERT(has_value());
4052
9.86M
    return valptr();
4053
9.86M
  }
tl::expected<std::__1::vector<ada::url_pattern_part, std::__1::allocator<ada::url_pattern_part> >, ada::errors>::operator->()
Line
Count
Source
4050
6.73M
  TL_EXPECTED_11_CONSTEXPR T* operator->() {
4051
6.73M
    TL_ASSERT(has_value());
4052
6.73M
    return valptr();
4053
6.73M
  }
tl::expected<ada::url_pattern_list<ada::url_pattern_regex::std_regex_provider>, ada::errors>::operator->()
Line
Count
Source
4050
279k
  TL_EXPECTED_11_CONSTEXPR T* operator->() {
4051
279k
    TL_ASSERT(has_value());
4052
279k
    return valptr();
4053
279k
  }
tl::expected<ada::url_pattern_component<ada::url_pattern_regex::std_regex_provider>, ada::errors>::operator->()
Line
Count
Source
4050
23.2k
  TL_EXPECTED_11_CONSTEXPR T* operator->() {
4051
23.2k
    TL_ASSERT(has_value());
4052
23.2k
    return valptr();
4053
23.2k
  }
tl::expected<std::__1::optional<ada::url_pattern_result>, ada::errors>::operator->()
Line
Count
Source
4050
767k
  TL_EXPECTED_11_CONSTEXPR T* operator->() {
4051
767k
    TL_ASSERT(has_value());
4052
767k
    return valptr();
4053
767k
  }
4054
4055
  template <class U = T,
4056
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
4057
  constexpr const U& operator*() const& {
4058
    TL_ASSERT(has_value());
4059
    return val();
4060
  }
4061
  template <class U = T,
4062
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
4063
25.5M
  TL_EXPECTED_11_CONSTEXPR U& operator*() & {
4064
25.5M
    TL_ASSERT(has_value());
4065
25.5M
    return val();
4066
25.5M
  }
_ZNR2tl8expectedIN3ada3urlENS1_6errorsEEdeIS2_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERS8_v
Line
Count
Source
4063
1.02M
  TL_EXPECTED_11_CONSTEXPR U& operator*() & {
4064
1.02M
    TL_ASSERT(has_value());
4065
1.02M
    return val();
4066
1.02M
  }
_ZNR2tl8expectedIN3ada14url_aggregatorENS1_6errorsEEdeIS2_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERS8_v
Line
Count
Source
4063
1.83M
  TL_EXPECTED_11_CONSTEXPR U& operator*() & {
4064
1.83M
    TL_ASSERT(has_value());
4065
1.83M
    return val();
4066
1.83M
  }
_ZNR2tl8expectedINSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEN3ada6errorsEEdeIS7_TnPNS1_9enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSD_v
Line
Count
Source
4063
6.25M
  TL_EXPECTED_11_CONSTEXPR U& operator*() & {
4064
6.25M
    TL_ASSERT(has_value());
4065
6.25M
    return val();
4066
6.25M
  }
_ZNR2tl8expectedINSt3__16vectorIN3ada16url_pattern_partENS1_9allocatorIS4_EEEENS3_6errorsEEdeIS7_TnPNS1_9enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSC_v
Line
Count
Source
4063
9.83M
  TL_EXPECTED_11_CONSTEXPR U& operator*() & {
4064
9.83M
    TL_ASSERT(has_value());
4065
9.83M
    return val();
4066
9.83M
  }
_ZNR2tl8expectedINSt3__16vectorIN3ada19url_pattern_helpers5tokenENS1_9allocatorIS5_EEEENS3_6errorsEEdeIS8_TnPNS1_9enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSD_v
Line
Count
Source
4063
3.07M
  TL_EXPECTED_11_CONSTEXPR U& operator*() & {
4064
3.07M
    TL_ASSERT(has_value());
4065
3.07M
    return val();
4066
3.07M
  }
_ZNR2tl8expectedIN3ada16url_pattern_initENS1_6errorsEEdeIS2_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERS8_v
Line
Count
Source
4063
87.5k
  TL_EXPECTED_11_CONSTEXPR U& operator*() & {
4064
87.5k
    TL_ASSERT(has_value());
4065
87.5k
    return val();
4066
87.5k
  }
_ZNR2tl8expectedIN3ada21url_pattern_componentINS1_17url_pattern_regex18std_regex_providerEEENS1_6errorsEEdeIS5_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSB_v
Line
Count
Source
4063
2.58M
  TL_EXPECTED_11_CONSTEXPR U& operator*() & {
4064
2.58M
    TL_ASSERT(has_value());
4065
2.58M
    return val();
4066
2.58M
  }
_ZNR2tl8expectedIN3ada11url_patternINS1_17url_pattern_regex18std_regex_providerEEENS1_6errorsEEdeIS5_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSB_v
Line
Count
Source
4063
439k
  TL_EXPECTED_11_CONSTEXPR U& operator*() & {
4064
439k
    TL_ASSERT(has_value());
4065
439k
    return val();
4066
439k
  }
_ZNR2tl8expectedIN3ada16url_pattern_listINS1_17url_pattern_regex18std_regex_providerEEENS1_6errorsEEdeIS5_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSB_v
Line
Count
Source
4063
7.81k
  TL_EXPECTED_11_CONSTEXPR U& operator*() & {
4064
7.81k
    TL_ASSERT(has_value());
4065
7.81k
    return val();
4066
7.81k
  }
_ZNR2tl8expectedIN3ada23url_pattern_list_detail15compiled_routesENS1_6errorsEEdeIS3_TnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERS9_v
Line
Count
Source
4063
8.63k
  TL_EXPECTED_11_CONSTEXPR U& operator*() & {
4064
8.63k
    TL_ASSERT(has_value());
4065
8.63k
    return val();
4066
8.63k
  }
_ZNR2tl8expectedIbN3ada6errorsEEdeIbTnPNSt3__19enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERS7_v
Line
Count
Source
4063
383k
  TL_EXPECTED_11_CONSTEXPR U& operator*() & {
4064
383k
    TL_ASSERT(has_value());
4065
383k
    return val();
4066
383k
  }
_ZNR2tl8expectedINSt3__18optionalIN3ada18url_pattern_resultEEENS3_6errorsEEdeIS5_TnPNS1_9enable_ifIXntsr3std7is_voidIT_EE5valueEvE4typeELPv0EEERSA_v
Line
Count
Source
4063
45.3k
  TL_EXPECTED_11_CONSTEXPR U& operator*() & {
4064
45.3k
    TL_ASSERT(has_value());
4065
45.3k
    return val();
4066
45.3k
  }
4067
  template <class U = T,
4068
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
4069
  constexpr const U&& operator*() const&& {
4070
    TL_ASSERT(has_value());
4071
    return std::move(val());
4072
  }
4073
  template <class U = T,
4074
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
4075
  TL_EXPECTED_11_CONSTEXPR U&& operator*() && {
4076
    TL_ASSERT(has_value());
4077
    return std::move(val());
4078
  }
4079
4080
55.4M
  constexpr bool has_value() const noexcept { return this->m_has_val; }
tl::expected<ada::url, ada::errors>::has_value() const
Line
Count
Source
4080
3.35M
  constexpr bool has_value() const noexcept { return this->m_has_val; }
tl::expected<ada::url_aggregator, ada::errors>::has_value() const
Line
Count
Source
4080
11.0M
  constexpr bool has_value() const noexcept { return this->m_has_val; }
tl::expected<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, ada::errors>::has_value() const
Line
Count
Source
4080
6.26M
  constexpr bool has_value() const noexcept { return this->m_has_val; }
tl::expected<std::__1::vector<ada::url_pattern_part, std::__1::allocator<ada::url_pattern_part> >, ada::errors>::has_value() const
Line
Count
Source
4080
16.5M
  constexpr bool has_value() const noexcept { return this->m_has_val; }
tl::expected<ada::url_search_params, ada::errors>::has_value() const
Line
Count
Source
4080
205k
  constexpr bool has_value() const noexcept { return this->m_has_val; }
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
Line
Count
Source
4080
27.4k
  constexpr bool has_value() const noexcept { return this->m_has_val; }
tl::expected<ada::url_search_params_iter<std::__1::basic_string_view<char, std::__1::char_traits<char> >, (ada::url_search_params_iter_type)0>, ada::errors>::has_value() const
Line
Count
Source
4080
60.6k
  constexpr bool has_value() const noexcept { return this->m_has_val; }
tl::expected<ada::url_search_params_iter<std::__1::basic_string_view<char, std::__1::char_traits<char> >, (ada::url_search_params_iter_type)1>, ada::errors>::has_value() const
Line
Count
Source
4080
60.6k
  constexpr bool has_value() const noexcept { return this->m_has_val; }
tl::expected<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>, ada::errors>::has_value() const
Line
Count
Source
4080
60.6k
  constexpr bool has_value() const noexcept { return this->m_has_val; }
tl::expected<std::__1::vector<ada::url_pattern_helpers::token, std::__1::allocator<ada::url_pattern_helpers::token> >, ada::errors>::has_value() const
Line
Count
Source
4080
3.07M
  constexpr bool has_value() const noexcept { return this->m_has_val; }
tl::expected<ada::url_pattern_init, ada::errors>::has_value() const
Line
Count
Source
4080
10.1M
  constexpr bool has_value() const noexcept { return this->m_has_val; }
tl::expected<ada::url_pattern_component<ada::url_pattern_regex::std_regex_provider>, ada::errors>::has_value() const
Line
Count
Source
4080
2.61M
  constexpr bool has_value() const noexcept { return this->m_has_val; }
tl::expected<ada::url_pattern<ada::url_pattern_regex::std_regex_provider>, ada::errors>::has_value() const
Line
Count
Source
4080
439k
  constexpr bool has_value() const noexcept { return this->m_has_val; }
tl::expected<ada::url_pattern_list<ada::url_pattern_regex::std_regex_provider>, ada::errors>::has_value() const
Line
Count
Source
4080
296k
  constexpr bool has_value() const noexcept { return this->m_has_val; }
tl::expected<ada::url_pattern_list_detail::compiled_routes, ada::errors>::has_value() const
Line
Count
Source
4080
9.39k
  constexpr bool has_value() const noexcept { return this->m_has_val; }
tl::expected<std::__1::optional<ada::url_pattern_result>, ada::errors>::has_value() const
Line
Count
Source
4080
812k
  constexpr bool has_value() const noexcept { return this->m_has_val; }
tl::expected<bool, ada::errors>::has_value() const
Line
Count
Source
4080
383k
  constexpr bool has_value() const noexcept { return this->m_has_val; }
4081
22.5M
  constexpr explicit operator bool() const noexcept { return this->m_has_val; }
tl::expected<ada::url, ada::errors>::operator bool() const
Line
Count
Source
4081
776k
  constexpr explicit operator bool() const noexcept { return this->m_has_val; }
tl::expected<ada::url_aggregator, ada::errors>::operator bool() const
Line
Count
Source
4081
4.44M
  constexpr explicit operator bool() const noexcept { return this->m_has_val; }
tl::expected<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, ada::errors>::operator bool() const
Line
Count
Source
4081
6.26M
  constexpr explicit operator bool() const noexcept { return this->m_has_val; }
tl::expected<std::__1::vector<ada::url_pattern_part, std::__1::allocator<ada::url_pattern_part> >, ada::errors>::operator bool() const
Line
Count
Source
4081
2.99M
  constexpr explicit operator bool() const noexcept { return this->m_has_val; }
tl::expected<ada::url_search_params, ada::errors>::operator bool() const
Line
Count
Source
4081
205k
  constexpr explicit operator bool() const noexcept { return this->m_has_val; }
tl::expected<std::__1::vector<ada::url_pattern_helpers::token, std::__1::allocator<ada::url_pattern_helpers::token> >, ada::errors>::operator bool() const
Line
Count
Source
4081
3.07M
  constexpr explicit operator bool() const noexcept { return this->m_has_val; }
tl::expected<ada::url_pattern_init, ada::errors>::operator bool() const
Line
Count
Source
4081
593k
  constexpr explicit operator bool() const noexcept { return this->m_has_val; }
tl::expected<ada::url_pattern_component<ada::url_pattern_regex::std_regex_provider>, ada::errors>::operator bool() const
Line
Count
Source
4081
2.59M
  constexpr explicit operator bool() const noexcept { return this->m_has_val; }
tl::expected<ada::url_pattern<ada::url_pattern_regex::std_regex_provider>, ada::errors>::operator bool() const
Line
Count
Source
4081
421k
  constexpr explicit operator bool() const noexcept { return this->m_has_val; }
tl::expected<ada::url_pattern_list<ada::url_pattern_regex::std_regex_provider>, ada::errors>::operator bool() const
Line
Count
Source
4081
18.7k
  constexpr explicit operator bool() const noexcept { return this->m_has_val; }
tl::expected<ada::url_pattern_list_detail::compiled_routes, ada::errors>::operator bool() const
Line
Count
Source
4081
9.39k
  constexpr explicit operator bool() const noexcept { return this->m_has_val; }
tl::expected<std::__1::optional<ada::url_pattern_result>, ada::errors>::operator bool() const
Line
Count
Source
4081
767k
  constexpr explicit operator bool() const noexcept { return this->m_has_val; }
tl::expected<bool, ada::errors>::operator bool() const
Line
Count
Source
4081
383k
  constexpr explicit operator bool() const noexcept { return this->m_has_val; }
4082
4083
  template <class U = T,
4084
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
4085
  TL_EXPECTED_11_CONSTEXPR const U& value() const& {
4086
    if (!has_value())
4087
      detail::throw_exception(bad_expected_access<E>(err().value()));
4088
    return val();
4089
  }
4090
  template <class U = T,
4091
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
4092
4.49k
  TL_EXPECTED_11_CONSTEXPR U& value() & {
4093
4.49k
    if (!has_value())
4094
0
      detail::throw_exception(bad_expected_access<E>(err().value()));
4095
4.49k
    return val();
4096
4.49k
  }
4097
  template <class U = T,
4098
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
4099
  TL_EXPECTED_11_CONSTEXPR const U&& value() const&& {
4100
    if (!has_value())
4101
      detail::throw_exception(bad_expected_access<E>(std::move(err()).value()));
4102
    return std::move(val());
4103
  }
4104
  template <class U = T,
4105
            detail::enable_if_t<!std::is_void<U>::value>* = nullptr>
4106
  TL_EXPECTED_11_CONSTEXPR U&& value() && {
4107
    if (!has_value())
4108
      detail::throw_exception(bad_expected_access<E>(std::move(err()).value()));
4109
    return std::move(val());
4110
  }
4111
4112
  constexpr const E& error() const& {
4113
    TL_ASSERT(!has_value());
4114
    return err().value();
4115
  }
4116
84.3k
  TL_EXPECTED_11_CONSTEXPR E& error() & {
4117
84.3k
    TL_ASSERT(!has_value());
4118
84.3k
    return err().value();
4119
84.3k
  }
tl::expected<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, ada::errors>::error() &
Line
Count
Source
4116
5.06k
  TL_EXPECTED_11_CONSTEXPR E& error() & {
4117
5.06k
    TL_ASSERT(!has_value());
4118
5.06k
    return err().value();
4119
5.06k
  }
tl::expected<std::__1::vector<ada::url_pattern_part, std::__1::allocator<ada::url_pattern_part> >, ada::errors>::error() &
Line
Count
Source
4116
7.93k
  TL_EXPECTED_11_CONSTEXPR E& error() & {
4117
7.93k
    TL_ASSERT(!has_value());
4118
7.93k
    return err().value();
4119
7.93k
  }
tl::expected<std::__1::vector<ada::url_pattern_helpers::token, std::__1::allocator<ada::url_pattern_helpers::token> >, ada::errors>::error() &
Line
Count
Source
4116
2.07k
  TL_EXPECTED_11_CONSTEXPR E& error() & {
4117
2.07k
    TL_ASSERT(!has_value());
4118
2.07k
    return err().value();
4119
2.07k
  }
tl::expected<ada::url_pattern_init, ada::errors>::error() &
Line
Count
Source
4116
58.3k
  TL_EXPECTED_11_CONSTEXPR E& error() & {
4117
58.3k
    TL_ASSERT(!has_value());
4118
58.3k
    return err().value();
4119
58.3k
  }
tl::expected<ada::url_pattern_component<ada::url_pattern_regex::std_regex_provider>, ada::errors>::error() &
Line
Count
Source
4116
10.2k
  TL_EXPECTED_11_CONSTEXPR E& error() & {
4117
10.2k
    TL_ASSERT(!has_value());
4118
10.2k
    return err().value();
4119
10.2k
  }
tl::expected<ada::url_pattern_list_detail::compiled_routes, ada::errors>::error() &
Line
Count
Source
4116
760
  TL_EXPECTED_11_CONSTEXPR E& error() & {
4117
760
    TL_ASSERT(!has_value());
4118
760
    return err().value();
4119
760
  }
4120
  constexpr const E&& error() const&& {
4121
    TL_ASSERT(!has_value());
4122
    return std::move(err().value());
4123
  }
4124
  TL_EXPECTED_11_CONSTEXPR E&& error() && {
4125
    TL_ASSERT(!has_value());
4126
    return std::move(err().value());
4127
  }
4128
4129
  template <class U>
4130
  constexpr T value_or(U&& v) const& {
4131
    static_assert(std::is_copy_constructible<T>::value &&
4132
                      std::is_convertible<U&&, T>::value,
4133
                  "T must be copy-constructible and convertible to from U&&");
4134
    return bool(*this) ? **this : static_cast<T>(std::forward<U>(v));
4135
  }
4136
  template <class U>
4137
  TL_EXPECTED_11_CONSTEXPR T value_or(U&& v) && {
4138
    static_assert(std::is_move_constructible<T>::value &&
4139
                      std::is_convertible<U&&, T>::value,
4140
                  "T must be move-constructible and convertible to from U&&");
4141
    return bool(*this) ? std::move(**this) : static_cast<T>(std::forward<U>(v));
4142
  }
4143
};
4144
4145
namespace detail {
4146
template <class Exp>
4147
using exp_t = typename detail::decay_t<Exp>::value_type;
4148
template <class Exp>
4149
using err_t = typename detail::decay_t<Exp>::error_type;
4150
template <class Exp, class Ret>
4151
using ret_t = expected<Ret, err_t<Exp>>;
4152
4153
#ifdef TL_EXPECTED_CXX14
4154
template <class Exp, class F,
4155
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr,
4156
          class Ret = decltype(detail::invoke(std::declval<F>(),
4157
                                              *std::declval<Exp>()))>
4158
constexpr auto and_then_impl(Exp&& exp, F&& f) {
4159
  static_assert(detail::is_expected<Ret>::value, "F must return an expected");
4160
4161
  return exp.has_value()
4162
             ? detail::invoke(std::forward<F>(f), *std::forward<Exp>(exp))
4163
             : Ret(unexpect, std::forward<Exp>(exp).error());
4164
}
4165
4166
template <class Exp, class F,
4167
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr,
4168
          class Ret = decltype(detail::invoke(std::declval<F>()))>
4169
constexpr auto and_then_impl(Exp&& exp, F&& f) {
4170
  static_assert(detail::is_expected<Ret>::value, "F must return an expected");
4171
4172
  return exp.has_value() ? detail::invoke(std::forward<F>(f))
4173
                         : Ret(unexpect, std::forward<Exp>(exp).error());
4174
}
4175
#else
4176
template <class>
4177
struct TC;
4178
template <class Exp, class F,
4179
          class Ret = decltype(detail::invoke(std::declval<F>(),
4180
                                              *std::declval<Exp>())),
4181
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr>
4182
auto and_then_impl(Exp&& exp, F&& f) -> Ret {
4183
  static_assert(detail::is_expected<Ret>::value, "F must return an expected");
4184
4185
  return exp.has_value()
4186
             ? detail::invoke(std::forward<F>(f), *std::forward<Exp>(exp))
4187
             : Ret(unexpect, std::forward<Exp>(exp).error());
4188
}
4189
4190
template <class Exp, class F,
4191
          class Ret = decltype(detail::invoke(std::declval<F>())),
4192
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr>
4193
constexpr auto and_then_impl(Exp&& exp, F&& f) -> Ret {
4194
  static_assert(detail::is_expected<Ret>::value, "F must return an expected");
4195
4196
  return exp.has_value() ? detail::invoke(std::forward<F>(f))
4197
                         : Ret(unexpect, std::forward<Exp>(exp).error());
4198
}
4199
#endif
4200
4201
#ifdef TL_EXPECTED_CXX14
4202
template <class Exp, class F,
4203
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr,
4204
          class Ret = decltype(detail::invoke(std::declval<F>(),
4205
                                              *std::declval<Exp>())),
4206
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4207
constexpr auto expected_map_impl(Exp&& exp, F&& f) {
4208
  using result = ret_t<Exp, detail::decay_t<Ret>>;
4209
  return exp.has_value() ? result(detail::invoke(std::forward<F>(f),
4210
                                                 *std::forward<Exp>(exp)))
4211
                         : result(unexpect, std::forward<Exp>(exp).error());
4212
}
4213
4214
template <class Exp, class F,
4215
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr,
4216
          class Ret = decltype(detail::invoke(std::declval<F>(),
4217
                                              *std::declval<Exp>())),
4218
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4219
auto expected_map_impl(Exp&& exp, F&& f) {
4220
  using result = expected<void, err_t<Exp>>;
4221
  if (exp.has_value()) {
4222
    detail::invoke(std::forward<F>(f), *std::forward<Exp>(exp));
4223
    return result();
4224
  }
4225
4226
  return result(unexpect, std::forward<Exp>(exp).error());
4227
}
4228
4229
template <class Exp, class F,
4230
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr,
4231
          class Ret = decltype(detail::invoke(std::declval<F>())),
4232
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4233
constexpr auto expected_map_impl(Exp&& exp, F&& f) {
4234
  using result = ret_t<Exp, detail::decay_t<Ret>>;
4235
  return exp.has_value() ? result(detail::invoke(std::forward<F>(f)))
4236
                         : result(unexpect, std::forward<Exp>(exp).error());
4237
}
4238
4239
template <class Exp, class F,
4240
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr,
4241
          class Ret = decltype(detail::invoke(std::declval<F>())),
4242
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4243
auto expected_map_impl(Exp&& exp, F&& f) {
4244
  using result = expected<void, err_t<Exp>>;
4245
  if (exp.has_value()) {
4246
    detail::invoke(std::forward<F>(f));
4247
    return result();
4248
  }
4249
4250
  return result(unexpect, std::forward<Exp>(exp).error());
4251
}
4252
#else
4253
template <class Exp, class F,
4254
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr,
4255
          class Ret = decltype(detail::invoke(std::declval<F>(),
4256
                                              *std::declval<Exp>())),
4257
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4258
4259
constexpr auto expected_map_impl(Exp&& exp, F&& f)
4260
    -> ret_t<Exp, detail::decay_t<Ret>> {
4261
  using result = ret_t<Exp, detail::decay_t<Ret>>;
4262
4263
  return exp.has_value() ? result(detail::invoke(std::forward<F>(f),
4264
                                                 *std::forward<Exp>(exp)))
4265
                         : result(unexpect, std::forward<Exp>(exp).error());
4266
}
4267
4268
template <class Exp, class F,
4269
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr,
4270
          class Ret = decltype(detail::invoke(std::declval<F>(),
4271
                                              *std::declval<Exp>())),
4272
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4273
4274
auto expected_map_impl(Exp&& exp, F&& f) -> expected<void, err_t<Exp>> {
4275
  if (exp.has_value()) {
4276
    detail::invoke(std::forward<F>(f), *std::forward<Exp>(exp));
4277
    return {};
4278
  }
4279
4280
  return unexpected<err_t<Exp>>(std::forward<Exp>(exp).error());
4281
}
4282
4283
template <class Exp, class F,
4284
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr,
4285
          class Ret = decltype(detail::invoke(std::declval<F>())),
4286
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4287
4288
constexpr auto expected_map_impl(Exp&& exp, F&& f)
4289
    -> ret_t<Exp, detail::decay_t<Ret>> {
4290
  using result = ret_t<Exp, detail::decay_t<Ret>>;
4291
4292
  return exp.has_value() ? result(detail::invoke(std::forward<F>(f)))
4293
                         : result(unexpect, std::forward<Exp>(exp).error());
4294
}
4295
4296
template <class Exp, class F,
4297
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr,
4298
          class Ret = decltype(detail::invoke(std::declval<F>())),
4299
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4300
4301
auto expected_map_impl(Exp&& exp, F&& f) -> expected<void, err_t<Exp>> {
4302
  if (exp.has_value()) {
4303
    detail::invoke(std::forward<F>(f));
4304
    return {};
4305
  }
4306
4307
  return unexpected<err_t<Exp>>(std::forward<Exp>(exp).error());
4308
}
4309
#endif
4310
4311
#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \
4312
    !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55)
4313
template <class Exp, class F,
4314
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr,
4315
          class Ret = decltype(detail::invoke(std::declval<F>(),
4316
                                              std::declval<Exp>().error())),
4317
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4318
constexpr auto map_error_impl(Exp&& exp, F&& f) {
4319
  using result = expected<exp_t<Exp>, detail::decay_t<Ret>>;
4320
  return exp.has_value()
4321
             ? result(*std::forward<Exp>(exp))
4322
             : result(unexpect, detail::invoke(std::forward<F>(f),
4323
                                               std::forward<Exp>(exp).error()));
4324
}
4325
template <class Exp, class F,
4326
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr,
4327
          class Ret = decltype(detail::invoke(std::declval<F>(),
4328
                                              std::declval<Exp>().error())),
4329
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4330
auto map_error_impl(Exp&& exp, F&& f) {
4331
  using result = expected<exp_t<Exp>, monostate>;
4332
  if (exp.has_value()) {
4333
    return result(*std::forward<Exp>(exp));
4334
  }
4335
4336
  detail::invoke(std::forward<F>(f), std::forward<Exp>(exp).error());
4337
  return result(unexpect, monostate{});
4338
}
4339
template <class Exp, class F,
4340
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr,
4341
          class Ret = decltype(detail::invoke(std::declval<F>(),
4342
                                              std::declval<Exp>().error())),
4343
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4344
constexpr auto map_error_impl(Exp&& exp, F&& f) {
4345
  using result = expected<exp_t<Exp>, detail::decay_t<Ret>>;
4346
  return exp.has_value()
4347
             ? result()
4348
             : result(unexpect, detail::invoke(std::forward<F>(f),
4349
                                               std::forward<Exp>(exp).error()));
4350
}
4351
template <class Exp, class F,
4352
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr,
4353
          class Ret = decltype(detail::invoke(std::declval<F>(),
4354
                                              std::declval<Exp>().error())),
4355
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4356
auto map_error_impl(Exp&& exp, F&& f) {
4357
  using result = expected<exp_t<Exp>, monostate>;
4358
  if (exp.has_value()) {
4359
    return result();
4360
  }
4361
4362
  detail::invoke(std::forward<F>(f), std::forward<Exp>(exp).error());
4363
  return result(unexpect, monostate{});
4364
}
4365
#else
4366
template <class Exp, class F,
4367
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr,
4368
          class Ret = decltype(detail::invoke(std::declval<F>(),
4369
                                              std::declval<Exp>().error())),
4370
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4371
constexpr auto map_error_impl(Exp&& exp, F&& f)
4372
    -> expected<exp_t<Exp>, detail::decay_t<Ret>> {
4373
  using result = expected<exp_t<Exp>, detail::decay_t<Ret>>;
4374
4375
  return exp.has_value()
4376
             ? result(*std::forward<Exp>(exp))
4377
             : result(unexpect, detail::invoke(std::forward<F>(f),
4378
                                               std::forward<Exp>(exp).error()));
4379
}
4380
4381
template <class Exp, class F,
4382
          detail::enable_if_t<!std::is_void<exp_t<Exp>>::value>* = nullptr,
4383
          class Ret = decltype(detail::invoke(std::declval<F>(),
4384
                                              std::declval<Exp>().error())),
4385
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4386
auto map_error_impl(Exp&& exp, F&& f) -> expected<exp_t<Exp>, monostate> {
4387
  using result = expected<exp_t<Exp>, monostate>;
4388
  if (exp.has_value()) {
4389
    return result(*std::forward<Exp>(exp));
4390
  }
4391
4392
  detail::invoke(std::forward<F>(f), std::forward<Exp>(exp).error());
4393
  return result(unexpect, monostate{});
4394
}
4395
4396
template <class Exp, class F,
4397
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr,
4398
          class Ret = decltype(detail::invoke(std::declval<F>(),
4399
                                              std::declval<Exp>().error())),
4400
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4401
constexpr auto map_error_impl(Exp&& exp, F&& f)
4402
    -> expected<exp_t<Exp>, detail::decay_t<Ret>> {
4403
  using result = expected<exp_t<Exp>, detail::decay_t<Ret>>;
4404
4405
  return exp.has_value()
4406
             ? result()
4407
             : result(unexpect, detail::invoke(std::forward<F>(f),
4408
                                               std::forward<Exp>(exp).error()));
4409
}
4410
4411
template <class Exp, class F,
4412
          detail::enable_if_t<std::is_void<exp_t<Exp>>::value>* = nullptr,
4413
          class Ret = decltype(detail::invoke(std::declval<F>(),
4414
                                              std::declval<Exp>().error())),
4415
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4416
auto map_error_impl(Exp&& exp, F&& f) -> expected<exp_t<Exp>, monostate> {
4417
  using result = expected<exp_t<Exp>, monostate>;
4418
  if (exp.has_value()) {
4419
    return result();
4420
  }
4421
4422
  detail::invoke(std::forward<F>(f), std::forward<Exp>(exp).error());
4423
  return result(unexpect, monostate{});
4424
}
4425
#endif
4426
4427
#ifdef TL_EXPECTED_CXX14
4428
template <class Exp, class F,
4429
          class Ret = decltype(detail::invoke(std::declval<F>(),
4430
                                              std::declval<Exp>().error())),
4431
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4432
constexpr auto or_else_impl(Exp&& exp, F&& f) {
4433
  static_assert(detail::is_expected<Ret>::value, "F must return an expected");
4434
  return exp.has_value() ? std::forward<Exp>(exp)
4435
                         : detail::invoke(std::forward<F>(f),
4436
                                          std::forward<Exp>(exp).error());
4437
}
4438
4439
template <class Exp, class F,
4440
          class Ret = decltype(detail::invoke(std::declval<F>(),
4441
                                              std::declval<Exp>().error())),
4442
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4443
detail::decay_t<Exp> or_else_impl(Exp&& exp, F&& f) {
4444
  return exp.has_value() ? std::forward<Exp>(exp)
4445
                         : (detail::invoke(std::forward<F>(f),
4446
                                           std::forward<Exp>(exp).error()),
4447
                            std::forward<Exp>(exp));
4448
}
4449
#else
4450
template <class Exp, class F,
4451
          class Ret = decltype(detail::invoke(std::declval<F>(),
4452
                                              std::declval<Exp>().error())),
4453
          detail::enable_if_t<!std::is_void<Ret>::value>* = nullptr>
4454
auto or_else_impl(Exp&& exp, F&& f) -> Ret {
4455
  static_assert(detail::is_expected<Ret>::value, "F must return an expected");
4456
  return exp.has_value() ? std::forward<Exp>(exp)
4457
                         : detail::invoke(std::forward<F>(f),
4458
                                          std::forward<Exp>(exp).error());
4459
}
4460
4461
template <class Exp, class F,
4462
          class Ret = decltype(detail::invoke(std::declval<F>(),
4463
                                              std::declval<Exp>().error())),
4464
          detail::enable_if_t<std::is_void<Ret>::value>* = nullptr>
4465
detail::decay_t<Exp> or_else_impl(Exp&& exp, F&& f) {
4466
  return exp.has_value() ? std::forward<Exp>(exp)
4467
                         : (detail::invoke(std::forward<F>(f),
4468
                                           std::forward<Exp>(exp).error()),
4469
                            std::forward<Exp>(exp));
4470
}
4471
#endif
4472
}  // namespace detail
4473
4474
template <class T, class E, class U, class F>
4475
constexpr bool operator==(const expected<T, E>& lhs,
4476
                          const expected<U, F>& rhs) {
4477
  return (lhs.has_value() != rhs.has_value())
4478
             ? false
4479
             : (!lhs.has_value() ? lhs.error() == rhs.error() : *lhs == *rhs);
4480
}
4481
template <class T, class E, class U, class F>
4482
constexpr bool operator!=(const expected<T, E>& lhs,
4483
                          const expected<U, F>& rhs) {
4484
  return (lhs.has_value() != rhs.has_value())
4485
             ? true
4486
             : (!lhs.has_value() ? lhs.error() != rhs.error() : *lhs != *rhs);
4487
}
4488
template <class E, class F>
4489
constexpr bool operator==(const expected<void, E>& lhs,
4490
                          const expected<void, F>& rhs) {
4491
  return (lhs.has_value() != rhs.has_value())
4492
             ? false
4493
             : (!lhs.has_value() ? lhs.error() == rhs.error() : true);
4494
}
4495
template <class E, class F>
4496
constexpr bool operator!=(const expected<void, E>& lhs,
4497
                          const expected<void, F>& rhs) {
4498
  return (lhs.has_value() != rhs.has_value())
4499
             ? true
4500
             : (!lhs.has_value() ? lhs.error() == rhs.error() : false);
4501
}
4502
4503
template <class T, class E, class U>
4504
constexpr bool operator==(const expected<T, E>& x, const U& v) {
4505
  return x.has_value() ? *x == v : false;
4506
}
4507
template <class T, class E, class U>
4508
constexpr bool operator==(const U& v, const expected<T, E>& x) {
4509
  return x.has_value() ? *x == v : false;
4510
}
4511
template <class T, class E, class U>
4512
constexpr bool operator!=(const expected<T, E>& x, const U& v) {
4513
  return x.has_value() ? *x != v : true;
4514
}
4515
template <class T, class E, class U>
4516
constexpr bool operator!=(const U& v, const expected<T, E>& x) {
4517
  return x.has_value() ? *x != v : true;
4518
}
4519
4520
template <class T, class E>
4521
constexpr bool operator==(const expected<T, E>& x, const unexpected<E>& e) {
4522
  return x.has_value() ? false : x.error() == e.value();
4523
}
4524
template <class T, class E>
4525
constexpr bool operator==(const unexpected<E>& e, const expected<T, E>& x) {
4526
  return x.has_value() ? false : x.error() == e.value();
4527
}
4528
template <class T, class E>
4529
constexpr bool operator!=(const expected<T, E>& x, const unexpected<E>& e) {
4530
  return x.has_value() ? true : x.error() != e.value();
4531
}
4532
template <class T, class E>
4533
constexpr bool operator!=(const unexpected<E>& e, const expected<T, E>& x) {
4534
  return x.has_value() ? true : x.error() != e.value();
4535
}
4536
4537
template <class T, class E,
4538
          detail::enable_if_t<(std::is_void<T>::value ||
4539
                               std::is_move_constructible<T>::value) &&
4540
                              detail::is_swappable<T>::value &&
4541
                              std::is_move_constructible<E>::value &&
4542
                              detail::is_swappable<E>::value>* = nullptr>
4543
void swap(expected<T, E>& lhs,
4544
          expected<T, E>& rhs) noexcept(noexcept(lhs.swap(rhs))) {
4545
  lhs.swap(rhs);
4546
}
4547
}  // namespace tl
4548
4549
#endif
4550
/* end file include/ada/expected.h */
4551
4552
/* begin file include/ada/url_pattern_regex.h */
4553
/**
4554
 * @file url_search_params.h
4555
 * @brief Declaration for the URL Search Params
4556
 */
4557
#ifndef ADA_URL_PATTERN_REGEX_H
4558
#define ADA_URL_PATTERN_REGEX_H
4559
4560
#include <string>
4561
#include <string_view>
4562
4563
#ifdef ADA_USE_UNSAFE_STD_REGEX_PROVIDER
4564
#include <regex>
4565
#endif  // ADA_USE_UNSAFE_STD_REGEX_PROVIDER
4566
4567
#if ADA_INCLUDE_URL_PATTERN
4568
namespace ada::url_pattern_regex {
4569
4570
template <typename T>
4571
concept regex_concept = requires(T t, std::string_view pattern,
4572
                                 bool ignore_case, std::string_view input) {
4573
  // Ensure the class has a type alias 'regex_type'
4574
  typename T::regex_type;
4575
4576
  // Function to create a regex instance
4577
  {
4578
    T::create_instance(pattern, ignore_case)
4579
  } -> std::same_as<std::optional<typename T::regex_type>>;
4580
4581
  // Function to perform regex search
4582
  {
4583
    T::regex_search(input, std::declval<typename T::regex_type&>())
4584
  } -> std::same_as<std::optional<std::vector<std::optional<std::string>>>>;
4585
4586
  // Function to match regex pattern
4587
  {
4588
    T::regex_match(input, std::declval<typename T::regex_type&>())
4589
  } -> std::same_as<bool>;
4590
4591
  // Copy constructor
4592
  { T(std::declval<const T&>()) } -> std::same_as<T>;
4593
4594
  // Move constructor
4595
  { T(std::declval<T&&>()) } -> std::same_as<T>;
4596
};
4597
4598
#ifdef ADA_USE_UNSAFE_STD_REGEX_PROVIDER
4599
class std_regex_provider final {
4600
 public:
4601
  std_regex_provider() = default;
4602
  using regex_type = std::regex;
4603
  static std::optional<regex_type> create_instance(std::string_view pattern,
4604
                                                   bool ignore_case);
4605
  static std::optional<std::vector<std::optional<std::string>>> regex_search(
4606
      std::string_view input, const regex_type& pattern);
4607
  static bool regex_match(std::string_view input, const regex_type& pattern);
4608
};
4609
#endif  // ADA_USE_UNSAFE_STD_REGEX_PROVIDER
4610
4611
}  // namespace ada::url_pattern_regex
4612
#endif  // ADA_INCLUDE_URL_PATTERN
4613
#endif  // ADA_URL_PATTERN_REGEX_H
4614
/* end file include/ada/url_pattern_regex.h */
4615
/* begin file include/ada/url_pattern_init.h */
4616
/**
4617
 * @file url_pattern_init.h
4618
 * @brief Declaration for the url_pattern_init implementation.
4619
 */
4620
#ifndef ADA_URL_PATTERN_INIT_H
4621
#define ADA_URL_PATTERN_INIT_H
4622
4623
/* begin file include/ada/errors.h */
4624
/**
4625
 * @file errors.h
4626
 * @brief Error type definitions for URL parsing.
4627
 *
4628
 * Defines the error codes that can be returned when URL parsing fails.
4629
 */
4630
#ifndef ADA_ERRORS_H
4631
#define ADA_ERRORS_H
4632
4633
#include <cstdint>
4634
namespace ada {
4635
/**
4636
 * @brief Error codes for URL parsing operations.
4637
 *
4638
 * Used with `tl::expected` to indicate why a URL parsing operation failed.
4639
 */
4640
enum class errors : uint8_t {
4641
  type_error /**< A type error occurred (e.g., invalid URL syntax). */
4642
};
4643
}  // namespace ada
4644
#endif  // ADA_ERRORS_H
4645
/* end file include/ada/errors.h */
4646
4647
#include <string_view>
4648
#include <string>
4649
#include <optional>
4650
#include <iostream>
4651
4652
#if ADA_TESTING
4653
#include <iostream>
4654
#endif  // ADA_TESTING
4655
4656
#if ADA_INCLUDE_URL_PATTERN
4657
namespace ada {
4658
4659
// Important: C++20 allows us to use concept rather than `using` or `typedef
4660
// and allows functions with second argument, which is optional (using either
4661
// std::nullopt or a parameter with default value)
4662
template <typename F>
4663
concept url_pattern_encoding_callback = requires(F f, std::string_view sv) {
4664
  { f(sv) } -> std::same_as<tl::expected<std::string, errors>>;
4665
};
4666
4667
// A structure providing matching patterns for individual components
4668
// of a URL. When a URLPattern is created, or when a URLPattern is
4669
// used to match or test against a URL, the input can be given as
4670
// either a string or a URLPatternInit struct. If a string is given,
4671
// it will be parsed to create a URLPatternInit. The URLPatternInit
4672
// API is defined as part of the URLPattern specification.
4673
// All provided strings must be valid UTF-8.
4674
struct url_pattern_init {
4675
  enum class process_type : uint8_t {
4676
    url,
4677
    pattern,
4678
  };
4679
4680
0
  friend std::ostream& operator<<(std::ostream& os, process_type type) {
4681
0
    switch (type) {
4682
0
      case process_type::url:
4683
0
        return os << "url";
4684
0
      case process_type::pattern:
4685
0
        return os << "pattern";
4686
0
      default:
4687
0
        return os << "unknown";
4688
0
    }
4689
0
  }
4690
4691
  // All strings must be valid UTF-8.
4692
  // @see https://urlpattern.spec.whatwg.org/#process-a-urlpatterninit
4693
  static tl::expected<url_pattern_init, errors> process(
4694
      const url_pattern_init& init, process_type type,
4695
      std::optional<std::string_view> protocol = std::nullopt,
4696
      std::optional<std::string_view> username = std::nullopt,
4697
      std::optional<std::string_view> password = std::nullopt,
4698
      std::optional<std::string_view> hostname = std::nullopt,
4699
      std::optional<std::string_view> port = std::nullopt,
4700
      std::optional<std::string_view> pathname = std::nullopt,
4701
      std::optional<std::string_view> search = std::nullopt,
4702
      std::optional<std::string_view> hash = std::nullopt);
4703
4704
  // @see https://urlpattern.spec.whatwg.org/#process-protocol-for-init
4705
  static tl::expected<std::string, errors> process_protocol(
4706
      std::string_view value, process_type type);
4707
4708
  // @see https://urlpattern.spec.whatwg.org/#process-username-for-init
4709
  static tl::expected<std::string, errors> process_username(
4710
      std::string_view value, process_type type);
4711
4712
  // @see https://urlpattern.spec.whatwg.org/#process-password-for-init
4713
  static tl::expected<std::string, errors> process_password(
4714
      std::string_view value, process_type type);
4715
4716
  // @see https://urlpattern.spec.whatwg.org/#process-hostname-for-init
4717
  static tl::expected<std::string, errors> process_hostname(
4718
      std::string_view value, process_type type);
4719
4720
  // @see https://urlpattern.spec.whatwg.org/#process-port-for-init
4721
  static tl::expected<std::string, errors> process_port(
4722
      std::string_view port, std::string_view protocol, process_type type);
4723
4724
  // @see https://urlpattern.spec.whatwg.org/#process-pathname-for-init
4725
  static tl::expected<std::string, errors> process_pathname(
4726
      std::string_view value, std::string_view protocol, process_type type);
4727
4728
  // @see https://urlpattern.spec.whatwg.org/#process-search-for-init
4729
  static tl::expected<std::string, errors> process_search(
4730
      std::string_view value, process_type type);
4731
4732
  // @see https://urlpattern.spec.whatwg.org/#process-hash-for-init
4733
  static tl::expected<std::string, errors> process_hash(std::string_view value,
4734
                                                        process_type type);
4735
4736
#if ADA_TESTING
4737
  friend void PrintTo(const url_pattern_init& init, std::ostream* os) {
4738
    *os << "protocol: '" << init.protocol.value_or("undefined") << "', ";
4739
    *os << "username: '" << init.username.value_or("undefined") << "', ";
4740
    *os << "password: '" << init.password.value_or("undefined") << "', ";
4741
    *os << "hostname: '" << init.hostname.value_or("undefined") << "', ";
4742
    *os << "port: '" << init.port.value_or("undefined") << "', ";
4743
    *os << "pathname: '" << init.pathname.value_or("undefined") << "', ";
4744
    *os << "search: '" << init.search.value_or("undefined") << "', ";
4745
    *os << "hash: '" << init.hash.value_or("undefined") << "', ";
4746
    *os << "base_url: '" << init.base_url.value_or("undefined") << "', ";
4747
  }
4748
#endif  // ADA_TESTING
4749
4750
  bool operator==(const url_pattern_init&) const;
4751
  // If present, must be valid UTF-8.
4752
  std::optional<std::string> protocol{};
4753
  // If present, must be valid UTF-8.
4754
  std::optional<std::string> username{};
4755
  // If present, must be valid UTF-8.
4756
  std::optional<std::string> password{};
4757
  // If present, must be valid UTF-8.
4758
  std::optional<std::string> hostname{};
4759
  // If present, must be valid UTF-8.
4760
  std::optional<std::string> port{};
4761
  // If present, must be valid UTF-8.
4762
  std::optional<std::string> pathname{};
4763
  // If present, must be valid UTF-8.
4764
  std::optional<std::string> search{};
4765
  // If present, must be valid UTF-8.
4766
  std::optional<std::string> hash{};
4767
  // If present, must be valid UTF-8.
4768
  std::optional<std::string> base_url{};
4769
};
4770
}  // namespace ada
4771
#endif  // ADA_INCLUDE_URL_PATTERN
4772
#endif  // ADA_URL_PATTERN_INIT_H
4773
/* end file include/ada/url_pattern_init.h */
4774
4775
/** @private Forward declarations */
4776
namespace ada {
4777
struct url_aggregator;
4778
struct url;
4779
#if ADA_INCLUDE_URL_PATTERN
4780
template <url_pattern_regex::regex_concept regex_provider>
4781
class url_pattern;
4782
struct url_pattern_options;
4783
#endif  // ADA_INCLUDE_URL_PATTERN
4784
enum class errors : uint8_t;
4785
}  // namespace ada
4786
4787
/**
4788
 * @namespace ada::parser
4789
 * @brief Internal URL parsing implementation.
4790
 *
4791
 * Contains the core URL parsing algorithm as specified by the WHATWG URL
4792
 * Standard. These functions are used internally by `ada::parse()`.
4793
 */
4794
namespace ada::parser {
4795
/**
4796
 * Parses a URL string into a URL object.
4797
 *
4798
 * @tparam result_type The type of URL object to create (url or url_aggregator).
4799
 *
4800
 * @param user_input The URL string to parse (must be valid UTF-8).
4801
 * @param base_url Optional base URL for resolving relative URLs.
4802
 *
4803
 * @return The parsed URL object. Check `is_valid` to determine if parsing
4804
 *         succeeded.
4805
 *
4806
 * @see https://url.spec.whatwg.org/#concept-basic-url-parser
4807
 */
4808
template <typename result_type = url_aggregator>
4809
result_type parse_url(std::string_view user_input,
4810
                      const result_type* base_url = nullptr);
4811
4812
extern template url_aggregator parse_url<url_aggregator>(
4813
    std::string_view user_input, const url_aggregator* base_url);
4814
extern template url parse_url<url>(std::string_view user_input,
4815
                                   const url* base_url);
4816
4817
template <typename result_type = url_aggregator, bool store_values = true>
4818
result_type parse_url_impl(std::string_view user_input,
4819
                           const result_type* base_url = nullptr);
4820
4821
extern template url_aggregator parse_url_impl<url_aggregator, true>(
4822
    std::string_view user_input, const url_aggregator* base_url);
4823
extern template url_aggregator parse_url_impl<url_aggregator, false>(
4824
    std::string_view user_input, const url_aggregator* base_url);
4825
extern template url parse_url_impl<url, true>(std::string_view user_input,
4826
                                              const url* base_url);
4827
4828
/** @private */
4829
template <class result_type>
4830
bool try_parse_simple_absolute(std::string_view input, result_type& out);
4831
4832
/** @private */
4833
template <class result_type>
4834
bool finish_simple_absolute_with_port(std::string_view input, result_type& out,
4835
                                      ada::scheme::type scheme_type,
4836
                                      uint32_t protocol_end, size_t host_start,
4837
                                      size_t host_end, size_t host_len,
4838
                                      bool has_upper);
4839
4840
/** @private */
4841
template <class result_type>
4842
bool try_parse_simple_relative(std::string_view input, const result_type& base,
4843
                               result_type& out);
4844
4845
#if ADA_INCLUDE_URL_PATTERN
4846
template <url_pattern_regex::regex_concept regex_provider>
4847
tl::expected<url_pattern<regex_provider>, errors> parse_url_pattern_impl(
4848
    std::variant<std::string_view, url_pattern_init>&& input,
4849
    const std::string_view* base_url, const url_pattern_options* options);
4850
#endif  // ADA_INCLUDE_URL_PATTERN
4851
4852
}  // namespace ada::parser
4853
4854
#endif  // ADA_PARSER_H
4855
/* end file include/ada/parser.h */
4856
/* begin file include/ada/parser-inl.h */
4857
/**
4858
 * @file parser-inl.h
4859
 */
4860
#ifndef ADA_PARSER_INL_H
4861
#define ADA_PARSER_INL_H
4862
4863
/* begin file include/ada/url_pattern.h */
4864
/**
4865
 * @file url_pattern.h
4866
 * @brief URLPattern API implementation.
4867
 *
4868
 * This header provides the URLPattern API as specified by the WHATWG URL
4869
 * Pattern Standard. URLPattern allows matching URLs against patterns with
4870
 * wildcards and named groups, similar to how regular expressions match strings.
4871
 *
4872
 * @see https://urlpattern.spec.whatwg.org/
4873
 * @see https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API
4874
 */
4875
#ifndef ADA_URL_PATTERN_H
4876
#define ADA_URL_PATTERN_H
4877
4878
/* begin file include/ada/implementation.h */
4879
/**
4880
 * @file implementation.h
4881
 * @brief User-facing functions for URL parsing and manipulation.
4882
 *
4883
 * This header provides the primary public API for parsing URLs in Ada.
4884
 * It includes the main `ada::parse()` function which is the recommended
4885
 * entry point for most users.
4886
 *
4887
 * @see https://url.spec.whatwg.org/#api
4888
 */
4889
#ifndef ADA_IMPLEMENTATION_H
4890
#define ADA_IMPLEMENTATION_H
4891
4892
#include <optional>
4893
#include <span>
4894
#include <string>
4895
#include <string_view>
4896
4897
/* begin file include/ada/url.h */
4898
/**
4899
 * @file url.h
4900
 * @brief Declaration for the `ada::url` class.
4901
 *
4902
 * This file contains the `ada::url` struct which represents a parsed URL
4903
 * using separate `std::string` instances for each component. This
4904
 * representation is more flexible but uses more memory than `url_aggregator`.
4905
 *
4906
 * @see url_aggregator.h for a more memory-efficient alternative
4907
 */
4908
#ifndef ADA_URL_H
4909
#define ADA_URL_H
4910
4911
#include <algorithm>
4912
#include <optional>
4913
#include <ostream>
4914
#include <string>
4915
#include <string_view>
4916
4917
/* begin file include/ada/url_components.h */
4918
/**
4919
 * @file url_components.h
4920
 * @brief URL component offset representation for url_aggregator.
4921
 *
4922
 * This file defines the `url_components` struct which stores byte offsets
4923
 * into a URL string buffer. It is used internally by `url_aggregator` to
4924
 * efficiently locate URL components without storing separate strings.
4925
 */
4926
#ifndef ADA_URL_COMPONENTS_H
4927
#define ADA_URL_COMPONENTS_H
4928
4929
namespace ada {
4930
4931
/**
4932
 * @brief Stores byte offsets for URL components within a buffer.
4933
 *
4934
 * The `url_components` struct uses 32-bit offsets to track the boundaries
4935
 * of each URL component within a single string buffer. This enables efficient
4936
 * component extraction without additional memory allocations.
4937
 *
4938
 * Component layout in a URL:
4939
 * ```
4940
 * https://user:pass@example.com:1234/foo/bar?baz#quux
4941
 *       |     |    |          | ^^^^|       |   |
4942
 *       |     |    |          | |   |       |   `----- hash_start
4943
 *       |     |    |          | |   |       `--------- search_start
4944
 *       |     |    |          | |   `----------------- pathname_start
4945
 *       |     |    |          | `--------------------- port
4946
 *       |     |    |          `----------------------- host_end
4947
 *       |     |    `---------------------------------- host_start
4948
 *       |     `--------------------------------------- username_end
4949
 *       `--------------------------------------------- protocol_end
4950
 * ```
4951
 *
4952
 * @note The 32-bit offsets limit URLs to 4GB in length.
4953
 * @note A value of `omitted` (UINT32_MAX) indicates the component is not
4954
 * present.
4955
 */
4956
struct url_components {
4957
  /** Sentinel value indicating a component is not present. */
4958
  constexpr static uint32_t omitted = uint32_t(-1);
4959
4960
3.50M
  url_components() = default;
4961
  url_components(const url_components& u) = default;
4962
  url_components(url_components&& u) noexcept = default;
4963
  url_components& operator=(url_components&& u) noexcept = default;
4964
  url_components& operator=(const url_components& u) = default;
4965
  ~url_components() = default;
4966
4967
  /** Offset of the end of the protocol/scheme (position of ':'). */
4968
  uint32_t protocol_end{0};
4969
4970
  /**
4971
   * Offset of the end of the username.
4972
   * Initialized to 0 (not `omitted`) to simplify username/password getters.
4973
   */
4974
  uint32_t username_end{0};
4975
4976
  /** Offset of the start of the host. */
4977
  uint32_t host_start{0};
4978
4979
  /** Offset of the end of the host. */
4980
  uint32_t host_end{0};
4981
4982
  /** Port number, or `omitted` if no port is specified. */
4983
  uint32_t port{omitted};
4984
4985
  /** Offset of the start of the pathname. */
4986
  uint32_t pathname_start{0};
4987
4988
  /** Offset of the '?' starting the query, or `omitted` if no query. */
4989
  uint32_t search_start{omitted};
4990
4991
  /** Offset of the '#' starting the fragment, or `omitted` if no fragment. */
4992
  uint32_t hash_start{omitted};
4993
4994
  /**
4995
   * Validates that offsets are in ascending order and consistent.
4996
   * Useful for debugging to detect internal corruption.
4997
   * @return `true` if offsets are consistent, `false` otherwise.
4998
   */
4999
  [[nodiscard]] constexpr bool check_offset_consistency() const noexcept;
5000
5001
  /**
5002
   * Returns a JSON string representation of the offsets for debugging.
5003
   * @return A JSON-formatted string with all offset values.
5004
   */
5005
  [[nodiscard]] std::string to_string() const;
5006
5007
};  // struct url_components
5008
}  // namespace ada
5009
#endif
5010
/* end file include/ada/url_components.h */
5011
5012
namespace ada {
5013
5014
struct url_aggregator;
5015
5016
// namespace parser {
5017
// template <typename result_type>
5018
// result_type parse_url(std::string_view user_input,
5019
//                       const result_type* base_url = nullptr);
5020
// template <typename result_type, bool store_values>
5021
// result_type parse_url_impl(std::string_view user_input,
5022
//                            const result_type* base_url = nullptr);
5023
// }
5024
5025
/**
5026
 * @brief Represents a parsed URL with individual string components.
5027
 *
5028
 * The `url` struct stores each URL component (scheme, username, password,
5029
 * host, port, path, query, fragment) as a separate `std::string`. This
5030
 * provides flexibility but incurs more memory allocations compared to
5031
 * `url_aggregator`.
5032
 *
5033
 * **When to use `ada::url`:**
5034
 * - When you need to frequently modify individual URL components
5035
 * - When you want independent ownership of component strings
5036
 *
5037
 * **When to use `ada::url_aggregator` instead:**
5038
 * - For read-mostly operations on parsed URLs
5039
 * - When memory efficiency is important
5040
 * - When you only need string_view access to components
5041
 *
5042
 * @note This type is returned when parsing with `ada::parse<ada::url>()`.
5043
 *       By default, `ada::parse()` returns `ada::url_aggregator`.
5044
 *
5045
 * @see url_aggregator For a more memory-efficient URL representation
5046
 * @see https://url.spec.whatwg.org/#url-representation
5047
 */
5048
struct url : url_base {
5049
767k
  url() = default;
5050
55.1k
  url(const url& u) = default;
5051
691k
  url(url&& u) noexcept = default;
5052
9.92k
  url& operator=(url&& u) noexcept = default;
5053
205k
  url& operator=(const url& u) = default;
5054
1.51M
  ~url() override = default;
5055
5056
  // Fields are ordered so that the most frequently accessed components
5057
  // tend to occupy earlier cache lines and remain close together in memory.
5058
  //
5059
  // Note: The exact object layout (including cache-line boundaries, byte
5060
  // offsets, and member sizes) is implementation- and platform-dependent.
5061
  // This ordering expresses an intent for better cache locality but does not
5062
  // guarantee any specific in-memory layout.
5063
5064
  /**
5065
   * @private
5066
   * A URL's host is null or a host. It is initially null.
5067
   */
5068
  std::optional<std::string> host{};
5069
5070
  /**
5071
   * @private
5072
   * A URL's path is either an ASCII string or a list of zero or more ASCII
5073
   * strings, usually identifying a location.
5074
   */
5075
  std::string path{};
5076
5077
  /**
5078
   * @private
5079
   * A URL's query is either null or an ASCII string. It is initially null.
5080
   */
5081
  std::optional<std::string> query{};
5082
5083
  /**
5084
   * @private
5085
   * A URL's fragment is either null or an ASCII string that can be used for
5086
   * further processing on the resource the URL's other components identify. It
5087
   * is initially null.
5088
   */
5089
  std::optional<std::string> hash{};
5090
5091
  /**
5092
   * @private
5093
   * A URL's port is either null or a 16-bit unsigned integer that identifies a
5094
   * networking port. It is initially null.
5095
   */
5096
  std::optional<uint16_t> port{};
5097
5098
  /**
5099
   * @private
5100
   * A URL's username is an ASCII string identifying a username. It is initially
5101
   * the empty string.
5102
   */
5103
  std::string username{};
5104
5105
  /**
5106
   * @private
5107
   * A URL's password is an ASCII string identifying a password. It is initially
5108
   * the empty string.
5109
   */
5110
  std::string password{};
5111
5112
  /**
5113
   * Checks if the URL has an empty hostname (host is set but empty string).
5114
   * @return `true` if host exists but is empty, `false` otherwise.
5115
   */
5116
  [[nodiscard]] inline bool has_empty_hostname() const noexcept;
5117
5118
  /**
5119
   * Checks if the URL has a non-default port explicitly specified.
5120
   * @return `true` if a port is present, `false` otherwise.
5121
   */
5122
  [[nodiscard]] inline bool has_port() const noexcept;
5123
5124
  /**
5125
   * Checks if the URL has a hostname (including empty hostnames).
5126
   * @return `true` if host is present, `false` otherwise.
5127
   */
5128
  [[nodiscard]] inline bool has_hostname() const noexcept;
5129
5130
  /**
5131
   * Validates whether the hostname is a valid domain according to RFC 1034.
5132
   * Checks that the domain and its labels have valid lengths (max 255 octets
5133
   * total, max 63 octets per label).
5134
   * @return `true` if the domain is valid, `false` otherwise.
5135
   */
5136
  [[nodiscard]] bool has_valid_domain() const noexcept override;
5137
5138
  /**
5139
   * Returns a JSON string representation of this URL for debugging.
5140
   * @return A JSON-formatted string with all URL components.
5141
   */
5142
  [[nodiscard]] std::string to_string() const override;
5143
5144
  /**
5145
   * Returns the full serialized URL (the href).
5146
   * @return The complete URL string (allocates a new string).
5147
   * @see https://url.spec.whatwg.org/#dom-url-href
5148
   */
5149
  [[nodiscard]] ada_really_inline std::string get_href() const;
5150
5151
  /**
5152
   * Returns the byte length of the serialized URL without allocating a string.
5153
   * @return Size of the href in bytes.
5154
   */
5155
  [[nodiscard]] size_t get_href_size() const noexcept;
5156
5157
  /**
5158
   * Returns the URL's origin as a string (scheme + host + port for special
5159
   * URLs).
5160
   * @return A newly allocated string containing the serialized origin.
5161
   * @see https://url.spec.whatwg.org/#concept-url-origin
5162
   */
5163
  [[nodiscard]] std::string get_origin() const override;
5164
5165
  /**
5166
   * Returns the URL's scheme followed by a colon (e.g., "https:").
5167
   * @return A newly allocated string with the protocol.
5168
   * @see https://url.spec.whatwg.org/#dom-url-protocol
5169
   */
5170
  [[nodiscard]] std::string get_protocol() const;
5171
5172
  /**
5173
   * Returns the URL's host and port (e.g., "example.com:8080").
5174
   * If no port is set, returns just the host. Returns empty string if no host.
5175
   * @return A newly allocated string with host:port.
5176
   * @see https://url.spec.whatwg.org/#dom-url-host
5177
   */
5178
  [[nodiscard]] std::string get_host() const;
5179
5180
  /**
5181
   * Returns the URL's hostname (without port).
5182
   * Returns empty string if no host is set.
5183
   * @return A newly allocated string with the hostname.
5184
   * @see https://url.spec.whatwg.org/#dom-url-hostname
5185
   */
5186
  [[nodiscard]] std::string get_hostname() const;
5187
5188
  /**
5189
   * Returns the URL's path component.
5190
   * @return A string_view pointing to the path.
5191
   * @see https://url.spec.whatwg.org/#dom-url-pathname
5192
   */
5193
  [[nodiscard]] constexpr std::string_view get_pathname() const noexcept;
5194
5195
  /**
5196
   * Returns the byte length of the pathname without creating a string.
5197
   * @return Size of the pathname in bytes.
5198
   * @see https://url.spec.whatwg.org/#dom-url-pathname
5199
   */
5200
  [[nodiscard]] ada_really_inline size_t get_pathname_length() const noexcept;
5201
5202
  /**
5203
   * Returns the URL's query string prefixed with '?' (e.g., "?foo=bar").
5204
   * Returns empty string if no query is set.
5205
   * @return A newly allocated string with the search/query.
5206
   * @see https://url.spec.whatwg.org/#dom-url-search
5207
   */
5208
  [[nodiscard]] std::string get_search() const;
5209
5210
  /**
5211
   * Returns the URL's username component.
5212
   * @return A constant reference to the username string.
5213
   * @see https://url.spec.whatwg.org/#dom-url-username
5214
   */
5215
  [[nodiscard]] const std::string& get_username() const noexcept;
5216
5217
  /**
5218
   * Sets the URL's username, percent-encoding special characters.
5219
   * @param input The new username value.
5220
   * @return `true` on success, `false` if the URL cannot have credentials.
5221
   * @see https://url.spec.whatwg.org/#dom-url-username
5222
   */
5223
  bool set_username(std::string_view input);
5224
5225
  /**
5226
   * Sets the URL's password, percent-encoding special characters.
5227
   * @param input The new password value.
5228
   * @return `true` on success, `false` if the URL cannot have credentials.
5229
   * @see https://url.spec.whatwg.org/#dom-url-password
5230
   */
5231
  bool set_password(std::string_view input);
5232
5233
  /**
5234
   * Sets the URL's port from a string (e.g., "8080").
5235
   * @param input The port string. Empty string removes the port.
5236
   * @return `true` on success, `false` if the URL cannot have a port.
5237
   * @see https://url.spec.whatwg.org/#dom-url-port
5238
   */
5239
  bool set_port(std::string_view input);
5240
5241
  /**
5242
   * Sets the URL's fragment/hash (the part after '#').
5243
   * @param input The new hash value (with or without leading '#').
5244
   * @see https://url.spec.whatwg.org/#dom-url-hash
5245
   */
5246
  void set_hash(std::string_view input);
5247
5248
  /**
5249
   * Sets the URL's query string (the part after '?').
5250
   * @param input The new query value (with or without leading '?').
5251
   * @see https://url.spec.whatwg.org/#dom-url-search
5252
   */
5253
  void set_search(std::string_view input);
5254
5255
  /**
5256
   * Sets the URL's pathname.
5257
   * @param input The new path value.
5258
   * @return `true` on success, `false` if the URL has an opaque path.
5259
   * @see https://url.spec.whatwg.org/#dom-url-pathname
5260
   */
5261
  bool set_pathname(std::string_view input);
5262
5263
  /**
5264
   * Sets the URL's host (hostname and optionally port).
5265
   * @param input The new host value (e.g., "example.com:8080").
5266
   * @return `true` on success, `false` if parsing fails.
5267
   * @see https://url.spec.whatwg.org/#dom-url-host
5268
   */
5269
  bool set_host(std::string_view input);
5270
5271
  /**
5272
   * Sets the URL's hostname (without port).
5273
   * @param input The new hostname value.
5274
   * @return `true` on success, `false` if parsing fails.
5275
   * @see https://url.spec.whatwg.org/#dom-url-hostname
5276
   */
5277
  bool set_hostname(std::string_view input);
5278
5279
  /**
5280
   * Sets the URL's protocol/scheme.
5281
   * @param input The new protocol (with or without trailing ':').
5282
   * @return `true` on success, `false` if the scheme is invalid.
5283
   * @see https://url.spec.whatwg.org/#dom-url-protocol
5284
   */
5285
  bool set_protocol(std::string_view input);
5286
5287
  /**
5288
   * Replaces the entire URL by parsing a new href string.
5289
   * @param input The new URL string to parse.
5290
   * @return `true` on success, `false` if parsing fails.
5291
   * @see https://url.spec.whatwg.org/#dom-url-href
5292
   */
5293
  bool set_href(std::string_view input);
5294
5295
  /**
5296
   * Returns the URL's password component.
5297
   * @return A constant reference to the password string.
5298
   * @see https://url.spec.whatwg.org/#dom-url-password
5299
   */
5300
  [[nodiscard]] const std::string& get_password() const noexcept;
5301
5302
  /**
5303
   * Returns the URL's port as a string (e.g., "8080").
5304
   * Returns empty string if no port is set.
5305
   * @return A newly allocated string with the port.
5306
   * @see https://url.spec.whatwg.org/#dom-url-port
5307
   */
5308
  [[nodiscard]] std::string get_port() const;
5309
5310
  /**
5311
   * Returns the URL's fragment prefixed with '#' (e.g., "#section").
5312
   * Returns empty string if no fragment is set.
5313
   * @return A newly allocated string with the hash.
5314
   * @see https://url.spec.whatwg.org/#dom-url-hash
5315
   */
5316
  [[nodiscard]] std::string get_hash() const;
5317
5318
  /**
5319
   * Checks if the URL has credentials (non-empty username or password).
5320
   * @return `true` if username or password is non-empty, `false` otherwise.
5321
   */
5322
  [[nodiscard]] ada_really_inline bool has_credentials() const noexcept;
5323
5324
  /**
5325
   * Returns the URL component offsets for efficient serialization.
5326
   *
5327
   * The components represent byte offsets into the serialized URL:
5328
   * ```
5329
   * https://user:pass@example.com:1234/foo/bar?baz#quux
5330
   *       |     |    |          | ^^^^|       |   |
5331
   *       |     |    |          | |   |       |   `----- hash_start
5332
   *       |     |    |          | |   |       `--------- search_start
5333
   *       |     |    |          | |   `----------------- pathname_start
5334
   *       |     |    |          | `--------------------- port
5335
   *       |     |    |          `----------------------- host_end
5336
   *       |     |    `---------------------------------- host_start
5337
   *       |     `--------------------------------------- username_end
5338
   *       `--------------------------------------------- protocol_end
5339
   * ```
5340
   * @return A newly constructed url_components struct.
5341
   * @see https://github.com/servo/rust-url
5342
   */
5343
  [[nodiscard]] ada_really_inline ada::url_components get_components() const;
5344
5345
  /**
5346
   * Checks if the URL has a fragment/hash component.
5347
   * @return `true` if hash is present, `false` otherwise.
5348
   */
5349
  [[nodiscard]] constexpr bool has_hash() const noexcept override;
5350
5351
  /**
5352
   * Checks if the URL has a query/search component.
5353
   * @return `true` if query is present, `false` otherwise.
5354
   */
5355
  [[nodiscard]] constexpr bool has_search() const noexcept override;
5356
5357
 private:
5358
  friend ada::url ada::parser::parse_url<ada::url>(std::string_view,
5359
                                                   const ada::url*);
5360
  friend ada::url_aggregator ada::parser::parse_url<ada::url_aggregator>(
5361
      std::string_view, const ada::url_aggregator*);
5362
  friend void ada::helpers::strip_trailing_spaces_from_opaque_path<ada::url>(
5363
      ada::url& url);
5364
5365
  friend ada::url ada::parser::parse_url_impl<ada::url, true>(std::string_view,
5366
                                                              const ada::url*);
5367
  friend ada::url_aggregator ada::parser::parse_url_impl<
5368
      ada::url_aggregator, true>(std::string_view, const ada::url_aggregator*);
5369
  friend ada::url_aggregator ada::parser::parse_url_impl<
5370
      ada::url_aggregator, false>(std::string_view, const ada::url_aggregator*);
5371
  template <class result_type>
5372
  friend bool ada::parser::try_parse_simple_absolute(std::string_view,
5373
                                                     result_type&);
5374
  template <class result_type>
5375
  friend bool ada::parser::finish_simple_absolute_with_port(
5376
      std::string_view, result_type&, ada::scheme::type, uint32_t, size_t,
5377
      size_t, size_t, bool);
5378
  template <class result_type>
5379
  friend bool ada::parser::try_parse_simple_relative(std::string_view,
5380
                                                     const result_type&,
5381
                                                     result_type&);
5382
5383
  inline void update_unencoded_base_hash(std::string_view input);
5384
  inline void update_base_hostname(std::string_view input);
5385
  inline void update_base_search(std::string_view input,
5386
                                 const uint8_t query_percent_encode_set[]);
5387
  inline void update_base_search(std::optional<std::string>&& input);
5388
  inline void update_base_pathname(std::string_view input);
5389
  inline void update_base_username(std::string_view input);
5390
  inline void update_base_password(std::string_view input);
5391
  inline void update_base_port(std::optional<uint16_t> input);
5392
5393
  /**
5394
   * Returns true if growing href by input_len (worst case) could exceed
5395
   * get_max_input_length(), meaning a rollback snapshot is actually needed.
5396
   */
5397
  [[nodiscard]] bool needs_rollback_snapshot(size_t input_len) const noexcept;
5398
5399
  /**
5400
   * Sets the host or hostname according to override condition.
5401
   * Return true on success.
5402
   * @see https://url.spec.whatwg.org/#hostname-state
5403
   */
5404
  template <bool override_hostname = false>
5405
  bool set_host_or_hostname(std::string_view input);
5406
5407
  /**
5408
   * Return true on success.
5409
   * @see https://url.spec.whatwg.org/#concept-ipv4-parser
5410
   */
5411
  [[nodiscard]] bool parse_ipv4(std::string_view input);
5412
5413
  /**
5414
   * Return true on success.
5415
   * @see https://url.spec.whatwg.org/#concept-ipv6-parser
5416
   */
5417
  [[nodiscard]] bool parse_ipv6(std::string_view input);
5418
5419
  /**
5420
   * Return true on success.
5421
   * @see https://url.spec.whatwg.org/#concept-opaque-host-parser
5422
   */
5423
  [[nodiscard]] bool parse_opaque_host(std::string_view input);
5424
5425
  /**
5426
   * A URL's scheme is an ASCII string that identifies the type of URL and can
5427
   * be used to dispatch a URL for further processing after parsing. It is
5428
   * initially the empty string. We only set non_special_scheme when the scheme
5429
   * is non-special, otherwise we avoid constructing string.
5430
   *
5431
   * Special schemes are stored in ada::scheme::details::is_special_list so we
5432
   * typically do not need to store them in each url instance.
5433
   */
5434
  std::string non_special_scheme{};
5435
5436
  /**
5437
   * A URL cannot have a username/password/port if its host is null or the empty
5438
   * string, or its scheme is "file".
5439
   */
5440
  [[nodiscard]] inline bool cannot_have_credentials_or_port() const;
5441
5442
  ada_really_inline size_t parse_port(
5443
      std::string_view view, bool check_trailing_content) noexcept override;
5444
5445
2.79k
  ada_really_inline size_t parse_port(std::string_view view) noexcept override {
5446
2.79k
    return this->parse_port(view, false);
5447
2.79k
  }
5448
5449
  /**
5450
   * Parse the host from the provided input. We assume that
5451
   * the input does not contain spaces or tabs. Control
5452
   * characters and spaces are not trimmed (they should have
5453
   * been removed if needed).
5454
   * Return true on success.
5455
   * @see https://url.spec.whatwg.org/#host-parsing
5456
   */
5457
  [[nodiscard]] ada_really_inline bool parse_host(std::string_view input);
5458
5459
  template <bool has_state_override = false>
5460
  [[nodiscard]] ada_really_inline bool parse_scheme(std::string_view input);
5461
5462
  constexpr void clear_pathname() override;
5463
  constexpr void clear_search() override;
5464
  constexpr void set_protocol_as_file();
5465
5466
  /**
5467
   * Parse the path from the provided input.
5468
   * Return true on success. Control characters not
5469
   * trimmed from the ends (they should have
5470
   * been removed if needed).
5471
   *
5472
   * The input is expected to be UTF-8.
5473
   *
5474
   * @see https://url.spec.whatwg.org/
5475
   */
5476
  ada_really_inline void parse_path(std::string_view input);
5477
5478
  /**
5479
   * Set the scheme for this URL. The provided scheme should be a valid
5480
   * scheme string, be lower-cased, not contain spaces or tabs. It should
5481
   * have no spurious trailing or leading content.
5482
   */
5483
  inline void set_scheme(std::string&& new_scheme) noexcept;
5484
5485
  /**
5486
   * Take the scheme from another URL. The scheme string is moved from the
5487
   * provided url.
5488
   */
5489
  constexpr void copy_scheme(ada::url&& u);
5490
5491
  /**
5492
   * Take the scheme from another URL. The scheme string is copied from the
5493
   * provided url.
5494
   */
5495
  constexpr void copy_scheme(const ada::url& u);
5496
5497
};  // struct url
5498
5499
inline std::ostream& operator<<(std::ostream& out, const ada::url& u);
5500
}  // namespace ada
5501
5502
#endif  // ADA_URL_H
5503
/* end file include/ada/url.h */
5504
5505
namespace ada {
5506
5507
/**
5508
 * Result type for URL parsing operations.
5509
 *
5510
 * Uses `tl::expected` to represent either a successfully parsed URL or an
5511
 * error. This allows for exception-free error handling.
5512
 *
5513
 * @tparam result_type The URL type to return (default: `ada::url_aggregator`)
5514
 *
5515
 * @example
5516
 * ```cpp
5517
 * ada::result<ada::url_aggregator> result = ada::parse("https://example.com");
5518
 * if (result) {
5519
 *     // Success: use result.value() or *result
5520
 * } else {
5521
 *     // Error: handle result.error()
5522
 * }
5523
 * ```
5524
 */
5525
template <class result_type = ada::url_aggregator>
5526
using result = tl::expected<result_type, ada::errors>;
5527
5528
/**
5529
 * Parses a URL string according to the WHATWG URL Standard.
5530
 *
5531
 * This is the main entry point for URL parsing in Ada. The function takes
5532
 * a string input and optionally a base URL for resolving relative URLs.
5533
 *
5534
 * @tparam result_type The URL type to return. Can be either `ada::url` or
5535
 *         `ada::url_aggregator` (default). The `url_aggregator` type is more
5536
 *         memory-efficient as it stores components as offsets into a single
5537
 *         buffer.
5538
 *
5539
 * @param input The URL string to parse. Must be valid ASCII or UTF-8 encoded.
5540
 *        Leading and trailing whitespace is automatically trimmed.
5541
 * @param base_url Optional pointer to a base URL for resolving relative URLs.
5542
 *        If nullptr (default), only absolute URLs can be parsed successfully.
5543
 *
5544
 * @return A `result<result_type>` containing either the parsed URL on success,
5545
 *         or an error code on failure. Use the boolean conversion or
5546
 *         `has_value()` to check for success.
5547
 *
5548
 * @note The parser is fully compliant with the WHATWG URL Standard.
5549
 *
5550
 * Parsing fails if the input or the resulting normalized URL exceeds
5551
 * `get_max_input_length()` bytes (default ~4 GB, configurable via
5552
 * `set_max_input_length()`). This accounts for percent-encoding expansion:
5553
 * a short input that normalizes into a long URL is still rejected.
5554
 *
5555
 * @example
5556
 * ```cpp
5557
 * // Parse an absolute URL
5558
 * auto url = ada::parse("https://user:pass@example.com:8080/path?query#hash");
5559
 * if (url) {
5560
 *     std::cout << url->get_hostname(); // "example.com"
5561
 *     std::cout << url->get_pathname(); // "/path"
5562
 * }
5563
 *
5564
 * // Parse a relative URL with a base
5565
 * auto base = ada::parse("https://example.com/dir/");
5566
 * if (base) {
5567
 *     auto relative = ada::parse("../other/page", &*base);
5568
 *     if (relative) {
5569
 *         std::cout << relative->get_href(); //
5570
 * "https://example.com/other/page"
5571
 *     }
5572
 * }
5573
 * ```
5574
 *
5575
 * @see https://url.spec.whatwg.org/#url-parsing
5576
 */
5577
template <class result_type = ada::url_aggregator>
5578
ada_warn_unused ada::result<result_type> parse(
5579
    std::string_view input, const result_type* base_url = nullptr);
5580
5581
extern template ada::result<url> parse<url>(std::string_view input,
5582
                                            const url* base_url);
5583
extern template ada::result<url_aggregator> parse<url_aggregator>(
5584
    std::string_view input, const url_aggregator* base_url);
5585
5586
/**
5587
 * Checks whether a URL string can be successfully parsed.
5588
 *
5589
 * Equivalent to `parse(input, base).has_value()` for every input, including
5590
 * when `set_max_input_length` rejects a normalized href that exceeds the limit.
5591
 *
5592
 * @param input The URL string to validate. Must be valid ASCII or UTF-8.
5593
 * @param base_input Optional base URL string for relative inputs.
5594
 * @return `true` if parsing would succeed, `false` otherwise.
5595
 * @see https://url.spec.whatwg.org/#dom-url-canparse
5596
 */
5597
bool can_parse(std::string_view input,
5598
               const std::string_view* base_input = nullptr);
5599
5600
#if ADA_INCLUDE_URL_PATTERN
5601
/**
5602
 * Parses a URL pattern according to the URLPattern specification.
5603
 *
5604
 * URL patterns provide a syntax for matching URLs against patterns, similar
5605
 * to how regular expressions match strings. This is useful for routing and
5606
 * URL-based dispatching.
5607
 *
5608
 * @tparam regex_provider The regex implementation to use for pattern matching.
5609
 *
5610
 * @param input Either a URL pattern string (valid UTF-8) or a URLPatternInit
5611
 *        struct specifying individual component patterns.
5612
 * @param base_url Optional pointer to a base URL string (valid UTF-8) for
5613
 *        resolving relative patterns.
5614
 * @param options Optional pointer to configuration options (e.g., ignore_case).
5615
 *
5616
 * @return A `tl::expected` containing either the parsed url_pattern on success,
5617
 *         or an error code on failure.
5618
 *
5619
 * @see https://urlpattern.spec.whatwg.org
5620
 */
5621
template <url_pattern_regex::regex_concept regex_provider>
5622
ada_warn_unused tl::expected<url_pattern<regex_provider>, errors>
5623
parse_url_pattern(std::variant<std::string_view, url_pattern_init>&& input,
5624
                  const std::string_view* base_url = nullptr,
5625
                  const url_pattern_options* options = nullptr);
5626
5627
template <url_pattern_regex::regex_concept regex_provider>
5628
class url_pattern_list;
5629
5630
/**
5631
 * Compiles a set of URLPattern pathname patterns into an ada::url_pattern_list
5632
 * (experimental): one structure that answers "which route matches this
5633
 * pathname, and what are its group values?" without a loop over the
5634
 * patterns and without executing regular expressions for routes written in
5635
 * the static / ":param" / "*" subset.
5636
 *
5637
 * @tparam regex_provider The regex implementation, as for parse_url_pattern;
5638
 *         it is used only for routes that need URLPattern regexp semantics.
5639
 *
5640
 * @param pathname_patterns URLPattern pathname patterns (valid UTF-8), for
5641
 *        example "/users/:id". The index of a pattern is the route index
5642
 *        reported by url_pattern_list::match; duplicates are allowed.
5643
 * @param base_url Optional pointer to a base URL string (valid UTF-8): each
5644
 *        pattern is then processed as the pathname of a URLPatternInit with
5645
 *        that base URL (relative patterns resolve against its path).
5646
 * @param options Optional pointer to configuration options (ignore_case),
5647
 *        applied to every route as parse_url_pattern applies them.
5648
 *
5649
 * @return A `tl::expected` containing either the compiled list on success,
5650
 *         or an error code when a pattern is not a valid URLPattern pathname
5651
 *         pattern (errors::type_error, as the URLPattern constructor).
5652
 *
5653
 * @see https://github.com/whatwg/urlpattern/issues/166
5654
 */
5655
template <url_pattern_regex::regex_concept regex_provider>
5656
ada_warn_unused tl::expected<url_pattern_list<regex_provider>, errors>
5657
parse_url_pattern_list(std::span<const std::string_view> pathname_patterns,
5658
                       const std::string_view* base_url = nullptr,
5659
                       const url_pattern_options* options = nullptr);
5660
5661
/**
5662
 * Compiles the pathname components of existing url_pattern objects into an
5663
 * ada::url_pattern_list (experimental). Only the pathname component of each
5664
 * pattern is used; routes that need the regex provider reuse the pattern's
5665
 * already compiled pathname component. All patterns must share the same
5666
 * ignore_case setting (errors::type_error otherwise); the pathname is
5667
 * compiled as for a special-scheme URL.
5668
 */
5669
template <url_pattern_regex::regex_concept regex_provider>
5670
ada_warn_unused tl::expected<url_pattern_list<regex_provider>, errors>
5671
parse_url_pattern_list(std::span<const url_pattern<regex_provider>> patterns);
5672
#endif  // ADA_INCLUDE_URL_PATTERN
5673
5674
/**
5675
 * Converts a file system path to a file:// URL.
5676
 *
5677
 * Creates a properly formatted file URL from a local file system path.
5678
 * Handles platform-specific path separators and percent-encoding.
5679
 *
5680
 * Respects `get_max_input_length()`: if the input path or the resulting
5681
 * `file://` href would exceed the limit, returns an empty string.
5682
 *
5683
 * @param path The file system path to convert. Must be valid ASCII or UTF-8.
5684
 *
5685
 * @return A file:// URL string representing the given path, or empty on
5686
 *         length-limit rejection.
5687
 */
5688
std::string href_from_file(std::string_view path);
5689
5690
/**
5691
 * Sets the maximum allowed length for URLs.
5692
 *
5693
 * Both the raw input and the resulting normalized URL (the href) are checked
5694
 * against this limit. Parsing or setter calls that would produce a URL
5695
 * exceeding this length are rejected. The same limit also applies to
5696
 * `href_from_file` and to query strings passed to `url_search_params`
5697
 * construction / `reset`. The value must fit in a uint32_t.
5698
 * The default is std::numeric_limits<uint32_t>::max() (approximately 4 GB).
5699
 *
5700
 * @param length The new maximum URL length in bytes.
5701
 */
5702
void set_max_input_length(uint32_t length);
5703
5704
/**
5705
 * Returns the current maximum allowed length for URLs.
5706
 *
5707
 * @return The current maximum URL length in bytes.
5708
 */
5709
uint32_t get_max_input_length();
5710
5711
}  // namespace ada
5712
5713
#endif  // ADA_IMPLEMENTATION_H
5714
/* end file include/ada/implementation.h */
5715
5716
#include <ostream>
5717
#include <string>
5718
#include <string_view>
5719
#include <unordered_map>
5720
#include <variant>
5721
#include <vector>
5722
5723
#if ADA_TESTING
5724
#include <iostream>
5725
#endif  // ADA_TESTING
5726
5727
#if ADA_INCLUDE_URL_PATTERN
5728
namespace ada {
5729
5730
enum class url_pattern_part_type : uint8_t {
5731
  // The part represents a simple fixed text string.
5732
  FIXED_TEXT,
5733
  // The part represents a matching group with a custom regular expression.
5734
  REGEXP,
5735
  // The part represents a matching group that matches code points up to the
5736
  // next separator code point. This is typically used for a named group like
5737
  // ":foo" that does not have a custom regular expression.
5738
  SEGMENT_WILDCARD,
5739
  // The part represents a matching group that greedily matches all code points.
5740
  // This is typically used for the "*" wildcard matching group.
5741
  FULL_WILDCARD,
5742
};
5743
5744
// Pattern type for fast-path matching optimization.
5745
// This allows skipping expensive regex evaluation for common simple patterns.
5746
enum class url_pattern_component_type : uint8_t {
5747
  // Pattern is "^$" - only matches empty string
5748
  EMPTY,
5749
  // Pattern is "^<literal>$" - exact string match (no regex needed)
5750
  EXACT_MATCH,
5751
  // Pattern is "^(.*)$" - matches anything (full wildcard)
5752
  FULL_WILDCARD,
5753
  // Pattern requires actual regex evaluation
5754
  REGEXP,
5755
};
5756
5757
enum class url_pattern_part_modifier : uint8_t {
5758
  // The part does not have a modifier.
5759
  none,
5760
  // The part has an optional modifier indicated by the U+003F (?) code point.
5761
  optional,
5762
  // The part has a "zero or more" modifier indicated by the U+002A (*) code
5763
  // point.
5764
  zero_or_more,
5765
  // The part has a "one or more" modifier indicated by the U+002B (+) code
5766
  // point.
5767
  one_or_more,
5768
};
5769
5770
// @see https://urlpattern.spec.whatwg.org/#part
5771
class url_pattern_part {
5772
 public:
5773
  url_pattern_part(url_pattern_part_type _type, std::string&& _value,
5774
                   url_pattern_part_modifier _modifier)
5775
910k
      : type(_type), value(std::move(_value)), modifier(_modifier) {}
5776
5777
  url_pattern_part(url_pattern_part_type _type, std::string&& _value,
5778
                   url_pattern_part_modifier _modifier, std::string&& _name,
5779
                   std::string&& _prefix, std::string&& _suffix)
5780
2.22M
      : type(_type),
5781
2.22M
        value(std::move(_value)),
5782
2.22M
        modifier(_modifier),
5783
2.22M
        name(std::move(_name)),
5784
2.22M
        prefix(std::move(_prefix)),
5785
2.22M
        suffix(std::move(_suffix)) {}
5786
  // A part has an associated type, a string, which must be set upon creation.
5787
  url_pattern_part_type type;
5788
  // A part has an associated value, a string, which must be set upon creation.
5789
  std::string value;
5790
  // A part has an associated modifier a string, which must be set upon
5791
  // creation.
5792
  url_pattern_part_modifier modifier;
5793
  // A part has an associated name, a string, initially the empty string.
5794
  std::string name{};
5795
  // A part has an associated prefix, a string, initially the empty string.
5796
  std::string prefix{};
5797
  // A part has an associated suffix, a string, initially the empty string.
5798
  std::string suffix{};
5799
5800
  inline bool is_regexp() const noexcept;
5801
};
5802
5803
// @see https://urlpattern.spec.whatwg.org/#options-header
5804
struct url_pattern_compile_component_options {
5805
  url_pattern_compile_component_options() = default;
5806
  explicit url_pattern_compile_component_options(
5807
      std::optional<char> new_delimiter = std::nullopt,
5808
      std::optional<char> new_prefix = std::nullopt) noexcept
5809
60
      : delimiter(new_delimiter), prefix(new_prefix) {}
5810
5811
  inline std::string_view get_delimiter() const ada_warn_unused;
5812
  inline std::string_view get_prefix() const ada_warn_unused;
5813
5814
  // @see https://urlpattern.spec.whatwg.org/#options-ignore-case
5815
  bool ignore_case = false;
5816
5817
  static url_pattern_compile_component_options DEFAULT;
5818
  static url_pattern_compile_component_options HOSTNAME;
5819
  static url_pattern_compile_component_options PATHNAME;
5820
5821
 private:
5822
  // @see https://urlpattern.spec.whatwg.org/#options-delimiter-code-point
5823
  std::optional<char> delimiter{};
5824
  // @see https://urlpattern.spec.whatwg.org/#options-prefix-code-point
5825
  std::optional<char> prefix{};
5826
};
5827
5828
// The default options is an options struct with delimiter code point set to
5829
// the empty string and prefix code point set to the empty string.
5830
inline url_pattern_compile_component_options
5831
    url_pattern_compile_component_options::DEFAULT(std::nullopt, std::nullopt);
5832
5833
// The hostname options is an options struct with delimiter code point set
5834
// "." and prefix code point set to the empty string.
5835
inline url_pattern_compile_component_options
5836
    url_pattern_compile_component_options::HOSTNAME('.', std::nullopt);
5837
5838
// The pathname options is an options struct with delimiter code point set
5839
// "/" and prefix code point set to "/".
5840
inline url_pattern_compile_component_options
5841
    url_pattern_compile_component_options::PATHNAME('/', '/');
5842
5843
// A struct providing the URLPattern matching results for a single
5844
// URL component. The URLPatternComponentResult is only ever used
5845
// as a member attribute of a URLPatternResult struct. The
5846
// URLPatternComponentResult API is defined as part of the URLPattern
5847
// specification.
5848
struct url_pattern_component_result {
5849
  std::string input;
5850
  std::unordered_map<std::string, std::optional<std::string>> groups;
5851
5852
  bool operator==(const url_pattern_component_result&) const;
5853
5854
#if ADA_TESTING
5855
  friend void PrintTo(const url_pattern_component_result& result,
5856
                      std::ostream* os) {
5857
    *os << "input: '" << result.input << "', group: ";
5858
    for (const auto& group : result.groups) {
5859
      *os << "(" << group.first << ", " << group.second.value_or("undefined")
5860
          << ") ";
5861
    }
5862
  }
5863
#endif  // ADA_TESTING
5864
};
5865
5866
template <url_pattern_regex::regex_concept regex_provider>
5867
class url_pattern_component {
5868
 public:
5869
4.03M
  url_pattern_component() = default;
5870
5871
  // This function explicitly takes a std::string because it is moved.
5872
  // To avoid unnecessary copy, move each value while calling the constructor.
5873
  url_pattern_component(std::string&& new_pattern,
5874
                        typename regex_provider::regex_type&& new_regexp,
5875
                        std::vector<std::string>&& new_group_name_list,
5876
                        bool new_has_regexp_groups,
5877
                        url_pattern_component_type new_type,
5878
                        std::string&& new_exact_match_value = {})
5879
2.58M
      : regexp(std::move(new_regexp)),
5880
2.58M
        pattern(std::move(new_pattern)),
5881
2.58M
        group_name_list(std::move(new_group_name_list)),
5882
2.58M
        exact_match_value(std::move(new_exact_match_value)),
5883
2.58M
        has_regexp_groups(new_has_regexp_groups),
5884
2.58M
        type(new_type) {}
5885
5886
  // @see https://urlpattern.spec.whatwg.org/#compile-a-component
5887
  template <url_pattern_encoding_callback F>
5888
  static tl::expected<url_pattern_component, errors> compile(
5889
      std::string_view input, F& encoding_callback,
5890
      url_pattern_compile_component_options& options);
5891
5892
  // @see https://urlpattern.spec.whatwg.org/#create-a-component-match-result
5893
  url_pattern_component_result create_component_match_result(
5894
      std::string&& input,
5895
      std::vector<std::optional<std::string>>&& exec_result);
5896
5897
  // Fast path test that returns true/false without constructing result groups.
5898
  // Uses cached pattern type to skip regex evaluation for simple patterns.
5899
  bool fast_test(std::string_view input) const noexcept;
5900
5901
  // Fast path match that returns capture groups without regex for simple
5902
  // patterns. Returns nullopt if pattern doesn't match, otherwise returns
5903
  // capture groups.
5904
  std::optional<std::vector<std::optional<std::string>>> fast_match(
5905
      std::string_view input) const;
5906
5907
#if ADA_TESTING
5908
  friend void PrintTo(const url_pattern_component& component,
5909
                      std::ostream* os) {
5910
    *os << "pattern: '" << component.pattern
5911
        << "', has_regexp_groups: " << component.has_regexp_groups
5912
        << "group_name_list: ";
5913
    for (const auto& name : component.group_name_list) {
5914
      *os << name << ", ";
5915
    }
5916
  }
5917
#endif  // ADA_TESTING
5918
5919
  typename regex_provider::regex_type regexp{};
5920
  std::string pattern{};
5921
  std::vector<std::string> group_name_list{};
5922
  // For EXACT_MATCH type: the literal string to compare against
5923
  std::string exact_match_value{};
5924
  bool has_regexp_groups = false;
5925
  // Cached pattern type for fast-path optimization
5926
  url_pattern_component_type type = url_pattern_component_type::REGEXP;
5927
};
5928
5929
// A URLPattern input can be either a string or a URLPatternInit object.
5930
// If it is a string, it must be a valid UTF-8 string.
5931
using url_pattern_input = std::variant<std::string_view, url_pattern_init>;
5932
5933
// A struct providing the URLPattern matching results for all
5934
// components of a URL. The URLPatternResult API is defined as
5935
// part of the URLPattern specification.
5936
struct url_pattern_result {
5937
  std::vector<url_pattern_input> inputs;
5938
  url_pattern_component_result protocol;
5939
  url_pattern_component_result username;
5940
  url_pattern_component_result password;
5941
  url_pattern_component_result hostname;
5942
  url_pattern_component_result port;
5943
  url_pattern_component_result pathname;
5944
  url_pattern_component_result search;
5945
  url_pattern_component_result hash;
5946
};
5947
5948
struct url_pattern_options {
5949
  bool ignore_case = false;
5950
5951
#if ADA_TESTING
5952
  friend void PrintTo(const url_pattern_options& options, std::ostream* os) {
5953
    *os << "ignore_case: '" << options.ignore_case;
5954
  }
5955
#endif  // ADA_TESTING
5956
};
5957
5958
/**
5959
 * @brief URL pattern matching class implementing the URLPattern API.
5960
 *
5961
 * URLPattern provides a way to match URLs against patterns with wildcards
5962
 * and named capture groups. It's useful for routing, URL-based dispatching,
5963
 * and URL validation.
5964
 *
5965
 * Pattern syntax supports:
5966
 * - Literal text matching
5967
 * - Named groups: `:name` (matches up to the next separator)
5968
 * - Wildcards: `*` (matches everything)
5969
 * - Custom regex: `(pattern)`
5970
 * - Optional segments: `:name?`
5971
 * - Repeated segments: `:name+`, `:name*`
5972
 *
5973
 * @tparam regex_provider The regex implementation to use for pattern matching.
5974
 *         Must satisfy the url_pattern_regex::regex_concept.
5975
 *
5976
 * @note All string inputs must be valid UTF-8.
5977
 *
5978
 * @see https://urlpattern.spec.whatwg.org/
5979
 */
5980
template <url_pattern_regex::regex_concept regex_provider>
5981
class url_pattern {
5982
 public:
5983
504k
  url_pattern() = default;
5984
5985
  /**
5986
   * If non-null, base_url must pointer at a valid UTF-8 string.
5987
   * @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-exec
5988
   */
5989
  result<std::optional<url_pattern_result>> exec(
5990
      const url_pattern_input& input,
5991
      const std::string_view* base_url = nullptr);
5992
5993
  /**
5994
   * If non-null, base_url must pointer at a valid UTF-8 string.
5995
   * @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-test
5996
   */
5997
  result<bool> test(const url_pattern_input& input,
5998
                    const std::string_view* base_url = nullptr);
5999
6000
  /**
6001
   * @see https://urlpattern.spec.whatwg.org/#url-pattern-match
6002
   * This function expects a valid UTF-8 string if input is a string.
6003
   */
6004
  result<std::optional<url_pattern_result>> match(
6005
      const url_pattern_input& input,
6006
      const std::string_view* base_url_string = nullptr);
6007
6008
  // @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-protocol
6009
  [[nodiscard]] std::string_view get_protocol() const ada_lifetime_bound;
6010
  // @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-username
6011
  [[nodiscard]] std::string_view get_username() const ada_lifetime_bound;
6012
  // @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-password
6013
  [[nodiscard]] std::string_view get_password() const ada_lifetime_bound;
6014
  // @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-hostname
6015
  [[nodiscard]] std::string_view get_hostname() const ada_lifetime_bound;
6016
  // @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-port
6017
  [[nodiscard]] std::string_view get_port() const ada_lifetime_bound;
6018
  // @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-pathname
6019
  [[nodiscard]] std::string_view get_pathname() const ada_lifetime_bound;
6020
  // @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-search
6021
  [[nodiscard]] std::string_view get_search() const ada_lifetime_bound;
6022
  // @see https://urlpattern.spec.whatwg.org/#dom-urlpattern-hash
6023
  [[nodiscard]] std::string_view get_hash() const ada_lifetime_bound;
6024
6025
  // If ignoreCase is true, the JavaScript regular expression created for each
6026
  // pattern must use the `vi` flag. Otherwise, they must use the `v` flag.
6027
  [[nodiscard]] bool ignore_case() const;
6028
6029
  // @see https://urlpattern.spec.whatwg.org/#url-pattern-has-regexp-groups
6030
  [[nodiscard]] bool has_regexp_groups() const;
6031
6032
  // Helper to test all components at once. Returns true if all match.
6033
  [[nodiscard]] bool test_components(
6034
      std::string_view protocol, std::string_view username,
6035
      std::string_view password, std::string_view hostname,
6036
      std::string_view port, std::string_view pathname, std::string_view search,
6037
      std::string_view hash) const;
6038
6039
#if ADA_TESTING
6040
  friend void PrintTo(const url_pattern& c, std::ostream* os) {
6041
    *os << "protocol_component: '" << c.get_protocol() << ", ";
6042
    *os << "username_component: '" << c.get_username() << ", ";
6043
    *os << "password_component: '" << c.get_password() << ", ";
6044
    *os << "hostname_component: '" << c.get_hostname() << ", ";
6045
    *os << "port_component: '" << c.get_port() << ", ";
6046
    *os << "pathname_component: '" << c.get_pathname() << ", ";
6047
    *os << "search_component: '" << c.get_search() << ", ";
6048
    *os << "hash_component: '" << c.get_hash();
6049
  }
6050
#endif  // ADA_TESTING
6051
6052
  template <url_pattern_regex::regex_concept P>
6053
  friend tl::expected<url_pattern<P>, errors> parser::parse_url_pattern_impl(
6054
      std::variant<std::string_view, url_pattern_init>&& input,
6055
      const std::string_view* base_url, const url_pattern_options* options);
6056
6057
  /**
6058
   * @private
6059
   * We can not make this private due to a LLVM bug.
6060
   * Ref: https://github.com/ada-url/ada/pull/859
6061
   */
6062
  url_pattern_component<regex_provider> protocol_component{};
6063
  /**
6064
   * @private
6065
   * We can not make this private due to a LLVM bug.
6066
   * Ref: https://github.com/ada-url/ada/pull/859
6067
   */
6068
  url_pattern_component<regex_provider> username_component{};
6069
  /**
6070
   * @private
6071
   * We can not make this private due to a LLVM bug.
6072
   * Ref: https://github.com/ada-url/ada/pull/859
6073
   */
6074
  url_pattern_component<regex_provider> password_component{};
6075
  /**
6076
   * @private
6077
   * We can not make this private due to a LLVM bug.
6078
   * Ref: https://github.com/ada-url/ada/pull/859
6079
   */
6080
  url_pattern_component<regex_provider> hostname_component{};
6081
  /**
6082
   * @private
6083
   * We can not make this private due to a LLVM bug.
6084
   * Ref: https://github.com/ada-url/ada/pull/859
6085
   */
6086
  url_pattern_component<regex_provider> port_component{};
6087
  /**
6088
   * @private
6089
   * We can not make this private due to a LLVM bug.
6090
   * Ref: https://github.com/ada-url/ada/pull/859
6091
   */
6092
  url_pattern_component<regex_provider> pathname_component{};
6093
  /**
6094
   * @private
6095
   * We can not make this private due to a LLVM bug.
6096
   * Ref: https://github.com/ada-url/ada/pull/859
6097
   */
6098
  url_pattern_component<regex_provider> search_component{};
6099
  /**
6100
   * @private
6101
   * We can not make this private due to a LLVM bug.
6102
   * Ref: https://github.com/ada-url/ada/pull/859
6103
   */
6104
  url_pattern_component<regex_provider> hash_component{};
6105
  /**
6106
   * @private
6107
   * We can not make this private due to a LLVM bug.
6108
   * Ref: https://github.com/ada-url/ada/pull/859
6109
   */
6110
  bool ignore_case_ = false;
6111
};
6112
}  // namespace ada
6113
#endif  // ADA_INCLUDE_URL_PATTERN
6114
#endif
6115
/* end file include/ada/url_pattern.h */
6116
/* begin file include/ada/url_pattern_helpers.h */
6117
/**
6118
 * @file url_pattern_helpers.h
6119
 * @brief Declaration for the URLPattern helpers.
6120
 */
6121
#ifndef ADA_URL_PATTERN_HELPERS_H
6122
#define ADA_URL_PATTERN_HELPERS_H
6123
6124
6125
#include <string>
6126
#include <tuple>
6127
#include <unordered_set>
6128
#include <vector>
6129
6130
#if ADA_INCLUDE_URL_PATTERN
6131
namespace ada {
6132
enum class errors : uint8_t;
6133
}
6134
6135
namespace ada::url_pattern_helpers {
6136
6137
// @see https://urlpattern.spec.whatwg.org/#token
6138
enum class token_type : uint8_t {
6139
  INVALID_CHAR,    // 0
6140
  OPEN,            // 1
6141
  CLOSE,           // 2
6142
  REGEXP,          // 3
6143
  NAME,            // 4
6144
  CHAR,            // 5
6145
  ESCAPED_CHAR,    // 6
6146
  OTHER_MODIFIER,  // 7
6147
  ASTERISK,        // 8
6148
  END,             // 9
6149
};
6150
6151
#ifdef ADA_TESTING
6152
std::string to_string(token_type type);
6153
#endif  // ADA_TESTING
6154
6155
// @see https://urlpattern.spec.whatwg.org/#tokenize-policy
6156
enum class token_policy {
6157
  strict,
6158
  lenient,
6159
};
6160
6161
// @see https://urlpattern.spec.whatwg.org/#tokens
6162
class token {
6163
 public:
6164
  token(token_type _type, size_t _index, std::string_view _value)
6165
12.0M
      : type(_type), index(_index), value(_value) {}
6166
6167
  // A token has an associated type, a string, initially "invalid-char".
6168
  token_type type = token_type::INVALID_CHAR;
6169
6170
  // A token has an associated index, a number, initially 0. It is the position
6171
  // of the first code point in the pattern string represented by the token.
6172
  size_t index = 0;
6173
6174
  // A token has an associated value, a string, initially the empty string. It
6175
  // contains the code points from the pattern string represented by the token.
6176
  std::string_view value{};
6177
};
6178
6179
// @see https://urlpattern.spec.whatwg.org/#pattern-parser
6180
template <url_pattern_encoding_callback F>
6181
class url_pattern_parser {
6182
 public:
6183
  url_pattern_parser(F& encoding_callback_,
6184
                     std::string_view segment_wildcard_regexp_)
6185
2.99M
      : encoding_callback(encoding_callback_),
6186
2.99M
        segment_wildcard_regexp(segment_wildcard_regexp_) {}
6187
6188
13.0M
  bool can_continue() const { return index < tokens.size(); }
6189
6190
  // @see https://urlpattern.spec.whatwg.org/#try-to-consume-a-token
6191
  token* try_consume_token(token_type type);
6192
  // @see https://urlpattern.spec.whatwg.org/#try-to-consume-a-modifier-token
6193
  token* try_consume_modifier_token();
6194
  // @see
6195
  // https://urlpattern.spec.whatwg.org/#try-to-consume-a-regexp-or-wildcard-token
6196
  token* try_consume_regexp_or_wildcard_token(const token* name_token);
6197
  // @see https://urlpattern.spec.whatwg.org/#consume-text
6198
  std::string consume_text();
6199
  // @see https://urlpattern.spec.whatwg.org/#consume-a-required-token
6200
  bool consume_required_token(token_type type);
6201
  // @see
6202
  // https://urlpattern.spec.whatwg.org/#maybe-add-a-part-from-the-pending-fixed-value
6203
  std::optional<errors> maybe_add_part_from_the_pending_fixed_value()
6204
      ada_warn_unused;
6205
  // @see https://urlpattern.spec.whatwg.org/#add-a-part
6206
  std::optional<errors> add_part(std::string_view prefix, token* name_token,
6207
                                 token* regexp_or_wildcard_token,
6208
                                 std::string_view suyffix,
6209
                                 token* modifier_token) ada_warn_unused;
6210
6211
  std::vector<token> tokens{};
6212
  F& encoding_callback;
6213
  std::string segment_wildcard_regexp;
6214
  std::vector<url_pattern_part> parts{};
6215
  std::string pending_fixed_value{};
6216
  size_t index = 0;
6217
  size_t next_numeric_name = 0;
6218
  // Names already taken by a part, for the "is a duplicate name" check in
6219
  // add_part. A linear scan of the part list there is O(n^2) over a pattern
6220
  // with n named parts (e.g. "/*" repeated); this set keeps it amortized O(1).
6221
  std::unordered_set<std::string> seen_names{};
6222
};
6223
6224
// @see https://urlpattern.spec.whatwg.org/#tokenizer
6225
class Tokenizer {
6226
 public:
6227
  explicit Tokenizer(std::string_view new_input, token_policy new_policy)
6228
3.07M
      : input(new_input), policy(new_policy) {}
6229
6230
  // @see https://urlpattern.spec.whatwg.org/#get-the-next-code-point
6231
  constexpr void get_next_code_point();
6232
6233
  // True when the most recent decoded unit was malformed UTF-8.
6234
10.3M
  bool had_invalid_code_point() const { return invalid_code_point; }
6235
6236
  // @see https://urlpattern.spec.whatwg.org/#seek-and-get-the-next-code-point
6237
  constexpr void seek_and_get_next_code_point(size_t index);
6238
6239
  // @see https://urlpattern.spec.whatwg.org/#add-a-token
6240
6241
  void add_token(token_type type, size_t next_position, size_t value_position,
6242
                 size_t value_length);
6243
6244
  // @see https://urlpattern.spec.whatwg.org/#add-a-token-with-default-length
6245
  void add_token_with_default_length(token_type type, size_t next_position,
6246
                                     size_t value_position);
6247
6248
  // @see
6249
  // https://urlpattern.spec.whatwg.org/#add-a-token-with-default-position-and-length
6250
  void add_token_with_defaults(token_type type);
6251
6252
  // @see https://urlpattern.spec.whatwg.org/#process-a-tokenizing-error
6253
  std::optional<errors> process_tokenizing_error(
6254
      size_t next_position, size_t value_position) ada_warn_unused;
6255
6256
  friend tl::expected<std::vector<token>, errors> tokenize(
6257
      std::string_view input, token_policy policy);
6258
6259
 private:
6260
  // has an associated input, a pattern string, initially the empty string.
6261
  std::string_view input;
6262
  // has an associated policy, a tokenize policy, initially "strict".
6263
  token_policy policy;
6264
  // has an associated token list, a token list, initially an empty list.
6265
  std::vector<token> token_list{};
6266
  // has an associated index, a number, initially 0.
6267
  size_t index = 0;
6268
  // has an associated next index, a number, initially 0.
6269
  size_t next_index = 0;
6270
  // has an associated code point, a Unicode code point, initially null.
6271
  char32_t code_point{};
6272
  // Tracks whether the last decoded code point was malformed UTF-8.
6273
  bool invalid_code_point = false;
6274
};
6275
6276
// @see https://urlpattern.spec.whatwg.org/#constructor-string-parser
6277
template <url_pattern_regex::regex_concept regex_provider>
6278
struct constructor_string_parser {
6279
  explicit constructor_string_parser(std::string_view new_input,
6280
                                     std::vector<token>&& new_token_list)
6281
88.9k
      : input(new_input), token_list(std::move(new_token_list)) {}
6282
  // @see https://urlpattern.spec.whatwg.org/#parse-a-constructor-string
6283
  static tl::expected<url_pattern_init, errors> parse(std::string_view input);
6284
6285
  // @see https://urlpattern.spec.whatwg.org/#constructor-string-parser-state
6286
  enum class State {
6287
    INIT,
6288
    PROTOCOL,
6289
    AUTHORITY,
6290
    USERNAME,
6291
    PASSWORD,
6292
    HOSTNAME,
6293
    PORT,
6294
    PATHNAME,
6295
    SEARCH,
6296
    HASH,
6297
    DONE,
6298
  };
6299
6300
  // @see
6301
  // https://urlpattern.spec.whatwg.org/#compute-protocol-matches-a-special-scheme-flag
6302
  std::optional<errors> compute_protocol_matches_special_scheme_flag();
6303
6304
 private:
6305
  // @see https://urlpattern.spec.whatwg.org/#rewind
6306
  constexpr void rewind();
6307
6308
  // @see https://urlpattern.spec.whatwg.org/#is-a-hash-prefix
6309
  constexpr bool is_hash_prefix();
6310
6311
  // @see https://urlpattern.spec.whatwg.org/#is-a-search-prefix
6312
  constexpr bool is_search_prefix();
6313
6314
  // @see https://urlpattern.spec.whatwg.org/#change-state
6315
  void change_state(State state, size_t skip);
6316
6317
  // @see https://urlpattern.spec.whatwg.org/#is-a-group-open
6318
  constexpr bool is_group_open() const;
6319
6320
  // @see https://urlpattern.spec.whatwg.org/#is-a-group-close
6321
  constexpr bool is_group_close() const;
6322
6323
  // @see https://urlpattern.spec.whatwg.org/#is-a-protocol-suffix
6324
  constexpr bool is_protocol_suffix() const;
6325
6326
  // @see https://urlpattern.spec.whatwg.org/#next-is-authority-slashes
6327
  constexpr bool next_is_authority_slashes() const;
6328
6329
  // @see https://urlpattern.spec.whatwg.org/#is-an-identity-terminator
6330
  constexpr bool is_an_identity_terminator() const;
6331
6332
  // @see https://urlpattern.spec.whatwg.org/#is-a-pathname-start
6333
  constexpr bool is_pathname_start() const;
6334
6335
  // @see https://urlpattern.spec.whatwg.org/#is-a-password-prefix
6336
  constexpr bool is_password_prefix() const;
6337
6338
  // @see https://urlpattern.spec.whatwg.org/#is-an-ipv6-open
6339
  constexpr bool is_an_ipv6_open() const;
6340
6341
  // @see https://urlpattern.spec.whatwg.org/#is-an-ipv6-close
6342
  constexpr bool is_an_ipv6_close() const;
6343
6344
  // @see https://urlpattern.spec.whatwg.org/#is-a-port-prefix
6345
  constexpr bool is_port_prefix() const;
6346
6347
  // @see https://urlpattern.spec.whatwg.org/#is-a-non-special-pattern-char
6348
  constexpr bool is_non_special_pattern_char(size_t index,
6349
                                             uint32_t value) const;
6350
6351
  // @see https://urlpattern.spec.whatwg.org/#get-a-safe-token
6352
  constexpr const token* get_safe_token(size_t index) const;
6353
6354
  // @see https://urlpattern.spec.whatwg.org/#make-a-component-string
6355
  std::string make_component_string();
6356
  // has an associated input, a string, which must be set upon creation.
6357
  std::string_view input;
6358
  // has an associated token list, a token list, which must be set upon
6359
  // creation.
6360
  std::vector<token> token_list;
6361
  // has an associated result, a URLPatternInit, initially set to a new
6362
  // URLPatternInit.
6363
  url_pattern_init result{};
6364
  // has an associated component start, a number, initially set to 0.
6365
  size_t component_start = 0;
6366
  // has an associated token index, a number, initially set to 0.
6367
  size_t token_index = 0;
6368
  // has an associated token increment, a number, initially set to 1.
6369
  size_t token_increment = 1;
6370
  // has an associated group depth, a number, initially set to 0.
6371
  size_t group_depth = 0;
6372
  // has an associated hostname IPv6 bracket depth, a number, initially set to
6373
  // 0.
6374
  size_t hostname_ipv6_bracket_depth = 0;
6375
  // has an associated protocol matches a special scheme flag, a boolean,
6376
  // initially set to false.
6377
  bool protocol_matches_a_special_scheme_flag = false;
6378
  // has an associated state, a string, initially set to "init".
6379
  State state = State::INIT;
6380
};
6381
6382
// @see https://urlpattern.spec.whatwg.org/#canonicalize-a-protocol
6383
tl::expected<std::string, errors> canonicalize_protocol(std::string_view input);
6384
6385
// @see https://wicg.github.io/urlpattern/#canonicalize-a-username
6386
tl::expected<std::string, errors> canonicalize_username(std::string_view input);
6387
6388
// @see https://wicg.github.io/urlpattern/#canonicalize-a-password
6389
tl::expected<std::string, errors> canonicalize_password(std::string_view input);
6390
6391
// @see https://wicg.github.io/urlpattern/#canonicalize-a-password
6392
tl::expected<std::string, errors> canonicalize_hostname(std::string_view input);
6393
6394
// @see https://wicg.github.io/urlpattern/#canonicalize-an-ipv6-hostname
6395
tl::expected<std::string, errors> canonicalize_ipv6_hostname(
6396
    std::string_view input);
6397
6398
// @see https://wicg.github.io/urlpattern/#canonicalize-a-port
6399
tl::expected<std::string, errors> canonicalize_port(std::string_view input);
6400
6401
// @see https://wicg.github.io/urlpattern/#canonicalize-a-port
6402
tl::expected<std::string, errors> canonicalize_port_with_protocol(
6403
    std::string_view input, std::string_view protocol);
6404
6405
// @see https://wicg.github.io/urlpattern/#canonicalize-a-pathname
6406
tl::expected<std::string, errors> canonicalize_pathname(std::string_view input);
6407
6408
// @see https://wicg.github.io/urlpattern/#canonicalize-an-opaque-pathname
6409
tl::expected<std::string, errors> canonicalize_opaque_pathname(
6410
    std::string_view input);
6411
6412
// @see https://wicg.github.io/urlpattern/#canonicalize-a-search
6413
tl::expected<std::string, errors> canonicalize_search(std::string_view input);
6414
6415
// @see https://wicg.github.io/urlpattern/#canonicalize-a-hash
6416
tl::expected<std::string, errors> canonicalize_hash(std::string_view input);
6417
6418
// @see https://urlpattern.spec.whatwg.org/#tokenize
6419
tl::expected<std::vector<token>, errors> tokenize(std::string_view input,
6420
                                                  token_policy policy);
6421
6422
// @see https://urlpattern.spec.whatwg.org/#process-a-base-url-string
6423
std::string process_base_url_string(std::string_view input,
6424
                                    url_pattern_init::process_type type);
6425
6426
// @see https://urlpattern.spec.whatwg.org/#escape-a-pattern-string
6427
std::string escape_pattern_string(std::string_view input);
6428
6429
// @see https://urlpattern.spec.whatwg.org/#escape-a-regexp-string
6430
std::string escape_regexp_string(std::string_view input);
6431
6432
// @see https://urlpattern.spec.whatwg.org/#is-an-absolute-pathname
6433
constexpr bool is_absolute_pathname(
6434
    std::string_view input, url_pattern_init::process_type type) noexcept;
6435
6436
// @see https://urlpattern.spec.whatwg.org/#parse-a-pattern-string
6437
template <url_pattern_encoding_callback F>
6438
tl::expected<std::vector<url_pattern_part>, errors> parse_pattern_string(
6439
    std::string_view input, url_pattern_compile_component_options& options,
6440
    F& encoding_callback);
6441
6442
// @see https://urlpattern.spec.whatwg.org/#generate-a-pattern-string
6443
std::string generate_pattern_string(
6444
    std::vector<url_pattern_part>& part_list,
6445
    url_pattern_compile_component_options& options);
6446
6447
// @see
6448
// https://urlpattern.spec.whatwg.org/#generate-a-regular-expression-and-name-list
6449
std::tuple<std::string, std::vector<std::string>>
6450
generate_regular_expression_and_name_list(
6451
    const std::vector<url_pattern_part>& part_list,
6452
    url_pattern_compile_component_options options);
6453
6454
// @see https://urlpattern.spec.whatwg.org/#hostname-pattern-is-an-ipv6-address
6455
bool is_ipv6_address(std::string_view input) noexcept;
6456
6457
// @see
6458
// https://urlpattern.spec.whatwg.org/#protocol-component-matches-a-special-scheme
6459
template <url_pattern_regex::regex_concept regex_provider>
6460
bool protocol_component_matches_special_scheme(
6461
    ada::url_pattern_component<regex_provider>& input);
6462
6463
// @see https://urlpattern.spec.whatwg.org/#convert-a-modifier-to-a-string
6464
std::string_view convert_modifier_to_string(url_pattern_part_modifier modifier);
6465
6466
// @see https://urlpattern.spec.whatwg.org/#generate-a-segment-wildcard-regexp
6467
std::string generate_segment_wildcard_regexp(
6468
    url_pattern_compile_component_options options);
6469
6470
}  // namespace ada::url_pattern_helpers
6471
#endif  // ADA_INCLUDE_URL_PATTERN
6472
#endif
6473
/* end file include/ada/url_pattern_helpers.h */
6474
6475
#include <string>
6476
#include <string_view>
6477
#include <variant>
6478
6479
namespace ada::parser {
6480
#if ADA_INCLUDE_URL_PATTERN
6481
template <url_pattern_regex::regex_concept regex_provider>
6482
tl::expected<url_pattern<regex_provider>, errors> parse_url_pattern_impl(
6483
    std::variant<std::string_view, url_pattern_init>&& input,
6484
421k
    const std::string_view* base_url, const url_pattern_options* options) {
6485
  // Let init be null.
6486
421k
  url_pattern_init init;
6487
6488
  // If input is a scalar value string then:
6489
421k
  if (std::holds_alternative<std::string_view>(input)) {
6490
    // Set init to the result of running parse a constructor string given input.
6491
88.9k
    auto parse_result =
6492
88.9k
        url_pattern_helpers::constructor_string_parser<regex_provider>::parse(
6493
88.9k
            std::get<std::string_view>(input));
6494
88.9k
    if (!parse_result) {
6495
1.40k
      ada_log("constructor_string_parser::parse failed");
6496
1.40k
      return tl::unexpected(parse_result.error());
6497
1.40k
    }
6498
87.5k
    init = std::move(*parse_result);
6499
    // If baseURL is null and init["protocol"] does not exist, then throw a
6500
    // TypeError.
6501
87.5k
    if (!base_url && !init.protocol) {
6502
14.3k
      ada_log("base url is null and protocol is not set");
6503
14.3k
      return tl::unexpected(errors::type_error);
6504
14.3k
    }
6505
6506
    // If baseURL is not null, set init["baseURL"] to baseURL.
6507
73.1k
    if (base_url) {
6508
58.3k
      init.base_url = std::string(*base_url);
6509
58.3k
    }
6510
333k
  } else {
6511
    // Assert: input is a URLPatternInit.
6512
333k
    ADA_ASSERT_TRUE(std::holds_alternative<url_pattern_init>(input));
6513
    // If baseURL is not null, then throw a TypeError.
6514
333k
    if (base_url) {
6515
29.6k
      ada_log("base url is not null");
6516
29.6k
      return tl::unexpected(errors::type_error);
6517
29.6k
    }
6518
    // Optimization: Avoid copy by moving the input value.
6519
    // Set init to input.
6520
303k
    init = std::move(std::get<url_pattern_init>(input));
6521
303k
  }
6522
6523
  // Let processedInit be the result of process a URLPatternInit given init,
6524
  // "pattern", null, null, null, null, null, null, null, and null.
6525
376k
  auto processed_init =
6526
376k
      url_pattern_init::process(init, url_pattern_init::process_type::pattern);
6527
376k
  if (!processed_init) {
6528
56.8k
    ada_log("url_pattern_init::process failed for init and 'pattern'");
6529
56.8k
    return tl::unexpected(processed_init.error());
6530
56.8k
  }
6531
6532
  // For each componentName of  "protocol", "username", "password", "hostname",
6533
  // "port", "pathname", "search", "hash" If processedInit[componentName] does
6534
  // not exist, then set processedInit[componentName] to "*".
6535
319k
  ADA_ASSERT_TRUE(processed_init.has_value());
6536
319k
  if (!processed_init->protocol) processed_init->protocol = "*";
6537
319k
  if (!processed_init->username) processed_init->username = "*";
6538
319k
  if (!processed_init->password) processed_init->password = "*";
6539
319k
  if (!processed_init->hostname) processed_init->hostname = "*";
6540
319k
  if (!processed_init->port) processed_init->port = "*";
6541
319k
  if (!processed_init->pathname) processed_init->pathname = "*";
6542
319k
  if (!processed_init->search) processed_init->search = "*";
6543
319k
  if (!processed_init->hash) processed_init->hash = "*";
6544
6545
319k
  ada_log("-- processed_init->protocol: ", processed_init->protocol.value());
6546
319k
  ada_log("-- processed_init->username: ", processed_init->username.value());
6547
319k
  ada_log("-- processed_init->password: ", processed_init->password.value());
6548
319k
  ada_log("-- processed_init->hostname: ", processed_init->hostname.value());
6549
319k
  ada_log("-- processed_init->port: ", processed_init->port.value());
6550
319k
  ada_log("-- processed_init->pathname: ", processed_init->pathname.value());
6551
319k
  ada_log("-- processed_init->search: ", processed_init->search.value());
6552
319k
  ada_log("-- processed_init->hash: ", processed_init->hash.value());
6553
6554
  // If processedInit["protocol"] is a special scheme and processedInit["port"]
6555
  // is a string which represents its corresponding default port in radix-10
6556
  // using ASCII digits then set processedInit["port"] to the empty string.
6557
  // TODO: Optimization opportunity.
6558
319k
  if (scheme::is_special(*processed_init->protocol)) {
6559
    // file is the only special scheme with no default port; get_special_port
6560
    // returns 0 as its sentinel, so a literal "0" port must not be mistaken for
6561
    // a default and dropped.
6562
75.6k
    uint16_t default_port = scheme::get_special_port(*processed_init->protocol);
6563
75.6k
    if (default_port != 0 &&
6564
75.6k
        std::to_string(default_port) == processed_init->port.value()) {
6565
3
      processed_init->port->clear();
6566
3
    }
6567
75.6k
  }
6568
6569
  // Let urlPattern be a new URL pattern.
6570
319k
  url_pattern<regex_provider> url_pattern_{};
6571
6572
  // Set urlPattern's protocol component to the result of compiling a component
6573
  // given processedInit["protocol"], canonicalize a protocol, and default
6574
  // options.
6575
319k
  auto protocol_component = url_pattern_component<regex_provider>::compile(
6576
319k
      processed_init->protocol.value(),
6577
319k
      url_pattern_helpers::canonicalize_protocol,
6578
319k
      url_pattern_compile_component_options::DEFAULT);
6579
319k
  if (!protocol_component) {
6580
1.80k
    ada_log("url_pattern_component::compile failed for protocol ",
6581
1.80k
            processed_init->protocol.value());
6582
1.80k
    return tl::unexpected(protocol_component.error());
6583
1.80k
  }
6584
317k
  url_pattern_.protocol_component = std::move(*protocol_component);
6585
6586
  // Set urlPattern's username component to the result of compiling a component
6587
  // given processedInit["username"], canonicalize a username, and default
6588
  // options.
6589
317k
  auto username_component = url_pattern_component<regex_provider>::compile(
6590
317k
      processed_init->username.value(),
6591
317k
      url_pattern_helpers::canonicalize_username,
6592
317k
      url_pattern_compile_component_options::DEFAULT);
6593
317k
  if (!username_component) {
6594
392
    ada_log("url_pattern_component::compile failed for username ",
6595
392
            processed_init->username.value());
6596
392
    return tl::unexpected(username_component.error());
6597
392
  }
6598
317k
  url_pattern_.username_component = std::move(*username_component);
6599
6600
  // Set urlPattern's password component to the result of compiling a component
6601
  // given processedInit["password"], canonicalize a password, and default
6602
  // options.
6603
317k
  auto password_component = url_pattern_component<regex_provider>::compile(
6604
317k
      processed_init->password.value(),
6605
317k
      url_pattern_helpers::canonicalize_password,
6606
317k
      url_pattern_compile_component_options::DEFAULT);
6607
317k
  if (!password_component) {
6608
120
    ada_log("url_pattern_component::compile failed for password ",
6609
120
            processed_init->password.value());
6610
120
    return tl::unexpected(password_component.error());
6611
120
  }
6612
317k
  url_pattern_.password_component = std::move(*password_component);
6613
6614
  // TODO: Optimization opportunity. The following if statement can be
6615
  // simplified.
6616
  // If the result running hostname pattern is an IPv6 address given
6617
  // processedInit["hostname"] is true, then set urlPattern's hostname component
6618
  // to the result of compiling a component given processedInit["hostname"],
6619
  // canonicalize an IPv6 hostname, and hostname options.
6620
317k
  if (url_pattern_helpers::is_ipv6_address(processed_init->hostname.value())) {
6621
184
    ada_log("processed_init->hostname is ipv6 address");
6622
    // then set urlPattern's hostname component to the result of compiling a
6623
    // component given processedInit["hostname"], canonicalize an IPv6 hostname,
6624
    // and hostname options.
6625
184
    auto hostname_component = url_pattern_component<regex_provider>::compile(
6626
184
        processed_init->hostname.value(),
6627
184
        url_pattern_helpers::canonicalize_ipv6_hostname,
6628
184
        url_pattern_compile_component_options::DEFAULT);
6629
184
    if (!hostname_component) {
6630
37
      ada_log("url_pattern_component::compile failed for ipv6 hostname ",
6631
37
              processed_init->hostname.value());
6632
37
      return tl::unexpected(hostname_component.error());
6633
37
    }
6634
147
    url_pattern_.hostname_component = std::move(*hostname_component);
6635
317k
  } else {
6636
    // Otherwise, set urlPattern's hostname component to the result of compiling
6637
    // a component given processedInit["hostname"], canonicalize a hostname, and
6638
    // hostname options.
6639
317k
    auto hostname_component = url_pattern_component<regex_provider>::compile(
6640
317k
        processed_init->hostname.value(),
6641
317k
        url_pattern_helpers::canonicalize_hostname,
6642
317k
        url_pattern_compile_component_options::HOSTNAME);
6643
317k
    if (!hostname_component) {
6644
1.74k
      ada_log("url_pattern_component::compile failed for hostname ",
6645
1.74k
              processed_init->hostname.value());
6646
1.74k
      return tl::unexpected(hostname_component.error());
6647
1.74k
    }
6648
315k
    url_pattern_.hostname_component = std::move(*hostname_component);
6649
315k
  }
6650
6651
  // Set urlPattern's port component to the result of compiling a component
6652
  // given processedInit["port"], canonicalize a port, and default options.
6653
315k
  auto port_component = url_pattern_component<regex_provider>::compile(
6654
315k
      processed_init->port.value(), url_pattern_helpers::canonicalize_port,
6655
315k
      url_pattern_compile_component_options::DEFAULT);
6656
315k
  if (!port_component) {
6657
713
    ada_log("url_pattern_component::compile failed for port ",
6658
713
            processed_init->port.value());
6659
713
    return tl::unexpected(port_component.error());
6660
713
  }
6661
314k
  url_pattern_.port_component = std::move(*port_component);
6662
6663
  // Let compileOptions be a copy of the default options with the ignore case
6664
  // property set to options["ignoreCase"].
6665
314k
  auto compile_options = url_pattern_compile_component_options::DEFAULT;
6666
314k
  if (options) {
6667
199k
    compile_options.ignore_case = options->ignore_case;
6668
    // Recorded on the pattern so that url_pattern::ignore_case() reports the
6669
    // option it was created with.
6670
199k
    url_pattern_.ignore_case_ = options->ignore_case;
6671
199k
  }
6672
6673
  // TODO: Optimization opportunity: Simplify this if statement.
6674
  // If the result of running protocol component matches a special scheme given
6675
  // urlPattern's protocol component is true, then:
6676
314k
  if (url_pattern_helpers::protocol_component_matches_special_scheme<
6677
314k
          regex_provider>(url_pattern_.protocol_component)) {
6678
    // Let pathCompileOptions be copy of the pathname options with the ignore
6679
    // case property set to options["ignoreCase"].
6680
290k
    auto path_compile_options = url_pattern_compile_component_options::PATHNAME;
6681
290k
    if (options) {
6682
199k
      path_compile_options.ignore_case = options->ignore_case;
6683
199k
    }
6684
6685
    // Set urlPattern's pathname component to the result of compiling a
6686
    // component given processedInit["pathname"], canonicalize a pathname, and
6687
    // pathCompileOptions.
6688
290k
    auto pathname_component = url_pattern_component<regex_provider>::compile(
6689
290k
        processed_init->pathname.value(),
6690
290k
        url_pattern_helpers::canonicalize_pathname, path_compile_options);
6691
290k
    if (!pathname_component) {
6692
2.65k
      ada_log("url_pattern_component::compile failed for pathname ",
6693
2.65k
              processed_init->pathname.value());
6694
2.65k
      return tl::unexpected(pathname_component.error());
6695
2.65k
    }
6696
287k
    url_pattern_.pathname_component = std::move(*pathname_component);
6697
287k
  } else {
6698
    // Otherwise set urlPattern's pathname component to the result of compiling
6699
    // a component given processedInit["pathname"], canonicalize an opaque
6700
    // pathname, and compileOptions.
6701
24.6k
    auto pathname_component = url_pattern_component<regex_provider>::compile(
6702
24.6k
        processed_init->pathname.value(),
6703
24.6k
        url_pattern_helpers::canonicalize_opaque_pathname, compile_options);
6704
24.6k
    if (!pathname_component) {
6705
351
      ada_log("url_pattern_component::compile failed for opaque pathname ",
6706
351
              processed_init->pathname.value());
6707
351
      return tl::unexpected(pathname_component.error());
6708
351
    }
6709
24.2k
    url_pattern_.pathname_component = std::move(*pathname_component);
6710
24.2k
  }
6711
6712
  // Set urlPattern's search component to the result of compiling a component
6713
  // given processedInit["search"], canonicalize a search, and compileOptions.
6714
311k
  auto search_component = url_pattern_component<regex_provider>::compile(
6715
311k
      processed_init->search.value(), url_pattern_helpers::canonicalize_search,
6716
311k
      compile_options);
6717
311k
  if (!search_component) {
6718
86
    ada_log("url_pattern_component::compile failed for search ",
6719
86
            processed_init->search.value());
6720
86
    return tl::unexpected(search_component.error());
6721
86
  }
6722
311k
  url_pattern_.search_component = std::move(*search_component);
6723
6724
  // Set urlPattern's hash component to the result of compiling a component
6725
  // given processedInit["hash"], canonicalize a hash, and compileOptions.
6726
311k
  auto hash_component = url_pattern_component<regex_provider>::compile(
6727
311k
      processed_init->hash.value(), url_pattern_helpers::canonicalize_hash,
6728
311k
      compile_options);
6729
311k
  if (!hash_component) {
6730
84
    ada_log("url_pattern_component::compile failed for hash ",
6731
84
            processed_init->hash.value());
6732
84
    return tl::unexpected(hash_component.error());
6733
84
  }
6734
311k
  url_pattern_.hash_component = std::move(*hash_component);
6735
6736
  // Return urlPattern.
6737
311k
  return url_pattern_;
6738
311k
}
6739
#endif  // ADA_INCLUDE_URL_PATTERN
6740
6741
}  // namespace ada::parser
6742
6743
#endif  // ADA_PARSER_INL_H
6744
/* end file include/ada/parser-inl.h */
6745
/* begin file include/ada/scheme-inl.h */
6746
/**
6747
 * @file scheme-inl.h
6748
 * @brief Definitions for the URL scheme.
6749
 */
6750
#ifndef ADA_SCHEME_INL_H
6751
#define ADA_SCHEME_INL_H
6752
6753
6754
namespace ada::scheme {
6755
6756
/**
6757
 * @namespace ada::scheme::details
6758
 * @brief Includes the definitions for scheme specific entities
6759
 */
6760
namespace details {
6761
// for use with is_special and get_special_port
6762
// Spaces, if present, are removed from URL.
6763
constexpr std::string_view is_special_list[] = {"http", " ",   "https", "ws",
6764
                                                "ftp",  "wss", "file",  " "};
6765
// for use with get_special_port
6766
constexpr uint16_t special_ports[] = {80, 0, 443, 80, 21, 443, 0, 0};
6767
6768
// @private
6769
// convert a string_view to a 64-bit integer key for fast comparison
6770
0
constexpr uint64_t make_key(std::string_view sv) {
6771
0
  uint64_t val = 0;
6772
0
  for (size_t i = 0; i < sv.size(); i++)
6773
0
    val |= (uint64_t)(uint8_t)sv[i] << (i * 8);
6774
0
  return val;
6775
0
}
6776
// precomputed keys for the special schemes, indexed by a hash of the input
6777
// string
6778
constexpr uint64_t scheme_keys[] = {
6779
    make_key("http"),   // 0: HTTP
6780
    0,                  // 1: sentinel
6781
    make_key("https"),  // 2: HTTPS
6782
    make_key("ws"),     // 3: WS
6783
    make_key("ftp"),    // 4: FTP
6784
    make_key("wss"),    // 5: WSS
6785
    make_key("file"),   // 6: FILE
6786
    0,                  // 7: sentinel
6787
};
6788
6789
// @private
6790
// branchless load of up to 5 characters into a uint64_t, padding with zeros if
6791
// n < 5
6792
2.72M
inline uint64_t branchless_load5(const char* p, size_t n) {
6793
2.72M
  uint64_t input = (uint8_t)p[0];
6794
2.72M
  input |= ((uint64_t)(uint8_t)p[n > 1] << 8) & (0 - (uint64_t)(n > 1));
6795
2.72M
  input |= ((uint64_t)(uint8_t)p[(n > 2) * 2] << 16) & (0 - (uint64_t)(n > 2));
6796
2.72M
  input |= ((uint64_t)(uint8_t)p[(n > 3) * 3] << 24) & (0 - (uint64_t)(n > 3));
6797
2.72M
  input |= ((uint64_t)(uint8_t)p[(n > 4) * 4] << 32) & (0 - (uint64_t)(n > 4));
6798
2.72M
  return input;
6799
2.72M
}
6800
}  // namespace details
6801
6802
/****
6803
 * @private
6804
 * In is_special, get_scheme_type, and get_special_port, we
6805
 * use a standard hashing technique to find the index of the scheme in
6806
 * the is_special_list. The hashing technique is based on the size of
6807
 * the scheme and the first character of the scheme. It ensures that we
6808
 * do at most one string comparison per call. If the protocol is
6809
 * predictible (e.g., it is always "http"), we can get a better average
6810
 * performance by using a simpler approach where we loop and compare
6811
 * scheme with all possible protocols starting with the most likely
6812
 * protocol. Doing multiple comparisons may have a poor worst case
6813
 * performance, however. In this instance, we choose a potentially
6814
 * slightly lower best-case performance for a better worst-case
6815
 * performance. We can revisit this choice at any time.
6816
 *
6817
 * Reference:
6818
 * Schmidt, Douglas C. "Gperf: A perfect hash function generator."
6819
 * More C++ gems 17 (2000).
6820
 *
6821
 * Reference: https://en.wikipedia.org/wiki/Perfect_hash_function
6822
 *
6823
 * Reference: https://github.com/ada-url/ada/issues/617
6824
 ****/
6825
6826
507k
ada_really_inline constexpr bool is_special(std::string_view scheme) {
6827
507k
  if (scheme.empty()) {
6828
25.9k
    return false;
6829
25.9k
  }
6830
481k
  int hash_value = (2 * scheme.size() + (unsigned)(scheme[0])) & 7;
6831
481k
  const std::string_view target = details::is_special_list[hash_value];
6832
481k
  return (target[0] == scheme[0]) && (target.substr(1) == scheme.substr(1));
6833
507k
}
6834
75.6k
constexpr uint16_t get_special_port(std::string_view scheme) noexcept {
6835
75.6k
  if (scheme.empty()) {
6836
0
    return 0;
6837
0
  }
6838
75.6k
  int hash_value = (2 * scheme.size() + (unsigned)(scheme[0])) & 7;
6839
75.6k
  const std::string_view target = details::is_special_list[hash_value];
6840
75.6k
  if (scheme.size() == target.size() &&
6841
75.6k
      details::branchless_load5(scheme.data(), scheme.size()) ==
6842
75.6k
          details::scheme_keys[hash_value]) {
6843
75.6k
    return details::special_ports[hash_value];
6844
75.6k
  } else {
6845
0
    return 0;
6846
0
  }
6847
75.6k
}
6848
282k
constexpr uint16_t get_special_port(ada::scheme::type type) noexcept {
6849
282k
  return details::special_ports[int(type)];
6850
282k
}
6851
2.80M
constexpr ada::scheme::type get_scheme_type(std::string_view scheme) noexcept {
6852
2.80M
  if (scheme.empty()) {
6853
0
    return ada::scheme::NOT_SPECIAL;
6854
0
  }
6855
2.80M
  int hash_value = (2 * scheme.size() + (unsigned)(scheme[0])) & 7;
6856
2.80M
  const std::string_view target = details::is_special_list[hash_value];
6857
2.80M
  if (scheme.size() == target.size() &&
6858
2.65M
      details::branchless_load5(scheme.data(), scheme.size()) ==
6859
2.65M
          details::scheme_keys[hash_value]) {
6860
1.68M
    return ada::scheme::type(hash_value);
6861
1.68M
  } else {
6862
1.11M
    return ada::scheme::NOT_SPECIAL;
6863
1.11M
  }
6864
2.80M
}
6865
6866
}  // namespace ada::scheme
6867
6868
#endif  // ADA_SCHEME_INL_H
6869
/* end file include/ada/scheme-inl.h */
6870
/* begin file include/ada/serializers.h */
6871
/**
6872
 * @file serializers.h
6873
 * @brief IP address serialization utilities.
6874
 *
6875
 * This header provides functions for converting IP addresses to their
6876
 * string representations according to the WHATWG URL Standard.
6877
 */
6878
#ifndef ADA_SERIALIZERS_H
6879
#define ADA_SERIALIZERS_H
6880
6881
6882
#include <array>
6883
#include <string>
6884
6885
/**
6886
 * @namespace ada::serializers
6887
 * @brief IP address serialization functions.
6888
 *
6889
 * Contains utilities for serializing IPv4 and IPv6 addresses to strings.
6890
 */
6891
namespace ada::serializers {
6892
6893
/**
6894
 * Finds the longest consecutive sequence of zero pieces in an IPv6 address.
6895
 * Used for :: compression in IPv6 serialization.
6896
 *
6897
 * @param address The 8 16-bit pieces of the IPv6 address.
6898
 * @param[out] compress Index of the start of the longest zero sequence.
6899
 * @param[out] compress_length Length of the longest zero sequence.
6900
 */
6901
void find_longest_sequence_of_ipv6_pieces(
6902
    const std::array<uint16_t, 8>& address, size_t& compress,
6903
    size_t& compress_length) noexcept;
6904
6905
/**
6906
 * Serializes an IPv6 address to its string representation.
6907
 *
6908
 * @param address The 8 16-bit pieces of the IPv6 address.
6909
 * @return The serialized IPv6 string (e.g., "2001:db8::1").
6910
 * @see https://url.spec.whatwg.org/#concept-ipv6-serializer
6911
 */
6912
std::string ipv6(const std::array<uint16_t, 8>& address);
6913
6914
/**
6915
 * Serializes an IPv4 address to its dotted-decimal string representation.
6916
 *
6917
 * @param address The 32-bit IPv4 address as an integer.
6918
 * @return The serialized IPv4 string (e.g., "192.168.1.1").
6919
 * @see https://url.spec.whatwg.org/#concept-ipv4-serializer
6920
 */
6921
std::string ipv4(uint64_t address);
6922
6923
}  // namespace ada::serializers
6924
6925
#endif  // ADA_SERIALIZERS_H
6926
/* end file include/ada/serializers.h */
6927
/* begin file include/ada/state.h */
6928
/**
6929
 * @file state.h
6930
 * @brief URL parser state machine states.
6931
 *
6932
 * Defines the states used by the URL parsing state machine as specified
6933
 * in the WHATWG URL Standard.
6934
 *
6935
 * @see https://url.spec.whatwg.org/#url-parsing
6936
 */
6937
#ifndef ADA_STATE_H
6938
#define ADA_STATE_H
6939
6940
6941
#include <string>
6942
6943
namespace ada {
6944
6945
/**
6946
 * @brief States in the URL parsing state machine.
6947
 *
6948
 * The URL parser processes input through a sequence of states, each handling
6949
 * a specific part of the URL syntax.
6950
 *
6951
 * @see https://url.spec.whatwg.org/#url-parsing
6952
 */
6953
enum class state {
6954
  /**
6955
   * @see https://url.spec.whatwg.org/#authority-state
6956
   */
6957
  AUTHORITY,
6958
6959
  /**
6960
   * @see https://url.spec.whatwg.org/#scheme-start-state
6961
   */
6962
  SCHEME_START,
6963
6964
  /**
6965
   * @see https://url.spec.whatwg.org/#scheme-state
6966
   */
6967
  SCHEME,
6968
6969
  /**
6970
   * @see https://url.spec.whatwg.org/#host-state
6971
   */
6972
  HOST,
6973
6974
  /**
6975
   * @see https://url.spec.whatwg.org/#no-scheme-state
6976
   */
6977
  NO_SCHEME,
6978
6979
  /**
6980
   * @see https://url.spec.whatwg.org/#fragment-state
6981
   */
6982
  FRAGMENT,
6983
6984
  /**
6985
   * @see https://url.spec.whatwg.org/#relative-state
6986
   */
6987
  RELATIVE_SCHEME,
6988
6989
  /**
6990
   * @see https://url.spec.whatwg.org/#relative-slash-state
6991
   */
6992
  RELATIVE_SLASH,
6993
6994
  /**
6995
   * @see https://url.spec.whatwg.org/#file-state
6996
   */
6997
  FILE,
6998
6999
  /**
7000
   * @see https://url.spec.whatwg.org/#file-host-state
7001
   */
7002
  FILE_HOST,
7003
7004
  /**
7005
   * @see https://url.spec.whatwg.org/#file-slash-state
7006
   */
7007
  FILE_SLASH,
7008
7009
  /**
7010
   * @see https://url.spec.whatwg.org/#path-or-authority-state
7011
   */
7012
  PATH_OR_AUTHORITY,
7013
7014
  /**
7015
   * @see https://url.spec.whatwg.org/#special-authority-ignore-slashes-state
7016
   */
7017
  SPECIAL_AUTHORITY_IGNORE_SLASHES,
7018
7019
  /**
7020
   * @see https://url.spec.whatwg.org/#special-authority-slashes-state
7021
   */
7022
  SPECIAL_AUTHORITY_SLASHES,
7023
7024
  /**
7025
   * @see https://url.spec.whatwg.org/#special-relative-or-authority-state
7026
   */
7027
  SPECIAL_RELATIVE_OR_AUTHORITY,
7028
7029
  /**
7030
   * @see https://url.spec.whatwg.org/#query-state
7031
   */
7032
  QUERY,
7033
7034
  /**
7035
   * @see https://url.spec.whatwg.org/#path-state
7036
   */
7037
  PATH,
7038
7039
  /**
7040
   * @see https://url.spec.whatwg.org/#path-start-state
7041
   */
7042
  PATH_START,
7043
7044
  /**
7045
   * @see https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state
7046
   */
7047
  OPAQUE_PATH,
7048
7049
  /**
7050
   * @see https://url.spec.whatwg.org/#port-state
7051
   */
7052
  PORT,
7053
};
7054
7055
/**
7056
 * Converts a parser state to its string name for debugging.
7057
 * @param s The state to convert.
7058
 * @return A string representation of the state.
7059
 */
7060
ada_warn_unused std::string to_string(ada::state s);
7061
7062
}  // namespace ada
7063
7064
#endif  // ADA_STATE_H
7065
/* end file include/ada/state.h */
7066
/* begin file include/ada/unicode.h */
7067
/**
7068
 * @file unicode.h
7069
 * @brief Definitions for all unicode specific functions.
7070
 */
7071
#ifndef ADA_UNICODE_H
7072
#define ADA_UNICODE_H
7073
7074
7075
#include <string>
7076
#include <string_view>
7077
#include <optional>
7078
7079
/**
7080
 * Unicode operations. These functions are not part of our public API and may
7081
 * change at any time.
7082
 *
7083
 * @private
7084
 * @namespace ada::unicode
7085
 * @brief Includes the definitions for unicode operations
7086
 */
7087
namespace ada::unicode {
7088
7089
/**
7090
 * @private
7091
 * We receive a UTF-8 string representing a domain name.
7092
 * If the string is percent encoded, we apply percent decoding.
7093
 *
7094
 * Given a domain, we need to identify its labels.
7095
 * They are separated by label-separators:
7096
 *
7097
 * U+002E (.) FULL STOP
7098
 * U+FF0E FULLWIDTH FULL STOP
7099
 * U+3002 IDEOGRAPHIC FULL STOP
7100
 * U+FF61 HALFWIDTH IDEOGRAPHIC FULL STOP
7101
 *
7102
 * They are all mapped to U+002E.
7103
 *
7104
 * We process each label into a string that should not exceed 63 octets.
7105
 * If the string is already punycode (starts with "xn--"), then we must
7106
 * scan it to look for unallowed code points.
7107
 * Otherwise, if the string is not pure ASCII, we need to transcode it
7108
 * to punycode by following RFC 3454 which requires us to
7109
 * - Map characters  (see section 3),
7110
 * - Normalize (see section 4),
7111
 * - Reject forbidden characters,
7112
 * - Check for right-to-left characters and if so, check all requirements (see
7113
 * section 6),
7114
 * - Optionally reject based on unassigned code points (section 7).
7115
 *
7116
 * The Unicode standard provides a table of code points with a mapping, a list
7117
 * of forbidden code points and so forth. This table is subject to change and
7118
 * will vary based on the implementation. For Unicode 15, the table is at
7119
 * https://www.unicode.org/Public/idna/15.0.0/IdnaMappingTable.txt
7120
 * If you use ICU, they parse this table and map it to code using a Python
7121
 * script.
7122
 *
7123
 * The resulting strings should not exceed 255 octets according to RFC 1035
7124
 * section 2.3.4. ICU checks for label size and domain size, but these errors
7125
 * are ignored.
7126
 *
7127
 * @see https://url.spec.whatwg.org/#concept-domain-to-ascii
7128
 *
7129
 */
7130
bool to_ascii(std::optional<std::string>& out, std::string_view plain,
7131
              size_t first_percent);
7132
7133
/**
7134
 * @private
7135
 * Checks if the input has tab or newline characters.
7136
 *
7137
 * @attention The has_tabs_or_newline function is a bottleneck and it is simple
7138
 * enough that compilers like GCC can 'autovectorize it'.
7139
 */
7140
ada_really_inline bool has_tabs_or_newline(
7141
    std::string_view user_input) noexcept;
7142
7143
/**
7144
 * @private
7145
 * Checks if the input is a forbidden host code point.
7146
 * @see https://url.spec.whatwg.org/#forbidden-host-code-point
7147
 */
7148
ada_really_inline constexpr bool is_forbidden_host_code_point(char c) noexcept;
7149
7150
/**
7151
 * @private
7152
 * Checks if the input contains a forbidden domain code point.
7153
 * @see https://url.spec.whatwg.org/#forbidden-domain-code-point
7154
 */
7155
ada_really_inline constexpr bool contains_forbidden_domain_code_point(
7156
    const char* input, size_t length) noexcept;
7157
7158
/**
7159
 * @private
7160
 * Checks if the input contains a forbidden domain code point in which case
7161
 * the first bit is set to 1. If the input contains an upper case ASCII letter,
7162
 * then the second bit is set to 1.
7163
 * @see https://url.spec.whatwg.org/#forbidden-domain-code-point
7164
 */
7165
ada_really_inline constexpr uint8_t
7166
contains_forbidden_domain_code_point_or_upper(const char* input,
7167
                                              size_t length) noexcept;
7168
7169
/**
7170
 * @private
7171
 * Checks if the input is a forbidden domain code point.
7172
 * @see https://url.spec.whatwg.org/#forbidden-domain-code-point
7173
 */
7174
ada_really_inline constexpr bool is_forbidden_domain_code_point(
7175
    char c) noexcept;
7176
7177
/**
7178
 * @private
7179
 * Checks if the input is alphanumeric, '+', '-' or '.'
7180
 */
7181
ada_really_inline constexpr bool is_alnum_plus(char c) noexcept;
7182
7183
/**
7184
 * @private
7185
 * @details An ASCII hex digit is an ASCII upper hex digit or ASCII lower hex
7186
 * digit. An ASCII upper hex digit is an ASCII digit or a code point in the
7187
 * range U+0041 (A) to U+0046 (F), inclusive. An ASCII lower hex digit is an
7188
 * ASCII digit or a code point in the range U+0061 (a) to U+0066 (f), inclusive.
7189
 */
7190
ada_really_inline constexpr bool is_ascii_hex_digit(char c) noexcept;
7191
7192
/**
7193
 * @private
7194
 * An ASCII digit is a code point in the range U+0030 (0) to U+0039 (9),
7195
 * inclusive.
7196
 */
7197
ada_really_inline constexpr bool is_ascii_digit(char c) noexcept;
7198
7199
/**
7200
 * @private
7201
 * @details If a char is between U+0000 and U+007F inclusive, then it's an ASCII
7202
 * character.
7203
 */
7204
ada_really_inline constexpr bool is_ascii(char32_t c) noexcept;
7205
7206
/**
7207
 * @private
7208
 * Checks if the input is a C0 control or space character.
7209
 *
7210
 * @details A C0 control or space is a C0 control or U+0020 SPACE.
7211
 * A C0 control is a code point in the range U+0000 NULL to U+001F INFORMATION
7212
 * SEPARATOR ONE, inclusive.
7213
 */
7214
ada_really_inline constexpr bool is_c0_control_or_space(char c) noexcept;
7215
7216
/**
7217
 * @private
7218
 * Checks if the input is a ASCII tab or newline character.
7219
 *
7220
 * @details An ASCII tab or newline is U+0009 TAB, U+000A LF, or U+000D CR.
7221
 */
7222
ada_really_inline constexpr bool is_ascii_tab_or_newline(char c) noexcept;
7223
7224
/**
7225
 * @private
7226
 * @details A double-dot path segment must be ".." or an ASCII case-insensitive
7227
 * match for ".%2e", "%2e.", or "%2e%2e".
7228
 */
7229
ada_really_inline constexpr bool is_double_dot_path_segment(
7230
    std::string_view input) noexcept;
7231
7232
/**
7233
 * @private
7234
 * @details A single-dot path segment must be "." or an ASCII case-insensitive
7235
 * match for "%2e".
7236
 */
7237
ada_really_inline constexpr bool is_single_dot_path_segment(
7238
    std::string_view input) noexcept;
7239
7240
/**
7241
 * @private
7242
 * @details ipv4 character might contain 0-9 or a-f character ranges.
7243
 */
7244
ada_really_inline constexpr bool is_lowercase_hex(char c) noexcept;
7245
7246
/**
7247
 * @private
7248
 * @details Convert hex to binary. Caller is responsible to ensure that
7249
 * the parameter is an hexadecimal digit (0-9, A-F, a-f).
7250
 */
7251
ada_really_inline unsigned constexpr convert_hex_to_binary(char c) noexcept;
7252
7253
/**
7254
 * @private
7255
 * first_percent should be  = input.find('%')
7256
 *
7257
 * @todo It would be faster as noexcept maybe, but it could be unsafe since.
7258
 * @author Node.js
7259
 * @see https://github.com/nodejs/node/blob/main/src/node_url.cc#L245
7260
 * @see https://encoding.spec.whatwg.org/#utf-8-decode-without-bom
7261
 */
7262
std::string percent_decode(std::string_view input, size_t first_percent);
7263
7264
/**
7265
 * Decode an application/x-www-form-urlencoded component: map '+' to space,
7266
 * then percent-decode. Single allocation; no intermediate string.
7267
 *
7268
 * @param input A form-urlencoded component (key or value).
7269
 * @return The decoded string.
7270
 * @see https://url.spec.whatwg.org/#concept-urlencoded-parser
7271
 */
7272
std::string form_urlencoded_decode(std::string_view input);
7273
7274
/**
7275
 * @private
7276
 * Returns a percent-encoding string whether percent encoding was needed or not.
7277
 * @see https://github.com/nodejs/node/blob/main/src/node_url.cc#L226
7278
 */
7279
std::string percent_encode(std::string_view input,
7280
                           const uint8_t character_set[]);
7281
/**
7282
 * @private
7283
 * Returns a percent-encoded string version of input, while starting the percent
7284
 * encoding at the provided index.
7285
 * @see https://github.com/nodejs/node/blob/main/src/node_url.cc#L226
7286
 */
7287
std::string percent_encode(std::string_view input,
7288
                           const uint8_t character_set[], size_t index);
7289
/**
7290
 * @private
7291
 * Returns true if percent encoding was needed, in which case, we store
7292
 * the percent-encoded content in 'out'. If the boolean 'append' is set to
7293
 * true, the content is appended to 'out'.
7294
 * If percent encoding is not needed, out is left unchanged.
7295
 * @see https://github.com/nodejs/node/blob/main/src/node_url.cc#L226
7296
 */
7297
template <bool append>
7298
bool percent_encode(std::string_view input, const uint8_t character_set[],
7299
                    std::string& out);
7300
/**
7301
 * @private
7302
 * Returns the index at which percent encoding should start, or (equivalently),
7303
 * the length of the prefix that does not require percent encoding.
7304
 */
7305
ada_really_inline size_t percent_encode_index(std::string_view input,
7306
                                              const uint8_t character_set[]);
7307
/**
7308
 * @private
7309
 * Lowers the string in-place, assuming that the content is ASCII.
7310
 * Return true if the content was ASCII.
7311
 */
7312
constexpr bool to_lower_ascii(char* input, size_t length) noexcept;
7313
}  // namespace ada::unicode
7314
7315
#endif  // ADA_UNICODE_H
7316
/* end file include/ada/unicode.h */
7317
/* begin file include/ada/url_base-inl.h */
7318
/**
7319
 * @file url_base-inl.h
7320
 * @brief Inline functions for url base
7321
 */
7322
#ifndef ADA_URL_BASE_INL_H
7323
#define ADA_URL_BASE_INL_H
7324
7325
7326
#include <string>
7327
#if ADA_REGULAR_VISUAL_STUDIO
7328
#include <intrin.h>
7329
#endif  // ADA_REGULAR_VISUAL_STUDIO
7330
7331
namespace ada {
7332
7333
[[nodiscard]] ada_really_inline constexpr bool url_base::is_special()
7334
15.5M
    const noexcept {
7335
15.5M
  return type != ada::scheme::NOT_SPECIAL;
7336
15.5M
}
7337
7338
16.8k
[[nodiscard]] inline uint16_t url_base::get_special_port() const noexcept {
7339
16.8k
  return ada::scheme::get_special_port(type);
7340
16.8k
}
7341
7342
[[nodiscard]] ada_really_inline uint16_t
7343
138k
url_base::scheme_default_port() const noexcept {
7344
138k
  return scheme::get_special_port(type);
7345
138k
}
7346
7347
}  // namespace ada
7348
7349
#endif  // ADA_URL_BASE_INL_H
7350
/* end file include/ada/url_base-inl.h */
7351
/* begin file include/ada/url-inl.h */
7352
/**
7353
 * @file url-inl.h
7354
 * @brief Definitions for the URL
7355
 */
7356
#ifndef ADA_URL_INL_H
7357
#define ADA_URL_INL_H
7358
7359
7360
#include <charconv>
7361
#include <cstring>
7362
#include <optional>
7363
#include <string>
7364
#if ADA_REGULAR_VISUAL_STUDIO
7365
#include <intrin.h>
7366
#endif  // ADA_REGULAR_VISUAL_STUDIO
7367
7368
namespace ada {
7369
1.63M
[[nodiscard]] ada_really_inline bool url::has_credentials() const noexcept {
7370
1.63M
  return !username.empty() || !password.empty();
7371
1.63M
}
7372
31.9k
[[nodiscard]] ada_really_inline bool url::has_port() const noexcept {
7373
31.9k
  return port.has_value();
7374
31.9k
}
7375
73.5k
[[nodiscard]] inline bool url::cannot_have_credentials_or_port() const {
7376
73.5k
  return !host.has_value() || host->empty() || type == ada::scheme::type::FILE;
7377
73.5k
}
7378
31.9k
[[nodiscard]] inline bool url::has_empty_hostname() const noexcept {
7379
31.9k
  if (!host.has_value()) {
7380
3.63k
    return false;
7381
3.63k
  }
7382
28.3k
  return host->empty();
7383
31.9k
}
7384
31.9k
[[nodiscard]] inline bool url::has_hostname() const noexcept {
7385
31.9k
  return host.has_value();
7386
31.9k
}
7387
0
inline std::ostream& operator<<(std::ostream& out, const ada::url& u) {
7388
0
  return out << u.to_string();
7389
0
}
7390
7391
31.9k
[[nodiscard]] size_t url::get_pathname_length() const noexcept {
7392
31.9k
  return path.size();
7393
31.9k
}
7394
7395
230k
[[nodiscard]] constexpr std::string_view url::get_pathname() const noexcept {
7396
230k
  return path;
7397
230k
}
7398
7399
[[nodiscard]] ada_really_inline ada::url_components url::get_components()
7400
31.9k
    const {
7401
31.9k
  url_components out{};
7402
7403
  // protocol ends with ':'. for example: "https:"
7404
31.9k
  out.protocol_end = uint32_t(get_protocol().size());
7405
7406
  // Trailing index is always the next character of the current one.
7407
  // NOLINTNEXTLINE(clang-analyzer-deadcode.DeadStores)
7408
31.9k
  size_t running_index = out.protocol_end;
7409
7410
31.9k
  if (host.has_value()) {
7411
    // 2 characters for "//" and 1 character for starting index
7412
28.3k
    out.host_start = out.protocol_end + 2;
7413
7414
28.3k
    if (has_credentials()) {
7415
16.2k
      out.username_end = uint32_t(out.host_start + username.size());
7416
7417
16.2k
      out.host_start += uint32_t(username.size());
7418
7419
16.2k
      if (!password.empty()) {
7420
15.8k
        out.host_start += uint32_t(password.size() + 1);
7421
15.8k
      }
7422
7423
      // host_start is the '@' when there are credentials, exactly as
7424
      // url_aggregator reports it, so the host itself begins one byte later.
7425
16.2k
      out.host_end = uint32_t(out.host_start + 1 + host->size());
7426
16.2k
    } else {
7427
12.1k
      out.username_end = out.host_start;
7428
7429
      // Host does not start with "@" if it does not include credentials.
7430
12.1k
      out.host_end = uint32_t(out.host_start + host->size());
7431
12.1k
    }
7432
7433
    // host_end is one past the host, so it is already the next index.
7434
28.3k
    running_index = out.host_end;
7435
28.3k
  } else {
7436
    // Update host start and end date to the same index, since it does not
7437
    // exist.
7438
3.63k
    out.host_start = out.protocol_end;
7439
3.63k
    out.host_end = out.host_start;
7440
7441
3.63k
    if (!has_opaque_path && path.starts_with("//")) {
7442
      // If url's host is null, url does not have an opaque path, url's path's
7443
      // size is greater than 1, and url's path[0] is the empty string, then
7444
      // append U+002F (/) followed by U+002E (.) to output.
7445
52
      running_index = out.protocol_end + 2;
7446
3.58k
    } else {
7447
3.58k
      running_index = out.protocol_end;
7448
3.58k
    }
7449
3.63k
  }
7450
7451
31.9k
  if (port.has_value()) {
7452
2.44k
    out.port = *port;
7453
2.44k
    running_index += helpers::fast_digit_count(*port) + 1;  // Port omits ':'
7454
2.44k
  }
7455
7456
31.9k
  out.pathname_start = uint32_t(running_index);
7457
7458
31.9k
  running_index += path.size();
7459
7460
31.9k
  if (query.has_value()) {
7461
17.6k
    out.search_start = uint32_t(running_index);
7462
17.6k
    running_index += get_search().size();
7463
17.6k
    if (get_search().empty()) {
7464
479
      running_index++;
7465
479
    }
7466
17.6k
  }
7467
7468
31.9k
  if (hash.has_value()) {
7469
17.5k
    out.hash_start = uint32_t(running_index);
7470
17.5k
  }
7471
7472
31.9k
  return out;
7473
31.9k
}
7474
7475
408
inline void url::update_base_hostname(std::string_view input) { host = input; }
7476
7477
36.8k
inline void url::update_unencoded_base_hash(std::string_view input) {
7478
  // We do the percent encoding
7479
36.8k
  hash = unicode::percent_encode(input,
7480
36.8k
                                 ada::character_sets::FRAGMENT_PERCENT_ENCODE);
7481
36.8k
}
7482
7483
inline void url::update_base_search(std::string_view input,
7484
37.5k
                                    const uint8_t query_percent_encode_set[]) {
7485
37.5k
  query = ada::unicode::percent_encode(input, query_percent_encode_set);
7486
37.5k
}
7487
7488
0
inline void url::update_base_search(std::optional<std::string>&& input) {
7489
0
  query = std::move(input);
7490
0
}
7491
7492
56.8k
inline void url::update_base_pathname(const std::string_view input) {
7493
56.8k
  path = input;
7494
56.8k
}
7495
7496
0
inline void url::update_base_username(const std::string_view input) {
7497
0
  username = input;
7498
0
}
7499
7500
0
inline void url::update_base_password(const std::string_view input) {
7501
0
  password = input;
7502
0
}
7503
7504
0
inline void url::update_base_port(std::optional<uint16_t> input) {
7505
0
  port = input;
7506
0
}
7507
7508
64
constexpr void url::clear_pathname() { path.clear(); }
7509
7510
1.19k
constexpr void url::clear_search() { query = std::nullopt; }
7511
7512
31.9k
[[nodiscard]] constexpr bool url::has_hash() const noexcept {
7513
31.9k
  return hash.has_value();
7514
31.9k
}
7515
7516
63.9k
[[nodiscard]] constexpr bool url::has_search() const noexcept {
7517
63.9k
  return query.has_value();
7518
63.9k
}
7519
7520
9.01k
constexpr void url::set_protocol_as_file() { type = ada::scheme::type::FILE; }
7521
7522
33.7k
inline void url::set_scheme(std::string&& new_scheme) noexcept {
7523
33.7k
  type = ada::scheme::get_scheme_type(new_scheme);
7524
  // We only move the 'scheme' if it is non-special.
7525
33.7k
  if (!is_special()) {
7526
18.9k
    non_special_scheme = std::move(new_scheme);
7527
18.9k
  }
7528
33.7k
}
7529
7530
0
constexpr void url::copy_scheme(ada::url&& u) {
7531
0
  non_special_scheme = u.non_special_scheme;
7532
0
  type = u.type;
7533
0
}
7534
7535
2.06k
constexpr void url::copy_scheme(const ada::url& u) {
7536
2.06k
  non_special_scheme = u.non_special_scheme;
7537
2.06k
  type = u.type;
7538
2.06k
}
7539
7540
0
[[nodiscard]] ada_really_inline std::string url::get_href() const {
7541
0
  if (is_special() && host.has_value() && username.empty() &&
7542
0
      password.empty() && !port.has_value()) [[likely]] {
7543
0
    const std::string_view scheme = ada::scheme::details::is_special_list[type];
7544
0
    const size_t host_size = host->size();
7545
0
    const size_t path_size = path.size();
7546
0
    const size_t query_size = query.has_value() ? query->size() : 0;
7547
0
    const size_t hash_size = hash.has_value() ? hash->size() : 0;
7548
0
    const size_t total = scheme.size() + 3 + host_size + path_size +
7549
0
                         (query.has_value() ? query_size + 1 : 0) +
7550
0
                         (hash.has_value() ? hash_size + 1 : 0);
7551
0
    std::string output(total, '\0');
7552
0
    char* p = output.data();
7553
0
    std::memcpy(p, scheme.data(), scheme.size());
7554
0
    p += scheme.size();
7555
0
    p[0] = ':';
7556
0
    p[1] = '/';
7557
0
    p[2] = '/';
7558
0
    p += 3;
7559
0
    // NOLINTNEXTLINE(bugprone-not-null-terminated-result)
7560
0
    std::memcpy(p, host->data(), host_size);
7561
0
    p += host_size;
7562
0
    std::memcpy(p, path.data(), path_size);
7563
0
    p += path_size;
7564
0
    if (query.has_value()) {
7565
0
      *p++ = '?';
7566
0
      // NOLINTNEXTLINE(bugprone-not-null-terminated-result)
7567
0
      std::memcpy(p, query->data(), query_size);
7568
0
      p += query_size;
7569
0
    }
7570
0
    if (hash.has_value()) {
7571
0
      *p++ = '#';
7572
0
      // NOLINTNEXTLINE(bugprone-not-null-terminated-result)
7573
0
      std::memcpy(p, hash->data(), hash_size);
7574
0
    }
7575
0
    return output;
7576
0
  }
7577
0
7578
0
  std::string output;
7579
0
  output.reserve(get_href_size());
7580
0
7581
0
  if (is_special()) {
7582
0
    output.append(ada::scheme::details::is_special_list[type]);
7583
0
    output += ':';
7584
0
  } else {
7585
0
    output.append(non_special_scheme);
7586
0
    output += ':';
7587
0
  }
7588
0
7589
0
  if (host.has_value()) {
7590
0
    output += '/';
7591
0
    output += '/';
7592
0
    if (has_credentials()) {
7593
0
      output.append(username);
7594
0
      if (!password.empty()) {
7595
0
        output += ':';
7596
0
        output.append(password);
7597
0
      }
7598
0
      output += '@';
7599
0
    }
7600
0
    output.append(*host);
7601
0
    if (port.has_value()) {
7602
0
      output += ':';
7603
0
      char port_buf[5];
7604
0
      auto [ptr, ec] = std::to_chars(port_buf, port_buf + 5, *port);
7605
0
      (void)ec;
7606
0
      output.append(port_buf, static_cast<size_t>(ptr - port_buf));
7607
0
    }
7608
0
  } else if (!has_opaque_path && path.starts_with("//")) {
7609
0
    // If url's host is null, url does not have an opaque path, url's path's
7610
0
    // size is greater than 1, and url's path[0] is the empty string, then
7611
0
    // append U+002F (/) followed by U+002E (.) to output.
7612
0
    output += '/';
7613
0
    output += '.';
7614
0
  }
7615
0
  output.append(path);
7616
0
  if (query.has_value()) {
7617
0
    output += '?';
7618
0
    output.append(*query);
7619
0
  }
7620
0
  if (hash.has_value()) {
7621
0
    output += '#';
7622
0
    output.append(*hash);
7623
0
  }
7624
0
  return output;
7625
0
}
7626
7627
1.33M
[[nodiscard]] inline size_t url::get_href_size() const noexcept {
7628
1.33M
  size_t size = 0;
7629
1.33M
  if (is_special()) {
7630
1.26M
    size += ada::scheme::details::is_special_list[type].size() + 1;
7631
1.26M
  } else {
7632
65.8k
    size += non_special_scheme.size() + 1;
7633
65.8k
  }
7634
1.33M
  if (host.has_value()) {
7635
1.27M
    size += host->size();
7636
1.27M
    size += 2;
7637
1.27M
    if (has_credentials()) {
7638
294k
      size += username.size();
7639
294k
      if (!password.empty()) {
7640
263k
        size += 1 + password.size();
7641
263k
      }
7642
294k
      size += 1;
7643
294k
    }
7644
1.27M
    if (port.has_value()) {
7645
280k
      size += 1;
7646
280k
      uint16_t p = *port;
7647
280k
      size += (p >= 10000)  ? 5
7648
280k
              : (p >= 1000) ? 4
7649
273k
              : (p >= 100)  ? 3
7650
114k
              : (p >= 10)   ? 2
7651
113k
                            : 1;
7652
280k
    }
7653
1.27M
  } else if (!has_opaque_path && path.starts_with("//")) {
7654
702
    size += 2;
7655
702
  }
7656
1.33M
  size += path.size();
7657
1.33M
  if (query.has_value()) {
7658
236k
    size += 1 + query->size();
7659
236k
  }
7660
1.33M
  if (hash.has_value()) {
7661
191k
    size += 1 + hash->size();
7662
191k
  }
7663
1.33M
  return size;
7664
1.33M
}
7665
7666
ada_really_inline size_t url::parse_port(std::string_view view,
7667
30.0k
                                         bool check_trailing_content) noexcept {
7668
30.0k
  ada_log("parse_port('", view, "') ", view.size());
7669
30.0k
  if (!view.empty() && view[0] == '-') {
7670
24
    ada_log("parse_port: view[0] == '0' && view.size() > 1");
7671
24
    is_valid = false;
7672
24
    return 0;
7673
24
  }
7674
30.0k
  uint16_t parsed_port{};
7675
30.0k
  auto r = std::from_chars(view.data(), view.data() + view.size(), parsed_port);
7676
30.0k
  if (r.ec == std::errc::result_out_of_range) {
7677
363
    ada_log("parse_port: r.ec == std::errc::result_out_of_range");
7678
363
    is_valid = false;
7679
363
    return 0;
7680
363
  }
7681
29.6k
  ada_log("parse_port: ", parsed_port);
7682
29.6k
  const auto consumed = size_t(r.ptr - view.data());
7683
29.6k
  ada_log("parse_port: consumed ", consumed);
7684
29.6k
  if (check_trailing_content) {
7685
27.1k
    is_valid &=
7686
27.1k
        (consumed == view.size() || view[consumed] == '/' ||
7687
943
         view[consumed] == '?' || (is_special() && view[consumed] == '\\'));
7688
27.1k
  }
7689
29.6k
  ada_log("parse_port: is_valid = ", is_valid);
7690
29.6k
  if (is_valid) {
7691
    // scheme_default_port can return 0, and we should allow 0 as a base port.
7692
29.1k
    auto default_port = scheme_default_port();
7693
29.1k
    bool is_port_valid = (default_port == 0 && parsed_port == 0) ||
7694
29.0k
                         (default_port != parsed_port);
7695
29.1k
    port = (r.ec == std::errc() && is_port_valid) ? std::optional(parsed_port)
7696
29.1k
                                                  : std::nullopt;
7697
29.1k
  }
7698
29.6k
  return consumed;
7699
30.0k
}
7700
7701
}  // namespace ada
7702
7703
#endif  // ADA_URL_H
7704
/* end file include/ada/url-inl.h */
7705
/* begin file include/ada/url_components-inl.h */
7706
/**
7707
 * @file url_components.h
7708
 * @brief Declaration for the URL Components
7709
 */
7710
#ifndef ADA_URL_COMPONENTS_INL_H
7711
#define ADA_URL_COMPONENTS_INL_H
7712
7713
7714
namespace ada {
7715
7716
[[nodiscard]] constexpr bool url_components::check_offset_consistency()
7717
0
    const noexcept {
7718
0
  /**
7719
0
   * https://user:pass@example.com:1234/foo/bar?baz#quux
7720
0
   *       |     |    |          | ^^^^|       |   |
7721
0
   *       |     |    |          | |   |       |   `----- hash_start
7722
0
   *       |     |    |          | |   |       `--------- search_start
7723
0
   *       |     |    |          | |   `----------------- pathname_start
7724
0
   *       |     |    |          | `--------------------- port
7725
0
   *       |     |    |          `----------------------- host_end
7726
0
   *       |     |    `---------------------------------- host_start
7727
0
   *       |     `--------------------------------------- username_end
7728
0
   *       `--------------------------------------------- protocol_end
7729
0
   */
7730
0
  // These conditions can be made more strict.
7731
0
  if (protocol_end == url_components::omitted) {
7732
0
    return false;
7733
0
  }
7734
0
  uint32_t index = protocol_end;
7735
0
7736
0
  if (username_end == url_components::omitted) {
7737
0
    return false;
7738
0
  }
7739
0
  if (username_end < index) {
7740
0
    return false;
7741
0
  }
7742
0
  index = username_end;
7743
0
7744
0
  if (host_start == url_components::omitted) {
7745
0
    return false;
7746
0
  }
7747
0
  if (host_start < index) {
7748
0
    return false;
7749
0
  }
7750
0
  index = host_start;
7751
0
7752
0
  if (port != url_components::omitted) {
7753
0
    if (port > 0xffff) {
7754
0
      return false;
7755
0
    }
7756
0
    uint32_t port_length = helpers::fast_digit_count(port) + 1;
7757
0
    if (index + port_length < index) {
7758
0
      return false;
7759
0
    }
7760
0
    index += port_length;
7761
0
  }
7762
0
7763
0
  if (pathname_start == url_components::omitted) {
7764
0
    return false;
7765
0
  }
7766
0
  if (pathname_start < index) {
7767
0
    return false;
7768
0
  }
7769
0
  index = pathname_start;
7770
0
7771
0
  if (search_start != url_components::omitted) {
7772
0
    if (search_start < index) {
7773
0
      return false;
7774
0
    }
7775
0
    index = search_start;
7776
0
  }
7777
0
7778
0
  if (hash_start != url_components::omitted) {
7779
0
    if (hash_start < index) {
7780
0
      return false;
7781
0
    }
7782
0
  }
7783
0
7784
0
  return true;
7785
0
}
7786
7787
}  // namespace ada
7788
#endif
7789
/* end file include/ada/url_components-inl.h */
7790
/* begin file include/ada/url_aggregator.h */
7791
/**
7792
 * @file url_aggregator.h
7793
 * @brief Declaration for the `ada::url_aggregator` class.
7794
 *
7795
 * This file contains the `ada::url_aggregator` struct which represents a parsed
7796
 * URL using a single buffer with component offsets. This is the default and
7797
 * most memory-efficient URL representation in Ada.
7798
 *
7799
 * @see url.h for an alternative representation using separate strings
7800
 */
7801
#ifndef ADA_URL_AGGREGATOR_H
7802
#define ADA_URL_AGGREGATOR_H
7803
7804
#include <ostream>
7805
#include <string>
7806
#include <string_view>
7807
#include <variant>
7808
7809
7810
namespace ada {
7811
7812
namespace parser {}
7813
7814
/**
7815
 * @brief Memory-efficient URL representation using a single buffer.
7816
 *
7817
 * The `url_aggregator` stores the entire normalized URL in a single string
7818
 * buffer and tracks component boundaries using offsets. This design minimizes
7819
 * memory allocations and is ideal for read-mostly access patterns.
7820
 *
7821
 * Getter methods return `std::string_view` pointing into the internal buffer.
7822
 * These views are lightweight (no allocation) but become invalid if the
7823
 * url_aggregator is modified or destroyed.
7824
 *
7825
 * @warning Views returned by getters (e.g., `get_pathname()`) are invalidated
7826
 * when any setter is called. Do not use a getter's result as input to a
7827
 * setter on the same object without copying first.
7828
 *
7829
 * @note This is the default URL type returned by `ada::parse()`.
7830
 *
7831
 * @see url For an alternative using separate std::string instances
7832
 */
7833
struct url_aggregator : url_base {
7834
3.47M
  url_aggregator() = default;
7835
247k
  url_aggregator(const url_aggregator& u) = default;
7836
2.02M
  url_aggregator(url_aggregator&& u) noexcept = default;
7837
302k
  url_aggregator& operator=(url_aggregator&& u) noexcept = default;
7838
270k
  url_aggregator& operator=(const url_aggregator& u) = default;
7839
5.74M
  ~url_aggregator() override = default;
7840
7841
  /**
7842
   * The setter functions follow the steps defined in the URL Standard.
7843
   *
7844
   * The url_aggregator has a single buffer that contains the entire normalized
7845
   * URL. The various components are represented as offsets into that buffer.
7846
   * When you call get_pathname(), for example, you get a std::string_view that
7847
   * points into that buffer. If the url_aggregator is modified, the buffer may
7848
   * be reallocated, and the std::string_view you obtained earlier may become
7849
   * invalid. In particular, this implies that you cannot modify the URL using
7850
   * a setter function with a std::string_view that points into the
7851
   * url_aggregator E.g., the following is incorrect:
7852
   * url->set_hostname(url->get_pathname()).
7853
   * You must first copy the pathname to a separate string.
7854
   * std::string pathname(url->get_pathname());
7855
   * url->set_hostname(pathname);
7856
   *
7857
   * The caller is responsible for ensuring that the url_aggregator is not
7858
   * modified while any std::string_view obtained from it is in use.
7859
   */
7860
  bool set_href(std::string_view input);
7861
  bool set_host(std::string_view input);
7862
  bool set_hostname(std::string_view input);
7863
  bool set_protocol(std::string_view input);
7864
  bool set_username(std::string_view input);
7865
  bool set_password(std::string_view input);
7866
  bool set_port(std::string_view input);
7867
  bool set_pathname(std::string_view input);
7868
  void set_search(std::string_view input);
7869
  void set_hash(std::string_view input);
7870
7871
  /**
7872
   * Validates whether the hostname is a valid domain according to RFC 1034.
7873
   * @return `true` if the domain is valid, `false` otherwise.
7874
   */
7875
  [[nodiscard]] bool has_valid_domain() const noexcept override;
7876
7877
  /**
7878
   * Returns the URL's origin (scheme + host + port for special URLs).
7879
   * @return A newly allocated string containing the serialized origin.
7880
   * @see https://url.spec.whatwg.org/#concept-url-origin
7881
   */
7882
  [[nodiscard]] std::string get_origin() const override;
7883
7884
  /**
7885
   * Returns the full serialized URL (the href) as a string_view.
7886
   * Does not allocate memory. The returned view becomes invalid if this
7887
   * url_aggregator is modified or destroyed.
7888
   * @return A string_view into the internal buffer.
7889
   * @see https://url.spec.whatwg.org/#dom-url-href
7890
   */
7891
  [[nodiscard]] constexpr std::string_view get_href() const noexcept
7892
      ada_lifetime_bound;
7893
7894
  /**
7895
   * Returns the byte length of the serialized URL without allocating a string.
7896
   * @return Size of the href in bytes.
7897
   */
7898
  [[nodiscard]] constexpr size_t get_href_size() const noexcept;
7899
7900
  /**
7901
   * Returns the URL's username component.
7902
   * Does not allocate memory. The returned view becomes invalid if this
7903
   * url_aggregator is modified or destroyed.
7904
   * @return A string_view of the username.
7905
   * @see https://url.spec.whatwg.org/#dom-url-username
7906
   */
7907
  [[nodiscard]] std::string_view get_username() const ada_lifetime_bound;
7908
7909
  /**
7910
   * Returns the URL's password component.
7911
   * Does not allocate memory. The returned view becomes invalid if this
7912
   * url_aggregator is modified or destroyed.
7913
   * @return A string_view of the password.
7914
   * @see https://url.spec.whatwg.org/#dom-url-password
7915
   */
7916
  [[nodiscard]] std::string_view get_password() const ada_lifetime_bound;
7917
7918
  /**
7919
   * Returns the URL's port as a string (e.g., "8080").
7920
   * Does not allocate memory. Returns empty view if no port is set.
7921
   * The returned view becomes invalid if this url_aggregator is modified.
7922
   * @return A string_view of the port.
7923
   * @see https://url.spec.whatwg.org/#dom-url-port
7924
   */
7925
  [[nodiscard]] std::string_view get_port() const ada_lifetime_bound;
7926
7927
  /**
7928
   * Returns the URL's fragment prefixed with '#' (e.g., "#section").
7929
   * Does not allocate memory. Returns empty view if no fragment is set.
7930
   * The returned view becomes invalid if this url_aggregator is modified.
7931
   * @return A string_view of the hash.
7932
   * @see https://url.spec.whatwg.org/#dom-url-hash
7933
   */
7934
  [[nodiscard]] std::string_view get_hash() const ada_lifetime_bound;
7935
7936
  /**
7937
   * Returns the URL's host and port (e.g., "example.com:8080").
7938
   * Does not allocate memory. Returns empty view if no host is set.
7939
   * The returned view becomes invalid if this url_aggregator is modified.
7940
   * @return A string_view of host:port.
7941
   * @see https://url.spec.whatwg.org/#dom-url-host
7942
   */
7943
  [[nodiscard]] std::string_view get_host() const ada_lifetime_bound;
7944
7945
  /**
7946
   * Returns the URL's hostname (without port).
7947
   * Does not allocate memory. Returns empty view if no host is set.
7948
   * The returned view becomes invalid if this url_aggregator is modified.
7949
   * @return A string_view of the hostname.
7950
   * @see https://url.spec.whatwg.org/#dom-url-hostname
7951
   */
7952
  [[nodiscard]] std::string_view get_hostname() const ada_lifetime_bound;
7953
7954
  /**
7955
   * Returns the URL's path component.
7956
   * Does not allocate memory. The returned view becomes invalid if this
7957
   * url_aggregator is modified or destroyed.
7958
   * @return A string_view of the pathname.
7959
   * @see https://url.spec.whatwg.org/#dom-url-pathname
7960
   */
7961
  [[nodiscard]] constexpr std::string_view get_pathname() const
7962
      ada_lifetime_bound;
7963
7964
  /**
7965
   * Returns the byte length of the pathname without creating a string.
7966
   * @return Size of the pathname in bytes.
7967
   * @see https://url.spec.whatwg.org/#dom-url-pathname
7968
   */
7969
  [[nodiscard]] ada_really_inline uint32_t get_pathname_length() const noexcept;
7970
7971
  /**
7972
   * Returns the URL's query string prefixed with '?' (e.g., "?foo=bar").
7973
   * Does not allocate memory. Returns empty view if no query is set.
7974
   * The returned view becomes invalid if this url_aggregator is modified.
7975
   * @return A string_view of the search/query.
7976
   * @see https://url.spec.whatwg.org/#dom-url-search
7977
   */
7978
  [[nodiscard]] std::string_view get_search() const ada_lifetime_bound;
7979
7980
  /**
7981
   * Returns the URL's scheme followed by a colon (e.g., "https:").
7982
   * Does not allocate memory. The returned view becomes invalid if this
7983
   * url_aggregator is modified or destroyed.
7984
   * @return A string_view of the protocol.
7985
   * @see https://url.spec.whatwg.org/#dom-url-protocol
7986
   */
7987
  [[nodiscard]] std::string_view get_protocol() const ada_lifetime_bound;
7988
7989
  /**
7990
   * Checks if the URL has credentials (non-empty username or password).
7991
   * @return `true` if username or password is non-empty, `false` otherwise.
7992
   */
7993
  [[nodiscard]] ada_really_inline constexpr bool has_credentials()
7994
      const noexcept;
7995
7996
  /**
7997
   * Returns the URL component offsets for efficient serialization.
7998
   *
7999
   * The components represent byte offsets into the serialized URL:
8000
   * ```
8001
   * https://user:pass@example.com:1234/foo/bar?baz#quux
8002
   *       |     |    |          | ^^^^|       |   |
8003
   *       |     |    |          | |   |       |   `----- hash_start
8004
   *       |     |    |          | |   |       `--------- search_start
8005
   *       |     |    |          | |   `----------------- pathname_start
8006
   *       |     |    |          | `--------------------- port
8007
   *       |     |    |          `----------------------- host_end
8008
   *       |     |    `---------------------------------- host_start
8009
   *       |     `--------------------------------------- username_end
8010
   *       `--------------------------------------------- protocol_end
8011
   * ```
8012
   * @return A constant reference to the url_components struct.
8013
   * @see https://github.com/servo/rust-url
8014
   */
8015
  [[nodiscard]] ada_really_inline const url_components& get_components()
8016
      const noexcept;
8017
8018
  /**
8019
   * Returns a JSON string representation of this URL for debugging.
8020
   * @return A JSON-formatted string with all URL components.
8021
   */
8022
  [[nodiscard]] std::string to_string() const override;
8023
8024
  /**
8025
   * Returns a visual diagram showing component boundaries in the URL.
8026
   * Useful for debugging and understanding URL structure.
8027
   * @return A multi-line string diagram.
8028
   */
8029
  [[nodiscard]] std::string to_diagram() const;
8030
8031
  /**
8032
   * Validates internal consistency of component offsets (for debugging).
8033
   * @return `true` if offsets are consistent, `false` if corrupted.
8034
   */
8035
  [[nodiscard]] constexpr bool validate() const noexcept;
8036
8037
  /**
8038
   * Checks if the URL has an empty hostname (host is set but empty string).
8039
   * @return `true` if host exists but is empty, `false` otherwise.
8040
   */
8041
  [[nodiscard]] constexpr bool has_empty_hostname() const noexcept;
8042
8043
  /**
8044
   * Checks if the URL has a hostname (including empty hostnames).
8045
   * @return `true` if host is present, `false` otherwise.
8046
   */
8047
  [[nodiscard]] constexpr bool has_hostname() const noexcept;
8048
8049
  /**
8050
   * Checks if the URL has a non-empty username.
8051
   * @return `true` if username is non-empty, `false` otherwise.
8052
   */
8053
  [[nodiscard]] constexpr bool has_non_empty_username() const noexcept;
8054
8055
  /**
8056
   * Checks if the URL has a non-empty password.
8057
   * @return `true` if password is non-empty, `false` otherwise.
8058
   */
8059
  [[nodiscard]] constexpr bool has_non_empty_password() const noexcept;
8060
8061
  /**
8062
   * Checks if the URL has a non-default port explicitly specified.
8063
   * @return `true` if a port is present, `false` otherwise.
8064
   */
8065
  [[nodiscard]] constexpr bool has_port() const noexcept;
8066
8067
  /**
8068
   * Checks if the URL has a password component (may be empty).
8069
   * @return `true` if password is present, `false` otherwise.
8070
   */
8071
  [[nodiscard]] constexpr bool has_password() const noexcept;
8072
8073
  /**
8074
   * Checks if the URL has a fragment/hash component.
8075
   * @return `true` if hash is present, `false` otherwise.
8076
   */
8077
  [[nodiscard]] constexpr bool has_hash() const noexcept override;
8078
8079
  /**
8080
   * Checks if the URL has a query/search component.
8081
   * @return `true` if query is present, `false` otherwise.
8082
   */
8083
  [[nodiscard]] constexpr bool has_search() const noexcept override;
8084
8085
  /**
8086
   * Removes the port from the URL.
8087
   */
8088
  inline void clear_port();
8089
8090
  /**
8091
   * Removes the hash/fragment from the URL.
8092
   */
8093
  inline void clear_hash();
8094
8095
  /**
8096
   * Removes the query/search string from the URL.
8097
   */
8098
  inline void clear_search() override;
8099
8100
 private:
8101
  // helper methods
8102
  friend void helpers::strip_trailing_spaces_from_opaque_path<url_aggregator>(
8103
      url_aggregator& url);
8104
  // parse_url methods
8105
  friend url_aggregator parser::parse_url<url_aggregator>(
8106
      std::string_view, const url_aggregator*);
8107
8108
  friend url_aggregator parser::parse_url_impl<url_aggregator, true>(
8109
      std::string_view, const url_aggregator*);
8110
  friend url_aggregator parser::parse_url_impl<url_aggregator, false>(
8111
      std::string_view, const url_aggregator*);
8112
  template <class result_type>
8113
  friend bool parser::try_parse_simple_absolute(std::string_view, result_type&);
8114
  template <class result_type>
8115
  friend bool parser::finish_simple_absolute_with_port(std::string_view,
8116
                                                       result_type&,
8117
                                                       ada::scheme::type,
8118
                                                       uint32_t, size_t, size_t,
8119
                                                       size_t, bool);
8120
  template <class result_type>
8121
  friend bool parser::try_parse_simple_relative(std::string_view,
8122
                                                const result_type&,
8123
                                                result_type&);
8124
8125
#if ADA_INCLUDE_URL_PATTERN
8126
  // url_pattern methods
8127
  template <url_pattern_regex::regex_concept regex_provider>
8128
  friend tl::expected<url_pattern<regex_provider>, errors>
8129
  parse_url_pattern_impl(
8130
      std::variant<std::string_view, url_pattern_init>&& input,
8131
      const std::string_view* base_url, const url_pattern_options* options);
8132
#endif  // ADA_INCLUDE_URL_PATTERN
8133
8134
  // components is declared before buffer so that the offset fields land
8135
  // close to url_base in memory, improving cache locality for getter calls.
8136
  // Note: exact cache-line placement is implementation- and platform-dependent.
8137
  url_components components{};
8138
  std::string buffer{};
8139
8140
  /**
8141
   * Returns true if neither the search, nor the hash nor the pathname
8142
   * have been set.
8143
   * @return true if the buffer is ready to receive the path.
8144
   */
8145
  [[nodiscard]] ada_really_inline bool is_at_path() const noexcept;
8146
8147
  inline void add_authority_slashes_if_needed();
8148
8149
  /**
8150
   * To optimize performance, you may indicate how much memory to allocate
8151
   * within this instance.
8152
   */
8153
  constexpr void reserve(uint32_t capacity);
8154
8155
  ada_really_inline size_t parse_port(std::string_view view,
8156
                                      bool check_trailing_content) override;
8157
8158
3.52k
  ada_really_inline size_t parse_port(std::string_view view) override {
8159
3.52k
    return this->parse_port(view, false);
8160
3.52k
  }
8161
8162
  /**
8163
   * Return true on success. The 'in_place' parameter indicates whether the
8164
   * the string_view input is pointing in the buffer. When in_place is false,
8165
   * we must nearly always update the buffer.
8166
   * @see https://url.spec.whatwg.org/#concept-ipv4-parser
8167
   */
8168
  [[nodiscard]] bool parse_ipv4(std::string_view input, bool in_place);
8169
8170
  /**
8171
   * Return true on success.
8172
   * @see https://url.spec.whatwg.org/#concept-ipv6-parser
8173
   */
8174
  [[nodiscard]] bool parse_ipv6(std::string_view input);
8175
8176
  /**
8177
   * Return true on success.
8178
   * @see https://url.spec.whatwg.org/#concept-opaque-host-parser
8179
   */
8180
  [[nodiscard]] bool parse_opaque_host(std::string_view input);
8181
8182
  ada_really_inline void parse_path(std::string_view input);
8183
8184
  /**
8185
   * A URL cannot have a username/password/port if its host is null or the empty
8186
   * string, or its scheme is "file".
8187
   */
8188
  [[nodiscard]] constexpr bool cannot_have_credentials_or_port() const;
8189
8190
  /**
8191
   * @private
8192
   * Several setters restore a saved copy of the URL when the mutation pushes
8193
   * the buffer past get_max_input_length(). A setter grows the buffer by at
8194
   * most input_len * 3 (worst-case percent-encoding) plus a small constant for
8195
   * delimiters, so this returns false when that upper bound stays within the
8196
   * limit. It does not account for parse-failure rollbacks, which are
8197
   * unrelated to the length limit.
8198
   */
8199
  [[nodiscard]] bool needs_rollback_snapshot(size_t input_len) const noexcept;
8200
8201
  template <bool override_hostname = false>
8202
  bool set_host_or_hostname(std::string_view input);
8203
8204
  ada_really_inline bool parse_host(std::string_view input);
8205
8206
  inline void update_base_authority(std::string_view base_buffer,
8207
                                    const url_components& base);
8208
  inline void update_unencoded_base_hash(std::string_view input);
8209
  inline void update_base_hostname(std::string_view input);
8210
  inline void update_base_search(std::string_view input);
8211
  inline void update_base_search(std::string_view input,
8212
                                 const uint8_t* query_percent_encode_set);
8213
  inline void update_base_pathname(std::string_view input);
8214
  inline void update_base_username(std::string_view input);
8215
  inline void append_base_username(std::string_view input);
8216
  inline void update_base_password(std::string_view input);
8217
  inline void append_base_password(std::string_view input);
8218
  inline void update_base_port(uint32_t input);
8219
  inline void append_base_pathname(std::string_view input);
8220
  [[nodiscard]] inline uint32_t retrieve_base_port() const;
8221
  constexpr void clear_hostname();
8222
  constexpr void clear_password();
8223
  constexpr void clear_pathname() override;
8224
  [[nodiscard]] constexpr bool has_dash_dot() const noexcept;
8225
  void delete_dash_dot();
8226
  inline void consume_prepared_path(std::string_view input);
8227
  template <bool has_state_override = false>
8228
  [[nodiscard]] ada_really_inline bool parse_scheme_with_colon(
8229
      std::string_view input);
8230
  ada_really_inline uint32_t replace_and_resize(uint32_t start, uint32_t end,
8231
                                                std::string_view input);
8232
  [[nodiscard]] constexpr bool has_authority() const noexcept;
8233
  constexpr void set_protocol_as_file();
8234
  inline void set_scheme(std::string_view new_scheme);
8235
  /**
8236
   * Fast function to set the scheme from a view with a colon in the
8237
   * buffer, does not change type.
8238
   */
8239
  inline void set_scheme_from_view_with_colon(
8240
      std::string_view new_scheme_with_colon);
8241
  inline void copy_scheme(const url_aggregator& u);
8242
8243
  inline void update_host_to_base_host(const std::string_view input);
8244
8245
};  // url_aggregator
8246
8247
inline std::ostream& operator<<(std::ostream& out, const url& u);
8248
}  // namespace ada
8249
8250
#endif
8251
/* end file include/ada/url_aggregator.h */
8252
/* begin file include/ada/url_aggregator-inl.h */
8253
/**
8254
 * @file url_aggregator-inl.h
8255
 * @brief Inline functions for url aggregator
8256
 */
8257
#ifndef ADA_URL_AGGREGATOR_INL_H
8258
#define ADA_URL_AGGREGATOR_INL_H
8259
8260
/* begin file include/ada/unicode-inl.h */
8261
/**
8262
 * @file unicode-inl.h
8263
 * @brief Definitions for unicode operations.
8264
 */
8265
#ifndef ADA_UNICODE_INL_H
8266
#define ADA_UNICODE_INL_H
8267
8268
/**
8269
 * Unicode operations. These functions are not part of our public API and may
8270
 * change at any time.
8271
 *
8272
 * private
8273
 * @namespace ada::unicode
8274
 * @brief Includes the declarations for unicode operations
8275
 */
8276
namespace ada::unicode {
8277
ada_really_inline size_t percent_encode_index(const std::string_view input,
8278
585k
                                              const uint8_t character_set[]) {
8279
585k
  const char* data = input.data();
8280
585k
  const size_t size = input.size();
8281
8282
  // Process 8 bytes at a time using unrolled loop
8283
585k
  size_t i = 0;
8284
1.05M
  for (; i + 8 <= size; i += 8) {
8285
492k
    unsigned char chunk[8];
8286
492k
    std::memcpy(&chunk, data + i,
8287
492k
                8);  // entices compiler to unconditionally process 8 characters
8288
8289
    // Check 8 characters at once
8290
4.28M
    for (size_t j = 0; j < 8; j++) {
8291
3.82M
      if (character_sets::bit_at(character_set, chunk[j])) {
8292
24.6k
        return i + j;
8293
24.6k
      }
8294
3.82M
    }
8295
492k
  }
8296
8297
  // Handle remaining bytes
8298
698k
  for (; i < size; i++) {
8299
151k
    if (character_sets::bit_at(character_set, data[i])) {
8300
15.2k
      return i;
8301
15.2k
    }
8302
151k
  }
8303
8304
546k
  return size;
8305
561k
}
8306
}  // namespace ada::unicode
8307
8308
#endif  // ADA_UNICODE_INL_H
8309
/* end file include/ada/unicode-inl.h */
8310
8311
#include <charconv>
8312
#include <cstring>
8313
#include <ostream>
8314
#include <string_view>
8315
8316
namespace ada {
8317
8318
inline void url_aggregator::update_base_authority(
8319
16.2k
    std::string_view base_buffer, const ada::url_components& base) {
8320
16.2k
  std::string_view input = base_buffer.substr(
8321
16.2k
      base.protocol_end, base.host_start - base.protocol_end);
8322
16.2k
  ada_log("url_aggregator::update_base_authority ", input);
8323
8324
16.2k
  bool input_starts_with_dash = input.starts_with("//");
8325
16.2k
  uint32_t diff = components.host_start - components.protocol_end;
8326
8327
16.2k
  buffer.erase(components.protocol_end,
8328
16.2k
               components.host_start - components.protocol_end);
8329
16.2k
  components.username_end = components.protocol_end;
8330
8331
16.2k
  if (input_starts_with_dash) {
8332
14.9k
    input.remove_prefix(2);
8333
14.9k
    diff += 2;  // add "//"
8334
14.9k
    buffer.insert(components.protocol_end, "//");
8335
14.9k
    components.username_end += 2;
8336
14.9k
  }
8337
8338
16.2k
  size_t password_delimiter = input.find(':');
8339
8340
  // Check if input contains both username and password by checking the
8341
  // delimiter: ":" A typical input that contains authority would be "user:pass"
8342
16.2k
  if (password_delimiter != std::string_view::npos) {
8343
    // Insert both username and password
8344
191
    std::string_view username = input.substr(0, password_delimiter);
8345
191
    std::string_view password = input.substr(password_delimiter + 1);
8346
8347
191
    buffer.insert(components.protocol_end + diff, username);
8348
191
    diff += uint32_t(username.size());
8349
191
    buffer.insert(components.protocol_end + diff, ":");
8350
191
    components.username_end = components.protocol_end + diff;
8351
191
    buffer.insert(components.protocol_end + diff + 1, password);
8352
191
    diff += uint32_t(password.size()) + 1;
8353
16.0k
  } else if (!input.empty()) {
8354
    // Insert only username
8355
209
    buffer.insert(components.protocol_end + diff, input);
8356
209
    components.username_end =
8357
209
        components.protocol_end + diff + uint32_t(input.size());
8358
209
    diff += uint32_t(input.size());
8359
209
  }
8360
8361
16.2k
  components.host_start += diff;
8362
8363
16.2k
  if (buffer.size() > base.host_start && buffer[base.host_start] != '@') {
8364
0
    buffer.insert(components.host_start, "@");
8365
0
    diff++;
8366
0
  }
8367
16.2k
  components.host_end += diff;
8368
16.2k
  components.pathname_start += diff;
8369
16.2k
  if (components.search_start != url_components::omitted) {
8370
0
    components.search_start += diff;
8371
0
  }
8372
16.2k
  if (components.hash_start != url_components::omitted) {
8373
0
    components.hash_start += diff;
8374
0
  }
8375
16.2k
}
8376
8377
166k
inline void url_aggregator::update_unencoded_base_hash(std::string_view input) {
8378
166k
  ada_log("url_aggregator::update_unencoded_base_hash ", input, " [",
8379
166k
          input.size(), " bytes], buffer is '", buffer, "' [", buffer.size(),
8380
166k
          " bytes] components.hash_start = ", components.hash_start);
8381
166k
  ADA_ASSERT_TRUE(validate());
8382
166k
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
8383
166k
  if (components.hash_start != url_components::omitted) {
8384
14.9k
    buffer.resize(components.hash_start);
8385
14.9k
  }
8386
166k
  components.hash_start = uint32_t(buffer.size());
8387
166k
  buffer += "#";
8388
166k
  bool encoding_required = unicode::percent_encode<true>(
8389
166k
      input, ada::character_sets::FRAGMENT_PERCENT_ENCODE, buffer);
8390
  // When encoding_required is false, then buffer is left unchanged, and percent
8391
  // encoding was not deemed required.
8392
166k
  if (!encoding_required) {
8393
145k
    buffer.append(input);
8394
145k
  }
8395
166k
  ada_log("url_aggregator::update_unencoded_base_hash final buffer is '",
8396
166k
          buffer, "' [", buffer.size(), " bytes]");
8397
166k
  ADA_ASSERT_TRUE(validate());
8398
166k
}
8399
8400
ada_really_inline uint32_t url_aggregator::replace_and_resize(
8401
2.06M
    uint32_t start, uint32_t end, std::string_view input) {
8402
2.06M
  uint32_t current_length = end - start;
8403
2.06M
  uint32_t input_size = uint32_t(input.size());
8404
2.06M
  uint32_t new_difference = input_size - current_length;
8405
8406
2.06M
  if (current_length == 0) {
8407
1.65M
    buffer.insert(start, input);
8408
1.65M
  } else if (input_size == current_length) {
8409
105k
    if (input_size != 0) {
8410
105k
      std::memmove(buffer.data() + start, input.data(), input_size);
8411
105k
    }
8412
311k
  } else if (input_size < current_length) {
8413
148k
    buffer.erase(start, current_length - input_size);
8414
148k
    buffer.replace(start, input_size, input);
8415
163k
  } else {
8416
163k
    buffer.replace(start, current_length, input.substr(0, current_length));
8417
163k
    buffer.insert(start + current_length, input.substr(current_length));
8418
163k
  }
8419
8420
2.06M
  return new_difference;
8421
2.06M
}
8422
8423
1.49M
inline void url_aggregator::update_base_hostname(const std::string_view input) {
8424
1.49M
  ada_log("url_aggregator::update_base_hostname ", input, " [", input.size(),
8425
1.49M
          " bytes], buffer is '", buffer, "' [", buffer.size(), " bytes]");
8426
1.49M
  ADA_ASSERT_TRUE(validate());
8427
1.49M
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
8428
8429
  // This next line is required for when parsing a URL like `foo://`
8430
1.49M
  add_authority_slashes_if_needed();
8431
8432
1.49M
  bool has_credentials = components.protocol_end + 2 < components.host_start;
8433
1.49M
  uint32_t new_difference =
8434
1.49M
      replace_and_resize(components.host_start, components.host_end, input);
8435
8436
1.49M
  if (has_credentials) {
8437
199k
    buffer.insert(components.host_start, "@");
8438
199k
    new_difference++;
8439
199k
  }
8440
1.49M
  components.host_end += new_difference;
8441
1.49M
  components.pathname_start += new_difference;
8442
1.49M
  if (components.search_start != url_components::omitted) {
8443
34.5k
    components.search_start += new_difference;
8444
34.5k
  }
8445
1.49M
  if (components.hash_start != url_components::omitted) {
8446
34.2k
    components.hash_start += new_difference;
8447
34.2k
  }
8448
1.49M
  ADA_ASSERT_TRUE(validate());
8449
1.49M
}
8450
8451
[[nodiscard]] ada_really_inline uint32_t
8452
524k
url_aggregator::get_pathname_length() const noexcept {
8453
524k
  ada_log("url_aggregator::get_pathname_length");
8454
524k
  uint32_t ending_index = uint32_t(buffer.size());
8455
524k
  if (components.search_start != url_components::omitted) {
8456
38.9k
    ending_index = components.search_start;
8457
485k
  } else if (components.hash_start != url_components::omitted) {
8458
1.97k
    ending_index = components.hash_start;
8459
1.97k
  }
8460
524k
  return ending_index - components.pathname_start;
8461
524k
}
8462
8463
[[nodiscard]] ada_really_inline bool url_aggregator::is_at_path()
8464
840k
    const noexcept {
8465
840k
  return buffer.size() == components.pathname_start;
8466
840k
}
8467
8468
9.36k
inline void url_aggregator::update_base_search(std::string_view input) {
8469
9.36k
  ada_log("url_aggregator::update_base_search ", input);
8470
9.36k
  ADA_ASSERT_TRUE(validate());
8471
9.36k
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
8472
9.36k
  if (input.empty()) {
8473
0
    clear_search();
8474
0
    return;
8475
0
  }
8476
8477
9.36k
  if (input[0] == '?') {
8478
9.36k
    input.remove_prefix(1);
8479
9.36k
  }
8480
8481
9.36k
  if (components.hash_start == url_components::omitted) {
8482
9.36k
    if (components.search_start == url_components::omitted) {
8483
9.36k
      components.search_start = uint32_t(buffer.size());
8484
9.36k
      buffer += "?";
8485
9.36k
    } else {
8486
0
      buffer.resize(components.search_start + 1);
8487
0
    }
8488
8489
9.36k
    buffer.append(input);
8490
9.36k
  } else if (components.search_start != url_components::omitted) {
8491
0
    const uint32_t difference = replace_and_resize(
8492
0
        components.search_start + 1, components.hash_start, input);
8493
0
    components.hash_start += difference;
8494
0
  } else {
8495
0
    components.search_start = components.hash_start;
8496
0
    buffer.insert(components.search_start, input.size() + 1, '?');
8497
0
    if (!input.empty()) {
8498
0
      std::memmove(buffer.data() + components.search_start + 1, input.data(),
8499
0
                   input.size());
8500
0
    }
8501
0
    components.hash_start += uint32_t(input.size() + 1);  // Do not forget `?`
8502
0
  }
8503
8504
9.36k
  ADA_ASSERT_TRUE(validate());
8505
9.36k
}
8506
8507
inline void url_aggregator::update_base_search(
8508
200k
    std::string_view input, const uint8_t query_percent_encode_set[]) {
8509
200k
  ada_log("url_aggregator::update_base_search ", input,
8510
200k
          " with encoding parameter ", to_string(), "\n", to_diagram());
8511
200k
  ADA_ASSERT_TRUE(validate());
8512
200k
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
8513
8514
200k
  if (components.hash_start == url_components::omitted) {
8515
184k
    if (components.search_start == url_components::omitted) {
8516
162k
      components.search_start = uint32_t(buffer.size());
8517
162k
      buffer += "?";
8518
162k
    } else {
8519
21.8k
      buffer.resize(components.search_start + 1);
8520
21.8k
    }
8521
8522
184k
    bool encoding_required =
8523
184k
        unicode::percent_encode<true>(input, query_percent_encode_set, buffer);
8524
    // When encoding_required is false, then buffer is left unchanged, and
8525
    // percent encoding was not deemed required.
8526
184k
    if (!encoding_required) {
8527
153k
      buffer.append(input);
8528
153k
    }
8529
184k
  } else {
8530
16.0k
    const size_t idx =
8531
16.0k
        ada::unicode::percent_encode_index(input, query_percent_encode_set);
8532
16.0k
    std::string encoded;
8533
16.0k
    std::string_view replacement = input;
8534
16.0k
    if (idx != input.size()) {
8535
537
      encoded =
8536
537
          ada::unicode::percent_encode(input, query_percent_encode_set, idx);
8537
537
      replacement = encoded;
8538
537
    }
8539
8540
16.0k
    if (components.search_start != url_components::omitted) {
8541
15.2k
      const uint32_t difference = replace_and_resize(
8542
15.2k
          components.search_start + 1, components.hash_start, replacement);
8543
15.2k
      components.hash_start += difference;
8544
15.2k
    } else {
8545
834
      components.search_start = components.hash_start;
8546
834
      buffer.insert(components.search_start, replacement.size() + 1, '?');
8547
834
      if (!replacement.empty()) {
8548
814
        std::memmove(buffer.data() + components.search_start + 1,
8549
814
                     replacement.data(), replacement.size());
8550
814
      }
8551
834
      components.hash_start +=
8552
834
          uint32_t(replacement.size() + 1);  // Do not forget `?`
8553
834
    }
8554
16.0k
  }
8555
8556
200k
  ADA_ASSERT_TRUE(validate());
8557
200k
}
8558
8559
474k
inline void url_aggregator::update_base_pathname(const std::string_view input) {
8560
474k
  ada_log("url_aggregator::update_base_pathname '", input, "' [", input.size(),
8561
474k
          " bytes] \n", to_diagram());
8562
474k
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
8563
474k
  ADA_ASSERT_TRUE(validate());
8564
8565
474k
  const bool begins_with_dashdash = input.starts_with("//");
8566
474k
  if (!begins_with_dashdash && has_dash_dot()) {
8567
    // We must delete the ./
8568
54
    delete_dash_dot();
8569
54
  }
8570
8571
474k
  if (begins_with_dashdash && !has_opaque_path && !has_authority() &&
8572
594
      !has_dash_dot()) {
8573
    // If url's host is null, url does not have an opaque path, url's path's
8574
    // size is greater than 1, then append U+002F (/) followed by U+002E (.) to
8575
    // output.
8576
530
    buffer.insert(components.pathname_start, "/.");
8577
530
    components.pathname_start += 2;
8578
530
    if (components.search_start != url_components::omitted) {
8579
14
      components.search_start += 2;
8580
14
    }
8581
530
    if (components.hash_start != url_components::omitted) {
8582
9
      components.hash_start += 2;
8583
9
    }
8584
530
  }
8585
8586
474k
  uint32_t difference = replace_and_resize(
8587
474k
      components.pathname_start,
8588
474k
      components.pathname_start + get_pathname_length(), input);
8589
474k
  if (components.search_start != url_components::omitted) {
8590
16.7k
    components.search_start += difference;
8591
16.7k
  }
8592
474k
  if (components.hash_start != url_components::omitted) {
8593
16.5k
    components.hash_start += difference;
8594
16.5k
  }
8595
474k
  ADA_ASSERT_TRUE(validate());
8596
474k
}
8597
8598
33
inline void url_aggregator::append_base_pathname(const std::string_view input) {
8599
33
  ada_log("url_aggregator::append_base_pathname ", input, " ", to_string(),
8600
33
          "\n", to_diagram());
8601
33
  ADA_ASSERT_TRUE(validate());
8602
33
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
8603
#if ADA_DEVELOPMENT_CHECKS
8604
  // computing the expected password.
8605
  std::string path_expected(get_pathname());
8606
  path_expected.append(input);
8607
#endif  // ADA_DEVELOPMENT_CHECKS
8608
33
  uint32_t ending_index = uint32_t(buffer.size());
8609
33
  if (components.search_start != url_components::omitted) {
8610
0
    ending_index = components.search_start;
8611
33
  } else if (components.hash_start != url_components::omitted) {
8612
0
    ending_index = components.hash_start;
8613
0
  }
8614
33
  buffer.insert(ending_index, input);
8615
8616
33
  if (components.search_start != url_components::omitted) {
8617
0
    components.search_start += uint32_t(input.size());
8618
0
  }
8619
33
  if (components.hash_start != url_components::omitted) {
8620
0
    components.hash_start += uint32_t(input.size());
8621
0
  }
8622
#if ADA_DEVELOPMENT_CHECKS
8623
  std::string path_after = std::string(get_pathname());
8624
  ADA_ASSERT_EQUAL(
8625
      path_expected, path_after,
8626
      "append_base_pathname problem after inserting " + std::string(input));
8627
#endif  // ADA_DEVELOPMENT_CHECKS
8628
33
  ADA_ASSERT_TRUE(validate());
8629
33
}
8630
8631
73.5k
inline void url_aggregator::update_base_username(const std::string_view input) {
8632
73.5k
  ada_log("url_aggregator::update_base_username '", input, "' ", to_string(),
8633
73.5k
          "\n", to_diagram());
8634
73.5k
  ADA_ASSERT_TRUE(validate());
8635
73.5k
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
8636
8637
73.5k
  add_authority_slashes_if_needed();
8638
8639
73.5k
  bool has_password = has_non_empty_password();
8640
73.5k
  bool host_starts_with_at = buffer.size() > components.host_start &&
8641
73.5k
                             buffer[components.host_start] == '@';
8642
73.5k
  uint32_t diff = replace_and_resize(components.protocol_end + 2,
8643
73.5k
                                     components.username_end, input);
8644
8645
73.5k
  components.username_end += diff;
8646
73.5k
  components.host_start += diff;
8647
8648
73.5k
  if (!input.empty() && !host_starts_with_at) {
8649
46.7k
    buffer.insert(components.host_start, "@");
8650
46.7k
    diff++;
8651
46.7k
  } else if (input.empty() && host_starts_with_at && !has_password) {
8652
    // Input is empty, there is no password, and we need to remove "@" from
8653
    // hostname
8654
1.55k
    buffer.erase(components.host_start, 1);
8655
1.55k
    diff--;
8656
1.55k
  }
8657
8658
73.5k
  components.host_end += diff;
8659
73.5k
  components.pathname_start += diff;
8660
73.5k
  if (components.search_start != url_components::omitted) {
8661
16.8k
    components.search_start += diff;
8662
16.8k
  }
8663
73.5k
  if (components.hash_start != url_components::omitted) {
8664
16.6k
    components.hash_start += diff;
8665
16.6k
  }
8666
73.5k
  ADA_ASSERT_TRUE(validate());
8667
73.5k
}
8668
8669
292k
inline void url_aggregator::append_base_username(const std::string_view input) {
8670
292k
  ada_log("url_aggregator::append_base_username ", input);
8671
292k
  ADA_ASSERT_TRUE(validate());
8672
292k
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
8673
#if ADA_DEVELOPMENT_CHECKS
8674
  // computing the expected password.
8675
  std::string username_expected(get_username());
8676
  username_expected.append(input);
8677
#endif  // ADA_DEVELOPMENT_CHECKS
8678
292k
  add_authority_slashes_if_needed();
8679
8680
  // If input is empty, do nothing.
8681
292k
  if (input.empty()) {
8682
68.8k
    return;
8683
68.8k
  }
8684
8685
223k
  uint32_t difference = uint32_t(input.size());
8686
223k
  buffer.insert(components.username_end, input);
8687
223k
  components.username_end += difference;
8688
223k
  components.host_start += difference;
8689
8690
223k
  if (buffer[components.host_start] != '@' &&
8691
147k
      components.host_start != components.host_end) {
8692
147k
    buffer.insert(components.host_start, "@");
8693
147k
    difference++;
8694
147k
  }
8695
8696
223k
  components.host_end += difference;
8697
223k
  components.pathname_start += difference;
8698
223k
  if (components.search_start != url_components::omitted) {
8699
0
    components.search_start += difference;
8700
0
  }
8701
223k
  if (components.hash_start != url_components::omitted) {
8702
0
    components.hash_start += difference;
8703
0
  }
8704
#if ADA_DEVELOPMENT_CHECKS
8705
  std::string username_after(get_username());
8706
  ADA_ASSERT_EQUAL(
8707
      username_expected, username_after,
8708
      "append_base_username problem after inserting " + std::string(input));
8709
#endif  // ADA_DEVELOPMENT_CHECKS
8710
223k
  ADA_ASSERT_TRUE(validate());
8711
223k
}
8712
8713
7.06k
constexpr void url_aggregator::clear_password() {
8714
7.06k
  ada_log("url_aggregator::clear_password ", to_string());
8715
7.06k
  ADA_ASSERT_TRUE(validate());
8716
7.06k
  if (!has_password()) {
8717
5.41k
    return;
8718
5.41k
  }
8719
8720
1.65k
  uint32_t diff = components.host_start - components.username_end;
8721
1.65k
  buffer.erase(components.username_end, diff);
8722
1.65k
  components.host_start -= diff;
8723
1.65k
  components.host_end -= diff;
8724
1.65k
  components.pathname_start -= diff;
8725
1.65k
  if (components.search_start != url_components::omitted) {
8726
1.51k
    components.search_start -= diff;
8727
1.51k
  }
8728
1.65k
  if (components.hash_start != url_components::omitted) {
8729
1.50k
    components.hash_start -= diff;
8730
1.50k
  }
8731
1.65k
}
8732
8733
68.2k
inline void url_aggregator::update_base_password(const std::string_view input) {
8734
68.2k
  ada_log("url_aggregator::update_base_password ", input);
8735
68.2k
  ADA_ASSERT_TRUE(validate());
8736
68.2k
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
8737
8738
68.2k
  add_authority_slashes_if_needed();
8739
8740
  // TODO: Optimization opportunity. Merge the following removal functions.
8741
68.2k
  if (input.empty()) {
8742
7.06k
    clear_password();
8743
8744
    // Remove username too, if it is empty.
8745
7.06k
    if (!has_non_empty_username()) {
8746
5.53k
      update_base_username("");
8747
5.53k
    }
8748
8749
7.06k
    return;
8750
7.06k
  }
8751
8752
61.1k
  bool password_exists = has_password();
8753
61.1k
  uint32_t difference = uint32_t(input.size());
8754
8755
61.1k
  if (password_exists) {
8756
14.3k
    difference = replace_and_resize(components.username_end + 1,
8757
14.3k
                                    components.host_start, input);
8758
46.8k
  } else {
8759
46.8k
    buffer.insert(components.username_end, input.size() + 1, ':');
8760
46.8k
    std::memmove(buffer.data() + components.username_end + 1, input.data(),
8761
46.8k
                 input.size());
8762
46.8k
    difference++;
8763
46.8k
  }
8764
61.1k
  components.host_start += difference;
8765
8766
  // The following line is required to add "@" to hostname. When updating
8767
  // password if hostname does not start with "@", it is "update_base_password"s
8768
  // responsibility to set it.
8769
61.1k
  if (buffer[components.host_start] != '@') {
8770
15
    buffer.insert(components.host_start, "@");
8771
15
    difference++;
8772
15
  }
8773
8774
61.1k
  components.host_end += difference;
8775
61.1k
  components.pathname_start += difference;
8776
61.1k
  if (components.search_start != url_components::omitted) {
8777
14.8k
    components.search_start += difference;
8778
14.8k
  }
8779
61.1k
  if (components.hash_start != url_components::omitted) {
8780
14.7k
    components.hash_start += difference;
8781
14.7k
  }
8782
61.1k
  ADA_ASSERT_TRUE(validate());
8783
61.1k
}
8784
8785
199k
inline void url_aggregator::append_base_password(const std::string_view input) {
8786
199k
  ada_log("url_aggregator::append_base_password ", input, " ", to_string(),
8787
199k
          "\n", to_diagram());
8788
199k
  ADA_ASSERT_TRUE(validate());
8789
199k
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
8790
#if ADA_DEVELOPMENT_CHECKS
8791
  // computing the expected password.
8792
  std::string password_expected = std::string(get_password());
8793
  password_expected.append(input);
8794
#endif  // ADA_DEVELOPMENT_CHECKS
8795
199k
  add_authority_slashes_if_needed();
8796
8797
  // If input is empty, do nothing.
8798
199k
  if (input.empty()) {
8799
28.2k
    return;
8800
28.2k
  }
8801
8802
171k
  uint32_t difference = uint32_t(input.size());
8803
171k
  if (has_password()) {
8804
39.7k
    buffer.insert(components.host_start, input);
8805
131k
  } else {
8806
131k
    difference++;  // Increment for ":"
8807
131k
    buffer.insert(components.username_end, ":");
8808
131k
    buffer.insert(components.username_end + 1, input);
8809
131k
  }
8810
171k
  components.host_start += difference;
8811
8812
  // The following line is required to add "@" to hostname. When updating
8813
  // password if hostname does not start with "@", it is "append_base_password"s
8814
  // responsibility to set it.
8815
171k
  if (buffer[components.host_start] != '@') {
8816
7.42k
    buffer.insert(components.host_start, "@");
8817
7.42k
    difference++;
8818
7.42k
  }
8819
8820
171k
  components.host_end += difference;
8821
171k
  components.pathname_start += difference;
8822
171k
  if (components.search_start != url_components::omitted) {
8823
0
    components.search_start += difference;
8824
0
  }
8825
171k
  if (components.hash_start != url_components::omitted) {
8826
0
    components.hash_start += difference;
8827
0
  }
8828
#if ADA_DEVELOPMENT_CHECKS
8829
  std::string password_after(get_password());
8830
  ADA_ASSERT_EQUAL(
8831
      password_expected, password_after,
8832
      "append_base_password problem after inserting " + std::string(input));
8833
#endif  // ADA_DEVELOPMENT_CHECKS
8834
171k
  ADA_ASSERT_TRUE(validate());
8835
171k
}
8836
8837
96.8k
inline void url_aggregator::update_base_port(uint32_t input) {
8838
96.8k
  ada_log("url_aggregator::update_base_port");
8839
96.8k
  ADA_ASSERT_TRUE(validate());
8840
96.8k
  if (input == url_components::omitted) {
8841
16.0k
    clear_port();
8842
16.0k
    return;
8843
16.0k
  }
8844
  // calling std::to_string(input.value()) is unfortunate given that the port
8845
  // value is probably already available as a string.
8846
80.8k
  std::string value = helpers::concat(":", std::to_string(input));
8847
80.8k
  uint32_t difference = uint32_t(value.size());
8848
8849
80.8k
  if (components.port != url_components::omitted) {
8850
392
    difference -= components.pathname_start - components.host_end;
8851
392
    buffer.erase(components.host_end,
8852
392
                 components.pathname_start - components.host_end);
8853
392
  }
8854
8855
80.8k
  buffer.insert(components.host_end, value);
8856
80.8k
  components.pathname_start += difference;
8857
80.8k
  if (components.search_start != url_components::omitted) {
8858
1.44k
    components.search_start += difference;
8859
1.44k
  }
8860
80.8k
  if (components.hash_start != url_components::omitted) {
8861
1.43k
    components.hash_start += difference;
8862
1.43k
  }
8863
80.8k
  components.port = input;
8864
80.8k
  ADA_ASSERT_TRUE(validate());
8865
80.8k
}
8866
8867
135k
inline void url_aggregator::clear_port() {
8868
135k
  ada_log("url_aggregator::clear_port");
8869
135k
  ADA_ASSERT_TRUE(validate());
8870
135k
  if (components.port == url_components::omitted) {
8871
117k
    return;
8872
117k
  }
8873
18.2k
  uint32_t length = components.pathname_start - components.host_end;
8874
18.2k
  buffer.erase(components.host_end, length);
8875
18.2k
  components.pathname_start -= length;
8876
18.2k
  if (components.search_start != url_components::omitted) {
8877
18.0k
    components.search_start -= length;
8878
18.0k
  }
8879
18.2k
  if (components.hash_start != url_components::omitted) {
8880
18.0k
    components.hash_start -= length;
8881
18.0k
  }
8882
18.2k
  components.port = url_components::omitted;
8883
18.2k
  ADA_ASSERT_TRUE(validate());
8884
18.2k
}
8885
8886
16.2k
[[nodiscard]] inline uint32_t url_aggregator::retrieve_base_port() const {
8887
16.2k
  ada_log("url_aggregator::retrieve_base_port");
8888
16.2k
  return components.port;
8889
16.2k
}
8890
8891
102k
inline void url_aggregator::clear_search() {
8892
102k
  ada_log("url_aggregator::clear_search");
8893
102k
  ADA_ASSERT_TRUE(validate());
8894
102k
  if (components.search_start == url_components::omitted) {
8895
16.6k
    return;
8896
16.6k
  }
8897
8898
85.8k
  if (components.hash_start == url_components::omitted) {
8899
68.5k
    buffer.resize(components.search_start);
8900
68.5k
  } else {
8901
17.3k
    buffer.erase(components.search_start,
8902
17.3k
                 components.hash_start - components.search_start);
8903
17.3k
    components.hash_start = components.search_start;
8904
17.3k
  }
8905
8906
85.8k
  components.search_start = url_components::omitted;
8907
8908
#if ADA_DEVELOPMENT_CHECKS
8909
  ADA_ASSERT_EQUAL(get_search(), "",
8910
                   "search should have been cleared on buffer=" + buffer +
8911
                       " with " + components.to_string() + "\n" + to_diagram());
8912
#endif
8913
85.8k
  ADA_ASSERT_TRUE(validate());
8914
85.8k
}
8915
8916
85.9k
inline void url_aggregator::clear_hash() {
8917
85.9k
  ada_log("url_aggregator::clear_hash");
8918
85.9k
  ADA_ASSERT_TRUE(validate());
8919
85.9k
  if (components.hash_start == url_components::omitted) {
8920
7.07k
    return;
8921
7.07k
  }
8922
78.8k
  buffer.resize(components.hash_start);
8923
78.8k
  components.hash_start = url_components::omitted;
8924
8925
#if ADA_DEVELOPMENT_CHECKS
8926
  ADA_ASSERT_EQUAL(get_hash(), "",
8927
                   "hash should have been cleared on buffer=" + buffer +
8928
                       " with " + components.to_string() + "\n" + to_diagram());
8929
#endif
8930
78.8k
  ADA_ASSERT_TRUE(validate());
8931
78.8k
}
8932
8933
503k
constexpr void url_aggregator::clear_pathname() {
8934
503k
  ada_log("url_aggregator::clear_pathname");
8935
503k
  ADA_ASSERT_TRUE(validate());
8936
503k
  uint32_t ending_index = uint32_t(buffer.size());
8937
503k
  if (components.search_start != url_components::omitted) {
8938
16.7k
    ending_index = components.search_start;
8939
486k
  } else if (components.hash_start != url_components::omitted) {
8940
1.08k
    ending_index = components.hash_start;
8941
1.08k
  }
8942
503k
  uint32_t pathname_length = ending_index - components.pathname_start;
8943
503k
  buffer.erase(components.pathname_start, pathname_length);
8944
503k
  uint32_t difference = pathname_length;
8945
503k
  if (components.pathname_start == components.host_end + 2 &&
8946
1.30k
      buffer[components.host_end] == '/' &&
8947
5
      buffer[components.host_end + 1] == '.') {
8948
5
    components.pathname_start -= 2;
8949
5
    buffer.erase(components.host_end, 2);
8950
5
    difference += 2;
8951
5
  }
8952
503k
  if (components.search_start != url_components::omitted) {
8953
16.7k
    components.search_start -= difference;
8954
16.7k
  }
8955
503k
  if (components.hash_start != url_components::omitted) {
8956
16.5k
    components.hash_start -= difference;
8957
16.5k
  }
8958
503k
  ada_log("url_aggregator::clear_pathname completed, running checks...");
8959
#if ADA_DEVELOPMENT_CHECKS
8960
  ADA_ASSERT_EQUAL(get_pathname(), "",
8961
                   "pathname should have been cleared on buffer=" + buffer +
8962
                       " with " + components.to_string() + "\n" + to_diagram());
8963
#endif
8964
503k
  ADA_ASSERT_TRUE(validate());
8965
503k
  ada_log("url_aggregator::clear_pathname completed, running checks... ok");
8966
503k
}
8967
8968
1.21k
constexpr void url_aggregator::clear_hostname() {
8969
1.21k
  ada_log("url_aggregator::clear_hostname");
8970
1.21k
  ADA_ASSERT_TRUE(validate());
8971
1.21k
  if (!has_authority()) {
8972
0
    return;
8973
0
  }
8974
1.21k
  ADA_ASSERT_TRUE(has_authority());
8975
8976
1.21k
  uint32_t hostname_length = components.host_end - components.host_start;
8977
1.21k
  uint32_t start = components.host_start;
8978
8979
  // If hostname starts with "@", we should not remove that character.
8980
1.21k
  if (hostname_length > 0 && buffer[start] == '@') {
8981
0
    start++;
8982
0
    hostname_length--;
8983
0
  }
8984
1.21k
  buffer.erase(start, hostname_length);
8985
1.21k
  components.host_end = start;
8986
1.21k
  components.pathname_start -= hostname_length;
8987
1.21k
  if (components.search_start != url_components::omitted) {
8988
316
    components.search_start -= hostname_length;
8989
316
  }
8990
1.21k
  if (components.hash_start != url_components::omitted) {
8991
269
    components.hash_start -= hostname_length;
8992
269
  }
8993
#if ADA_DEVELOPMENT_CHECKS
8994
  ADA_ASSERT_EQUAL(get_hostname(), "",
8995
                   "hostname should have been cleared on buffer=" + buffer +
8996
                       " with " + components.to_string() + "\n" + to_diagram());
8997
#endif
8998
1.21k
  ADA_ASSERT_TRUE(has_authority());
8999
1.21k
  ADA_ASSERT_EQUAL(has_empty_hostname(), true,
9000
1.21k
                   "hostname should have been cleared on buffer=" + buffer +
9001
1.21k
                       " with " + components.to_string() + "\n" + to_diagram());
9002
1.21k
  ADA_ASSERT_TRUE(validate());
9003
1.21k
}
9004
9005
252k
[[nodiscard]] constexpr bool url_aggregator::has_hash() const noexcept {
9006
252k
  ada_log("url_aggregator::has_hash");
9007
252k
  return components.hash_start != url_components::omitted;
9008
252k
}
9009
9010
270k
[[nodiscard]] constexpr bool url_aggregator::has_search() const noexcept {
9011
270k
  ada_log("url_aggregator::has_search");
9012
270k
  return components.search_start != url_components::omitted;
9013
270k
}
9014
9015
178k
constexpr bool url_aggregator::has_credentials() const noexcept {
9016
178k
  ada_log("url_aggregator::has_credentials");
9017
178k
  return has_non_empty_username() || has_non_empty_password();
9018
178k
}
9019
9020
264k
constexpr bool url_aggregator::cannot_have_credentials_or_port() const {
9021
264k
  ada_log("url_aggregator::cannot_have_credentials_or_port");
9022
264k
  return type == ada::scheme::type::FILE ||
9023
216k
         components.host_start == components.host_end;
9024
264k
}
9025
9026
[[nodiscard]] ada_really_inline const ada::url_components&
9027
133k
url_aggregator::get_components() const noexcept {
9028
133k
  return components;
9029
133k
}
9030
9031
[[nodiscard]] constexpr bool ada::url_aggregator::has_authority()
9032
2.52M
    const noexcept {
9033
2.52M
  ada_log("url_aggregator::has_authority");
9034
  // Performance: instead of doing this potentially expensive check, we could
9035
  // have a boolean in the struct.
9036
2.52M
  return components.protocol_end + 2 <= components.host_start &&
9037
1.31M
         buffer[components.protocol_end] == '/' &&
9038
1.31M
         buffer[components.protocol_end + 1] == '/';
9039
2.52M
}
9040
9041
2.12M
inline void ada::url_aggregator::add_authority_slashes_if_needed() {
9042
2.12M
  ada_log("url_aggregator::add_authority_slashes_if_needed");
9043
2.12M
  ADA_ASSERT_TRUE(validate());
9044
  // Protocol setter will insert `http:` to the URL. It is up to hostname setter
9045
  // to insert
9046
  // `//` initially to the buffer, since it depends on the hostname existence.
9047
2.12M
  if (has_authority()) {
9048
938k
    return;
9049
938k
  }
9050
  // Performance: the common case is components.protocol_end == buffer.size()
9051
  // Optimization opportunity: in many cases, the "//" is part of the input and
9052
  // the insert could be fused with another insert.
9053
1.18M
  buffer.insert(components.protocol_end, "//");
9054
1.18M
  components.username_end += 2;
9055
1.18M
  components.host_start += 2;
9056
1.18M
  components.host_end += 2;
9057
1.18M
  components.pathname_start += 2;
9058
1.18M
  if (components.search_start != url_components::omitted) {
9059
58
    components.search_start += 2;
9060
58
  }
9061
1.18M
  if (components.hash_start != url_components::omitted) {
9062
55
    components.hash_start += 2;
9063
55
  }
9064
1.18M
  ADA_ASSERT_TRUE(validate());
9065
1.18M
}
9066
9067
1.85M
constexpr void ada::url_aggregator::reserve(uint32_t capacity) {
9068
1.85M
  buffer.reserve(capacity);
9069
1.85M
}
9070
9071
858k
constexpr bool url_aggregator::has_non_empty_username() const noexcept {
9072
858k
  ada_log("url_aggregator::has_non_empty_username");
9073
858k
  return components.protocol_end + 2 < components.username_end;
9074
858k
}
9075
9076
846k
constexpr bool url_aggregator::has_non_empty_password() const noexcept {
9077
846k
  ada_log("url_aggregator::has_non_empty_password");
9078
846k
  return components.host_start > components.username_end;
9079
846k
}
9080
9081
353k
constexpr bool url_aggregator::has_password() const noexcept {
9082
353k
  ada_log("url_aggregator::has_password");
9083
  // This function does not care about the length of the password
9084
353k
  return components.host_start > components.username_end &&
9085
116k
         buffer[components.username_end] == ':';
9086
353k
}
9087
9088
113k
constexpr bool url_aggregator::has_empty_hostname() const noexcept {
9089
113k
  if (!has_hostname()) {
9090
6.63k
    return false;
9091
6.63k
  }
9092
107k
  if (components.host_start == components.host_end) {
9093
2.34k
    return true;
9094
2.34k
  }
9095
104k
  if (components.host_end > components.host_start + 1) {
9096
86.9k
    return false;
9097
86.9k
  }
9098
17.9k
  return components.username_end != components.host_start;
9099
104k
}
9100
9101
368k
constexpr bool url_aggregator::has_hostname() const noexcept {
9102
368k
  return has_authority();
9103
368k
}
9104
9105
138k
constexpr bool url_aggregator::has_port() const noexcept {
9106
138k
  ada_log("url_aggregator::has_port");
9107
  // A URL cannot have a username/password/port if its host is null or the empty
9108
  // string, or its scheme is "file".
9109
138k
  return has_hostname() && components.pathname_start != components.host_end;
9110
138k
}
9111
9112
562k
[[nodiscard]] constexpr bool url_aggregator::has_dash_dot() const noexcept {
9113
  // If url's host is null, url does not have an opaque path, url's path's size
9114
  // is greater than 1, and url's path[0] is the empty string, then append
9115
  // U+002F (/) followed by U+002E (.) to output.
9116
562k
  ada_log("url_aggregator::has_dash_dot");
9117
#if ADA_DEVELOPMENT_CHECKS
9118
  // If pathname_start and host_end are exactly two characters apart, then we
9119
  // either have a one-digit port such as http://test.com:5?param=1 or else we
9120
  // have a /.: sequence such as "non-spec:/.//". We test that this is the case.
9121
  if (components.pathname_start == components.host_end + 2) {
9122
    ADA_ASSERT_TRUE((buffer[components.host_end] == '/' &&
9123
                     buffer[components.host_end + 1] == '.') ||
9124
                    (buffer[components.host_end] == ':' &&
9125
                     checkers::is_digit(buffer[components.host_end + 1])));
9126
  }
9127
  if (components.pathname_start == components.host_end + 2 &&
9128
      buffer[components.host_end] == '/' &&
9129
      buffer[components.host_end + 1] == '.') {
9130
    ADA_ASSERT_TRUE(components.pathname_start + 1 < buffer.size());
9131
    ADA_ASSERT_TRUE(buffer[components.pathname_start] == '/');
9132
    ADA_ASSERT_TRUE(buffer[components.pathname_start + 1] == '/');
9133
  }
9134
#endif
9135
  // Performance: it should be uncommon for components.pathname_start ==
9136
  // components.host_end + 2 to be true. So we put this check first in the
9137
  // sequence. Most times, we do not have an opaque path. Checking for '/.' is
9138
  // more expensive, but should be uncommon.
9139
562k
  return components.pathname_start == components.host_end + 2 &&
9140
6.22k
         !has_opaque_path && buffer[components.host_end] == '/' &&
9141
175
         buffer[components.host_end + 1] == '.';
9142
562k
}
9143
9144
[[nodiscard]] constexpr std::string_view url_aggregator::get_href()
9145
1.68M
    const noexcept ada_lifetime_bound {
9146
1.68M
  ada_log("url_aggregator::get_href");
9147
1.68M
  return buffer;
9148
1.68M
}
9149
9150
408k
[[nodiscard]] constexpr size_t url_aggregator::get_href_size() const noexcept {
9151
408k
  return buffer.size();
9152
408k
}
9153
9154
ada_really_inline size_t
9155
115k
url_aggregator::parse_port(std::string_view view, bool check_trailing_content) {
9156
115k
  ada_log("url_aggregator::parse_port('", view, "') ", view.size());
9157
115k
  if (!view.empty() && view[0] == '-') {
9158
249
    ada_log("parse_port: view[0] == '0' && view.size() > 1");
9159
249
    is_valid = false;
9160
249
    return 0;
9161
249
  }
9162
115k
  uint16_t parsed_port{};
9163
115k
  auto r = std::from_chars(view.data(), view.data() + view.size(), parsed_port);
9164
115k
  if (r.ec == std::errc::result_out_of_range) {
9165
1.62k
    ada_log("parse_port: r.ec == std::errc::result_out_of_range");
9166
1.62k
    is_valid = false;
9167
1.62k
    return 0;
9168
1.62k
  }
9169
113k
  ada_log("parse_port: ", parsed_port);
9170
113k
  const size_t consumed = size_t(r.ptr - view.data());
9171
113k
  ada_log("parse_port: consumed ", consumed);
9172
113k
  if (check_trailing_content) {
9173
110k
    is_valid &=
9174
110k
        (consumed == view.size() || view[consumed] == '/' ||
9175
6.97k
         view[consumed] == '?' || (is_special() && view[consumed] == '\\'));
9176
110k
  }
9177
113k
  ada_log("parse_port: is_valid = ", is_valid);
9178
113k
  if (is_valid) {
9179
109k
    ada_log("parse_port", r.ec == std::errc());
9180
    // scheme_default_port can return 0, and we should allow 0 as a base port.
9181
109k
    auto default_port = scheme_default_port();
9182
109k
    bool is_port_valid = (default_port == 0 && parsed_port == 0) ||
9183
109k
                         (default_port != parsed_port);
9184
109k
    if (r.ec == std::errc() && is_port_valid) {
9185
80.5k
      update_base_port(parsed_port);
9186
80.5k
    } else {
9187
29.2k
      clear_port();
9188
29.2k
    }
9189
109k
  }
9190
113k
  return consumed;
9191
115k
}
9192
9193
80.1k
constexpr void url_aggregator::set_protocol_as_file() {
9194
80.1k
  ada_log("url_aggregator::set_protocol_as_file ");
9195
80.1k
  ADA_ASSERT_TRUE(validate());
9196
80.1k
  type = ada::scheme::type::FILE;
9197
  // next line could overflow but unsigned arithmetic has well-defined
9198
  // overflows.
9199
80.1k
  uint32_t new_difference = 5 - components.protocol_end;
9200
9201
80.1k
  if (buffer.empty()) {
9202
3.10k
    buffer.append("file:");
9203
77.0k
  } else {
9204
77.0k
    buffer.erase(0, components.protocol_end);
9205
77.0k
    buffer.insert(0, "file:");
9206
77.0k
  }
9207
80.1k
  components.protocol_end = 5;
9208
9209
  // Update the rest of the components.
9210
80.1k
  components.username_end += new_difference;
9211
80.1k
  components.host_start += new_difference;
9212
80.1k
  components.host_end += new_difference;
9213
80.1k
  components.pathname_start += new_difference;
9214
80.1k
  if (components.search_start != url_components::omitted) {
9215
0
    components.search_start += new_difference;
9216
0
  }
9217
80.1k
  if (components.hash_start != url_components::omitted) {
9218
0
    components.hash_start += new_difference;
9219
0
  }
9220
80.1k
  ADA_ASSERT_TRUE(validate());
9221
80.1k
}
9222
9223
321k
[[nodiscard]] constexpr bool url_aggregator::validate() const noexcept {
9224
321k
  if (!is_valid) {
9225
0
    return true;
9226
0
  }
9227
321k
  if (!components.check_offset_consistency()) {
9228
0
    ada_log("url_aggregator::validate inconsistent components \n",
9229
0
            to_diagram());
9230
0
    return false;
9231
0
  }
9232
  // We have a credible components struct, but let us investivate more
9233
  // carefully:
9234
  /**
9235
   * https://user:pass@example.com:1234/foo/bar?baz#quux
9236
   *       |     |    |          | ^^^^|       |   |
9237
   *       |     |    |          | |   |       |   `----- hash_start
9238
   *       |     |    |          | |   |       `--------- search_start
9239
   *       |     |    |          | |   `----------------- pathname_start
9240
   *       |     |    |          | `--------------------- port
9241
   *       |     |    |          `----------------------- host_end
9242
   *       |     |    `---------------------------------- host_start
9243
   *       |     `--------------------------------------- username_end
9244
   *       `--------------------------------------------- protocol_end
9245
   */
9246
321k
  if (components.protocol_end == url_components::omitted) {
9247
0
    ada_log("url_aggregator::validate omitted protocol_end \n", to_diagram());
9248
0
    return false;
9249
0
  }
9250
321k
  if (components.username_end == url_components::omitted) {
9251
0
    ada_log("url_aggregator::validate omitted username_end \n", to_diagram());
9252
0
    return false;
9253
0
  }
9254
321k
  if (components.host_start == url_components::omitted) {
9255
0
    ada_log("url_aggregator::validate omitted host_start \n", to_diagram());
9256
0
    return false;
9257
0
  }
9258
321k
  if (components.host_end == url_components::omitted) {
9259
0
    ada_log("url_aggregator::validate omitted host_end \n", to_diagram());
9260
0
    return false;
9261
0
  }
9262
321k
  if (components.pathname_start == url_components::omitted) {
9263
0
    ada_log("url_aggregator::validate omitted pathname_start \n", to_diagram());
9264
0
    return false;
9265
0
  }
9266
9267
321k
  if (components.protocol_end > buffer.size()) {
9268
0
    ada_log("url_aggregator::validate protocol_end overflow \n", to_diagram());
9269
0
    return false;
9270
0
  }
9271
321k
  if (components.username_end > buffer.size()) {
9272
0
    ada_log("url_aggregator::validate username_end overflow \n", to_diagram());
9273
0
    return false;
9274
0
  }
9275
321k
  if (components.host_start > buffer.size()) {
9276
0
    ada_log("url_aggregator::validate host_start overflow \n", to_diagram());
9277
0
    return false;
9278
0
  }
9279
321k
  if (components.host_end > buffer.size()) {
9280
0
    ada_log("url_aggregator::validate host_end overflow \n", to_diagram());
9281
0
    return false;
9282
0
  }
9283
321k
  if (components.pathname_start > buffer.size()) {
9284
0
    ada_log("url_aggregator::validate pathname_start overflow \n",
9285
0
            to_diagram());
9286
0
    return false;
9287
0
  }
9288
9289
321k
  if (components.protocol_end > 0) {
9290
321k
    if (buffer[components.protocol_end - 1] != ':') {
9291
0
      ada_log(
9292
0
          "url_aggregator::validate missing : at the end of the protocol \n",
9293
0
          to_diagram());
9294
0
      return false;
9295
0
    }
9296
321k
  }
9297
9298
321k
  if (components.username_end != buffer.size() &&
9299
320k
      components.username_end > components.protocol_end + 2) {
9300
60.3k
    if (buffer[components.username_end] != ':' &&
9301
3.52k
        buffer[components.username_end] != '@') {
9302
0
      ada_log(
9303
0
          "url_aggregator::validate missing : or @ at the end of the username "
9304
0
          "\n",
9305
0
          to_diagram());
9306
0
      return false;
9307
0
    }
9308
60.3k
  }
9309
9310
321k
  if (components.host_start != buffer.size()) {
9311
320k
    if (components.host_start > components.username_end) {
9312
57.9k
      if (buffer[components.host_start] != '@') {
9313
0
        ada_log(
9314
0
            "url_aggregator::validate missing @ at the end of the password \n",
9315
0
            to_diagram());
9316
0
        return false;
9317
0
      }
9318
262k
    } else if (components.host_start == components.username_end &&
9319
262k
               components.host_end > components.host_start) {
9320
251k
      if (components.host_start == components.protocol_end + 2) {
9321
247k
        if (buffer[components.protocol_end] != '/' ||
9322
247k
            buffer[components.protocol_end + 1] != '/') {
9323
0
          ada_log(
9324
0
              "url_aggregator::validate missing // between protocol and host "
9325
0
              "\n",
9326
0
              to_diagram());
9327
0
          return false;
9328
0
        }
9329
247k
      } else {
9330
3.52k
        if (components.host_start > components.protocol_end &&
9331
3.52k
            buffer[components.host_start] != '@') {
9332
0
          ada_log(
9333
0
              "url_aggregator::validate missing @ at the end of the username "
9334
0
              "\n",
9335
0
              to_diagram());
9336
0
          return false;
9337
0
        }
9338
3.52k
      }
9339
251k
    } else {
9340
11.0k
      if (components.host_end != components.host_start) {
9341
0
        ada_log("url_aggregator::validate expected omitted host \n",
9342
0
                to_diagram());
9343
0
        return false;
9344
0
      }
9345
11.0k
    }
9346
320k
  }
9347
321k
  if (components.host_end != buffer.size() &&
9348
319k
      components.pathname_start > components.host_end) {
9349
58.4k
    if (components.pathname_start == components.host_end + 2 &&
9350
3.99k
        buffer[components.host_end] == '/' &&
9351
130
        buffer[components.host_end + 1] == '.') {
9352
130
      if (components.pathname_start + 1 >= buffer.size() ||
9353
130
          buffer[components.pathname_start] != '/' ||
9354
130
          buffer[components.pathname_start + 1] != '/') {
9355
0
        ada_log(
9356
0
            "url_aggregator::validate expected the path to begin with // \n",
9357
0
            to_diagram());
9358
0
        return false;
9359
0
      }
9360
58.2k
    } else if (buffer[components.host_end] != ':') {
9361
0
      ada_log("url_aggregator::validate missing : at the port \n",
9362
0
              to_diagram());
9363
0
      return false;
9364
0
    }
9365
58.4k
  }
9366
321k
  if (components.pathname_start != buffer.size() &&
9367
319k
      components.pathname_start < components.search_start &&
9368
318k
      components.pathname_start < components.hash_start && !has_opaque_path) {
9369
313k
    if (buffer[components.pathname_start] != '/') {
9370
0
      ada_log("url_aggregator::validate missing / at the path \n",
9371
0
              to_diagram());
9372
0
      return false;
9373
0
    }
9374
313k
  }
9375
321k
  if (components.search_start != url_components::omitted) {
9376
120k
    if (buffer[components.search_start] != '?') {
9377
0
      ada_log("url_aggregator::validate missing ? at the search \n",
9378
0
              to_diagram());
9379
0
      return false;
9380
0
    }
9381
120k
  }
9382
321k
  if (components.hash_start != url_components::omitted) {
9383
86.3k
    if (buffer[components.hash_start] != '#') {
9384
0
      ada_log("url_aggregator::validate missing # at the hash \n",
9385
0
              to_diagram());
9386
0
      return false;
9387
0
    }
9388
86.3k
  }
9389
9390
321k
  return true;
9391
321k
}
9392
9393
[[nodiscard]] constexpr std::string_view url_aggregator::get_pathname() const
9394
1.90M
    ada_lifetime_bound {
9395
1.90M
  ada_log("url_aggregator::get_pathname pathname_start = ",
9396
1.90M
          components.pathname_start, " buffer.size() = ", buffer.size(),
9397
1.90M
          " components.search_start = ", components.search_start,
9398
1.90M
          " components.hash_start = ", components.hash_start);
9399
1.90M
  auto ending_index = uint32_t(buffer.size());
9400
1.90M
  if (components.search_start != url_components::omitted) {
9401
202k
    ending_index = components.search_start;
9402
1.69M
  } else if (components.hash_start != url_components::omitted) {
9403
30.4k
    ending_index = components.hash_start;
9404
30.4k
  }
9405
1.90M
  return helpers::substring(buffer, components.pathname_start, ending_index);
9406
1.90M
}
9407
9408
inline std::ostream& operator<<(std::ostream& out,
9409
0
                                const ada::url_aggregator& u) {
9410
0
  return out << u.to_string();
9411
0
}
9412
9413
19.2k
void url_aggregator::update_host_to_base_host(const std::string_view input) {
9414
19.2k
  ada_log("url_aggregator::update_host_to_base_host ", input);
9415
19.2k
  ADA_ASSERT_TRUE(validate());
9416
19.2k
  ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer));
9417
19.2k
  if (type != ada::scheme::type::FILE) {
9418
    // Let host be the result of host parsing host_view with url is not special.
9419
16.2k
    if (input.empty() && !is_special()) {
9420
1.42k
      if (has_hostname()) {
9421
112
        clear_hostname();
9422
1.31k
      } else if (has_dash_dot()) {
9423
0
        add_authority_slashes_if_needed();
9424
0
        delete_dash_dot();
9425
0
      }
9426
1.42k
      return;
9427
1.42k
    }
9428
16.2k
  }
9429
17.8k
  update_base_hostname(input);
9430
17.8k
  ADA_ASSERT_TRUE(validate());
9431
17.8k
  return;
9432
19.2k
}
9433
}  // namespace ada
9434
9435
#endif  // ADA_URL_AGGREGATOR_INL_H
9436
/* end file include/ada/url_aggregator-inl.h */
9437
/* begin file include/ada/url_search_params.h */
9438
/**
9439
 * @file url_search_params.h
9440
 * @brief URL query string parameter manipulation.
9441
 *
9442
 * This file provides the `url_search_params` class for parsing, manipulating,
9443
 * and serializing URL query strings. It implements the URLSearchParams API
9444
 * from the WHATWG URL Standard.
9445
 *
9446
 * @see https://url.spec.whatwg.org/#interface-urlsearchparams
9447
 */
9448
#ifndef ADA_URL_SEARCH_PARAMS_H
9449
#define ADA_URL_SEARCH_PARAMS_H
9450
9451
#include <optional>
9452
#include <string>
9453
#include <string_view>
9454
#include <vector>
9455
9456
namespace ada {
9457
9458
/**
9459
 * @brief Iterator types for url_search_params iteration.
9460
 */
9461
enum class url_search_params_iter_type {
9462
  KEYS,    /**< Iterate over parameter keys only */
9463
  VALUES,  /**< Iterate over parameter values only */
9464
  ENTRIES, /**< Iterate over key-value pairs */
9465
};
9466
9467
template <typename T, url_search_params_iter_type Type>
9468
struct url_search_params_iter;
9469
9470
/** Type alias for a key-value pair of string views. */
9471
typedef std::pair<std::string_view, std::string_view> key_value_view_pair;
9472
9473
/** Iterator over search parameter keys. */
9474
using url_search_params_keys_iter =
9475
    url_search_params_iter<std::string_view, url_search_params_iter_type::KEYS>;
9476
/** Iterator over search parameter values. */
9477
using url_search_params_values_iter =
9478
    url_search_params_iter<std::string_view,
9479
                           url_search_params_iter_type::VALUES>;
9480
/** Iterator over search parameter key-value pairs. */
9481
using url_search_params_entries_iter =
9482
    url_search_params_iter<key_value_view_pair,
9483
                           url_search_params_iter_type::ENTRIES>;
9484
9485
/**
9486
 * @brief Class for parsing and manipulating URL query strings.
9487
 *
9488
 * The `url_search_params` class provides methods to parse, modify, and
9489
 * serialize URL query parameters (the part after '?' in a URL). It handles
9490
 * percent-encoding and decoding automatically.
9491
 *
9492
 * All string inputs must be valid UTF-8. The caller is responsible for
9493
 * ensuring UTF-8 validity.
9494
 *
9495
 * Construction and `reset` refuse query strings longer than
9496
 * `get_max_input_length()` (the object is left empty). Individual `append` /
9497
 * `set` calls are not length-capped.
9498
 *
9499
 * @see https://url.spec.whatwg.org/#interface-urlsearchparams
9500
 */
9501
struct url_search_params {
9502
9.22k
  url_search_params() = default;
9503
9504
  /**
9505
   * Constructs url_search_params by parsing a query string.
9506
   * @param input A query string (with or without leading '?'). Must be UTF-8.
9507
   *        If longer than `get_max_input_length()`, the object stays empty.
9508
   */
9509
69.5k
  explicit url_search_params(const std::string_view input) {
9510
69.5k
    initialize(input);
9511
69.5k
  }
9512
9513
3.07k
  url_search_params(const url_search_params& u) = default;
9514
16.7k
  url_search_params(url_search_params&& u) noexcept = default;
9515
3.07k
  url_search_params& operator=(url_search_params&& u) noexcept = default;
9516
3.07k
  url_search_params& operator=(const url_search_params& u) = default;
9517
98.6k
  ~url_search_params() = default;
9518
9519
  /**
9520
   * Returns the number of key-value pairs.
9521
   * @return The total count of parameters.
9522
   */
9523
  [[nodiscard]] inline size_t size() const noexcept;
9524
9525
  /**
9526
   * Appends a new key-value pair to the parameter list.
9527
   * @param key The parameter name (must be valid UTF-8).
9528
   * @param value The parameter value (must be valid UTF-8).
9529
   * @see https://url.spec.whatwg.org/#dom-urlsearchparams-append
9530
   */
9531
  inline void append(std::string_view key, std::string_view value);
9532
9533
  /**
9534
   * Removes all pairs with the given key.
9535
   * @param key The parameter name to remove.
9536
   * @see https://url.spec.whatwg.org/#dom-urlsearchparams-delete
9537
   */
9538
  inline void remove(std::string_view key);
9539
9540
  /**
9541
   * Removes all pairs with the given key and value.
9542
   * @param key The parameter name.
9543
   * @param value The parameter value to match.
9544
   */
9545
  inline void remove(std::string_view key, std::string_view value);
9546
9547
  /**
9548
   * Returns the value of the first pair with the given key.
9549
   * @param key The parameter name to search for.
9550
   * @return The value if found, or std::nullopt if not present.
9551
   * @see https://url.spec.whatwg.org/#dom-urlsearchparams-get
9552
   */
9553
  inline std::optional<std::string_view> get(std::string_view key);
9554
9555
  /**
9556
   * Returns all values for pairs with the given key.
9557
   * @param key The parameter name to search for.
9558
   * @return A vector of all matching values (may be empty).
9559
   * @see https://url.spec.whatwg.org/#dom-urlsearchparams-getall
9560
   */
9561
  inline std::vector<std::string> get_all(std::string_view key);
9562
9563
  /**
9564
   * Checks if any pair has the given key.
9565
   * @param key The parameter name to search for.
9566
   * @return `true` if at least one pair has this key.
9567
   * @see https://url.spec.whatwg.org/#dom-urlsearchparams-has
9568
   */
9569
  inline bool has(std::string_view key) noexcept;
9570
9571
  /**
9572
   * Checks if any pair matches the given key and value.
9573
   * @param key The parameter name to search for.
9574
   * @param value The parameter value to match.
9575
   * @return `true` if a matching pair exists.
9576
   */
9577
  inline bool has(std::string_view key, std::string_view value) noexcept;
9578
9579
  /**
9580
   * Sets a parameter value, replacing any existing pairs with the same key.
9581
   * @param key The parameter name (must be valid UTF-8).
9582
   * @param value The parameter value (must be valid UTF-8).
9583
   * @see https://url.spec.whatwg.org/#dom-urlsearchparams-set
9584
   */
9585
  inline void set(std::string_view key, std::string_view value);
9586
9587
  /**
9588
   * Sorts all key-value pairs by their keys using code unit comparison.
9589
   * @see https://url.spec.whatwg.org/#dom-urlsearchparams-sort
9590
   */
9591
  inline void sort();
9592
9593
  /**
9594
   * Serializes the parameters to a query string (without leading '?').
9595
   * @return The percent-encoded query string.
9596
   * @see https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior
9597
   */
9598
  inline std::string to_string() const;
9599
9600
  /**
9601
   * Returns an iterator over all parameter keys.
9602
   * Keys may repeat if there are duplicate parameters.
9603
   * @return An iterator yielding string_view keys.
9604
   * @note The iterator is invalidated if this object is modified.
9605
   */
9606
  inline url_search_params_keys_iter get_keys();
9607
9608
  /**
9609
   * Returns an iterator over all parameter values.
9610
   * @return An iterator yielding string_view values.
9611
   * @note The iterator is invalidated if this object is modified.
9612
   */
9613
  inline url_search_params_values_iter get_values();
9614
9615
  /**
9616
   * Returns an iterator over all key-value pairs.
9617
   * @return An iterator yielding key-value pair views.
9618
   * @note The iterator is invalidated if this object is modified.
9619
   */
9620
  inline url_search_params_entries_iter get_entries();
9621
9622
  /**
9623
   * C++ style conventional iterator support. const only because we
9624
   * do not really want the params to be modified via the iterator.
9625
   */
9626
12.2k
  inline auto begin() const { return params.begin(); }
9627
12.2k
  inline auto end() const { return params.end(); }
9628
1.13k
  inline auto front() const { return params.front(); }
9629
1.13k
  inline auto back() const { return params.back(); }
9630
1.13k
  inline auto operator[](size_t index) const { return params[index]; }
9631
9632
  /**
9633
   * @private
9634
   * Used to reset the search params to a new input.
9635
   * Used primarily for C API.
9636
   * @param input
9637
   */
9638
  void reset(std::string_view input);
9639
9640
 private:
9641
  typedef std::pair<std::string, std::string> key_value_pair;
9642
  std::vector<key_value_pair> params{};
9643
9644
  /**
9645
   * The init parameter must be valid UTF-8.
9646
   * @see https://url.spec.whatwg.org/#concept-urlencoded-parser
9647
   */
9648
  void initialize(std::string_view init);
9649
9650
  template <typename T, url_search_params_iter_type Type>
9651
  friend struct url_search_params_iter;
9652
};  // url_search_params
9653
9654
/**
9655
 * @brief JavaScript-style iterator for url_search_params.
9656
 *
9657
 * Provides a `next()` method that returns successive values until exhausted.
9658
 * This matches the iterator pattern used in the Web Platform.
9659
 *
9660
 * @tparam T The type of value returned by the iterator.
9661
 * @tparam Type The type of iteration (KEYS, VALUES, or ENTRIES).
9662
 *
9663
 * @see https://webidl.spec.whatwg.org/#idl-iterable
9664
 */
9665
template <typename T, url_search_params_iter_type Type>
9666
struct url_search_params_iter {
9667
0
  inline url_search_params_iter() : params(EMPTY) {}
Unexecuted instantiation: 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()
Unexecuted instantiation: 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()
Unexecuted instantiation: 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()
9668
  url_search_params_iter(const url_search_params_iter& u) = default;
9669
  url_search_params_iter(url_search_params_iter&& u) noexcept = default;
9670
  url_search_params_iter& operator=(url_search_params_iter&& u) noexcept =
9671
      default;
9672
  url_search_params_iter& operator=(const url_search_params_iter& u) = default;
9673
  ~url_search_params_iter() = default;
9674
9675
  /**
9676
   * Returns the next value in the iteration sequence.
9677
   * @return The next value, or std::nullopt if iteration is complete.
9678
   */
9679
  inline std::optional<T> next();
9680
9681
  /**
9682
   * Checks if more values are available.
9683
   * @return `true` if `next()` will return a value, `false` if exhausted.
9684
   */
9685
  inline bool has_next() const;
9686
9687
 private:
9688
  static url_search_params EMPTY;
9689
50.3k
  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
9689
16.7k
  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
9689
16.7k
  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
9689
16.7k
  inline url_search_params_iter(url_search_params& params_) : params(params_) {}
9690
9691
  url_search_params& params;
9692
  size_t pos = 0;
9693
9694
  friend struct url_search_params;
9695
};
9696
9697
}  // namespace ada
9698
#endif
9699
/* end file include/ada/url_search_params.h */
9700
/* begin file include/ada/url_search_params-inl.h */
9701
/**
9702
 * @file url_search_params-inl.h
9703
 * @brief Inline declarations for the URL Search Params
9704
 */
9705
#ifndef ADA_URL_SEARCH_PARAMS_INL_H
9706
#define ADA_URL_SEARCH_PARAMS_INL_H
9707
9708
9709
#include <algorithm>
9710
#include <cstdint>
9711
#include <optional>
9712
#include <ranges>
9713
#include <string>
9714
#include <string_view>
9715
#include <vector>
9716
9717
namespace ada {
9718
9719
// Declared in implementation.h; used here as a DoS bound on untrusted query
9720
// strings (ada.h includes both headers).
9721
uint32_t get_max_input_length();
9722
9723
// A default, empty url_search_params for use with empty iterators.
9724
template <typename T, ada::url_search_params_iter_type Type>
9725
url_search_params url_search_params_iter<T, Type>::EMPTY;
9726
9727
16.7k
inline void url_search_params::reset(std::string_view input) {
9728
16.7k
  params.clear();
9729
16.7k
  initialize(input);
9730
16.7k
}
9731
9732
86.3k
inline void url_search_params::initialize(std::string_view input) {
9733
86.3k
  if (!input.empty() && input.front() == '?') {
9734
208
    input.remove_prefix(1);
9735
208
  }
9736
86.3k
  if (input.empty()) {
9737
22.8k
    return;
9738
22.8k
  }
9739
  // Refuse overlong query strings (same process-wide cap as URL parsing).
9740
63.5k
  if (input.size() > get_max_input_length()) {
9741
0
    return;
9742
0
  }
9743
9744
63.5k
  params.reserve(size_t(std::count(input.begin(), input.end(), '&')) + 1);
9745
9746
115k
  auto process_key_value = [&](const std::string_view current) {
9747
115k
    const auto equal = current.find('=');
9748
115k
    if (equal == std::string_view::npos) {
9749
52.7k
      params.emplace_back(unicode::form_urlencoded_decode(current), "");
9750
63.1k
    } else {
9751
63.1k
      params.emplace_back(
9752
63.1k
          unicode::form_urlencoded_decode(current.substr(0, equal)),
9753
63.1k
          unicode::form_urlencoded_decode(current.substr(equal + 1)));
9754
63.1k
    }
9755
115k
  };
9756
9757
124k
  while (!input.empty()) {
9758
124k
    const auto ampersand_index = input.find('&');
9759
9760
124k
    if (ampersand_index == std::string_view::npos) {
9761
63.1k
      if (!input.empty()) {
9762
63.1k
        process_key_value(input);
9763
63.1k
      }
9764
63.1k
      break;
9765
63.1k
    } else if (ampersand_index != 0) {
9766
52.6k
      process_key_value(input.substr(0, ampersand_index));
9767
52.6k
    }
9768
9769
60.9k
    input.remove_prefix(ampersand_index + 1);
9770
60.9k
  }
9771
63.5k
}
9772
9773
inline void url_search_params::append(const std::string_view key,
9774
51.1k
                                      const std::string_view value) {
9775
51.1k
  params.emplace_back(key, value);
9776
51.1k
}
9777
9778
41.3k
inline size_t url_search_params::size() const noexcept { return params.size(); }
9779
9780
inline std::optional<std::string_view> url_search_params::get(
9781
32.1k
    const std::string_view key) {
9782
32.1k
  auto entry = std::ranges::find_if(
9783
148k
      params, [&key](const auto& param) { return param.first == key; });
9784
9785
32.1k
  if (entry == params.end()) {
9786
5.84k
    return std::nullopt;
9787
5.84k
  }
9788
9789
26.3k
  return entry->second;
9790
32.1k
}
9791
9792
inline std::vector<std::string> url_search_params::get_all(
9793
19.8k
    const std::string_view key) {
9794
19.8k
  std::vector<std::string> out{};
9795
9796
39.9k
  for (auto& param : params) {
9797
39.9k
    if (param.first == key) {
9798
19.6k
      out.emplace_back(param.second);
9799
19.6k
    }
9800
39.9k
  }
9801
9802
19.8k
  return out;
9803
19.8k
}
9804
9805
35.3k
inline bool url_search_params::has(const std::string_view key) noexcept {
9806
35.3k
  auto entry = std::ranges::find_if(
9807
257k
      params, [&key](const auto& param) { return param.first == key; });
9808
35.3k
  return entry != params.end();
9809
35.3k
}
9810
9811
inline bool url_search_params::has(std::string_view key,
9812
26.0k
                                   std::string_view value) noexcept {
9813
143k
  auto entry = std::ranges::find_if(params, [&key, &value](const auto& param) {
9814
143k
    return param.first == key && param.second == value;
9815
143k
  });
9816
26.0k
  return entry != params.end();
9817
26.0k
}
9818
9819
81.8k
inline std::string url_search_params::to_string() const {
9820
81.8k
  auto character_set = ada::character_sets::WWW_FORM_URLENCODED_PERCENT_ENCODE;
9821
81.8k
  std::string out{};
9822
238k
  for (size_t i = 0; i < params.size(); i++) {
9823
156k
    auto key = ada::unicode::percent_encode(params[i].first, character_set);
9824
156k
    auto value = ada::unicode::percent_encode(params[i].second, character_set);
9825
9826
    // Performance optimization: Move this inside percent_encode.
9827
156k
    std::ranges::replace(key, ' ', '+');
9828
156k
    std::ranges::replace(value, ' ', '+');
9829
9830
156k
    if (i != 0) {
9831
89.1k
      out += "&";
9832
89.1k
    }
9833
156k
    out.append(key);
9834
156k
    out += "=";
9835
156k
    out.append(value);
9836
156k
  }
9837
81.8k
  return out;
9838
81.8k
}
9839
9840
inline void url_search_params::set(const std::string_view key,
9841
16.7k
                                   const std::string_view value) {
9842
39.6k
  const auto find = [&key](const auto& param) { return param.first == key; };
9843
9844
16.7k
  auto it = std::ranges::find_if(params, find);
9845
9846
16.7k
  if (it == params.end()) {
9847
0
    params.emplace_back(key, value);
9848
16.7k
  } else {
9849
16.7k
    it->second = value;
9850
16.7k
    params.erase(std::remove_if(std::next(it), params.end(), find),
9851
16.7k
                 params.end());
9852
16.7k
  }
9853
16.7k
}
9854
9855
18.1k
inline void url_search_params::remove(const std::string_view key) {
9856
18.1k
  std::erase_if(params,
9857
33.4k
                [&key](const auto& param) { return param.first == key; });
9858
18.1k
}
9859
9860
inline void url_search_params::remove(const std::string_view key,
9861
18.1k
                                      const std::string_view value) {
9862
18.1k
  std::erase_if(params, [&key, &value](const auto& param) {
9863
13.4k
    return param.first == key && param.second == value;
9864
13.4k
  });
9865
18.1k
}
9866
9867
19.8k
inline void url_search_params::sort() {
9868
  // Keys are expected to be valid UTF-8, but percent_decode can produce
9869
  // arbitrary byte sequences. Handle truncated/invalid sequences gracefully.
9870
19.8k
  std::ranges::stable_sort(params, [](const key_value_pair& lhs,
9871
64.1k
                                      const key_value_pair& rhs) {
9872
64.1k
    size_t i = 0, j = 0;
9873
64.1k
    uint32_t low_surrogate1 = 0, low_surrogate2 = 0;
9874
169k
    while ((i < lhs.first.size() || low_surrogate1 != 0) &&
9875
134k
           (j < rhs.first.size() || low_surrogate2 != 0)) {
9876
130k
      uint32_t codePoint1 = 0, codePoint2 = 0;
9877
9878
130k
      if (low_surrogate1 != 0) {
9879
1.90k
        codePoint1 = low_surrogate1;
9880
1.90k
        low_surrogate1 = 0;
9881
128k
      } else {
9882
128k
        uint8_t c1 = uint8_t(lhs.first[i]);
9883
128k
        if (c1 > 0x7F && c1 <= 0xDF && i + 1 < lhs.first.size()) {
9884
3.76k
          codePoint1 = ((c1 & 0x1F) << 6) | (uint8_t(lhs.first[i + 1]) & 0x3F);
9885
3.76k
          i += 2;
9886
125k
        } else if (c1 > 0xDF && c1 <= 0xEF && i + 2 < lhs.first.size()) {
9887
2.51k
          codePoint1 = ((c1 & 0x0F) << 12) |
9888
2.51k
                       ((uint8_t(lhs.first[i + 1]) & 0x3F) << 6) |
9889
2.51k
                       (uint8_t(lhs.first[i + 2]) & 0x3F);
9890
2.51k
          i += 3;
9891
122k
        } else if (c1 > 0xEF && c1 <= 0xF7 && i + 3 < lhs.first.size()) {
9892
2.44k
          codePoint1 = ((c1 & 0x07) << 18) |
9893
2.44k
                       ((uint8_t(lhs.first[i + 1]) & 0x3F) << 12) |
9894
2.44k
                       ((uint8_t(lhs.first[i + 2]) & 0x3F) << 6) |
9895
2.44k
                       (uint8_t(lhs.first[i + 3]) & 0x3F);
9896
2.44k
          i += 4;
9897
9898
2.44k
          codePoint1 -= 0x10000;
9899
2.44k
          uint16_t high_surrogate = uint16_t(0xD800 + (codePoint1 >> 10));
9900
2.44k
          low_surrogate1 = uint16_t(0xDC00 + (codePoint1 & 0x3FF));
9901
2.44k
          codePoint1 = high_surrogate;
9902
120k
        } else {
9903
          // ASCII (c1 <= 0x7F) or truncated/invalid UTF-8: treat as raw byte
9904
120k
          codePoint1 = c1;
9905
120k
          i++;
9906
120k
        }
9907
128k
      }
9908
9909
130k
      if (low_surrogate2 != 0) {
9910
1.90k
        codePoint2 = low_surrogate2;
9911
1.90k
        low_surrogate2 = 0;
9912
128k
      } else {
9913
128k
        uint8_t c2 = uint8_t(rhs.first[j]);
9914
128k
        if (c2 > 0x7F && c2 <= 0xDF && j + 1 < rhs.first.size()) {
9915
4.34k
          codePoint2 = ((c2 & 0x1F) << 6) | (uint8_t(rhs.first[j + 1]) & 0x3F);
9916
4.34k
          j += 2;
9917
124k
        } else if (c2 > 0xDF && c2 <= 0xEF && j + 2 < rhs.first.size()) {
9918
2.56k
          codePoint2 = ((c2 & 0x0F) << 12) |
9919
2.56k
                       ((uint8_t(rhs.first[j + 1]) & 0x3F) << 6) |
9920
2.56k
                       (uint8_t(rhs.first[j + 2]) & 0x3F);
9921
2.56k
          j += 3;
9922
121k
        } else if (c2 > 0xEF && c2 <= 0xF7 && j + 3 < rhs.first.size()) {
9923
2.65k
          codePoint2 = ((c2 & 0x07) << 18) |
9924
2.65k
                       ((uint8_t(rhs.first[j + 1]) & 0x3F) << 12) |
9925
2.65k
                       ((uint8_t(rhs.first[j + 2]) & 0x3F) << 6) |
9926
2.65k
                       (uint8_t(rhs.first[j + 3]) & 0x3F);
9927
2.65k
          j += 4;
9928
2.65k
          codePoint2 -= 0x10000;
9929
2.65k
          uint16_t high_surrogate = uint16_t(0xD800 + (codePoint2 >> 10));
9930
2.65k
          low_surrogate2 = uint16_t(0xDC00 + (codePoint2 & 0x3FF));
9931
2.65k
          codePoint2 = high_surrogate;
9932
119k
        } else {
9933
          // ASCII (c2 <= 0x7F) or truncated/invalid UTF-8: treat as raw byte
9934
119k
          codePoint2 = c2;
9935
119k
          j++;
9936
119k
        }
9937
128k
      }
9938
9939
130k
      if (codePoint1 != codePoint2) {
9940
25.4k
        return (codePoint1 < codePoint2);
9941
25.4k
      }
9942
130k
    }
9943
38.7k
    return (j < rhs.first.size() || low_surrogate2 != 0);
9944
64.1k
  });
9945
19.8k
}
9946
9947
16.7k
inline url_search_params_keys_iter url_search_params::get_keys() {
9948
16.7k
  return url_search_params_keys_iter(*this);
9949
16.7k
}
9950
9951
/**
9952
 * @see https://url.spec.whatwg.org/#interface-urlsearchparams
9953
 */
9954
16.7k
inline url_search_params_values_iter url_search_params::get_values() {
9955
16.7k
  return url_search_params_values_iter(*this);
9956
16.7k
}
9957
9958
/**
9959
 * @see https://url.spec.whatwg.org/#interface-urlsearchparams
9960
 */
9961
16.7k
inline url_search_params_entries_iter url_search_params::get_entries() {
9962
16.7k
  return url_search_params_entries_iter(*this);
9963
16.7k
}
9964
9965
template <typename T, url_search_params_iter_type Type>
9966
251k
inline bool url_search_params_iter<T, Type>::has_next() const {
9967
251k
  return pos < params.params.size();
9968
251k
}
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
9966
83.8k
inline bool url_search_params_iter<T, Type>::has_next() const {
9967
83.8k
  return pos < params.params.size();
9968
83.8k
}
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
9966
83.8k
inline bool url_search_params_iter<T, Type>::has_next() const {
9967
83.8k
  return pos < params.params.size();
9968
83.8k
}
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
9966
83.8k
inline bool url_search_params_iter<T, Type>::has_next() const {
9967
83.8k
  return pos < params.params.size();
9968
83.8k
}
9969
9970
template <>
9971
33.5k
inline std::optional<std::string_view> url_search_params_keys_iter::next() {
9972
33.5k
  if (!has_next()) {
9973
0
    return std::nullopt;
9974
0
  }
9975
33.5k
  return params.params[pos++].first;
9976
33.5k
}
9977
9978
template <>
9979
33.5k
inline std::optional<std::string_view> url_search_params_values_iter::next() {
9980
33.5k
  if (!has_next()) {
9981
0
    return std::nullopt;
9982
0
  }
9983
33.5k
  return params.params[pos++].second;
9984
33.5k
}
9985
9986
template <>
9987
inline std::optional<key_value_view_pair>
9988
33.5k
url_search_params_entries_iter::next() {
9989
33.5k
  if (!has_next()) {
9990
0
    return std::nullopt;
9991
0
  }
9992
33.5k
  return params.params[pos++];
9993
33.5k
}
9994
9995
}  // namespace ada
9996
9997
#endif  // ADA_URL_SEARCH_PARAMS_INL_H
9998
/* end file include/ada/url_search_params-inl.h */
9999
10000
/* begin file include/ada/url_pattern-inl.h */
10001
/**
10002
 * @file url_pattern-inl.h
10003
 * @brief Declaration for the URLPattern inline functions.
10004
 */
10005
#ifndef ADA_URL_PATTERN_INL_H
10006
#define ADA_URL_PATTERN_INL_H
10007
10008
10009
#include <algorithm>
10010
#include <string_view>
10011
#include <utility>
10012
10013
#if ADA_INCLUDE_URL_PATTERN
10014
namespace ada {
10015
10016
0
inline bool url_pattern_init::operator==(const url_pattern_init& other) const {
10017
0
  return protocol == other.protocol && username == other.username &&
10018
0
         password == other.password && hostname == other.hostname &&
10019
0
         port == other.port && search == other.search && hash == other.hash &&
10020
0
         pathname == other.pathname;
10021
0
}
10022
10023
inline bool url_pattern_component_result::operator==(
10024
0
    const url_pattern_component_result& other) const {
10025
0
  return input == other.input && groups == other.groups;
10026
0
}
10027
10028
template <url_pattern_regex::regex_concept regex_provider>
10029
url_pattern_component_result
10030
url_pattern_component<regex_provider>::create_component_match_result(
10031
    std::string&& input,
10032
433k
    std::vector<std::optional<std::string>>&& exec_result) {
10033
  // Let result be a new URLPatternComponentResult.
10034
  // Set result["input"] to input.
10035
  // Let groups be a record<USVString, (USVString or undefined)>.
10036
433k
  auto result =
10037
433k
      url_pattern_component_result{.input = std::move(input), .groups = {}};
10038
10039
  // We explicitly start iterating from 0 even though the spec
10040
  // says we should start from 1. This case is handled by the
10041
  // std_regex_provider which removes the full match from index 0.
10042
  // Use min() to guard against potential mismatches between
10043
  // exec_result size and group_name_list size.
10044
433k
  const size_t size = std::min(exec_result.size(), group_name_list.size());
10045
433k
  result.groups.reserve(size);
10046
859k
  for (size_t index = 0; index < size; index++) {
10047
425k
    result.groups.emplace(group_name_list[index],
10048
425k
                          std::move(exec_result[index]));
10049
425k
  }
10050
433k
  return result;
10051
433k
}
10052
10053
template <url_pattern_regex::regex_concept regex_provider>
10054
std::string_view url_pattern<regex_provider>::get_protocol() const
10055
127k
    ada_lifetime_bound {
10056
  // Return this's associated URL pattern's protocol component's pattern string.
10057
127k
  return protocol_component.pattern;
10058
127k
}
10059
template <url_pattern_regex::regex_concept regex_provider>
10060
std::string_view url_pattern<regex_provider>::get_username() const
10061
127k
    ada_lifetime_bound {
10062
  // Return this's associated URL pattern's username component's pattern string.
10063
127k
  return username_component.pattern;
10064
127k
}
10065
template <url_pattern_regex::regex_concept regex_provider>
10066
std::string_view url_pattern<regex_provider>::get_password() const
10067
127k
    ada_lifetime_bound {
10068
  // Return this's associated URL pattern's password component's pattern string.
10069
127k
  return password_component.pattern;
10070
127k
}
10071
template <url_pattern_regex::regex_concept regex_provider>
10072
std::string_view url_pattern<regex_provider>::get_hostname() const
10073
127k
    ada_lifetime_bound {
10074
  // Return this's associated URL pattern's hostname component's pattern string.
10075
127k
  return hostname_component.pattern;
10076
127k
}
10077
template <url_pattern_regex::regex_concept regex_provider>
10078
std::string_view url_pattern<regex_provider>::get_port() const
10079
127k
    ada_lifetime_bound {
10080
  // Return this's associated URL pattern's port component's pattern string.
10081
127k
  return port_component.pattern;
10082
127k
}
10083
template <url_pattern_regex::regex_concept regex_provider>
10084
std::string_view url_pattern<regex_provider>::get_pathname() const
10085
127k
    ada_lifetime_bound {
10086
  // Return this's associated URL pattern's pathname component's pattern string.
10087
127k
  return pathname_component.pattern;
10088
127k
}
10089
template <url_pattern_regex::regex_concept regex_provider>
10090
std::string_view url_pattern<regex_provider>::get_search() const
10091
127k
    ada_lifetime_bound {
10092
  // Return this's associated URL pattern's search component's pattern string.
10093
127k
  return search_component.pattern;
10094
127k
}
10095
template <url_pattern_regex::regex_concept regex_provider>
10096
std::string_view url_pattern<regex_provider>::get_hash() const
10097
127k
    ada_lifetime_bound {
10098
  // Return this's associated URL pattern's hash component's pattern string.
10099
127k
  return hash_component.pattern;
10100
127k
}
10101
template <url_pattern_regex::regex_concept regex_provider>
10102
127k
bool url_pattern<regex_provider>::ignore_case() const {
10103
127k
  return ignore_case_;
10104
127k
}
10105
template <url_pattern_regex::regex_concept regex_provider>
10106
127k
bool url_pattern<regex_provider>::has_regexp_groups() const {
10107
  // If this's associated URL pattern's has regexp groups, then return true.
10108
127k
  return protocol_component.has_regexp_groups ||
10109
127k
         username_component.has_regexp_groups ||
10110
127k
         password_component.has_regexp_groups ||
10111
127k
         hostname_component.has_regexp_groups ||
10112
127k
         port_component.has_regexp_groups ||
10113
127k
         pathname_component.has_regexp_groups ||
10114
127k
         search_component.has_regexp_groups || hash_component.has_regexp_groups;
10115
127k
}
10116
10117
2.48M
inline bool url_pattern_part::is_regexp() const noexcept {
10118
2.48M
  return type == url_pattern_part_type::REGEXP;
10119
2.48M
}
10120
10121
inline std::string_view url_pattern_compile_component_options::get_delimiter()
10122
3.01M
    const {
10123
3.01M
  if (delimiter) {
10124
1.05M
    return {&delimiter.value(), 1};
10125
1.05M
  }
10126
1.96M
  return {};
10127
3.01M
}
10128
10129
inline std::string_view url_pattern_compile_component_options::get_prefix()
10130
718k
    const {
10131
718k
  if (prefix) {
10132
710k
    return {&prefix.value(), 1};
10133
710k
  }
10134
8.00k
  return {};
10135
718k
}
10136
10137
template <url_pattern_regex::regex_concept regex_provider>
10138
template <url_pattern_encoding_callback F>
10139
tl::expected<url_pattern_component<regex_provider>, errors>
10140
url_pattern_component<regex_provider>::compile(
10141
    std::string_view input, F& encoding_callback,
10142
2.59M
    url_pattern_compile_component_options& options) {
10143
2.59M
  ada_log("url_pattern_component::compile input: ", input);
10144
  // Let part list be the result of running parse a pattern string given input,
10145
  // options, and encoding callback.
10146
2.59M
  auto part_list = url_pattern_helpers::parse_pattern_string(input, options,
10147
2.59M
                                                             encoding_callback);
10148
10149
2.59M
  if (!part_list) {
10150
7.17k
    ada_log("parse_pattern_string failed");
10151
7.17k
    return tl::unexpected(part_list.error());
10152
7.17k
  }
10153
10154
  // Detect pattern type early to potentially skip expensive regex compilation
10155
2.58M
  const auto has_regexp = [](const auto& part) { return part.is_regexp(); };
10156
2.58M
  const bool has_regexp_groups = std::ranges::any_of(*part_list, has_regexp);
10157
10158
2.58M
  url_pattern_component_type component_type =
10159
2.58M
      url_pattern_component_type::REGEXP;
10160
2.58M
  std::string exact_match_value{};
10161
10162
2.58M
  if (part_list->empty()) {
10163
259k
    component_type = url_pattern_component_type::EMPTY;
10164
2.32M
  } else if (part_list->size() == 1) {
10165
2.27M
    const auto& part = (*part_list)[0];
10166
2.27M
    if (part.type == url_pattern_part_type::FIXED_TEXT &&
10167
401k
        part.modifier == url_pattern_part_modifier::none &&
10168
401k
        !options.ignore_case) {
10169
396k
      component_type = url_pattern_component_type::EXACT_MATCH;
10170
396k
      exact_match_value = part.value;
10171
1.88M
    } else if (part.type == url_pattern_part_type::FULL_WILDCARD &&
10172
1.86M
               part.modifier == url_pattern_part_modifier::none &&
10173
1.86M
               part.prefix.empty() && part.suffix.empty()) {
10174
1.81M
      component_type = url_pattern_component_type::FULL_WILDCARD;
10175
1.81M
    }
10176
2.27M
  }
10177
10178
  // For simple patterns, skip regex generation and compilation entirely
10179
2.58M
  if (component_type != url_pattern_component_type::REGEXP) {
10180
2.47M
    auto pattern_string =
10181
2.47M
        url_pattern_helpers::generate_pattern_string(*part_list, options);
10182
    // For FULL_WILDCARD, we need the group name from
10183
    // generate_regular_expression
10184
2.47M
    std::vector<std::string> name_list;
10185
2.47M
    if (component_type == url_pattern_component_type::FULL_WILDCARD &&
10186
1.81M
        !part_list->empty()) {
10187
1.81M
      name_list.push_back((*part_list)[0].name);
10188
1.81M
    }
10189
2.47M
    return url_pattern_component<regex_provider>(
10190
2.47M
        std::move(pattern_string), typename regex_provider::regex_type{},
10191
2.47M
        std::move(name_list), has_regexp_groups, component_type,
10192
2.47M
        std::move(exact_match_value));
10193
2.47M
  }
10194
10195
  // Generate regex for complex patterns
10196
115k
  auto [regular_expression_string, name_list] =
10197
115k
      url_pattern_helpers::generate_regular_expression_and_name_list(*part_list,
10198
115k
                                                                     options);
10199
115k
  auto pattern_string =
10200
115k
      url_pattern_helpers::generate_pattern_string(*part_list, options);
10201
10202
115k
  std::optional<typename regex_provider::regex_type> regular_expression =
10203
115k
      regex_provider::create_instance(regular_expression_string,
10204
115k
                                      options.ignore_case);
10205
115k
  if (!regular_expression) {
10206
3.03k
    return tl::unexpected(errors::type_error);
10207
3.03k
  }
10208
10209
112k
  return url_pattern_component<regex_provider>(
10210
112k
      std::move(pattern_string), std::move(*regular_expression),
10211
112k
      std::move(name_list), has_regexp_groups, component_type,
10212
112k
      std::move(exact_match_value));
10213
115k
}
10214
10215
template <url_pattern_regex::regex_concept regex_provider>
10216
bool url_pattern_component<regex_provider>::fast_test(
10217
900k
    std::string_view input) const noexcept {
10218
  // Fast path for simple patterns - avoid regex evaluation
10219
  // Using if-else for better branch prediction on common cases
10220
900k
  if (type == url_pattern_component_type::FULL_WILDCARD) {
10221
508k
    return true;
10222
508k
  }
10223
391k
  if (type == url_pattern_component_type::EXACT_MATCH) {
10224
208k
    return input == exact_match_value;
10225
208k
  }
10226
182k
  if (type == url_pattern_component_type::EMPTY) {
10227
147k
    return input.empty();
10228
147k
  }
10229
  // type == REGEXP
10230
35.4k
  return regex_provider::regex_match(input, regexp);
10231
182k
}
10232
10233
template <url_pattern_regex::regex_concept regex_provider>
10234
std::optional<std::vector<std::optional<std::string>>>
10235
url_pattern_component<regex_provider>::fast_match(
10236
1.20M
    std::string_view input) const {
10237
  // Handle each type directly without redundant checks
10238
1.20M
  if (type == url_pattern_component_type::FULL_WILDCARD) {
10239
    // FULL_WILDCARD always matches - capture the input (even if empty)
10240
    // If there's no group name, return empty groups
10241
552k
    if (group_name_list.empty()) {
10242
0
      return std::vector<std::optional<std::string>>{};
10243
0
    }
10244
    // Capture the matched input (including empty strings)
10245
552k
    return std::vector<std::optional<std::string>>{std::string(input)};
10246
552k
  }
10247
648k
  if (type == url_pattern_component_type::EXACT_MATCH) {
10248
392k
    if (input == exact_match_value) {
10249
67.8k
      return std::vector<std::optional<std::string>>{};
10250
67.8k
    }
10251
325k
    return std::nullopt;
10252
392k
  }
10253
255k
  if (type == url_pattern_component_type::EMPTY) {
10254
147k
    if (input.empty()) {
10255
126k
      return std::vector<std::optional<std::string>>{};
10256
126k
    }
10257
20.8k
    return std::nullopt;
10258
147k
  }
10259
  // type == REGEXP - use regex
10260
107k
  return regex_provider::regex_search(input, regexp);
10261
255k
}
10262
10263
template <url_pattern_regex::regex_concept regex_provider>
10264
result<std::optional<url_pattern_result>> url_pattern<regex_provider>::exec(
10265
383k
    const url_pattern_input& input, const std::string_view* base_url) {
10266
  // Return the result of match given this's associated URL pattern, input, and
10267
  // baseURL if given.
10268
383k
  return match(input, base_url);
10269
383k
}
10270
10271
template <url_pattern_regex::regex_concept regex_provider>
10272
bool url_pattern<regex_provider>::test_components(
10273
    std::string_view protocol, std::string_view username,
10274
    std::string_view password, std::string_view hostname, std::string_view port,
10275
    std::string_view pathname, std::string_view search,
10276
241k
    std::string_view hash) const {
10277
241k
  return protocol_component.fast_test(protocol) &&
10278
123k
         username_component.fast_test(username) &&
10279
122k
         password_component.fast_test(password) &&
10280
122k
         hostname_component.fast_test(hostname) &&
10281
77.3k
         port_component.fast_test(port) &&
10282
77.0k
         pathname_component.fast_test(pathname) &&
10283
54.2k
         search_component.fast_test(search) && hash_component.fast_test(hash);
10284
241k
}
10285
10286
template <url_pattern_regex::regex_concept regex_provider>
10287
result<bool> url_pattern<regex_provider>::test(
10288
383k
    const url_pattern_input& input, const std::string_view* base_url_string) {
10289
  // If input is a URLPatternInit
10290
383k
  if (std::holds_alternative<url_pattern_init>(input)) {
10291
127k
    if (base_url_string) {
10292
0
      return tl::unexpected(errors::type_error);
10293
0
    }
10294
10295
127k
    std::string protocol{}, username{}, password{}, hostname{};
10296
127k
    std::string port{}, pathname{}, search{}, hash{};
10297
10298
127k
    auto apply_result = url_pattern_init::process(
10299
127k
        std::get<url_pattern_init>(input), url_pattern_init::process_type::url,
10300
127k
        protocol, username, password, hostname, port, pathname, search, hash);
10301
10302
127k
    if (!apply_result) {
10303
287
      return false;
10304
287
    }
10305
10306
127k
    std::string_view search_view = *apply_result->search;
10307
127k
    if (search_view.starts_with("?")) {
10308
0
      search_view.remove_prefix(1);
10309
0
    }
10310
10311
127k
    return test_components(*apply_result->protocol, *apply_result->username,
10312
127k
                           *apply_result->password, *apply_result->hostname,
10313
127k
                           *apply_result->port, *apply_result->pathname,
10314
127k
                           search_view, *apply_result->hash);
10315
127k
  }
10316
10317
  // URL string input path
10318
255k
  result<url_aggregator> base_url;
10319
255k
  if (base_url_string) {
10320
127k
    base_url = ada::parse<url_aggregator>(*base_url_string, nullptr);
10321
127k
    if (!base_url) {
10322
0
      return false;
10323
0
    }
10324
127k
  }
10325
10326
255k
  auto url =
10327
255k
      ada::parse<url_aggregator>(std::get<std::string_view>(input),
10328
255k
                                 base_url.has_value() ? &*base_url : nullptr);
10329
255k
  if (!url) {
10330
180k
    return false;
10331
180k
  }
10332
10333
  // Extract components as string_view
10334
75.6k
  auto protocol_view = url->get_protocol();
10335
75.6k
  if (protocol_view.ends_with(":")) {
10336
75.6k
    protocol_view.remove_suffix(1);
10337
75.6k
  }
10338
10339
75.6k
  auto search_view = url->get_search();
10340
75.6k
  if (search_view.starts_with("?")) {
10341
6.55k
    search_view.remove_prefix(1);
10342
6.55k
  }
10343
10344
75.6k
  auto hash_view = url->get_hash();
10345
75.6k
  if (hash_view.starts_with("#")) {
10346
6.11k
    hash_view.remove_prefix(1);
10347
6.11k
  }
10348
10349
75.6k
  return test_components(protocol_view, url->get_username(),
10350
75.6k
                         url->get_password(), url->get_hostname(),
10351
75.6k
                         url->get_port(), url->get_pathname(), search_view,
10352
75.6k
                         hash_view);
10353
255k
}
10354
10355
template <url_pattern_regex::regex_concept regex_provider>
10356
result<std::optional<url_pattern_result>> url_pattern<regex_provider>::match(
10357
511k
    const url_pattern_input& input, const std::string_view* base_url_string) {
10358
511k
  std::string protocol{};
10359
511k
  std::string username{};
10360
511k
  std::string password{};
10361
511k
  std::string hostname{};
10362
511k
  std::string port{};
10363
511k
  std::string pathname{};
10364
511k
  std::string search{};
10365
511k
  std::string hash{};
10366
10367
  // Let inputs be an empty list.
10368
  // Append input to inputs.
10369
511k
  std::vector inputs{input};
10370
10371
  // If input is a URLPatternInit then:
10372
511k
  if (std::holds_alternative<url_pattern_init>(input)) {
10373
127k
    ada_log(
10374
127k
        "url_pattern::match called with url_pattern_init and base_url_string=",
10375
127k
        base_url_string);
10376
    // If baseURLString was given, throw a TypeError.
10377
127k
    if (base_url_string) {
10378
0
      ada_log("failed to match because base_url_string was given");
10379
0
      return tl::unexpected(errors::type_error);
10380
0
    }
10381
10382
    // Let applyResult be the result of process a URLPatternInit given input,
10383
    // "url", protocol, username, password, hostname, port, pathname, search,
10384
    // and hash.
10385
127k
    auto apply_result = url_pattern_init::process(
10386
127k
        std::get<url_pattern_init>(input), url_pattern_init::process_type::url,
10387
127k
        protocol, username, password, hostname, port, pathname, search, hash);
10388
10389
    // If this throws an exception, catch it, and return null.
10390
127k
    if (!apply_result.has_value()) {
10391
287
      ada_log("match returned std::nullopt because process threw");
10392
287
      return std::nullopt;
10393
287
    }
10394
10395
    // Set protocol to applyResult["protocol"].
10396
127k
    ADA_ASSERT_TRUE(apply_result->protocol.has_value());
10397
127k
    protocol = std::move(apply_result->protocol.value());
10398
10399
    // Set username to applyResult["username"].
10400
127k
    ADA_ASSERT_TRUE(apply_result->username.has_value());
10401
127k
    username = std::move(apply_result->username.value());
10402
10403
    // Set password to applyResult["password"].
10404
127k
    ADA_ASSERT_TRUE(apply_result->password.has_value());
10405
127k
    password = std::move(apply_result->password.value());
10406
10407
    // Set hostname to applyResult["hostname"].
10408
127k
    ADA_ASSERT_TRUE(apply_result->hostname.has_value());
10409
127k
    hostname = std::move(apply_result->hostname.value());
10410
10411
    // Set port to applyResult["port"].
10412
127k
    ADA_ASSERT_TRUE(apply_result->port.has_value());
10413
127k
    port = std::move(apply_result->port.value());
10414
10415
    // Set pathname to applyResult["pathname"].
10416
127k
    ADA_ASSERT_TRUE(apply_result->pathname.has_value());
10417
127k
    pathname = std::move(apply_result->pathname.value());
10418
10419
    // Set search to applyResult["search"].
10420
127k
    ADA_ASSERT_TRUE(apply_result->search.has_value());
10421
127k
    if (apply_result->search->starts_with("?")) {
10422
0
      search = apply_result->search->substr(1);
10423
127k
    } else {
10424
127k
      search = std::move(apply_result->search.value());
10425
127k
    }
10426
10427
    // Set hash to applyResult["hash"].
10428
127k
    ADA_ASSERT_TRUE(apply_result->hash.has_value());
10429
127k
    ADA_ASSERT_TRUE(!apply_result->hash->starts_with("#"));
10430
127k
    hash = std::move(apply_result->hash.value());
10431
383k
  } else {
10432
383k
    ADA_ASSERT_TRUE(std::holds_alternative<std::string_view>(input));
10433
10434
    // Let baseURL be null.
10435
383k
    result<url_aggregator> base_url;
10436
10437
    // If baseURLString was given, then:
10438
383k
    if (base_url_string) {
10439
      // Let baseURL be the result of parsing baseURLString.
10440
127k
      base_url = ada::parse<url_aggregator>(*base_url_string, nullptr);
10441
10442
      // If baseURL is failure, return null.
10443
127k
      if (!base_url) {
10444
0
        ada_log("match returned std::nullopt because failed to parse base_url=",
10445
0
                *base_url_string);
10446
0
        return std::nullopt;
10447
0
      }
10448
10449
      // Append baseURLString to inputs.
10450
127k
      inputs.emplace_back(*base_url_string);
10451
127k
    }
10452
10453
383k
    url_aggregator* base_url_value =
10454
383k
        base_url.has_value() ? &*base_url : nullptr;
10455
10456
    // Set url to the result of parsing input given baseURL.
10457
383k
    auto url = ada::parse<url_aggregator>(std::get<std::string_view>(input),
10458
383k
                                          base_url_value);
10459
10460
    // If url is failure, return null.
10461
383k
    if (!url) {
10462
270k
      ada_log("match returned std::nullopt because url failed");
10463
270k
      return std::nullopt;
10464
270k
    }
10465
10466
    // Set protocol to url's scheme.
10467
    // IMPORTANT: Not documented on the URLPattern spec, but protocol suffix ':'
10468
    // is removed. Similar work was done on workerd:
10469
    // https://github.com/cloudflare/workerd/blob/8620d14012513a6ce04d079e401d3becac3c67bd/src/workerd/jsg/url.c%2B%2B#L2038
10470
113k
    protocol = url->get_protocol().substr(0, url->get_protocol().size() - 1);
10471
    // Set username to url's username.
10472
113k
    username = url->get_username();
10473
    // Set password to url's password.
10474
113k
    password = url->get_password();
10475
    // Set hostname to url's host, serialized, or the empty string if the value
10476
    // is null.
10477
113k
    hostname = url->get_hostname();
10478
    // Set port to url's port, serialized, or the empty string if the value is
10479
    // null.
10480
113k
    port = url->get_port();
10481
    // Set pathname to the result of URL path serializing url.
10482
113k
    pathname = url->get_pathname();
10483
    // Set search to url's query or the empty string if the value is null.
10484
    // IMPORTANT: Not documented on the URLPattern spec, but search prefix '?'
10485
    // is removed. Similar work was done on workerd:
10486
    // https://github.com/cloudflare/workerd/blob/8620d14012513a6ce04d079e401d3becac3c67bd/src/workerd/jsg/url.c%2B%2B#L2232
10487
113k
    if (url->has_search()) {
10488
10.8k
      auto view = url->get_search();
10489
10.8k
      search = view.starts_with("?") ? url->get_search().substr(1) : view;
10490
10.8k
    }
10491
    // Set hash to url's fragment or the empty string if the value is null.
10492
    // IMPORTANT: Not documented on the URLPattern spec, but hash prefix '#' is
10493
    // removed. Similar work was done on workerd:
10494
    // https://github.com/cloudflare/workerd/blob/8620d14012513a6ce04d079e401d3becac3c67bd/src/workerd/jsg/url.c%2B%2B#L2242
10495
113k
    if (url->has_hash()) {
10496
9.93k
      auto view = url->get_hash();
10497
9.93k
      hash = view.starts_with("#") ? url->get_hash().substr(1) : view;
10498
9.93k
    }
10499
113k
  }
10500
10501
  // Use fast_match which skips regex for simple patterns (EMPTY, EXACT_MATCH,
10502
  // FULL_WILDCARD) and only falls back to regex for complex REGEXP patterns.
10503
10504
  // Let protocolExecResult be RegExpBuiltinExec(urlPattern's protocol
10505
  // component's regular expression, protocol).
10506
241k
  auto protocol_exec_result = protocol_component.fast_match(protocol);
10507
241k
  if (!protocol_exec_result) {
10508
95.7k
    return std::nullopt;
10509
95.7k
  }
10510
10511
  // Let usernameExecResult be RegExpBuiltinExec(urlPattern's username
10512
  // component's regular expression, username).
10513
145k
  auto username_exec_result = username_component.fast_match(username);
10514
145k
  if (!username_exec_result) {
10515
1.04k
    return std::nullopt;
10516
1.04k
  }
10517
10518
  // Let passwordExecResult be RegExpBuiltinExec(urlPattern's password
10519
  // component's regular expression, password).
10520
144k
  auto password_exec_result = password_component.fast_match(password);
10521
144k
  if (!password_exec_result) {
10522
420
    return std::nullopt;
10523
420
  }
10524
10525
  // Let hostnameExecResult be RegExpBuiltinExec(urlPattern's hostname
10526
  // component's regular expression, hostname).
10527
143k
  auto hostname_exec_result = hostname_component.fast_match(hostname);
10528
143k
  if (!hostname_exec_result) {
10529
66.2k
    return std::nullopt;
10530
66.2k
  }
10531
10532
  // Let portExecResult be RegExpBuiltinExec(urlPattern's port component's
10533
  // regular expression, port).
10534
77.6k
  auto port_exec_result = port_component.fast_match(port);
10535
77.6k
  if (!port_exec_result) {
10536
302
    return std::nullopt;
10537
302
  }
10538
10539
  // Let pathnameExecResult be RegExpBuiltinExec(urlPattern's pathname
10540
  // component's regular expression, pathname).
10541
77.3k
  auto pathname_exec_result = pathname_component.fast_match(pathname);
10542
77.3k
  if (!pathname_exec_result) {
10543
22.8k
    return std::nullopt;
10544
22.8k
  }
10545
10546
  // Let searchExecResult be RegExpBuiltinExec(urlPattern's search component's
10547
  // regular expression, search).
10548
54.4k
  auto search_exec_result = search_component.fast_match(search);
10549
54.4k
  if (!search_exec_result) {
10550
169
    return std::nullopt;
10551
169
  }
10552
10553
  // Let hashExecResult be RegExpBuiltinExec(urlPattern's hash component's
10554
  // regular expression, hash).
10555
54.3k
  auto hash_exec_result = hash_component.fast_match(hash);
10556
54.3k
  if (!hash_exec_result) {
10557
83
    return std::nullopt;
10558
83
  }
10559
10560
  // Let result be a new URLPatternResult.
10561
54.2k
  auto result = url_pattern_result{};
10562
  // Set result["inputs"] to inputs.
10563
54.2k
  result.inputs = std::move(inputs);
10564
  // Set result["protocol"] to the result of creating a component match result
10565
  // given urlPattern's protocol component, protocol, and protocolExecResult.
10566
54.2k
  result.protocol = protocol_component.create_component_match_result(
10567
54.2k
      std::move(protocol), std::move(*protocol_exec_result));
10568
10569
  // Set result["username"] to the result of creating a component match result
10570
  // given urlPattern's username component, username, and usernameExecResult.
10571
54.2k
  result.username = username_component.create_component_match_result(
10572
54.2k
      std::move(username), std::move(*username_exec_result));
10573
10574
  // Set result["password"] to the result of creating a component match result
10575
  // given urlPattern's password component, password, and passwordExecResult.
10576
54.2k
  result.password = password_component.create_component_match_result(
10577
54.2k
      std::move(password), std::move(*password_exec_result));
10578
10579
  // Set result["hostname"] to the result of creating a component match result
10580
  // given urlPattern's hostname component, hostname, and hostnameExecResult.
10581
54.2k
  result.hostname = hostname_component.create_component_match_result(
10582
54.2k
      std::move(hostname), std::move(*hostname_exec_result));
10583
10584
  // Set result["port"] to the result of creating a component match result given
10585
  // urlPattern's port component, port, and portExecResult.
10586
54.2k
  result.port = port_component.create_component_match_result(
10587
54.2k
      std::move(port), std::move(*port_exec_result));
10588
10589
  // Set result["pathname"] to the result of creating a component match result
10590
  // given urlPattern's pathname component, pathname, and pathnameExecResult.
10591
54.2k
  result.pathname = pathname_component.create_component_match_result(
10592
54.2k
      std::move(pathname), std::move(*pathname_exec_result));
10593
10594
  // Set result["search"] to the result of creating a component match result
10595
  // given urlPattern's search component, search, and searchExecResult.
10596
54.2k
  result.search = search_component.create_component_match_result(
10597
54.2k
      std::move(search), std::move(*search_exec_result));
10598
10599
  // Set result["hash"] to the result of creating a component match result given
10600
  // urlPattern's hash component, hash, and hashExecResult.
10601
54.2k
  result.hash = hash_component.create_component_match_result(
10602
54.2k
      std::move(hash), std::move(*hash_exec_result));
10603
10604
54.2k
  return result;
10605
54.3k
}
10606
10607
}  // namespace ada
10608
#endif  // ADA_INCLUDE_URL_PATTERN
10609
#endif
10610
/* end file include/ada/url_pattern-inl.h */
10611
/* begin file include/ada/url_pattern_helpers-inl.h */
10612
/**
10613
 * @file url_pattern_helpers-inl.h
10614
 * @brief Declaration for the URLPattern helpers.
10615
 */
10616
#ifndef ADA_URL_PATTERN_HELPERS_INL_H
10617
#define ADA_URL_PATTERN_HELPERS_INL_H
10618
10619
#include <optional>
10620
#include <string_view>
10621
10622
10623
#if ADA_INCLUDE_URL_PATTERN
10624
namespace ada::url_pattern_helpers {
10625
#if defined(ADA_TESTING) || defined(ADA_LOGGING)
10626
0
inline std::string to_string(token_type type) {
10627
0
  switch (type) {
10628
0
    case token_type::INVALID_CHAR:
10629
0
      return "INVALID_CHAR";
10630
0
    case token_type::OPEN:
10631
0
      return "OPEN";
10632
0
    case token_type::CLOSE:
10633
0
      return "CLOSE";
10634
0
    case token_type::REGEXP:
10635
0
      return "REGEXP";
10636
0
    case token_type::NAME:
10637
0
      return "NAME";
10638
0
    case token_type::CHAR:
10639
0
      return "CHAR";
10640
0
    case token_type::ESCAPED_CHAR:
10641
0
      return "ESCAPED_CHAR";
10642
0
    case token_type::OTHER_MODIFIER:
10643
0
      return "OTHER_MODIFIER";
10644
0
    case token_type::ASTERISK:
10645
0
      return "ASTERISK";
10646
0
    case token_type::END:
10647
0
      return "END";
10648
0
    default:
10649
0
      ada::unreachable();
10650
0
  }
10651
0
}
10652
#endif  // defined(ADA_TESTING) || defined(ADA_LOGGING)
10653
10654
template <url_pattern_regex::regex_concept regex_provider>
10655
133k
constexpr void constructor_string_parser<regex_provider>::rewind() {
10656
  // Set parser's token index to parser's component start.
10657
133k
  token_index = component_start;
10658
  // Set parser's token increment to 0.
10659
133k
  token_increment = 0;
10660
133k
}
10661
10662
template <url_pattern_regex::regex_concept regex_provider>
10663
1.20M
constexpr bool constructor_string_parser<regex_provider>::is_hash_prefix() {
10664
  // Return the result of running is a non-special pattern char given parser,
10665
  // parser's token index and "#".
10666
1.20M
  return is_non_special_pattern_char(token_index, '#');
10667
1.20M
}
10668
10669
template <url_pattern_regex::regex_concept regex_provider>
10670
1.20M
constexpr bool constructor_string_parser<regex_provider>::is_search_prefix() {
10671
  // If result of running is a non-special pattern char given parser, parser's
10672
  // token index and "?" is true, then return true.
10673
1.20M
  if (is_non_special_pattern_char(token_index, '?')) {
10674
3
    return true;
10675
3
  }
10676
10677
  // If parser's token list[parser's token index]'s value is not "?", then
10678
  // return false.
10679
1.20M
  if (token_list[token_index].value != "?") {
10680
1.20M
    return false;
10681
1.20M
  }
10682
10683
  // If previous index is less than 0, then return true.
10684
864
  if (token_index == 0) return true;
10685
  // Let previous index be parser's token index - 1.
10686
864
  auto previous_index = token_index - 1;
10687
  // Let previous token be the result of running get a safe token given parser
10688
  // and previous index.
10689
864
  auto previous_token = get_safe_token(previous_index);
10690
864
  ADA_ASSERT_TRUE(previous_token);
10691
  // If any of the following are true, then return false:
10692
  // - previous token's type is "name".
10693
  // - previous token's type is "regexp".
10694
  // - previous token's type is "close".
10695
  // - previous token's type is "asterisk".
10696
864
  return !(previous_token->type == token_type::NAME ||
10697
789
           previous_token->type == token_type::REGEXP ||
10698
708
           previous_token->type == token_type::CLOSE ||
10699
492
           previous_token->type == token_type::ASTERISK);
10700
864
}
10701
10702
template <url_pattern_regex::regex_concept regex_provider>
10703
constexpr bool
10704
constructor_string_parser<regex_provider>::is_non_special_pattern_char(
10705
6.37M
    size_t index, uint32_t value) const {
10706
  // Let token be the result of running get a safe token given parser and index.
10707
6.37M
  auto token = get_safe_token(index);
10708
6.37M
  ADA_ASSERT_TRUE(token);
10709
10710
  // If token's value is not value, then return false.
10711
  // TODO: Remove this once we make sure get_safe_token returns a non-empty
10712
  // string.
10713
6.37M
  if (!token->value.empty() &&
10714
6.37M
      static_cast<uint32_t>(token->value[0]) != value) {
10715
6.10M
    return false;
10716
6.10M
  }
10717
10718
  // If any of the following are true:
10719
  // - token's type is "char";
10720
  // - token's type is "escaped-char"; or
10721
  // - token's type is "invalid-char",
10722
  // - then return true.
10723
271k
  return token->type == token_type::CHAR ||
10724
93.5k
         token->type == token_type::ESCAPED_CHAR ||
10725
93.5k
         token->type == token_type::INVALID_CHAR;
10726
6.37M
}
10727
10728
template <url_pattern_regex::regex_concept regex_provider>
10729
constexpr const token*
10730
6.59M
constructor_string_parser<regex_provider>::get_safe_token(size_t index) const {
10731
  // If index is less than parser's token list's size, then return parser's
10732
  // token list[index].
10733
6.59M
  if (index < token_list.size()) [[likely]] {
10734
6.59M
    return &token_list[index];
10735
6.59M
  }
10736
10737
  // Assert: parser's token list's size is greater than or equal to 1.
10738
0
  ADA_ASSERT_TRUE(!token_list.empty());
10739
10740
  // Let token be parser's token list[last index].
10741
  // Assert: token's type is "end".
10742
0
  ADA_ASSERT_TRUE(token_list.back().type == token_type::END);
10743
10744
  // Return token.
10745
0
  return &token_list.back();
10746
6.59M
}
10747
10748
template <url_pattern_regex::regex_concept regex_provider>
10749
constexpr bool constructor_string_parser<regex_provider>::is_group_open()
10750
1.94M
    const {
10751
  // If parser's token list[parser's token index]'s type is "open", then return
10752
  // true.
10753
1.94M
  return token_list[token_index].type == token_type::OPEN;
10754
1.94M
}
10755
10756
template <url_pattern_regex::regex_concept regex_provider>
10757
constexpr bool constructor_string_parser<regex_provider>::is_group_close()
10758
13.5k
    const {
10759
  // If parser's token list[parser's token index]'s type is "close", then return
10760
  // true.
10761
13.5k
  return token_list[token_index].type == token_type::CLOSE;
10762
13.5k
}
10763
10764
template <url_pattern_regex::regex_concept regex_provider>
10765
constexpr bool
10766
44.4k
constructor_string_parser<regex_provider>::next_is_authority_slashes() const {
10767
  // If the result of running is a non-special pattern char given parser,
10768
  // parser's token index + 1, and "/" is false, then return false.
10769
44.4k
  if (!is_non_special_pattern_char(token_index + 1, '/')) {
10770
0
    return false;
10771
0
  }
10772
  // If the result of running is a non-special pattern char given parser,
10773
  // parser's token index + 2, and "/" is false, then return false.
10774
44.4k
  if (!is_non_special_pattern_char(token_index + 2, '/')) {
10775
0
    return false;
10776
0
  }
10777
44.4k
  return true;
10778
44.4k
}
10779
10780
template <url_pattern_regex::regex_concept regex_provider>
10781
constexpr bool constructor_string_parser<regex_provider>::is_protocol_suffix()
10782
671k
    const {
10783
  // Return the result of running is a non-special pattern char given parser,
10784
  // parser's token index, and ":".
10785
671k
  return is_non_special_pattern_char(token_index, ':');
10786
671k
}
10787
10788
template <url_pattern_regex::regex_concept regex_provider>
10789
void constructor_string_parser<regex_provider>::change_state(State new_state,
10790
310k
                                                             size_t skip) {
10791
  // If parser's state is not "init", not "authority", and not "done", then set
10792
  // parser's result[parser's state] to the result of running make a component
10793
  // string given parser.
10794
310k
  if (state != State::INIT && state != State::AUTHORITY &&
10795
176k
      state != State::DONE) {
10796
176k
    auto value = make_component_string();
10797
    // TODO: Simplify this.
10798
176k
    switch (state) {
10799
44.4k
      case State::PROTOCOL: {
10800
44.4k
        result.protocol = value;
10801
44.4k
        break;
10802
0
      }
10803
0
      case State::USERNAME: {
10804
0
        result.username = value;
10805
0
        break;
10806
0
      }
10807
0
      case State::PASSWORD: {
10808
0
        result.password = value;
10809
0
        break;
10810
0
      }
10811
44.4k
      case State::HOSTNAME: {
10812
44.4k
        result.hostname = value;
10813
44.4k
        break;
10814
0
      }
10815
0
      case State::PORT: {
10816
0
        result.port = value;
10817
0
        break;
10818
0
      }
10819
87.5k
      case State::PATHNAME: {
10820
87.5k
        result.pathname = value;
10821
87.5k
        break;
10822
0
      }
10823
198
      case State::SEARCH: {
10824
198
        result.search = value;
10825
198
        break;
10826
0
      }
10827
141
      case State::HASH: {
10828
141
        result.hash = value;
10829
141
        break;
10830
0
      }
10831
0
      default:
10832
0
        ada::unreachable();
10833
176k
    }
10834
176k
  }
10835
10836
  // If parser's state is not "init" and new state is not "done", then:
10837
310k
  if (state != State::INIT && new_state != State::DONE) {
10838
    // If parser's state is "protocol", "authority", "username", or "password";
10839
    // new state is "port", "pathname", "search", or "hash"; and parser's
10840
    // result["hostname"] does not exist, then set parser's result["hostname"]
10841
    // to the empty string.
10842
133k
    if ((state == State::PROTOCOL || state == State::AUTHORITY ||
10843
44.8k
         state == State::USERNAME || state == State::PASSWORD) &&
10844
88.9k
        (new_state == State::PORT || new_state == State::PATHNAME ||
10845
88.9k
         new_state == State::SEARCH || new_state == State::HASH) &&
10846
0
        !result.hostname)
10847
0
      result.hostname = "";
10848
133k
  }
10849
10850
  // If parser's state is "protocol", "authority", "username", "password",
10851
  // "hostname", or "port"; new state is "search" or "hash"; and parser's
10852
  // result["pathname"] does not exist, then:
10853
310k
  if ((state == State::PROTOCOL || state == State::AUTHORITY ||
10854
221k
       state == State::USERNAME || state == State::PASSWORD ||
10855
221k
       state == State::HOSTNAME || state == State::PORT) &&
10856
133k
      (new_state == State::SEARCH || new_state == State::HASH) &&
10857
0
      !result.pathname) {
10858
0
    if (protocol_matches_a_special_scheme_flag) {
10859
0
      result.pathname = "/";
10860
0
    } else {
10861
      // Otherwise, set parser's result["pathname"] to the empty string.
10862
0
      result.pathname = "";
10863
0
    }
10864
0
  }
10865
10866
  // If parser's state is "protocol", "authority", "username", "password",
10867
  // "hostname", "port", or "pathname"; new state is "hash"; and parser's
10868
  // result["search"] does not exist, then set parser's result["search"] to
10869
  // the empty string.
10870
310k
  if ((state == State::PROTOCOL || state == State::AUTHORITY ||
10871
221k
       state == State::USERNAME || state == State::PASSWORD ||
10872
221k
       state == State::HOSTNAME || state == State::PORT ||
10873
176k
       state == State::PATHNAME) &&
10874
220k
      new_state == State::HASH && !result.search) {
10875
105
    result.search = "";
10876
105
  }
10877
10878
  // Set parser's state to new state.
10879
310k
  state = new_state;
10880
  // Increment parser's token index by skip.
10881
310k
  token_index += skip;
10882
  // Set parser's component start to parser's token index.
10883
310k
  component_start = token_index;
10884
  // Set parser's token increment to 0.
10885
310k
  token_increment = 0;
10886
310k
}
10887
10888
template <url_pattern_regex::regex_concept regex_provider>
10889
222k
std::string constructor_string_parser<regex_provider>::make_component_string() {
10890
  // Assert: parser's token index is less than parser's token list's size.
10891
222k
  ADA_ASSERT_TRUE(token_index < token_list.size());
10892
10893
  // Let token be parser's token list[parser's token index].
10894
  // Let end index be token's index.
10895
222k
  const auto end_index = token_list[token_index].index;
10896
  // Let component start token be the result of running get a safe token given
10897
  // parser and parser's component start.
10898
222k
  const auto component_start_token = get_safe_token(component_start);
10899
222k
  ADA_ASSERT_TRUE(component_start_token);
10900
  // Let component start input index be component start token's index.
10901
222k
  const auto component_start_input_index = component_start_token->index;
10902
  // Return the code point substring from component start input index to end
10903
  // index within parser's input.
10904
222k
  return std::string(input.substr(component_start_input_index,
10905
222k
                                  end_index - component_start_input_index));
10906
222k
}
10907
10908
template <url_pattern_regex::regex_concept regex_provider>
10909
constexpr bool
10910
533k
constructor_string_parser<regex_provider>::is_an_identity_terminator() const {
10911
  // Return the result of running is a non-special pattern char given parser,
10912
  // parser's token index, and "@".
10913
533k
  return is_non_special_pattern_char(token_index, '@');
10914
533k
}
10915
10916
template <url_pattern_regex::regex_concept regex_provider>
10917
constexpr bool constructor_string_parser<regex_provider>::is_pathname_start()
10918
1.06M
    const {
10919
  // Return the result of running is a non-special pattern char given parser,
10920
  // parser's token index, and "/".
10921
1.06M
  return is_non_special_pattern_char(token_index, '/');
10922
1.06M
}
10923
10924
template <url_pattern_regex::regex_concept regex_provider>
10925
constexpr bool constructor_string_parser<regex_provider>::is_password_prefix()
10926
0
    const {
10927
  // Return the result of running is a non-special pattern char given parser,
10928
  // parser's token index, and ":".
10929
0
  return is_non_special_pattern_char(token_index, ':');
10930
0
}
10931
10932
template <url_pattern_regex::regex_concept regex_provider>
10933
constexpr bool constructor_string_parser<regex_provider>::is_an_ipv6_open()
10934
533k
    const {
10935
  // Return the result of running is a non-special pattern char given parser,
10936
  // parser's token index, and "[".
10937
533k
  return is_non_special_pattern_char(token_index, '[');
10938
533k
}
10939
10940
template <url_pattern_regex::regex_concept regex_provider>
10941
constexpr bool constructor_string_parser<regex_provider>::is_an_ipv6_close()
10942
533k
    const {
10943
  // Return the result of running is a non-special pattern char given parser,
10944
  // parser's token index, and "]".
10945
533k
  return is_non_special_pattern_char(token_index, ']');
10946
533k
}
10947
10948
template <url_pattern_regex::regex_concept regex_provider>
10949
constexpr bool constructor_string_parser<regex_provider>::is_port_prefix()
10950
533k
    const {
10951
  // Return the result of running is a non-special pattern char given parser,
10952
  // parser's token index, and ":".
10953
533k
  return is_non_special_pattern_char(token_index, ':');
10954
533k
}
10955
10956
10.3M
constexpr void Tokenizer::get_next_code_point() {
10957
10.3M
  ada_log("Tokenizer::get_next_code_point called with index=", next_index);
10958
10.3M
  ADA_ASSERT_TRUE(next_index < input.size());
10959
  // Decode the next UTF-8 code point. If malformed or truncated, mark it as
10960
  // invalid, return the offending byte as the code point, and advance by one
10961
  // to guarantee forward progress.
10962
10.3M
  invalid_code_point = false;
10963
10.3M
  code_point = 0;
10964
10.3M
  size_t number_bytes = 0;
10965
10.3M
  const size_t initial_index = next_index;
10966
10.3M
  unsigned char first_byte = input[next_index];
10967
10968
10.3M
  if ((first_byte & 0x80) == 0) {
10969
    // 1-byte character (ASCII)
10970
10.3M
    next_index++;
10971
10.3M
    code_point = first_byte;
10972
10.3M
    ada_log("Tokenizer::get_next_code_point returning ASCII code point=",
10973
10.3M
            uint32_t(code_point));
10974
10.3M
    ada_log("Tokenizer::get_next_code_point next_index =", next_index,
10975
10.3M
            " input.size()=", input.size());
10976
10.3M
    return;
10977
10.3M
  }
10978
0
  ada_log("Tokenizer::get_next_code_point read first byte=",
10979
0
          uint32_t(first_byte));
10980
0
  if ((first_byte & 0xE0) == 0xC0) {
10981
0
    code_point = first_byte & 0x1F;
10982
0
    number_bytes = 2;
10983
0
    ada_log("Tokenizer::get_next_code_point two bytes");
10984
0
  } else if ((first_byte & 0xF0) == 0xE0) {
10985
0
    code_point = first_byte & 0x0F;
10986
0
    number_bytes = 3;
10987
0
    ada_log("Tokenizer::get_next_code_point three bytes");
10988
0
  } else if ((first_byte & 0xF8) == 0xF0) {
10989
0
    code_point = first_byte & 0x07;
10990
0
    number_bytes = 4;
10991
0
    ada_log("Tokenizer::get_next_code_point four bytes");
10992
0
  }
10993
10994
  // Invalid leading bytes that still match a multi-byte prefix.
10995
0
  if ((number_bytes == 2 && first_byte < 0xC2) ||
10996
0
      (number_bytes == 4 && first_byte > 0xF4)) {
10997
0
    invalid_code_point = true;
10998
0
    code_point = first_byte;
10999
0
    next_index = initial_index + 1;
11000
0
    return;
11001
0
  }
11002
11003
  // Invalid leading byte (e.g., continuation byte outside a sequence).
11004
0
  if (number_bytes == 0) {
11005
0
    invalid_code_point = true;
11006
0
    code_point = first_byte;
11007
0
    next_index = initial_index + 1;
11008
0
    return;
11009
0
  }
11010
11011
  // Truncated UTF-8 sequence.
11012
0
  if (number_bytes + next_index > input.size()) {
11013
0
    invalid_code_point = true;
11014
0
    code_point = first_byte;
11015
0
    next_index = initial_index + 1;
11016
0
    return;
11017
0
  }
11018
11019
0
  for (size_t i = 1 + next_index; i < number_bytes + next_index; ++i) {
11020
0
    unsigned char byte = input[i];
11021
0
    if ((byte & 0xC0) != 0x80) {
11022
0
      invalid_code_point = true;
11023
0
      code_point = first_byte;
11024
0
      next_index = initial_index + 1;
11025
0
      return;
11026
0
    }
11027
0
    ada_log("Tokenizer::get_next_code_point read byte=", uint32_t(byte));
11028
0
    code_point = (code_point << 6) | (byte & 0x3F);
11029
0
  }
11030
0
  ada_log("Tokenizer::get_next_code_point returning non-ASCII code point=",
11031
0
          uint32_t(code_point));
11032
0
  ada_log("Tokenizer::get_next_code_point next_index =", next_index,
11033
0
          " input.size()=", input.size());
11034
0
  next_index += number_bytes;
11035
0
}
11036
11037
10.3M
constexpr void Tokenizer::seek_and_get_next_code_point(size_t new_index) {
11038
10.3M
  ada_log("Tokenizer::seek_and_get_next_code_point called with new_index=",
11039
10.3M
          new_index);
11040
  // Set tokenizer's next index to index.
11041
10.3M
  next_index = new_index;
11042
  // Run get the next code point given tokenizer.
11043
10.3M
  get_next_code_point();
11044
10.3M
}
11045
11046
inline void Tokenizer::add_token(token_type type, size_t next_position,
11047
12.0M
                                 size_t value_position, size_t value_length) {
11048
12.0M
  ada_log("Tokenizer::add_token called with type=", to_string(type),
11049
12.0M
          " next_position=", next_position, " value_position=", value_position);
11050
12.0M
  ADA_ASSERT_TRUE(next_position >= value_position);
11051
11052
  // Let token be a new token.
11053
  // Set token's type to type.
11054
  // Set token's index to tokenizer's index.
11055
  // Set token's value to the code point substring from value position with
11056
  // length value length within tokenizer's input.
11057
  // Append token to the back of tokenizer's token list.
11058
12.0M
  token_list.emplace_back(type, index,
11059
12.0M
                          input.substr(value_position, value_length));
11060
  // Set tokenizer's index to next position.
11061
12.0M
  index = next_position;
11062
12.0M
}
11063
11064
inline void Tokenizer::add_token_with_default_length(token_type type,
11065
                                                     size_t next_position,
11066
12.0M
                                                     size_t value_position) {
11067
  // Let computed length be next position - value position.
11068
12.0M
  auto computed_length = next_position - value_position;
11069
  // Run add a token given tokenizer, type, next position, value position, and
11070
  // computed length.
11071
12.0M
  add_token(type, next_position, value_position, computed_length);
11072
12.0M
}
11073
11074
8.67M
inline void Tokenizer::add_token_with_defaults(token_type type) {
11075
8.67M
  ada_log("Tokenizer::add_token_with_defaults called with type=",
11076
8.67M
          to_string(type));
11077
  // Run add a token with default length given tokenizer, type, tokenizer's next
11078
  // index, and tokenizer's index.
11079
8.67M
  add_token_with_default_length(type, next_index, index);
11080
8.67M
}
11081
11082
inline ada_warn_unused std::optional<errors>
11083
Tokenizer::process_tokenizing_error(size_t next_position,
11084
52.2k
                                    size_t value_position) {
11085
  // If tokenizer's policy is "strict", then throw a TypeError.
11086
52.2k
  if (policy == token_policy::strict) {
11087
2.07k
    ada_log("process_tokenizing_error failed with next_position=",
11088
2.07k
            next_position, " value_position=", value_position);
11089
2.07k
    return errors::type_error;
11090
2.07k
  }
11091
  // Assert: tokenizer's policy is "lenient".
11092
50.2k
  ADA_ASSERT_TRUE(policy == token_policy::lenient);
11093
  // Run add a token with default length given tokenizer, "invalid-char", next
11094
  // position, and value position.
11095
50.2k
  add_token_with_default_length(token_type::INVALID_CHAR, next_position,
11096
50.2k
                                value_position);
11097
50.2k
  return std::nullopt;
11098
52.2k
}
11099
11100
template <url_pattern_encoding_callback F>
11101
2.24M
token* url_pattern_parser<F>::try_consume_modifier_token() {
11102
  // Let token be the result of running try to consume a token given parser and
11103
  // "other-modifier".
11104
2.24M
  auto token = try_consume_token(token_type::OTHER_MODIFIER);
11105
  // If token is not null, then return token.
11106
2.24M
  if (token) return token;
11107
  // Set token to the result of running try to consume a token given parser and
11108
  // "asterisk".
11109
  // Return token.
11110
2.20M
  return try_consume_token(token_type::ASTERISK);
11111
2.24M
}
11112
11113
template <url_pattern_encoding_callback F>
11114
token* url_pattern_parser<F>::try_consume_regexp_or_wildcard_token(
11115
10.1M
    const token* name_token) {
11116
  // Let token be the result of running try to consume a token given parser and
11117
  // "regexp".
11118
10.1M
  auto token = try_consume_token(token_type::REGEXP);
11119
  // If name token is null and token is null, then set token to the result of
11120
  // running try to consume a token given parser and "asterisk".
11121
10.1M
  if (!name_token && !token) {
11122
9.83M
    token = try_consume_token(token_type::ASTERISK);
11123
9.83M
  }
11124
  // Return token.
11125
10.1M
  return token;
11126
10.1M
}
11127
11128
template <url_pattern_encoding_callback F>
11129
54.1M
token* url_pattern_parser<F>::try_consume_token(token_type type) {
11130
54.1M
  ada_log("url_pattern_parser::try_consume_token called with type=",
11131
54.1M
          to_string(type));
11132
  // Assert: parser's index is less than parser's token list size.
11133
54.1M
  ADA_ASSERT_TRUE(index < tokens.size());
11134
  // Let next token be parser's token list[parser's index].
11135
54.1M
  auto& next_token = tokens[index];
11136
  // If next token's type is not type return null.
11137
54.1M
  if (next_token.type != type) return nullptr;
11138
  // Increase parser's index by 1.
11139
10.9M
  index++;
11140
  // Return next token.
11141
10.9M
  return &next_token;
11142
54.1M
}
11143
11144
template <url_pattern_encoding_callback F>
11145
80.9k
std::string url_pattern_parser<F>::consume_text() {
11146
  // Let result be the empty string.
11147
80.9k
  std::string result{};
11148
  // While true:
11149
437k
  while (true) {
11150
    // Let token be the result of running try to consume a token given parser
11151
    // and "char".
11152
437k
    auto token = try_consume_token(token_type::CHAR);
11153
    // If token is null, then set token to the result of running try to consume
11154
    // a token given parser and "escaped-char".
11155
437k
    if (!token) token = try_consume_token(token_type::ESCAPED_CHAR);
11156
    // If token is null, then break.
11157
437k
    if (!token) break;
11158
    // Append token's value to the end of result.
11159
356k
    result.append(token->value);
11160
356k
  }
11161
  // Return result.
11162
80.9k
  return result;
11163
80.9k
}
11164
11165
template <url_pattern_encoding_callback F>
11166
3.02M
bool url_pattern_parser<F>::consume_required_token(token_type type) {
11167
3.02M
  ada_log("url_pattern_parser::consume_required_token called with type=",
11168
3.02M
          to_string(type));
11169
  // Let result be the result of running try to consume a token given parser and
11170
  // type.
11171
3.02M
  return try_consume_token(type) != nullptr;
11172
3.02M
}
11173
11174
template <url_pattern_encoding_callback F>
11175
std::optional<errors>
11176
7.42M
url_pattern_parser<F>::maybe_add_part_from_the_pending_fixed_value() {
11177
  // If parser's pending fixed value is the empty string, then return.
11178
7.42M
  if (pending_fixed_value.empty()) {
11179
6.52M
    ada_log("pending_fixed_value is empty");
11180
6.52M
    return std::nullopt;
11181
6.52M
  }
11182
  // Let encoded value be the result of running parser's encoding callback given
11183
  // parser's pending fixed value.
11184
904k
  auto encoded_value = encoding_callback(pending_fixed_value);
11185
904k
  if (!encoded_value) {
11186
4.43k
    ada_log("failed to encode pending_fixed_value: ", pending_fixed_value);
11187
4.43k
    return encoded_value.error();
11188
4.43k
  }
11189
  // Set parser's pending fixed value to the empty string.
11190
899k
  pending_fixed_value.clear();
11191
  // Let part be a new part whose type is "fixed-text", value is encoded value,
11192
  // and modifier is "none".
11193
  // Append part to parser's part list.
11194
899k
  parts.emplace_back(url_pattern_part_type::FIXED_TEXT,
11195
899k
                     std::move(*encoded_value),
11196
899k
                     url_pattern_part_modifier::none);
11197
899k
  return std::nullopt;
11198
904k
}
11199
11200
template <url_pattern_encoding_callback F>
11201
std::optional<errors> url_pattern_parser<F>::add_part(
11202
    std::string_view prefix, token* name_token, token* regexp_or_wildcard_token,
11203
2.24M
    std::string_view suffix, token* modifier_token) {
11204
  // Let modifier be "none".
11205
2.24M
  auto modifier = url_pattern_part_modifier::none;
11206
  // If modifier token is not null:
11207
2.24M
  if (modifier_token) {
11208
    // If modifier token's value is "?" then set modifier to "optional".
11209
80.8k
    if (modifier_token->value == "?") {
11210
25.1k
      modifier = url_pattern_part_modifier::optional;
11211
55.6k
    } else if (modifier_token->value == "*") {
11212
      // Otherwise if modifier token's value is "*" then set modifier to
11213
      // "zero-or-more".
11214
47.2k
      modifier = url_pattern_part_modifier::zero_or_more;
11215
47.2k
    } else if (modifier_token->value == "+") {
11216
      // Otherwise if modifier token's value is "+" then set modifier to
11217
      // "one-or-more".
11218
8.38k
      modifier = url_pattern_part_modifier::one_or_more;
11219
8.38k
    }
11220
80.8k
  }
11221
  // If name token is null and regexp or wildcard token is null and modifier
11222
  // is "none":
11223
2.24M
  if (!name_token && !regexp_or_wildcard_token &&
11224
15.7k
      modifier == url_pattern_part_modifier::none) {
11225
    // Append prefix to the end of parser's pending fixed value.
11226
4.53k
    pending_fixed_value.append(prefix);
11227
4.53k
    return std::nullopt;
11228
4.53k
  }
11229
  // Run maybe add a part from the pending fixed value given parser.
11230
2.23M
  if (auto error = maybe_add_part_from_the_pending_fixed_value()) {
11231
64
    return *error;
11232
64
  }
11233
  // If name token is null and regexp or wildcard token is null:
11234
2.23M
  if (!name_token && !regexp_or_wildcard_token) {
11235
    // Assert: suffix is the empty string.
11236
11.2k
    ADA_ASSERT_TRUE(suffix.empty());
11237
    // If prefix is the empty string, then return.
11238
11.2k
    if (prefix.empty()) return std::nullopt;
11239
    // Let encoded value be the result of running parser's encoding callback
11240
    // given prefix.
11241
10.4k
    auto encoded_value = encoding_callback(prefix);
11242
10.4k
    if (!encoded_value) {
11243
15
      return encoded_value.error();
11244
15
    }
11245
    // Let part be a new part whose type is "fixed-text", value is encoded
11246
    // value, and modifier is modifier.
11247
    // Append part to parser's part list.
11248
10.4k
    parts.emplace_back(url_pattern_part_type::FIXED_TEXT,
11249
10.4k
                       std::move(*encoded_value), modifier);
11250
10.4k
    return std::nullopt;
11251
10.4k
  }
11252
  // Let regexp value be the empty string.
11253
2.22M
  std::string regexp_value{};
11254
  // If regexp or wildcard token is null, then set regexp value to parser's
11255
  // segment wildcard regexp.
11256
2.22M
  if (!regexp_or_wildcard_token) {
11257
217k
    regexp_value = segment_wildcard_regexp;
11258
2.00M
  } else if (regexp_or_wildcard_token->type == token_type::ASTERISK) {
11259
    // Otherwise if regexp or wildcard token's type is "asterisk", then set
11260
    // regexp value to the full wildcard regexp value.
11261
1.95M
    regexp_value = ".*";
11262
1.95M
  } else {
11263
    // Otherwise set regexp value to regexp or wildcard token's value.
11264
52.9k
    regexp_value = regexp_or_wildcard_token->value;
11265
52.9k
  }
11266
  // Let type be "regexp".
11267
2.22M
  auto type = url_pattern_part_type::REGEXP;
11268
  // If regexp value is parser's segment wildcard regexp:
11269
2.22M
  if (regexp_value == segment_wildcard_regexp) {
11270
    // Set type to "segment-wildcard".
11271
217k
    type = url_pattern_part_type::SEGMENT_WILDCARD;
11272
    // Set regexp value to the empty string.
11273
217k
    regexp_value.clear();
11274
2.00M
  } else if (regexp_value == ".*") {
11275
    // Otherwise if regexp value is the full wildcard regexp value:
11276
    // Set type to "full-wildcard".
11277
1.95M
    type = url_pattern_part_type::FULL_WILDCARD;
11278
    // Set regexp value to the empty string.
11279
1.95M
    regexp_value.clear();
11280
1.95M
  }
11281
  // Let name be the empty string.
11282
2.22M
  std::string name{};
11283
  // If name token is not null, then set name to name token's value.
11284
2.22M
  if (name_token) {
11285
218k
    name = name_token->value;
11286
2.00M
  } else if (regexp_or_wildcard_token != nullptr) {
11287
    // Otherwise if regexp or wildcard token is not null:
11288
    // Set name to parser's next numeric name, serialized.
11289
2.00M
    name = std::to_string(next_numeric_name);
11290
    // Increment parser's next numeric name by 1.
11291
2.00M
    next_numeric_name++;
11292
2.00M
  }
11293
  // If the result of running is a duplicate name given parser and name is
11294
  // true, then throw a TypeError. Tracked in a set so this stays O(1): a
11295
  // linear scan of the part list here is O(n^2) over a pattern string with n
11296
  // named parts (e.g. "/*" repeated), an algorithmic-complexity DoS.
11297
2.22M
  if (!name.empty() && !seen_names.insert(name).second) {
11298
14
    return errors::type_error;
11299
14
  }
11300
  // Let encoded prefix be the result of running parser's encoding callback
11301
  // given prefix.
11302
2.22M
  auto encoded_prefix = encoding_callback(prefix);
11303
2.22M
  if (!encoded_prefix) return encoded_prefix.error();
11304
  // Let encoded suffix be the result of running parser's encoding callback
11305
  // given suffix.
11306
2.22M
  auto encoded_suffix = encoding_callback(suffix);
11307
2.22M
  if (!encoded_suffix) return encoded_suffix.error();
11308
  // Let part be a new part whose type is type, value is regexp value,
11309
  // modifier is modifier, name is name, prefix is encoded prefix, and suffix
11310
  // is encoded suffix.
11311
  // Append part to parser's part list.
11312
2.22M
  parts.emplace_back(type, std::move(regexp_value), modifier, std::move(name),
11313
2.22M
                     std::move(*encoded_prefix), std::move(*encoded_suffix));
11314
2.22M
  return std::nullopt;
11315
2.22M
}
11316
11317
template <url_pattern_encoding_callback F>
11318
tl::expected<std::vector<url_pattern_part>, errors> parse_pattern_string(
11319
    std::string_view input, url_pattern_compile_component_options& options,
11320
2.99M
    F& encoding_callback) {
11321
2.99M
  ada_log("parse_pattern_string input=", input);
11322
  // Let parser be a new pattern parser whose encoding callback is encoding
11323
  // callback and segment wildcard regexp is the result of running generate a
11324
  // segment wildcard regexp given options.
11325
2.99M
  auto parser = url_pattern_parser<F>(
11326
2.99M
      encoding_callback, generate_segment_wildcard_regexp(options));
11327
  // Set parser's token list to the result of running tokenize given input and
11328
  // "strict".
11329
2.99M
  auto tokenize_result = tokenize(input, token_policy::strict);
11330
2.99M
  if (!tokenize_result) {
11331
2.07k
    ada_log("parse_pattern_string tokenize failed");
11332
2.07k
    return tl::unexpected(tokenize_result.error());
11333
2.07k
  }
11334
2.98M
  parser.tokens = std::move(*tokenize_result);
11335
11336
  // While parser's index is less than parser's token list's size:
11337
13.0M
  while (parser.can_continue()) {
11338
    // Let char token be the result of running try to consume a token given
11339
    // parser and "char".
11340
10.0M
    auto char_token = parser.try_consume_token(token_type::CHAR);
11341
    // Let name token be the result of running try to consume a token given
11342
    // parser and "name".
11343
10.0M
    auto name_token = parser.try_consume_token(token_type::NAME);
11344
    // Let regexp or wildcard token be the result of running try to consume a
11345
    // regexp or wildcard token given parser and name token.
11346
10.0M
    auto regexp_or_wildcard_token =
11347
10.0M
        parser.try_consume_regexp_or_wildcard_token(name_token);
11348
    // If name token is not null or regexp or wildcard token is not null:
11349
10.0M
    if (name_token || regexp_or_wildcard_token) {
11350
      // Let prefix be the empty string.
11351
2.20M
      std::string prefix{};
11352
      // If char token is not null then set prefix to char token's value.
11353
2.20M
      if (char_token) prefix = char_token->value;
11354
      // If prefix is not the empty string and not options's prefix code point:
11355
2.20M
      if (!prefix.empty() && prefix != options.get_prefix()) {
11356
        // Append prefix to the end of parser's pending fixed value.
11357
69.8k
        parser.pending_fixed_value.append(prefix);
11358
        // Set prefix to the empty string.
11359
69.8k
        prefix.clear();
11360
69.8k
      }
11361
      // Run maybe add a part from the pending fixed value given parser.
11362
2.20M
      if (auto error = parser.maybe_add_part_from_the_pending_fixed_value()) {
11363
386
        ada_log("maybe_add_part_from_the_pending_fixed_value failed");
11364
386
        return tl::unexpected(*error);
11365
386
      }
11366
      // Let modifier token be the result of running try to consume a modifier
11367
      // token given parser.
11368
2.20M
      auto modifier_token = parser.try_consume_modifier_token();
11369
      // Run add a part given parser, prefix, name token, regexp or wildcard
11370
      // token, the empty string, and modifier token.
11371
2.20M
      if (auto error =
11372
2.20M
              parser.add_part(prefix, name_token, regexp_or_wildcard_token, "",
11373
2.20M
                              modifier_token)) {
11374
14
        ada_log("parser.add_part failed");
11375
14
        return tl::unexpected(*error);
11376
14
      }
11377
      // Continue.
11378
2.20M
      continue;
11379
2.20M
    }
11380
11381
    // Let fixed token be char token.
11382
7.86M
    auto fixed_token = char_token;
11383
    // If fixed token is null, then set fixed token to the result of running try
11384
    // to consume a token given parser and "escaped-char".
11385
7.86M
    if (!fixed_token)
11386
3.03M
      fixed_token = parser.try_consume_token(token_type::ESCAPED_CHAR);
11387
    // If fixed token is not null:
11388
7.86M
    if (fixed_token) {
11389
      // Append fixed token's value to parser's pending fixed value.
11390
4.83M
      parser.pending_fixed_value.append(fixed_token->value);
11391
      // Continue.
11392
4.83M
      continue;
11393
4.83M
    }
11394
    // Let open token be the result of running try to consume a token given
11395
    // parser and "open".
11396
3.02M
    auto open_token = parser.try_consume_token(token_type::OPEN);
11397
    // If open token is not null:
11398
3.02M
    if (open_token) {
11399
      // Set prefix be the result of running consume text given parser.
11400
40.4k
      auto prefix_ = parser.consume_text();
11401
      // Set name token to the result of running try to consume a token given
11402
      // parser and "name".
11403
40.4k
      name_token = parser.try_consume_token(token_type::NAME);
11404
      // Set regexp or wildcard token to the result of running try to consume a
11405
      // regexp or wildcard token given parser and name token.
11406
40.4k
      regexp_or_wildcard_token =
11407
40.4k
          parser.try_consume_regexp_or_wildcard_token(name_token);
11408
      // Let suffix be the result of running consume text given parser.
11409
40.4k
      auto suffix_ = parser.consume_text();
11410
      // Run consume a required token given parser and "close".
11411
40.4k
      if (!parser.consume_required_token(token_type::CLOSE)) {
11412
243
        ada_log("parser.consume_required_token failed");
11413
243
        return tl::unexpected(errors::type_error);
11414
243
      }
11415
      // Set modifier token to the result of running try to consume a modifier
11416
      // token given parser.
11417
40.2k
      auto modifier_token = parser.try_consume_modifier_token();
11418
      // Run add a part given parser, prefix, name token, regexp or wildcard
11419
      // token, suffix, and modifier token.
11420
40.2k
      if (auto error =
11421
40.2k
              parser.add_part(prefix_, name_token, regexp_or_wildcard_token,
11422
40.2k
                              suffix_, modifier_token)) {
11423
117
        return tl::unexpected(*error);
11424
117
      }
11425
      // Continue.
11426
40.1k
      continue;
11427
40.2k
    }
11428
    // Run maybe add a part from the pending fixed value given parser.
11429
2.98M
    if (auto error = parser.maybe_add_part_from_the_pending_fixed_value()) {
11430
3.98k
      ada_log("maybe_add_part_from_the_pending_fixed_value failed on line 992");
11431
3.98k
      return tl::unexpected(*error);
11432
3.98k
    }
11433
    // Run consume a required token given parser and "end".
11434
2.98M
    if (!parser.consume_required_token(token_type::END)) {
11435
1.65k
      return tl::unexpected(errors::type_error);
11436
1.65k
    }
11437
2.98M
  }
11438
2.98M
  ada_log("parser.parts size is: ", parser.parts.size());
11439
  // Return parser's part list.
11440
2.98M
  return parser.parts;
11441
2.98M
}
11442
11443
template <url_pattern_regex::regex_concept regex_provider>
11444
bool protocol_component_matches_special_scheme(
11445
359k
    url_pattern_component<regex_provider>& component) {
11446
  // Optimization: Use fast_test for simple patterns to avoid regex overhead
11447
359k
  switch (component.type) {
11448
23.7k
    case url_pattern_component_type::EMPTY:
11449
      // Empty pattern can't match any special scheme
11450
23.7k
      return false;
11451
120k
    case url_pattern_component_type::EXACT_MATCH:
11452
      // Direct string comparison for exact match patterns
11453
120k
      return component.exact_match_value == "http" ||
11454
120k
             component.exact_match_value == "https" ||
11455
239
             component.exact_match_value == "ws" ||
11456
211
             component.exact_match_value == "wss" ||
11457
199
             component.exact_match_value == "ftp" ||
11458
185
             component.exact_match_value == "file";
11459
213k
    case url_pattern_component_type::FULL_WILDCARD:
11460
      // Full wildcard matches everything including special schemes
11461
213k
      return true;
11462
1.31k
    case url_pattern_component_type::REGEXP:
11463
      // Fall back to regex matching for complex patterns
11464
1.31k
      auto& regex = component.regexp;
11465
1.31k
      return regex_provider::regex_match("http", regex) ||
11466
855
             regex_provider::regex_match("https", regex) ||
11467
808
             regex_provider::regex_match("ws", regex) ||
11468
776
             regex_provider::regex_match("wss", regex) ||
11469
755
             regex_provider::regex_match("ftp", regex) ||
11470
734
             regex_provider::regex_match("file", regex);
11471
359k
  }
11472
0
  ada::unreachable();
11473
0
}
11474
11475
template <url_pattern_regex::regex_concept regex_provider>
11476
inline std::optional<errors> constructor_string_parser<
11477
45.8k
    regex_provider>::compute_protocol_matches_special_scheme_flag() {
11478
45.8k
  ada_log(
11479
45.8k
      "constructor_string_parser::compute_protocol_matches_special_scheme_"
11480
45.8k
      "flag");
11481
  // Let protocol string be the result of running make a component string given
11482
  // parser.
11483
45.8k
  auto protocol_string = make_component_string();
11484
  // Let protocol component be the result of compiling a component given
11485
  // protocol string, canonicalize a protocol, and default options.
11486
45.8k
  auto protocol_component = url_pattern_component<regex_provider>::compile(
11487
45.8k
      protocol_string, canonicalize_protocol,
11488
45.8k
      url_pattern_compile_component_options::DEFAULT);
11489
45.8k
  if (!protocol_component) {
11490
1.40k
    ada_log("url_pattern_component::compile failed for protocol_string ",
11491
1.40k
            protocol_string);
11492
1.40k
    return protocol_component.error();
11493
1.40k
  }
11494
  // If the result of running protocol component matches a special scheme given
11495
  // protocol component is true, then set parser's protocol matches a special
11496
  // scheme flag to true.
11497
44.4k
  if (protocol_component_matches_special_scheme(*protocol_component)) {
11498
44.4k
    protocol_matches_a_special_scheme_flag = true;
11499
44.4k
  }
11500
44.4k
  return std::nullopt;
11501
45.8k
}
11502
11503
template <url_pattern_regex::regex_concept regex_provider>
11504
tl::expected<url_pattern_init, errors>
11505
88.9k
constructor_string_parser<regex_provider>::parse(std::string_view input) {
11506
88.9k
  ada_log("constructor_string_parser::parse input=", input);
11507
  // Let parser be a new constructor string parser whose input is input and
11508
  // token list is the result of running tokenize given input and "lenient".
11509
88.9k
  auto token_list = tokenize(input, token_policy::lenient);
11510
88.9k
  if (!token_list) {
11511
0
    return tl::unexpected(token_list.error());
11512
0
  }
11513
88.9k
  auto parser = constructor_string_parser(input, std::move(*token_list));
11514
11515
  // While parser's token index is less than parser's token list size:
11516
2.07M
  while (parser.token_index < parser.token_list.size()) {
11517
    // Set parser's token increment to 1.
11518
2.07M
    parser.token_increment = 1;
11519
11520
    // If parser's token list[parser's token index]'s type is "end" then:
11521
2.07M
    if (parser.token_list[parser.token_index].type == token_type::END) {
11522
      // If parser's state is "init":
11523
130k
      if (parser.state == State::INIT) {
11524
        // Run rewind given parser.
11525
43.0k
        parser.rewind();
11526
        // If the result of running is a hash prefix given parser is true, then
11527
        // run change state given parser, "hash" and 1.
11528
43.0k
        if (parser.is_hash_prefix()) {
11529
0
          parser.change_state(State::HASH, 1);
11530
43.0k
        } else if (parser.is_search_prefix()) {
11531
          // Otherwise if the result of running is a search prefix given parser
11532
          // is true: Run change state given parser, "search" and 1.
11533
0
          parser.change_state(State::SEARCH, 1);
11534
43.0k
        } else {
11535
          // Run change state given parser, "pathname" and 0.
11536
43.0k
          parser.change_state(State::PATHNAME, 0);
11537
43.0k
        }
11538
        // Increment parser's token index by parser's token increment.
11539
43.0k
        parser.token_index += parser.token_increment;
11540
        // Continue.
11541
43.0k
        continue;
11542
43.0k
      }
11543
11544
87.5k
      if (parser.state == State::AUTHORITY) {
11545
        // If parser's state is "authority":
11546
        // Run rewind and set state given parser, and "hostname".
11547
0
        parser.rewind();
11548
0
        parser.change_state(State::HOSTNAME, 0);
11549
        // Increment parser's token index by parser's token increment.
11550
0
        parser.token_index += parser.token_increment;
11551
        // Continue.
11552
0
        continue;
11553
0
      }
11554
11555
      // Run change state given parser, "done" and 0.
11556
87.5k
      parser.change_state(State::DONE, 0);
11557
      // Break.
11558
87.5k
      break;
11559
87.5k
    }
11560
11561
    // If the result of running is a group open given parser is true:
11562
1.94M
    if (parser.is_group_open()) {
11563
      // Increment parser's group depth by 1.
11564
3.61k
      parser.group_depth += 1;
11565
      // Increment parser's token index by parser's token increment.
11566
3.61k
      parser.token_index += parser.token_increment;
11567
      // Continue.
11568
3.61k
      continue;
11569
3.61k
    }
11570
11571
    // If parser's group depth is greater than 0:
11572
1.93M
    if (parser.group_depth > 0) {
11573
      // If the result of running is a group close given parser is true, then
11574
      // decrement parser's group depth by 1.
11575
13.5k
      if (parser.is_group_close()) {
11576
2.63k
        parser.group_depth -= 1;
11577
10.9k
      } else {
11578
        // Increment parser's token index by parser's token increment.
11579
10.9k
        parser.token_index += parser.token_increment;
11580
10.9k
        continue;
11581
10.9k
      }
11582
13.5k
    }
11583
11584
    // Switch on parser's state and run the associated steps:
11585
1.92M
    switch (parser.state) {
11586
385k
      case State::INIT: {
11587
        // If the result of running is a protocol suffix given parser is true:
11588
385k
        if (parser.is_protocol_suffix()) {
11589
          // Run rewind and set state given parser and "protocol".
11590
45.8k
          parser.rewind();
11591
45.8k
          parser.change_state(State::PROTOCOL, 0);
11592
45.8k
        }
11593
385k
        break;
11594
0
      }
11595
286k
      case State::PROTOCOL: {
11596
        // If the result of running is a protocol suffix given parser is true:
11597
286k
        if (parser.is_protocol_suffix()) {
11598
          // Run compute protocol matches a special scheme flag given parser.
11599
45.8k
          if (const auto error =
11600
45.8k
                  parser.compute_protocol_matches_special_scheme_flag()) {
11601
1.40k
            ada_log("compute_protocol_matches_special_scheme_flag failed");
11602
1.40k
            return tl::unexpected(*error);
11603
1.40k
          }
11604
          // Let next state be "pathname".
11605
44.4k
          auto next_state = State::PATHNAME;
11606
          // Let skip be 1.
11607
44.4k
          auto skip = 1;
11608
          // If the result of running next is authority slashes given parser is
11609
          // true:
11610
44.4k
          if (parser.next_is_authority_slashes()) {
11611
            // Set next state to "authority".
11612
44.4k
            next_state = State::AUTHORITY;
11613
            // Set skip to 3.
11614
44.4k
            skip = 3;
11615
44.4k
          } else if (parser.protocol_matches_a_special_scheme_flag) {
11616
            // Otherwise if parser's protocol matches a special scheme flag is
11617
            // true, then set next state to "authority".
11618
0
            next_state = State::AUTHORITY;
11619
0
          }
11620
11621
          // Run change state given parser, next state, and skip.
11622
44.4k
          parser.change_state(next_state, skip);
11623
44.4k
        }
11624
284k
        break;
11625
286k
      }
11626
533k
      case State::AUTHORITY: {
11627
        // If the result of running is an identity terminator given parser is
11628
        // true, then run rewind and set state given parser and "username".
11629
533k
        if (parser.is_an_identity_terminator()) {
11630
0
          parser.rewind();
11631
0
          parser.change_state(State::USERNAME, 0);
11632
533k
        } else if (parser.is_pathname_start() || parser.is_search_prefix() ||
11633
489k
                   parser.is_hash_prefix()) {
11634
          // Otherwise if any of the following are true:
11635
          // - the result of running is a pathname start given parser;
11636
          // - the result of running is a search prefix given parser; or
11637
          // - the result of running is a hash prefix given parser,
11638
          // then run rewind and set state given parser and "hostname".
11639
44.4k
          parser.rewind();
11640
44.4k
          parser.change_state(State::HOSTNAME, 0);
11641
44.4k
        }
11642
533k
        break;
11643
286k
      }
11644
0
      case State::USERNAME: {
11645
        // If the result of running is a password prefix given parser is true,
11646
        // then run change state given parser, "password", and 1.
11647
0
        if (parser.is_password_prefix()) {
11648
0
          parser.change_state(State::PASSWORD, 1);
11649
0
        } else if (parser.is_an_identity_terminator()) {
11650
          // Otherwise if the result of running is an identity terminator given
11651
          // parser is true, then run change state given parser, "hostname",
11652
          // and 1.
11653
0
          parser.change_state(State::HOSTNAME, 1);
11654
0
        }
11655
0
        break;
11656
286k
      }
11657
0
      case State::PASSWORD: {
11658
        // If the result of running is an identity terminator given parser is
11659
        // true, then run change state given parser, "hostname", and 1.
11660
0
        if (parser.is_an_identity_terminator()) {
11661
0
          parser.change_state(State::HOSTNAME, 1);
11662
0
        }
11663
0
        break;
11664
286k
      }
11665
533k
      case State::HOSTNAME: {
11666
        // If the result of running is an IPv6 open given parser is true, then
11667
        // increment parser's hostname IPv6 bracket depth by 1.
11668
533k
        if (parser.is_an_ipv6_open()) {
11669
0
          parser.hostname_ipv6_bracket_depth += 1;
11670
533k
        } else if (parser.is_an_ipv6_close()) {
11671
          // Otherwise if the result of running is an IPv6 close given parser is
11672
          // true, then decrement parser's hostname IPv6 bracket depth by 1.
11673
0
          parser.hostname_ipv6_bracket_depth -= 1;
11674
533k
        } else if (parser.is_port_prefix() &&
11675
0
                   parser.hostname_ipv6_bracket_depth == 0) {
11676
          // Otherwise if the result of running is a port prefix given parser is
11677
          // true and parser's hostname IPv6 bracket depth is zero, then run
11678
          // change state given parser, "port", and 1.
11679
0
          parser.change_state(State::PORT, 1);
11680
533k
        } else if (parser.is_pathname_start()) {
11681
          // Otherwise if the result of running is a pathname start given parser
11682
          // is true, then run change state given parser, "pathname", and 0.
11683
44.4k
          parser.change_state(State::PATHNAME, 0);
11684
489k
        } else if (parser.is_search_prefix()) {
11685
          // Otherwise if the result of running is a search prefix given parser
11686
          // is true, then run change state given parser, "search", and 1.
11687
0
          parser.change_state(State::SEARCH, 1);
11688
489k
        } else if (parser.is_hash_prefix()) {
11689
          // Otherwise if the result of running is a hash prefix given parser is
11690
          // true, then run change state given parser, "hash", and 1.
11691
0
          parser.change_state(State::HASH, 1);
11692
0
        }
11693
11694
533k
        break;
11695
286k
      }
11696
0
      case State::PORT: {
11697
        // If the result of running is a pathname start given parser is true,
11698
        // then run change state given parser, "pathname", and 0.
11699
0
        if (parser.is_pathname_start()) {
11700
0
          parser.change_state(State::PATHNAME, 0);
11701
0
        } else if (parser.is_search_prefix()) {
11702
          // Otherwise if the result of running is a search prefix given parser
11703
          // is true, then run change state given parser, "search", and 1.
11704
0
          parser.change_state(State::SEARCH, 1);
11705
0
        } else if (parser.is_hash_prefix()) {
11706
          // Otherwise if the result of running is a hash prefix given parser is
11707
          // true, then run change state given parser, "hash", and 1.
11708
0
          parser.change_state(State::HASH, 1);
11709
0
        }
11710
0
        break;
11711
286k
      }
11712
184k
      case State::PATHNAME: {
11713
        // If the result of running is a search prefix given parser is true,
11714
        // then run change state given parser, "search", and 1.
11715
184k
        if (parser.is_search_prefix()) {
11716
198
          parser.change_state(State::SEARCH, 1);
11717
183k
        } else if (parser.is_hash_prefix()) {
11718
          // Otherwise if the result of running is a hash prefix given parser is
11719
          // true, then run change state given parser, "hash", and 1.
11720
105
          parser.change_state(State::HASH, 1);
11721
105
        }
11722
184k
        break;
11723
286k
      }
11724
2.21k
      case State::SEARCH: {
11725
        // If the result of running is a hash prefix given parser is true, then
11726
        // run change state given parser, "hash", and 1.
11727
2.21k
        if (parser.is_hash_prefix()) {
11728
36
          parser.change_state(State::HASH, 1);
11729
36
        }
11730
2.21k
        break;
11731
286k
      }
11732
1.29k
      case State::HASH: {
11733
        // Do nothing
11734
1.29k
        break;
11735
286k
      }
11736
0
      default: {
11737
        // Assert: This step is never reached.
11738
0
        unreachable();
11739
0
      }
11740
1.92M
    }
11741
11742
    // Increment parser's token index by parser's token increment.
11743
1.92M
    parser.token_index += parser.token_increment;
11744
1.92M
  }
11745
11746
  // If parser's result contains "hostname" and not "port", then set parser's
11747
  // result["port"] to the empty string.
11748
87.5k
  if (parser.result.hostname && !parser.result.port) {
11749
44.4k
    parser.result.port = "";
11750
44.4k
  }
11751
11752
  // Return parser's result.
11753
87.5k
  return parser.result;
11754
88.9k
}
11755
11756
}  // namespace ada::url_pattern_helpers
11757
#endif  // ADA_INCLUDE_URL_PATTERN
11758
#endif
11759
/* end file include/ada/url_pattern_helpers-inl.h */
11760
/* begin file include/ada/url_pattern_list.h */
11761
/**
11762
 * @file url_pattern_list.h
11763
 * @brief Compiled set-level matching over URLPattern pathname patterns.
11764
 *
11765
 * `ada::url_pattern_list` answers the question "which of my N routes matches
11766
 * this pathname, and what are the parameter values?" in a single walk
11767
 * instead of a loop of N `url_pattern::exec` calls. The whole route set is
11768
 * compiled once, by ada::parse_url_pattern_list, into a segment trie with
11769
 * per-node dispatch (direct compares for small fanouts, a first-byte index
11770
 * at the root, perfect-hash projection for wide nodes). Matching a pathname
11771
 * against the compiled set is allocation-free and does not execute any
11772
 * regular expression for routes written in the common static / ":param" /
11773
 * "*" subset; other routes are matched through the regex provider, exactly
11774
 * as ada::url_pattern does.
11775
 *
11776
 * This implements the route-set ("URLPatternList") use case discussed in
11777
 * https://github.com/whatwg/urlpattern/issues/166 for the pathname component.
11778
 *
11779
 * Correctness does not depend on the fast path: inputs or routes that exceed
11780
 * the fast-path limits (documented on the constants in
11781
 * `ada::url_pattern_list_limits`) are matched by a sequential fallback with
11782
 * identical priority semantics, never rejected and never answered wrongly.
11783
 *
11784
 * @see https://urlpattern.spec.whatwg.org/
11785
 */
11786
#ifndef ADA_URL_PATTERN_LIST_H
11787
#define ADA_URL_PATTERN_LIST_H
11788
11789
11790
#include <array>
11791
#include <cstdint>
11792
#include <optional>
11793
#include <span>
11794
#include <string>
11795
#include <string_view>
11796
#include <vector>
11797
11798
#if ADA_INCLUDE_URL_PATTERN
11799
namespace ada {
11800
11801
/**
11802
 * The limits of the url_pattern_list fast path. None of them changes what a
11803
 * list matches: routes and inputs beyond a limit are matched by a sequential
11804
 * fallback with identical semantics.
11805
 * @namespace ada::url_pattern_list_limits
11806
 */
11807
namespace url_pattern_list_limits {
11808
11809
/**
11810
 * Maximum number of captures (":param" groups plus one trailing "*" group)
11811
 * a route may declare and still be compiled into the fast path. Routes with
11812
 * more groups are matched by the sequential fallback; their match is still
11813
 * correct, but only the first `max_captures_per_route` captures are reported
11814
 * (see url_pattern_list_match_result::captures_truncated).
11815
 */
11816
inline constexpr uint32_t max_captures_per_route = 8;
11817
11818
/**
11819
 * Maximum number of '/'-separated segments an input pathname may have and
11820
 * still be matched by the fast path. Longer inputs fall back to the
11821
 * sequential matcher and are still matched correctly.
11822
 */
11823
inline constexpr uint32_t max_fast_path_segments = 24;
11824
11825
/**
11826
 * Maximum input pathname length (bytes) accepted by the fast path; segment
11827
 * offsets are tracked in 16-bit integers internally. Longer inputs fall back
11828
 * to the sequential matcher and are still matched correctly.
11829
 */
11830
inline constexpr uint32_t max_fast_path_pathname_length = 4096;
11831
11832
/**
11833
 * Maximum number of pattern segments a route may have and still be compiled
11834
 * into the trie fast path. Deeper routes are matched by the sequential
11835
 * fallback with identical semantics.
11836
 */
11837
inline constexpr uint32_t max_trie_pattern_segments = 16;
11838
11839
}  // namespace url_pattern_list_limits
11840
11841
/**
11842
 * The result of url_pattern_list::match. A winning route reports its group
11843
 * values in one of two forms, mirroring url_pattern_list::group_names():
11844
 *
11845
 * - Routes in the static / ":param" / "*" subset report zero-allocation
11846
 *   captures: (offset, length) slices of the pathname passed to match, in
11847
 *   capture order (":param" groups left to right, then the "*" group).
11848
 *   `regexp_route` is false and `regexp_groups` is empty.
11849
 * - Routes matched through the regex provider (patterns with custom regexp
11850
 *   groups or "?" / "+" / "*" modifiers) report the group values the
11851
 *   provider's regex_search returned, exactly as url_pattern::exec would for
11852
 *   the pathname component: `regexp_route` is true, `regexp_groups[i]` is the
11853
 *   value of group_names(route_index)[i] (nullopt for a group that did not
11854
 *   participate), and capture_count is 0.
11855
 *
11856
 * Routes with more than url_pattern_list_limits::max_captures_per_route
11857
 * groups report only the first max_captures_per_route slices and set
11858
 * captures_truncated.
11859
 */
11860
struct url_pattern_list_match_result {
11861
  /** One capture: an (offset, length) slice of the matched pathname. */
11862
  struct capture {
11863
    uint32_t offset = 0;
11864
    uint32_t length = 0;
11865
  };
11866
  /** Index of the winning route in the creation order, or -1 for no match. */
11867
  int32_t route_index = -1;
11868
  /** Number of valid entries in captures. */
11869
  uint32_t capture_count = 0;
11870
  /** True when the route has more groups than could be reported as slices. */
11871
  bool captures_truncated = false;
11872
  /** True when the winning route was matched through the regex provider; its
11873
   * group values are in regexp_groups. */
11874
  bool regexp_route = false;
11875
  std::array<capture, url_pattern_list_limits::max_captures_per_route>
11876
      captures{};
11877
  /** Group values of a regexp route, as returned by the provider. */
11878
  std::vector<std::optional<std::string>> regexp_groups{};
11879
11880
20.6k
  [[nodiscard]] bool has_match() const noexcept { return route_index >= 0; }
11881
};
11882
11883
/**
11884
 * @private
11885
 * The compiled tables url_pattern_list::match walks, and the inline matcher
11886
 * over them (url_pattern_list-inl.h). Nothing here is part of the supported
11887
 * API. The route-set compiler that produces these tables is not part of the
11888
 * public headers at all (src/url_pattern_list_compiler.h).
11889
 * @namespace ada::url_pattern_list_detail
11890
 */
11891
namespace url_pattern_list_detail {
11892
11893
/** @private One trie node. Nodes with a projection dispatch keep their hash
11894
 * payload in a separate hash_record, so the common 0/1/direct nodes stay at
11895
 * 24 bytes. */
11896
struct node_record {
11897
  // First static edge (edges are laid out per node, contiguously).
11898
  int32_t first_child = 0;
11899
  // Child node index, -2 - route (pure-leaf shortcut), or -1.
11900
  int32_t param_child = -1;
11901
  // Route index of a "*" ending at this prefix, or -1.
11902
  int32_t wild_route = -1;
11903
  // Route ending exactly here, or -1.
11904
  int32_t terminal_route = -1;
11905
  uint16_t n_static = 0;
11906
  // 0 none, 1 direct compares, 2 projection, 3 linear scan, 4 first-byte
11907
  // index (root only).
11908
  uint8_t dispatch = 0;
11909
  // 1 if the node still has a param/wildcard alternative to backtrack to.
11910
  uint8_t has_alternative = 0;
11911
  // Index of the node's hash_record (dispatch == 2 only).
11912
  uint32_t hash_index = 0;
11913
};
11914
11915
/** @private Projection-dispatch payload of a hashed node. */
11916
struct hash_record {
11917
  uint64_t multiplier = 0;
11918
  uint32_t slot_base = 0;
11919
  // Witness plan: 3 nibble ids | count << 12 | use_len << 14.
11920
  uint16_t witness_plan = 0;
11921
  // Slot table size == 1 << slot_bits.
11922
  uint8_t slot_bits = 0;
11923
  uint8_t reserved = 0;
11924
};
11925
11926
/** @private One static edge; keys <= 16 bytes verify from the packed
11927
 * windows alone. */
11928
struct edge_record {
11929
  // Key bytes [0, min(8, len)), little-endian, zero-padded.
11930
  uint64_t prefix = 0;
11931
  // Key bytes [max(0, len - 8), len), little-endian, zero-padded.
11932
  uint64_t suffix = 0;
11933
  // Child node index; negative values encode -2 - route pure-leaf shortcuts.
11934
  int32_t node = -1;
11935
  // Full key in the blob (read only when key_length > 16).
11936
  uint32_t key_offset = 0;
11937
  uint16_t key_length = 0;
11938
};
11939
11940
/** @private How one route of the set is matched. */
11941
enum class route_mode : uint8_t {
11942
  // Compiled into the trie fast path.
11943
  trie = 0,
11944
  // Safe static/":param"/"*" syntax beyond a fast-path build limit: matched
11945
  // by the sequential segment matcher.
11946
  sequential = 1,
11947
  // Needs URLPattern regexp semantics: matched through the regex provider.
11948
  regexp = 2,
11949
};
11950
11951
/** @private Everything the matcher knows about one route after a hit. */
11952
struct route_record {
11953
  // Packed per-segment kinds, two bits per segment, most significant first;
11954
  // (kind_sequence, kind_length, route index) compared as a tuple is the
11955
  // specificity order.
11956
  uint64_t kind_sequence = 0;
11957
  // Sequential-mode routes: their segments in the segment table.
11958
  uint32_t segment_first = 0;
11959
  uint32_t segment_count = 0;
11960
  // Auxiliary routes that can outrank this route when it wins the fast
11961
  // path: a range of the aux table (usually empty).
11962
  uint32_t challenger_first = 0;
11963
  uint32_t challenger_count = 0;
11964
  // Ordinal among the regexp-mode routes, or -1.
11965
  int32_t regexp_component = -1;
11966
  uint8_t kind_length = 0;
11967
  route_mode mode = route_mode::sequential;
11968
  // Trie-mode routes: capture positions.
11969
  uint8_t n_params = 0;
11970
  uint8_t wild = 0;
11971
  std::array<uint8_t, url_pattern_list_limits::max_captures_per_route>
11972
      param_positions{};
11973
};
11974
11975
/** @private One pattern segment of a sequential-mode route. */
11976
struct segment_record {
11977
  uint32_t text_offset = 0;
11978
  uint32_t text_length = 0;
11979
  // 0 literal, 1 ":param", 2 "*".
11980
  uint8_t kind = 0;
11981
};
11982
11983
/**
11984
 * @private
11985
 * The compiled route set: one arena holding every table, addressed by
11986
 * section offsets, plus the per-route group names. Sections are 8-byte
11987
 * aligned; the blob is zero-padded by 8 bytes so short key windows can be
11988
 * loaded whole.
11989
 */
11990
struct compiled_routes {
11991
  std::vector<uint8_t> arena{};
11992
  std::vector<std::vector<std::string>> group_names{};
11993
  uint32_t nodes_offset = 0;
11994
  uint32_t hashes_offset = 0;
11995
  uint32_t edges_offset = 0;
11996
  uint32_t slots_offset = 0;
11997
  uint32_t blob_offset = 0;
11998
  uint32_t routes_offset = 0;
11999
  uint32_t segments_offset = 0;
12000
  uint32_t aux_offset = 0;
12001
  uint32_t root_index_offset = 0;
12002
  uint32_t n_routes = 0;
12003
  // All auxiliary routes (regexp mode and sequential mode) in insertion
12004
  // order: the aux table's first n_aux_all entries; challenger ranges
12005
  // follow.
12006
  uint32_t n_aux_all = 0;
12007
  uint8_t ignore_case = 0;
12008
12009
  template <typename T>
12010
999k
  [[nodiscard]] const T* section(uint32_t offset) const noexcept {
12011
999k
    return reinterpret_cast<const T*>(arena.data() + offset);
12012
999k
  }
char const* ada::url_pattern_list_detail::compiled_routes::section<char>(unsigned int) const
Line
Count
Source
12010
236k
  [[nodiscard]] const T* section(uint32_t offset) const noexcept {
12011
236k
    return reinterpret_cast<const T*>(arena.data() + offset);
12012
236k
  }
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
Line
Count
Source
12010
482k
  [[nodiscard]] const T* section(uint32_t offset) const noexcept {
12011
482k
    return reinterpret_cast<const T*>(arena.data() + offset);
12012
482k
  }
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
Line
Count
Source
12010
230k
  [[nodiscard]] const T* section(uint32_t offset) const noexcept {
12011
230k
    return reinterpret_cast<const T*>(arena.data() + offset);
12012
230k
  }
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
Line
Count
Source
12010
6.14k
  [[nodiscard]] const T* section(uint32_t offset) const noexcept {
12011
6.14k
    return reinterpret_cast<const T*>(arena.data() + offset);
12012
6.14k
  }
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
Line
Count
Source
12010
6.14k
  [[nodiscard]] const T* section(uint32_t offset) const noexcept {
12011
6.14k
    return reinterpret_cast<const T*>(arena.data() + offset);
12012
6.14k
  }
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
Line
Count
Source
12010
6.14k
  [[nodiscard]] const T* section(uint32_t offset) const noexcept {
12011
6.14k
    return reinterpret_cast<const T*>(arena.data() + offset);
12012
6.14k
  }
unsigned char const* ada::url_pattern_list_detail::compiled_routes::section<unsigned char>(unsigned int) const
Line
Count
Source
12010
6.14k
  [[nodiscard]] const T* section(uint32_t offset) const noexcept {
12011
6.14k
    return reinterpret_cast<const T*>(arena.data() + offset);
12012
6.14k
  }
unsigned short const* ada::url_pattern_list_detail::compiled_routes::section<unsigned short>(unsigned int) const
Line
Count
Source
12010
6.14k
  [[nodiscard]] const T* section(uint32_t offset) const noexcept {
12011
6.14k
    return reinterpret_cast<const T*>(arena.data() + offset);
12012
6.14k
  }
unsigned int const* ada::url_pattern_list_detail::compiled_routes::section<unsigned int>(unsigned int) const
Line
Count
Source
12010
20.6k
  [[nodiscard]] const T* section(uint32_t offset) const noexcept {
12011
20.6k
    return reinterpret_cast<const T*>(arena.data() + offset);
12012
20.6k
  }
12013
};
12014
12015
/** @private Result of the fast-path engine or of the sequential matcher. */
12016
struct engine_result {
12017
  using capture = url_pattern_list_match_result::capture;
12018
  int32_t route = -1;
12019
  uint32_t capture_count = 0;
12020
  // False when the input exceeded a fast-path limit and the caller must run
12021
  // the sequential fallback over the whole route set.
12022
  bool within_fast_path = true;
12023
  bool captures_truncated = false;
12024
  std::array<capture, url_pattern_list_limits::max_captures_per_route>
12025
      captures{};
12026
};
12027
12028
/**
12029
 * @private
12030
 * Parses and compiles a set of pathname patterns (already base-URL
12031
 * processed). Routes that need the regex provider come back with
12032
 * route_record::regexp_component set to their ordinal in insertion order;
12033
 * the caller compiles those components and fills their group names.
12034
 */
12035
tl::expected<compiled_routes, errors> compile_pathname_patterns(
12036
    std::span<const std::string> patterns, bool ignore_case);
12037
12038
/**
12039
 * @private
12040
 * Sequential reference matcher for one non-regexp route of the compiled set;
12041
 * matches any input (no fast-path limits) with the same semantics as the
12042
 * compiled engine. With `fold_input`, input bytes are ASCII case-folded on
12043
 * the fly (the compiled literals are already folded). On a match, fills
12044
 * `result` (route index is NOT set) and returns true.
12045
 */
12046
bool match_route_sequential(const compiled_routes& tables, uint32_t route,
12047
                            std::string_view pathname, bool fold_input,
12048
                            engine_result& result) noexcept;
12049
12050
/**
12051
 * @private
12052
 * True when the bytes [p, p + n) hold no line terminator. A "*" segment
12053
 * compiles to "(.*)" in the URLPattern regexp, and "." in an ECMAScript
12054
 * regular expression does not match LF or CR, so a wildcard may not capture
12055
 * past one. Deliberately not inlined into the walk (it costs the static and
12056
 * ":param" paths, which never run it), and deliberately defined in
12057
 * url_pattern_list.cpp rather than here: MSVC's ada_never_inline carries no
12058
 * inline linkage, so a definition in this header is emitted in every
12059
 * translation unit.
12060
 */
12061
bool wildcard_tail_ok(const char* p, uint32_t n) noexcept;
12062
12063
/**
12064
 * @private
12065
 * Cheap pre-check for a regexp-mode route before running the provider: the
12066
 * part of the route's segment shape that is certain (see the compiler's
12067
 * approximate_kind_sequence) must fit the pathname -- its anchored literal
12068
 * segments, and its exact segment count when every group is a ":name"
12069
 * segment wildcard. False proves the regular expression cannot match.
12070
 */
12071
bool match_regexp_shape(const compiled_routes& tables, uint32_t route,
12072
                        std::string_view pathname, bool fold_input) noexcept;
12073
12074
/**
12075
 * @private
12076
 * True when route `a` (at insertion index `a_index`) outranks route `b` (at
12077
 * `b_index`): lexicographically smaller kind sequence, insertion order as the
12078
 * tiebreak.
12079
 */
12080
constexpr bool outranks(uint64_t a_sequence, uint32_t a_length, size_t a_index,
12081
                        uint64_t b_sequence, uint32_t b_length,
12082
525k
                        size_t b_index) noexcept {
12083
525k
  if (a_sequence != b_sequence) {
12084
511k
    return a_sequence < b_sequence;
12085
511k
  }
12086
13.2k
  if (a_length != b_length) {
12087
7.23k
    return a_length < b_length;
12088
7.23k
  }
12089
6.05k
  return a_index < b_index;
12090
13.2k
}
12091
12092
}  // namespace url_pattern_list_detail
12093
12094
template <url_pattern_regex::regex_concept regex_provider>
12095
class url_pattern_list;
12096
12097
/**
12098
 * @private
12099
 * url_pattern_list befriends these two specializations, so they have to be
12100
 * declared before it: a friend declaration that redeclares the function
12101
 * template instead is not matched by every compiler we support (Apple clang
12102
 * 15 rejects the resulting member access). The documented declarations are
12103
 * in implementation.h, next to parse_url_pattern, and carry the default
12104
 * arguments: this header includes url_pattern.h, which includes
12105
 * implementation.h, so those declarations are always seen first, and a
12106
 * function template may not gain default arguments in a later declaration.
12107
 */
12108
template <url_pattern_regex::regex_concept regex_provider>
12109
ada_warn_unused tl::expected<url_pattern_list<regex_provider>, errors>
12110
parse_url_pattern_list(std::span<const std::string_view> pathname_patterns,
12111
                       const std::string_view* base_url,
12112
                       const url_pattern_options* options);
12113
12114
/** @private See above. */
12115
template <url_pattern_regex::regex_concept regex_provider>
12116
ada_warn_unused tl::expected<url_pattern_list<regex_provider>, errors>
12117
parse_url_pattern_list(std::span<const url_pattern<regex_provider>> patterns);
12118
12119
/**
12120
 * @brief A compiled set of URLPattern pathname patterns with one-shot
12121
 * matching.
12122
 *
12123
 * Build once with ada::parse_url_pattern_list, then call match() per
12124
 * request. Matching within the fast-path limits is allocation-free and
12125
 * regex-free for routes written in the static / ":param" / "*" subset; other
12126
 * routes are matched through the regex provider (the same regex_search call
12127
 * url_pattern::exec makes) and still participate in the priority order.
12128
 *
12129
 * Match priority is specificity order, not registration order: routes are
12130
 * compared by their per-segment kind sequence (literal < ":param" < "*",
12131
 * lexicographically from the first segment), with insertion order breaking
12132
 * ties. This is the priority scheme of find-my-way (Fastify) and Express-
12133
 * style routers. Whether a standardized URLPatternList should instead use
12134
 * pure first-match-in-insertion-order semantics is an open question; the
12135
 * compiled representation supports either, and the priority rule is
12136
 * deliberately centralized in url_pattern_list_detail::outranks.
12137
 *
12138
 * Scope (v1): the pathname component only. Other URL components are treated
12139
 * as fully wildcarded; match() takes an already-extracted pathname (for
12140
 * example ada::url_aggregator::get_pathname()). Inputs are matched as given
12141
 * and are expected to be in canonical (percent-encoded) form; the pattern
12142
 * side is canonicalized by the URLPattern pattern parser at creation. The
12143
 * subset follows the URLPattern regexp it stands for: a ":param" segment
12144
 * ("[^/]+?") is one non-empty segment, and a "*" tail ("(.*)") matches any
12145
 * bytes except the line terminators LF and CR, which "." never matches.
12146
 *
12147
 * With url_pattern_options::ignore_case, regexp routes are compiled through
12148
 * the provider with the flag set (as url_pattern does), and the static /
12149
 * ":param" / "*" subset compares literal segments with ASCII case folding,
12150
 * which is what a case-insensitive regular expression does over the ASCII
12151
 * text of a canonical pathname.
12152
 *
12153
 * @tparam regex_provider The regex implementation used only for routes that
12154
 *         need URLPattern regexp semantics. Must satisfy
12155
 *         url_pattern_regex::regex_concept.
12156
 */
12157
template <url_pattern_regex::regex_concept regex_provider>
12158
class url_pattern_list {
12159
 public:
12160
9.39k
  url_pattern_list() = default;
12161
12162
  /**
12163
   * Matches a pathname against the set and returns the winning route with
12164
   * its captures (see url_pattern_list_match_result). The fast path is
12165
   * allocation-free; inputs beyond the fast-path limits are matched by the
12166
   * sequential fallback with identical semantics.
12167
   */
12168
  [[nodiscard]] url_pattern_list_match_result match(
12169
      std::string_view pathname) const;
12170
12171
  /** Number of routes in the set. */
12172
198k
  [[nodiscard]] size_t size() const noexcept { return patterns_.size(); }
12173
12174
  /** The pathname pattern string the route at `route_index` was created
12175
   * from (after base URL processing, if a base URL was given). */
12176
  [[nodiscard]] std::string_view pattern(size_t route_index) const
12177
182k
      ada_lifetime_bound {
12178
182k
    return patterns_[route_index];
12179
182k
  }
12180
12181
  /**
12182
   * Capture group names of the route at `route_index`, in the order of
12183
   * url_pattern_list_match_result::captures / regexp_groups ("*" groups have
12184
   * numeric names, per URLPattern).
12185
   */
12186
  [[nodiscard]] const std::vector<std::string>& group_names(
12187
182k
      size_t route_index) const ada_lifetime_bound {
12188
182k
    return compiled_.group_names[route_index];
12189
182k
  }
12190
12191
  /** The ignore_case option the set was created with. */
12192
7.81k
  [[nodiscard]] bool ignore_case() const noexcept {
12193
7.81k
    return compiled_.ignore_case != 0;
12194
7.81k
  }
12195
12196
  friend tl::expected<url_pattern_list, errors>
12197
  parse_url_pattern_list<regex_provider>(
12198
      std::span<const std::string_view> pathname_patterns,
12199
      const std::string_view* base_url, const url_pattern_options* options);
12200
12201
  friend tl::expected<url_pattern_list, errors> parse_url_pattern_list<
12202
      regex_provider>(std::span<const url_pattern<regex_provider>> patterns);
12203
12204
 private:
12205
  /** @private Compiles the (already processed) pattern strings; the regexp
12206
   * components are then supplied by the caller in insertion order. */
12207
  static tl::expected<url_pattern_list, errors> create(
12208
      std::vector<std::string>&& pathname_patterns, bool ignore_case);
12209
12210
  /** @private Tests one auxiliary route (sequential or regexp mode) and,
12211
   * when it matches and outranks `best`, replaces `best` with it. `probe`
12212
   * is the (possibly case-folded) pathname for the sequential matcher,
12213
   * `pathname` the original for the provider. */
12214
  void consider_route(
12215
      uint32_t route_index, std::string_view pathname, std::string_view probe,
12216
      bool fold_input, url_pattern_list_detail::engine_result& best,
12217
      std::vector<std::optional<std::string>>& best_groups) const;
12218
12219
  /** @private The pattern strings, by route index. */
12220
  std::vector<std::string> patterns_{};
12221
  /** @private The compiled tables. */
12222
  url_pattern_list_detail::compiled_routes compiled_{};
12223
  /** @private Compiled pathname components of the regexp-mode routes, in
12224
   * insertion order. */
12225
  std::vector<url_pattern_component<regex_provider>> regexp_components_{};
12226
};
12227
12228
}  // namespace ada
12229
#endif  // ADA_INCLUDE_URL_PATTERN
12230
#endif  // ADA_URL_PATTERN_LIST_H
12231
/* end file include/ada/url_pattern_list.h */
12232
/* begin file include/ada/url_pattern_list-inl.h */
12233
/**
12234
 * @file url_pattern_list-inl.h
12235
 * @brief The url_pattern_list matcher (inline) and the class template's
12236
 * member definitions.
12237
 *
12238
 * The walk over the compiled tables lives here, as ada_really_inline
12239
 * functions, so that it inlines into url_pattern_list::match; the route-set
12240
 * compiler that builds the tables is in its own translation unit
12241
 * (src/url_pattern_list.cpp) and is not part of the public headers.
12242
 */
12243
#ifndef ADA_URL_PATTERN_LIST_INL_H
12244
#define ADA_URL_PATTERN_LIST_INL_H
12245
12246
12247
#include <bit>
12248
#include <cstring>
12249
#include <optional>
12250
#include <string>
12251
#include <string_view>
12252
#include <utility>
12253
#include <vector>
12254
12255
#if ADA_NEON
12256
#include <arm_neon.h>
12257
#endif
12258
12259
#if ADA_INCLUDE_URL_PATTERN
12260
namespace ada::url_pattern_list_detail {
12261
12262
// ---- byte helpers ----------------------------------------------------------
12263
12264
// Unaligned 8-byte little-endian load; all 8 bytes must be readable. The
12265
// byte-assembly fallback keeps big-endian targets correct (the compiler
12266
// lowers it to a single load plus byte swap).
12267
34.0k
ada_really_inline uint64_t load8_le(const char* p) noexcept {
12268
34.0k
  if constexpr (std::endian::native == std::endian::little) {
12269
34.0k
    uint64_t x;
12270
34.0k
    std::memcpy(&x, p, 8);
12271
34.0k
    return x;
12272
  } else {
12273
    uint64_t x = 0;
12274
    for (uint32_t j = 0; j < 8; j++) {
12275
      x |= static_cast<uint64_t>(static_cast<uint8_t>(p[j])) << (8 * j);
12276
    }
12277
    return x;
12278
  }
12279
34.0k
}
12280
12281
// Bytes [0, n) of p packed little-endian, zero-padded; reads exactly n
12282
// bytes (n < 8). This is the byte-compare path for short tails.
12283
7.41k
ada_really_inline uint64_t gather_le(const char* p, uint32_t n) noexcept {
12284
7.41k
  uint64_t x = 0;
12285
35.0k
  for (uint32_t j = 0; j < n; j++) {
12286
27.6k
    x |= static_cast<uint64_t>(static_cast<uint8_t>(p[j])) << (8 * j);
12287
27.6k
  }
12288
7.41k
  return x;
12289
7.41k
}
12290
12291
// Mask selecting the low n bytes, 1 <= n <= 7.
12292
2.13k
constexpr uint64_t low_bytes_mask(uint32_t n) noexcept {
12293
2.13k
  return ~0ull >> (64 - 8 * n);
12294
2.13k
}
12295
12296
// ASCII case folding of n bytes from src into dst (the compiler vectorizes
12297
// this loop). Only ASCII letters change: canonical pathnames are ASCII, and
12298
// this is what a case-insensitive regular expression does over them.
12299
26.6k
inline void ascii_fold(const char* src, uint32_t n, char* dst) noexcept {
12300
800k
  for (uint32_t i = 0; i < n; i++) {
12301
773k
    const uint8_t c = static_cast<uint8_t>(src[i]);
12302
773k
    dst[i] = static_cast<char>(c | ((c >= 'A' && c <= 'Z') ? 0x20u : 0u));
12303
773k
  }
12304
26.6k
}
12305
12306
// ---- witness machinery -----------------------------------------------------
12307
// Projection dispatch for wide trie nodes. A witness id names a feature of a
12308
// byte string:
12309
//   0..7   the byte at absolute offset id           (0 when out of range)
12310
//   8..15  the byte at offset id-8 counted from the end
12311
// A projection is three witness bytes plus the length packed into one
12312
// uint64; a perfect multiplier turns it into a slot index. Builder and
12313
// matcher call the same accessors and the same packing, so a slot table
12314
// cannot disagree with the gather that reads it.
12315
12316
2.42M
constexpr uint8_t length_byte(uint32_t len) noexcept {
12317
2.42M
  return len < 255u ? static_cast<uint8_t>(len) : static_cast<uint8_t>(255);
12318
2.42M
}
12319
12320
constexpr uint8_t witness_byte(const char* p, uint32_t len,
12321
7.26M
                               uint8_t id) noexcept {  // ids 0..15
12322
7.26M
  uint32_t o = id & 7u;
12323
7.26M
  bool in = o < len;
12324
7.26M
  uint32_t pos = (id & 8u) ? len - 1u - o : o;  // wraps when !in; masked then
12325
7.26M
  pos = in ? pos : 0u;
12326
7.26M
  uint8_t v = len ? static_cast<uint8_t>(p[pos]) : static_cast<uint8_t>(0);
12327
7.26M
  return in ? v : static_cast<uint8_t>(0);
12328
7.26M
}
12329
12330
constexpr uint64_t pack_projection(uint8_t f0, uint8_t f1, uint8_t f2,
12331
2.42M
                                   uint8_t f3) noexcept {
12332
2.42M
  return (static_cast<uint64_t>(f0) << 24) | (static_cast<uint64_t>(f1) << 16) |
12333
2.42M
         (static_cast<uint64_t>(f2) << 8) | static_cast<uint64_t>(f3);
12334
2.42M
}
12335
12336
// Perfect-multiplier slot index; b <= 12 everywhere, so the shift is in
12337
// range and the product needs no modulus.
12338
constexpr uint64_t slot_of(uint64_t proj, uint64_t multiplier,
12339
5.99k
                           uint8_t b) noexcept {
12340
5.99k
  return (proj * multiplier) >> (64 - b);
12341
5.99k
}
12342
12343
// Fixed-shape projection of one string: always 3 witness bytes plus the
12344
// length. Duplicated ids add no information but keep the gather uniform.
12345
constexpr uint64_t project(const char* p, uint32_t len,
12346
2.42M
                           uint16_t plan) noexcept {
12347
2.42M
  return pack_projection(
12348
2.42M
      witness_byte(p, len, static_cast<uint8_t>(plan & 15u)),
12349
2.42M
      witness_byte(p, len, static_cast<uint8_t>((plan >> 4) & 15u)),
12350
2.42M
      witness_byte(p, len, static_cast<uint8_t>((plan >> 8) & 15u)),
12351
2.42M
      length_byte(len));
12352
2.42M
}
12353
12354
// ---- segment scan ----------------------------------------------------------
12355
12356
// Splits the pathname into segments in one pass, in place: only segment
12357
// starts are recorded, with a sentinel soff[nseg] = ulen + 1 so that
12358
// seg_len(i) == soff[i + 1] - soff[i] - 1. Returns the segment count, or 0
12359
// when the input has more than max_fast_path_segments segments (the caller
12360
// falls back to the sequential matcher). Requires ulen >= 1 and
12361
// url[0] == '/'.
12362
//
12363
// Two implementations with the same contract: the portable SWAR scan (8
12364
// bytes per step, an exact zero-byte test on x ^ '/'-fill with no false
12365
// positives, bytes >= 0x80 included, and a byte-exact partial load for the
12366
// tail, so the input is never over-read), and on AArch64 a NEON scan for
12367
// inputs of 16 bytes or more (16 bytes per step, the '/' compare narrowed
12368
// to one nibble per byte, the last block overlapping the previous one so
12369
// the input is never over-read). The 1k+ pathname benchmark in the PR
12370
// discussion is what keeps the NEON scan: it is faster at every length and
12371
// 3-4x faster past 1 KB.
12372
struct segment_emitter {
12373
  uint16_t* soff;
12374
  uint32_t nseg = 0;
12375
  uint32_t start = 1;
12376
  // One segment start per set bit of `lanes`; a lane is 1 << shift bits
12377
  // wide (8 for the SWAR masks, 4 for the NEON nibble masks).
12378
  ada_really_inline bool emit(uint64_t lanes, uint32_t base,
12379
17.8k
                              unsigned shift) noexcept {
12380
17.8k
    using url_pattern_list_limits::max_fast_path_segments;
12381
49.0k
    while (lanes) {
12382
31.7k
      const uint32_t pos =
12383
31.7k
          base + (static_cast<uint32_t>(std::countr_zero(lanes)) >> shift);
12384
31.7k
      if (nseg >= max_fast_path_segments) {
12385
542
        return false;
12386
542
      }
12387
31.1k
      soff[nseg++] = static_cast<uint16_t>(start);
12388
31.1k
      start = pos + 1;
12389
31.1k
      lanes &= lanes - 1;
12390
31.1k
    }
12391
17.3k
    return true;
12392
17.8k
  }
12393
5.60k
  ada_really_inline uint32_t finish(uint32_t ulen) noexcept {
12394
5.60k
    using url_pattern_list_limits::max_fast_path_segments;
12395
5.60k
    if (nseg >= max_fast_path_segments) {
12396
86
      return 0;
12397
86
    }
12398
5.51k
    soff[nseg++] = static_cast<uint16_t>(start);
12399
5.51k
    soff[nseg] = static_cast<uint16_t>(ulen + 1);  // sentinel
12400
5.51k
    return nseg;
12401
5.60k
  }
12402
};
12403
12404
ada_really_inline uint32_t scan_segments_swar(const char* url, uint32_t ulen,
12405
0
                                              uint16_t* soff) noexcept {
12406
0
  constexpr uint64_t slashes = 0x2F2F2F2F2F2F2F2Full;
12407
0
  constexpr uint64_t low7 = 0x7F7F7F7F7F7F7F7Full;
12408
0
  // Bit 7 of every byte of x that is zero, exactly: (b & 0x7F) + 0x7F has
12409
0
  // bit 7 set iff the low bits are non-zero, b itself has it set iff b is
12410
0
  // >= 0x80, and no lane can carry into its neighbour.
12411
30.9k
  const auto zero_lanes = [](uint64_t x) noexcept {
12412
30.9k
    return ~(((x & low7) + low7) | x | low7);
12413
30.9k
  };
12414
0
  segment_emitter out{soff};
12415
0
  uint32_t i = 1;
12416
0
  for (; i + 8 <= ulen; i += 8) {
12417
0
    const uint64_t lanes = zero_lanes(load8_le(url + i) ^ slashes);
12418
0
    if (lanes != 0 && !out.emit(lanes, i, 3)) {
12419
0
      return 0;
12420
0
    }
12421
0
  }
12422
0
  if (i < ulen) {  // tail of 1..7 bytes: zero padding is never a '/'
12423
0
    const uint64_t lanes = zero_lanes(gather_le(url + i, ulen - i) ^ slashes);
12424
0
    if (lanes != 0 && !out.emit(lanes, i, 3)) {
12425
0
      return 0;
12426
0
    }
12427
0
  }
12428
0
  return out.finish(ulen);
12429
0
}
12430
12431
#if ADA_NEON
12432
ada_really_inline uint32_t scan_segments_neon(const char* url, uint32_t ulen,
12433
                                              uint16_t* soff) noexcept {
12434
  // Requires ulen >= 16.
12435
  const uint8x16_t slash = vdupq_n_u8('/');
12436
  // One bit per byte lane that holds a '/': compare, narrow each 16-bit
12437
  // pair to its high nibble, keep bit 0 of every nibble.
12438
  const auto slash_lanes = [&](const char* p) noexcept {
12439
    const uint8x16_t v = vld1q_u8(reinterpret_cast<const uint8_t*>(p));
12440
    const uint64_t nibbles =
12441
        vget_lane_u64(vreinterpret_u64_u8(vshrn_n_u16(
12442
                          vreinterpretq_u16_u8(vceqq_u8(v, slash)), 4)),
12443
                      0);
12444
    return nibbles & 0x1111111111111111ull;
12445
  };
12446
  segment_emitter out{soff};
12447
  uint32_t i = 0;
12448
  for (; i + 16 <= ulen; i += 16) {
12449
    uint64_t lanes = slash_lanes(url + i);
12450
    if (i == 0) {
12451
      lanes &= ~0xFull;  // the leading '/' is not a separator
12452
    }
12453
    if (lanes != 0 && !out.emit(lanes, i, 2)) {
12454
      return 0;
12455
    }
12456
  }
12457
  if (i < ulen) {  // overlapped last block: drop the lanes already scanned
12458
    const uint32_t off = ulen - 16;
12459
    const uint64_t lanes = slash_lanes(url + off) & (~0ull << ((i - off) * 4));
12460
    if (lanes != 0 && !out.emit(lanes, off, 2)) {
12461
      return 0;
12462
    }
12463
  }
12464
  return out.finish(ulen);
12465
}
12466
#endif  // ADA_NEON
12467
12468
ada_really_inline uint32_t scan_segments(const char* url, uint32_t ulen,
12469
6.14k
                                         uint16_t* soff) noexcept {
12470
#if ADA_NEON
12471
  if (ulen >= 16) {
12472
    return scan_segments_neon(url, ulen, soff);
12473
  }
12474
#endif
12475
6.14k
  return scan_segments_swar(url, ulen, soff);
12476
6.14k
}
12477
12478
// ---- verify / dispatch -----------------------------------------------------
12479
12480
// One input segment prepared for dispatch: its bytes, its length, and how
12481
// many bytes are readable from p (to the end of the pathname).
12482
struct segment_ref {
12483
  const char* p;
12484
  uint32_t len;
12485
  uint32_t avail;
12486
};
12487
12488
// Segment-vs-edge compare. Keys of 8..16 bytes verify from two whole-word
12489
// loads inside the segment; shorter keys from one masked load when the
12490
// input has 8 readable bytes, else from a byte gather (short tails such as
12491
// "42" or "me"); longer keys through memcmp against the blob. An empty key
12492
// (a pattern such as "/users/") matches exactly the empty segment.
12493
ada_really_inline bool verify_edge(const edge_record& e, const segment_ref& s,
12494
13.2k
                                   const char* blob) noexcept {
12495
13.2k
  const uint32_t len = s.len;
12496
13.2k
  if (len != e.key_length) {
12497
5.29k
    return false;
12498
5.29k
  }
12499
7.96k
  if (len == 0) {
12500
1.00k
    return true;
12501
1.00k
  }
12502
6.96k
  if (len > 16) {
12503
2.25k
    return std::memcmp(s.p, blob + e.key_offset, len) == 0;
12504
2.25k
  }
12505
4.70k
  if (len >= 8) {
12506
2.05k
    return ((load8_le(s.p) ^ e.prefix) |
12507
2.05k
            (load8_le(s.p + len - 8) ^ e.suffix)) == 0;
12508
2.05k
  }
12509
2.64k
  const uint64_t x = s.avail >= 8 ? (load8_le(s.p) & low_bytes_mask(len))
12510
2.64k
                                  : gather_le(s.p, len);
12511
2.64k
  return x == e.prefix;
12512
4.70k
}
12513
12514
// The typed view of the arena the walk reads; derived once per match.
12515
struct table_view {
12516
  const node_record* nodes;
12517
  const hash_record* hashes;
12518
  const edge_record* edges;
12519
  const uint8_t* slots;
12520
  const char* blob;
12521
  const uint16_t* root_index;
12522
};
12523
12524
6.14k
ada_really_inline table_view view_of(const compiled_routes& r) noexcept {
12525
6.14k
  return table_view{r.section<node_record>(r.nodes_offset),
12526
6.14k
                    r.section<hash_record>(r.hashes_offset),
12527
6.14k
                    r.section<edge_record>(r.edges_offset),
12528
6.14k
                    r.section<uint8_t>(r.slots_offset),
12529
6.14k
                    r.section<char>(r.blob_offset),
12530
6.14k
                    r.section<uint16_t>(r.root_index_offset)};
12531
6.14k
}
12532
12533
// Static-child dispatch: returns the child ordinal within the node or -1.
12534
// Correctness never depends on the projection or the index: the candidate
12535
// is always confirmed by a full segment compare, so a bad table can only
12536
// cost time, never change an answer.
12537
ada_really_inline int32_t dispatch_static(const table_view& t,
12538
                                          const node_record& nd,
12539
0
                                          const segment_ref& s) noexcept {
12540
0
  const edge_record* e = t.edges + nd.first_child;
12541
0
  switch (nd.dispatch) {
12542
0
    case 0:
12543
0
      return -1;
12544
0
    case 1: {  // direct: up to 8 compares, each gated by the key length
12545
0
      for (uint32_t j = 0; j < nd.n_static; j++) {
12546
0
        if (verify_edge(e[j], s, t.blob)) {
12547
0
          return static_cast<int32_t>(j);
12548
0
        }
12549
0
      }
12550
0
      return -1;
12551
0
    }
12552
0
    case 2: {  // projection: gather -> multiply -> slot -> verify
12553
0
      const hash_record& h = t.hashes[nd.hash_index];
12554
0
      const uint64_t proj = project(s.p, s.len, h.witness_plan);
12555
0
      const uint8_t ord =
12556
0
          t.slots[h.slot_base + slot_of(proj, h.multiplier, h.slot_bits)];
12557
0
      if (ord == 0xFF) {
12558
0
        return -1;
12559
0
      }
12560
0
      return verify_edge(e[ord], s, t.blob) ? static_cast<int32_t>(ord) : -1;
12561
0
    }
12562
0
    case 4: {  // root first-byte index: jump to the run of children that
12563
0
               // share the segment's first byte (children are sorted by it)
12564
0
      if (s.len == 0) {
12565
0
        return -1;  // no first byte; an indexed root has no empty key
12566
0
      }
12567
0
      const uint8_t b = static_cast<uint8_t>(s.p[0]);
12568
0
      uint32_t j = t.root_index[b];
12569
0
      if (j == 0xFFFF) {
12570
0
        return -1;
12571
0
      }
12572
0
      for (; j < nd.n_static && static_cast<uint8_t>(e[j].prefix & 0xFFu) == b;
12573
0
           j++) {
12574
0
        if (verify_edge(e[j], s, t.blob)) {
12575
0
          return static_cast<int32_t>(j);
12576
0
        }
12577
0
      }
12578
0
      return -1;
12579
0
    }
12580
0
    default: {  // linear demotion rung (also carries fanout > 254)
12581
0
      for (uint32_t j = 0; j < nd.n_static; j++) {
12582
0
        if (verify_edge(e[j], s, t.blob)) {
12583
0
          return static_cast<int32_t>(j);
12584
0
        }
12585
0
      }
12586
0
      return -1;
12587
0
    }
12588
0
  }
12589
0
}
12590
12591
// ---- the match residual ----------------------------------------------------
12592
12593
// Matches `pathname` against the compiled tables. When the input is out of
12594
// the fast-path contract, returns with within_fast_path == false and no
12595
// answer; the caller falls back to the sequential matcher.
12596
ada_really_inline void match_compiled(const compiled_routes& r, const char* url,
12597
                                      uint32_t ulen,
12598
0
                                      engine_result& out) noexcept {
12599
0
  using url_pattern_list_limits::max_fast_path_pathname_length;
12600
0
  using url_pattern_list_limits::max_fast_path_segments;
12601
0
  out = engine_result{};
12602
0
  if (ulen == 0 || url[0] != '/' || ulen > max_fast_path_pathname_length) {
12603
0
    out.within_fast_path = false;  // the sequential fallback decides
12604
0
    return;
12605
0
  }
12606
0
  const table_view t = view_of(r);
12607
0
  const route_record* routes = r.section<route_record>(r.routes_offset);
12608
0
12609
0
  // Segment scan; overflow means the input is beyond the fast path.
12610
0
  uint16_t soff[max_fast_path_segments + 1];
12611
0
  const uint32_t nseg = scan_segments(url, ulen, soff);
12612
0
  if (nseg == 0) {
12613
0
    out.within_fast_path = false;
12614
0
    return;
12615
0
  }
12616
14.7k
  const auto seg_len = [&](uint32_t i) {
12617
14.7k
    return static_cast<uint32_t>(soff[i + 1]) - soff[i] - 1u;
12618
14.7k
  };
12619
10.5k
  const auto seg_ref = [&](uint32_t i) {
12620
10.5k
    const uint32_t off = soff[i];
12621
10.5k
    return segment_ref{url + off, seg_len(i), ulen - off};
12622
10.5k
  };
12623
0
12624
0
  // Trie walk with an explicit bounded backtrack stack. Every node offers
12625
0
  // the same three alternatives in the compiled priority order (static
12626
0
  // child, param child, wildcard); a backtrack record stores the resume
12627
0
  // point, and a record is pushed only when the node still has an untried
12628
0
  // alternative, so the stack never exceeds the walk depth. Edges encoded
12629
0
  // as -2 - route are pure-leaf shortcuts.
12630
0
  enum alternative : uint16_t {
12631
0
    alt_static = 0,
12632
0
    alt_param = 1,
12633
0
    alt_wild = 2,
12634
0
    alt_none = 3
12635
0
  };
12636
0
  struct backtrack {
12637
0
    int32_t node;
12638
0
    uint16_t i;
12639
0
    uint16_t resume;
12640
0
  };
12641
0
  backtrack stack[max_fast_path_segments + 1];
12642
0
  uint32_t sp = 0;
12643
0
  int32_t node = 0;
12644
0
  uint32_t i = 0;
12645
0
  uint32_t alt = alt_static;
12646
0
  int32_t route = -1;
12647
0
  uint32_t wild_from = 0;
12648
0
  bool wild = false;
12649
0
  for (;;) {
12650
0
    const node_record& nd = t.nodes[static_cast<size_t>(node)];
12651
0
    if (alt == alt_static) {
12652
0
      if (i == nseg) {
12653
0
        if (nd.terminal_route >= 0) {
12654
0
          route = nd.terminal_route;
12655
0
          break;
12656
0
        }
12657
0
        alt = alt_none;
12658
0
      } else {
12659
0
        const int32_t ord = dispatch_static(t, nd, seg_ref(i));
12660
0
        if (ord >= 0) {
12661
0
          const int32_t nxt = t.edges[static_cast<size_t>(nd.first_child) +
12662
0
                                      static_cast<size_t>(ord)]
12663
0
                                  .node;
12664
0
          if (nxt >= 0) {
12665
0
            if (nd.has_alternative) {
12666
0
              stack[sp++] = {node, static_cast<uint16_t>(i), alt_param};
12667
0
            }
12668
0
            node = nxt;
12669
0
            i++;
12670
0
            continue;
12671
0
          }
12672
0
          // Pure-leaf shortcut.
12673
0
          if (i + 1 == nseg) {
12674
0
            route = -2 - nxt;
12675
0
            break;
12676
0
          }
12677
0
          alt = alt_param;  // dead end: fall through to this node's fallbacks
12678
0
        } else {
12679
0
          alt = alt_param;
12680
0
        }
12681
0
      }
12682
0
    }
12683
0
    if (alt == alt_param) {
12684
0
      const int32_t pc = nd.param_child;
12685
0
      if (pc != -1 && seg_len(i) > 0) {
12686
0
        if (pc >= 0) {
12687
0
          if (nd.wild_route >= 0) {
12688
0
            stack[sp++] = {node, static_cast<uint16_t>(i), alt_wild};
12689
0
          }
12690
0
          node = pc;
12691
0
          i++;
12692
0
          alt = alt_static;
12693
0
          continue;
12694
0
        }
12695
0
        // Pure-leaf param shortcut.
12696
0
        if (i + 1 == nseg) {
12697
0
          route = -2 - pc;
12698
0
          break;
12699
0
        }
12700
0
        alt = alt_wild;  // only the wildcard remains here
12701
0
      } else {
12702
0
        alt = alt_wild;
12703
0
      }
12704
0
    }
12705
0
    if (alt == alt_wild) {
12706
0
      if (nd.wild_route >= 0 &&
12707
0
          wildcard_tail_ok(url + soff[i], ulen - soff[i])) {
12708
0
        route = nd.wild_route;
12709
0
        wild_from = i;
12710
0
        wild = true;
12711
0
        break;
12712
0
      }
12713
0
      // No alternative left at this node: resume from the backtrack stack
12714
0
      // (alt is overwritten by the popped record).
12715
0
    }
12716
0
    if (sp == 0) {
12717
0
      break;  // nothing to resume: miss
12718
0
    }
12719
0
    --sp;
12720
0
    node = stack[sp].node;
12721
0
    i = stack[sp].i;
12722
0
    alt = stack[sp].resume;
12723
0
  }
12724
0
12725
0
  out.route = route;
12726
0
  if (route >= 0) {  // capture extraction: params first, wildcard tail last
12727
0
    const route_record& rm = routes[static_cast<size_t>(route)];
12728
0
    uint32_t nc = 0;
12729
0
    for (uint32_t k = 0; k < rm.n_params; k++) {
12730
0
      const uint32_t p = rm.param_positions[k];
12731
0
      out.captures[nc++] = {soff[p], seg_len(p)};
12732
0
    }
12733
0
    if (wild) {
12734
0
      out.captures[nc++] = {soff[wild_from], ulen - soff[wild_from]};
12735
0
    }
12736
0
    out.capture_count = nc;
12737
0
  }
12738
0
}
12739
12740
}  // namespace ada::url_pattern_list_detail
12741
12742
namespace ada {
12743
12744
template <url_pattern_regex::regex_concept regex_provider>
12745
tl::expected<url_pattern_list<regex_provider>, errors>
12746
url_pattern_list<regex_provider>::create(
12747
9.39k
    std::vector<std::string>&& pathname_patterns, bool ignore_case) {
12748
9.39k
  url_pattern_list list{};
12749
9.39k
  list.patterns_ = std::move(pathname_patterns);
12750
9.39k
  auto compiled = url_pattern_list_detail::compile_pathname_patterns(
12751
9.39k
      list.patterns_, ignore_case);
12752
9.39k
  if (!compiled) {
12753
760
    return tl::unexpected(compiled.error());
12754
760
  }
12755
8.63k
  list.compiled_ = std::move(*compiled);
12756
8.63k
  return list;
12757
9.39k
}
12758
12759
template <url_pattern_regex::regex_concept regex_provider>
12760
void url_pattern_list<regex_provider>::consider_route(
12761
    uint32_t route_index, std::string_view pathname, std::string_view probe,
12762
    bool fold_input, url_pattern_list_detail::engine_result& best,
12763
231k
    std::vector<std::optional<std::string>>& best_groups) const {
12764
231k
  namespace detail = url_pattern_list_detail;
12765
231k
  const detail::route_record* routes =
12766
231k
      compiled_.section<detail::route_record>(compiled_.routes_offset);
12767
231k
  const detail::route_record& candidate = routes[route_index];
12768
  // Only test candidates that would outrank the current best.
12769
231k
  if (best.route >= 0) {
12770
4.92k
    const detail::route_record& current =
12771
4.92k
        routes[static_cast<size_t>(best.route)];
12772
4.92k
    if (!detail::outranks(candidate.kind_sequence, candidate.kind_length,
12773
4.92k
                          route_index, current.kind_sequence,
12774
4.92k
                          current.kind_length,
12775
4.92k
                          static_cast<size_t>(best.route))) {
12776
1.24k
      return;
12777
1.24k
    }
12778
4.92k
  }
12779
230k
  if (candidate.mode == detail::route_mode::regexp) {
12780
    // A route whose certain segment shape does not fit the input cannot
12781
    // match at all: skip the provider.
12782
43.2k
    if (!detail::match_regexp_shape(compiled_, route_index, probe,
12783
43.2k
                                    fold_input)) {
12784
15.3k
      return;
12785
15.3k
    }
12786
    // URLPattern's own test/exec split: regex_match answers yes/no (this is
12787
    // what rejects a non-matching route cheaply; a regex_search miss can
12788
    // cost a scan over every start position), and regex_search then
12789
    // produces the group values exactly as url_pattern::exec does.
12790
27.8k
    const url_pattern_component<regex_provider>& component =
12791
27.8k
        regexp_components_[static_cast<size_t>(candidate.regexp_component)];
12792
27.8k
    if (!component.fast_test(pathname)) {
12793
27.0k
      return;
12794
27.0k
    }
12795
796
    auto groups = component.fast_match(pathname);
12796
796
    if (groups) {
12797
796
      best = detail::engine_result{};
12798
796
      best.route = static_cast<int32_t>(route_index);
12799
796
      best_groups = std::move(*groups);
12800
796
    }
12801
186k
  } else {
12802
186k
    detail::engine_result scratch{};
12803
186k
    if (detail::match_route_sequential(compiled_, route_index, probe,
12804
186k
                                       fold_input, scratch)) {
12805
623
      scratch.route = static_cast<int32_t>(route_index);
12806
623
      best = scratch;
12807
623
      best_groups.clear();
12808
623
    }
12809
186k
  }
12810
230k
}
12811
12812
template <url_pattern_regex::regex_concept regex_provider>
12813
url_pattern_list_match_result url_pattern_list<regex_provider>::match(
12814
20.6k
    std::string_view pathname) const {
12815
20.6k
  namespace detail = url_pattern_list_detail;
12816
20.6k
  using url_pattern_list_limits::max_fast_path_pathname_length;
12817
  // With ignore_case the compiled literals are ASCII-folded, so the fast
12818
  // path probes a folded copy of the input (offsets are unchanged, so the
12819
  // captures still slice the original). Inputs beyond the fast-path length
12820
  // are folded on the fly by the sequential matcher instead.
12821
20.6k
  char folded[max_fast_path_pathname_length];
12822
20.6k
  std::string_view probe = pathname;
12823
20.6k
  bool fold_input = false;
12824
20.6k
  if (compiled_.ignore_case) {
12825
8.83k
    if (pathname.size() <= max_fast_path_pathname_length) {
12826
8.77k
      detail::ascii_fold(pathname.data(),
12827
8.77k
                         static_cast<uint32_t>(pathname.size()), folded);
12828
8.77k
      probe = std::string_view(folded, pathname.size());
12829
8.77k
    } else {
12830
55
      fold_input = true;
12831
55
    }
12832
8.83k
  }
12833
20.6k
  detail::engine_result best{};
12834
20.6k
  std::vector<std::optional<std::string>> best_groups{};
12835
20.6k
  detail::match_compiled(compiled_, probe.data(),
12836
20.6k
                         static_cast<uint32_t>(probe.size()), best);
12837
20.6k
  const uint32_t* aux = compiled_.section<uint32_t>(compiled_.aux_offset);
12838
20.6k
  if (!best.within_fast_path) {
12839
    // The input exceeds a fast-path limit (length, segment count, or no
12840
    // leading '/'): the sequential fallback matches every route with
12841
    // identical priority semantics.
12842
15.0k
    best = detail::engine_result{};
12843
239k
    for (size_t i = 0; i < patterns_.size(); i++) {
12844
224k
      consider_route(static_cast<uint32_t>(i), pathname, probe, fold_input,
12845
224k
                     best, best_groups);
12846
224k
    }
12847
15.0k
  } else if (best.route >= 0) {
12848
    // A fast-path winner is final except for the auxiliary routes recorded
12849
    // at creation as able to outrank it (usually none).
12850
2.37k
    const detail::route_record& winner =
12851
2.37k
        compiled_.section<detail::route_record>(
12852
2.37k
            compiled_.routes_offset)[static_cast<size_t>(best.route)];
12853
3.74k
    for (uint32_t k = 0; k < winner.challenger_count; k++) {
12854
1.36k
      consider_route(aux[winner.challenger_first + k], pathname, probe,
12855
1.36k
                     fold_input, best, best_groups);
12856
1.36k
    }
12857
3.13k
  } else {
12858
    // A fast-path miss: any auxiliary route may still match.
12859
8.54k
    for (uint32_t k = 0; k < compiled_.n_aux_all; k++) {
12860
5.40k
      consider_route(aux[k], pathname, probe, fold_input, best, best_groups);
12861
5.40k
    }
12862
3.13k
  }
12863
20.6k
  url_pattern_list_match_result result{};
12864
20.6k
  result.route_index = best.route;
12865
20.6k
  if (best.route >= 0) {
12866
3.45k
    const detail::route_record& winner =
12867
3.45k
        compiled_.section<detail::route_record>(
12868
3.45k
            compiled_.routes_offset)[static_cast<size_t>(best.route)];
12869
3.45k
    if (winner.mode == detail::route_mode::regexp) {
12870
645
      result.regexp_route = true;
12871
645
      result.regexp_groups = std::move(best_groups);
12872
2.81k
    } else {
12873
2.81k
      result.capture_count = best.capture_count;
12874
2.81k
      result.captures_truncated = best.captures_truncated;
12875
2.81k
      result.captures = best.captures;
12876
2.81k
    }
12877
3.45k
  }
12878
20.6k
  return result;
12879
20.6k
}
12880
12881
}  // namespace ada
12882
#endif  // ADA_INCLUDE_URL_PATTERN
12883
#endif  // ADA_URL_PATTERN_LIST_INL_H
12884
/* end file include/ada/url_pattern_list-inl.h */
12885
12886
// Public API
12887
/* begin file include/ada/ada_version.h */
12888
/**
12889
 * @file ada_version.h
12890
 * @brief Definitions for Ada's version number.
12891
 */
12892
#ifndef ADA_ADA_VERSION_H
12893
#define ADA_ADA_VERSION_H
12894
12895
13.7k
#define ADA_VERSION "4.0.0"
12896
12897
namespace ada {
12898
12899
enum {
12900
  ADA_VERSION_MAJOR = 4,
12901
  ADA_VERSION_MINOR = 0,
12902
  ADA_VERSION_REVISION = 0,
12903
};
12904
12905
}  // namespace ada
12906
12907
#endif  // ADA_ADA_VERSION_H
12908
/* end file include/ada/ada_version.h */
12909
/* begin file include/ada/implementation-inl.h */
12910
/**
12911
 * @file implementation-inl.h
12912
 */
12913
#ifndef ADA_IMPLEMENTATION_INL_H
12914
#define ADA_IMPLEMENTATION_INL_H
12915
12916
12917
12918
#include <variant>
12919
#include <string_view>
12920
12921
namespace ada {
12922
12923
#if ADA_INCLUDE_URL_PATTERN
12924
template <url_pattern_regex::regex_concept regex_provider>
12925
ada_warn_unused tl::expected<url_pattern<regex_provider>, errors>
12926
parse_url_pattern(std::variant<std::string_view, url_pattern_init>&& input,
12927
                  const std::string_view* base_url,
12928
421k
                  const url_pattern_options* options) {
12929
421k
  return parser::parse_url_pattern_impl<regex_provider>(std::move(input),
12930
421k
                                                        base_url, options);
12931
421k
}
12932
12933
template <url_pattern_regex::regex_concept regex_provider>
12934
ada_warn_unused tl::expected<url_pattern_list<regex_provider>, errors>
12935
parse_url_pattern_list(std::span<const std::string_view> pathname_patterns,
12936
                       const std::string_view* base_url,
12937
9.39k
                       const url_pattern_options* options) {
12938
9.39k
  std::vector<std::string> processed;
12939
9.39k
  processed.reserve(pathname_patterns.size());
12940
231k
  for (const std::string_view pattern : pathname_patterns) {
12941
231k
    if (base_url == nullptr) {
12942
231k
      processed.emplace_back(pattern);
12943
231k
      continue;
12944
231k
    }
12945
    // With a base URL, each pattern is processed exactly as the pathname of
12946
    // a URLPatternInit would be: a relative pattern is resolved against the
12947
    // base URL's path (and an unparsable base URL is a type error).
12948
0
    url_pattern_init init{};
12949
0
    init.pathname = std::string(pattern);
12950
0
    init.base_url = std::string(*base_url);
12951
0
    auto result = url_pattern_init::process(
12952
0
        init, url_pattern_init::process_type::pattern);
12953
0
    if (!result) {
12954
0
      return tl::unexpected(result.error());
12955
0
    }
12956
0
    processed.push_back(std::move(result->pathname).value_or(std::string{}));
12957
0
  }
12958
9.39k
  const bool ignore_case = options != nullptr && options->ignore_case;
12959
9.39k
  auto list = url_pattern_list<regex_provider>::create(std::move(processed),
12960
9.39k
                                                       ignore_case);
12961
9.39k
  if (!list) {
12962
760
    return list;
12963
760
  }
12964
  // Routes outside the static/":param"/"*" subset are compiled as a
12965
  // URLPattern pathname component through the provider, with the same
12966
  // options parse_url_pattern would use (ignore_case included).
12967
8.63k
  auto compile_options = url_pattern_compile_component_options::PATHNAME;
12968
8.63k
  compile_options.ignore_case = ignore_case;
12969
8.63k
  const url_pattern_list_detail::route_record* routes =
12970
8.63k
      list->compiled_.template section<url_pattern_list_detail::route_record>(
12971
8.63k
          list->compiled_.routes_offset);
12972
191k
  for (size_t i = 0; i < list->patterns_.size(); i++) {
12973
183k
    if (routes[i].regexp_component < 0) {
12974
159k
      continue;
12975
159k
    }
12976
24.0k
    auto component = url_pattern_component<regex_provider>::compile(
12977
24.0k
        list->patterns_[i], url_pattern_helpers::canonicalize_pathname,
12978
24.0k
        compile_options);
12979
24.0k
    if (!component) {
12980
818
      return tl::unexpected(component.error());
12981
818
    }
12982
23.2k
    list->compiled_.group_names[i] = component->group_name_list;
12983
23.2k
    list->regexp_components_.push_back(std::move(*component));
12984
23.2k
  }
12985
7.81k
  return list;
12986
8.63k
}
12987
12988
template <url_pattern_regex::regex_concept regex_provider>
12989
ada_warn_unused tl::expected<url_pattern_list<regex_provider>, errors>
12990
parse_url_pattern_list(std::span<const url_pattern<regex_provider>> patterns) {
12991
  std::vector<std::string> texts;
12992
  texts.reserve(patterns.size());
12993
  const bool ignore_case = !patterns.empty() && patterns[0].ignore_case();
12994
  for (const url_pattern<regex_provider>& pattern : patterns) {
12995
    if (pattern.ignore_case() != ignore_case) {
12996
      return tl::unexpected(errors::type_error);  // one flag per list
12997
    }
12998
    texts.emplace_back(pattern.get_pathname());
12999
  }
13000
  auto list =
13001
      url_pattern_list<regex_provider>::create(std::move(texts), ignore_case);
13002
  if (!list) {
13003
    return list;
13004
  }
13005
  // Routes outside the subset reuse the pattern's already compiled pathname
13006
  // component: no second create_instance through the provider.
13007
  const url_pattern_list_detail::route_record* routes =
13008
      list->compiled_.template section<url_pattern_list_detail::route_record>(
13009
          list->compiled_.routes_offset);
13010
  for (size_t i = 0; i < patterns.size(); i++) {
13011
    if (routes[i].regexp_component < 0) {
13012
      continue;
13013
    }
13014
    list->compiled_.group_names[i] =
13015
        patterns[i].pathname_component.group_name_list;
13016
    list->regexp_components_.push_back(patterns[i].pathname_component);
13017
  }
13018
  return list;
13019
}
13020
#endif  // ADA_INCLUDE_URL_PATTERN
13021
13022
}  // namespace ada
13023
13024
#endif  // ADA_IMPLEMENTATION_INL_H
13025
/* end file include/ada/implementation-inl.h */
13026
13027
#endif  // ADA_H
13028
/* end file include/ada.h */