rama-net 0.3.0

rama network types and utilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
//! Query component types — owned [`Query`] and borrowed [`QueryRef`].
//!
//! Per RFC 3986 §3.4, the query is opaque bytes between `?` and `#`. The
//! `key=value&…` shape is a convention (HTML forms, most APIs) — not part
//! of the URI grammar. Use [`QueryRef::pairs`] to iterate name/value pairs
//! and, with the `std` feature, [`QueryRef::deserialize`] to read straight into a typed value with
//! `application/x-www-form-urlencoded` semantics.

use core::fmt;
use core::hash::Hash;

use crate::std::borrow::Cow;
use crate::std::string::String;
use crate::std::vec::Vec;

use super::component_input::IntoUriComponent;
use super::encode::{
    encoded_pair_component, encoded_query, encoded_query_cmp, encoded_query_eq,
    extend_encoded_query, hash_encoded_query, write_encoded_query,
};

use rama_core::bytes::{Bytes, BytesMut};

use percent_encoding::percent_decode;

/// Owned query component. Cheaply mutable in-place via the
/// [`QueryMut`](super::QueryMut) RAII guard.
///
/// `Default` produces an empty query (zero bytes — distinct from
/// "no query"; the distinction is owned by [`super::Uri::query`] /
/// [`super::Uri::set_query`]). `Display` writes the explicitly encoded
/// query view (no leading `?`). `Hash` / `PartialOrd` / `Ord` use that
/// same encoded view, so raw component text and its pct-encoded spelling
/// compare consistently.
#[derive(Debug, Clone, Default)]
pub struct Query {
    pub(crate) bytes: BytesMut,
}

impl Query {
    /// Percent-encoded query string (no leading `?`).
    #[must_use]
    pub fn as_encoded_str(&self) -> Cow<'_, str> {
        encoded_query(&self.bytes)
    }

    /// `true` when the query contains no bytes. An empty query is still
    /// *present* (`?` on the wire) — the present-vs-absent distinction is
    /// owned by [`super::Uri::query`].
    #[must_use]
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.bytes.is_empty()
    }

    /// Percent-decoded query string. `Cow::Borrowed` when no `%XX`
    /// escapes are present; `Cow::Owned` otherwise. UTF-8 errors fall
    /// back to U+FFFD (matches curl, browsers).
    #[must_use]
    pub fn as_decoded_str(&self) -> Cow<'_, str> {
        percent_decode(&self.bytes).decode_utf8_lossy()
    }

    /// Borrowed view. Named `view` (not `as_ref`) so it doesn't shadow
    /// the std `AsRef` trait — see the type-level docs.
    #[must_use]
    #[inline]
    pub fn view(&self) -> QueryRef<'_> {
        QueryRef { bytes: &self.bytes }
    }

    /// Iterator over `name[=value]` pairs in the query string.
    ///
    /// Convenience pass-through to [`QueryRef::pairs`] on the borrowed
    /// view — see that method for the splitting / decoding contract.
    #[must_use]
    pub fn pairs(&self) -> QueryPairs<'_> {
        QueryPairs::new(&self.bytes)
    }

    /// Deserialize the query into `T`. See [`QueryRef::deserialize`] for
    /// the encoding and borrowing contract.
    #[cfg(feature = "std")]
    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
    pub fn deserialize<'de, T>(&'de self) -> Result<T, QueryDeserializeError>
    where
        T: serde::de::Deserialize<'de>,
    {
        self.view().deserialize::<T>()
    }

    /// The first form-decoded value for the pair named `name`. See
    /// [`QueryRef::first_value`] for the matching and bare-key rules.
    #[must_use]
    pub fn first_value(&self, name: impl IntoUriComponent) -> Option<Cow<'_, str>> {
        self.view().first_value(name)
    }

    /// Iterator over the form-decoded values of every pair named `name`.
    /// See [`QueryRef::values`].
    #[must_use]
    pub fn values(&self, name: impl IntoUriComponent) -> QueryValues<'_> {
        self.view().values(name)
    }

    /// `true` when any pair's form-decoded name equals `name`. See
    /// [`QueryRef::contains_name`].
    #[must_use]
    pub fn contains_name(&self, name: impl IntoUriComponent) -> bool {
        self.view().contains_name(name)
    }
}

impl PartialEq for Query {
    #[inline(always)]
    fn eq(&self, other: &Self) -> bool {
        self.view() == other.view()
    }
}

impl Eq for Query {}

impl PartialOrd for Query {
    #[inline(always)]
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Query {
    #[inline(always)]
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.view().cmp(&other.view())
    }
}

impl Hash for Query {
    #[inline(always)]
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.view().hash(state);
    }
}

/// Starting-capacity hint per pair when collecting via [`FromIterator`].
/// Covers a typical short `name=value` plus the `&` separator with
/// margin; [`BytesMut`] grows further if the iterator turns out to
/// produce longer content.
const COLLECT_BYTES_PER_PAIR: usize = 32;

/// Build a [`Query`] from an iterator of pair-byte slices, joining with `&`.
fn collect_pairs<'a, I>(iter: I) -> Query
where
    I: IntoIterator,
    I::Item: AsRef<[u8]> + 'a,
{
    let iter = iter.into_iter();
    let mut bytes = BytesMut::with_capacity(iter.size_hint().0 * COLLECT_BYTES_PER_PAIR);
    for pair in iter {
        if !bytes.is_empty() {
            bytes.extend_from_slice(b"&");
        }
        bytes.extend_from_slice(pair.as_ref());
    }
    Query { bytes }
}

impl FromIterator<QueryPair> for Query {
    /// Build a [`Query`] by concatenating pre-encoded pair bytes with
    /// `&` separators. No re-encoding — the pairs' bytes are assumed to
    /// already be in canonical on-wire form (which they are, when they
    /// come from [`QueryRef::pairs`], [`QueryMut::pop`](super::QueryMut::pop)
    /// or [`QueryMut::drain`](super::QueryMut::drain)).
    fn from_iter<I: IntoIterator<Item = QueryPair>>(iter: I) -> Self {
        collect_pairs(iter.into_iter().map(|p| p.raw))
    }
}

impl<'a> FromIterator<QueryPairRef<'a>> for Query {
    /// Build a [`Query`] from borrowed pair views by copying their raw
    /// bytes. See [`FromIterator<QueryPair>`](Query#impl-FromIterator<QueryPair>-for-Query)
    /// for the no-re-encoding contract.
    fn from_iter<I: IntoIterator<Item = QueryPairRef<'a>>>(iter: I) -> Self {
        collect_pairs(iter.into_iter().map(|p| p.raw))
    }
}

/// Borrowed view of a URI query component (no leading `?`).
#[derive(Debug, Clone, Copy)]
pub struct QueryRef<'a> {
    pub(crate) bytes: &'a [u8],
}

impl<'a> QueryRef<'a> {
    #[must_use]
    #[inline]
    pub(crate) const fn new(bytes: &'a [u8]) -> Self {
        Self { bytes }
    }

    /// Borrow a query string as a [`QueryRef`] — no allocation.
    ///
    /// The input is treated as component text. When rendered through
    /// [`QueryRef::as_encoded_str`], bytes outside the query grammar are
    /// percent-encoded while valid existing pct triplets are preserved.
    #[must_use]
    #[inline]
    pub fn from_raw_str(query: &'a str) -> Self {
        Self::new(query.as_bytes())
    }

    /// Percent-encoded query string (no leading `?`).
    #[must_use]
    pub fn as_encoded_str(self) -> Cow<'a, str> {
        encoded_query(self.bytes)
    }

    /// `true` when the query contains no bytes. An empty query is still
    /// *present* (`?` on the wire) — the present-vs-absent distinction is
    /// owned by [`super::Uri::query`].
    #[must_use]
    #[inline]
    pub fn is_empty(self) -> bool {
        self.bytes.is_empty()
    }

    pub(super) fn write_encoded_to(self, buf: &mut BytesMut) {
        extend_encoded_query(buf, self.bytes);
    }

    /// Percent-decoded query string. `Cow::Borrowed` when no `%XX`
    /// escapes are present; `Cow::Owned` otherwise. UTF-8 errors fall
    /// back to U+FFFD.
    #[must_use]
    pub fn as_decoded_str(&self) -> Cow<'a, str> {
        percent_decode(self.bytes).decode_utf8_lossy()
    }

    /// Returns an owned copy. Named `into_owned` (matching
    /// [`crate::std::borrow::Cow::into_owned`]) so it doesn't shadow the std `ToOwned`
    /// trait method.
    #[must_use]
    pub fn into_owned(self) -> Query {
        Query {
            bytes: BytesMut::from(self.bytes),
        }
    }

    /// Iterator over `name[=value]` pairs.
    ///
    /// Follows WHATWG `URLSearchParams` / form-urlencoded splitting:
    /// `&` delimits pairs, the first `=` in each pair delimits name from
    /// value, empty fragments (`&&`, leading/trailing `&`) are dropped.
    /// Each [`QueryPair`] keeps the bare-vs-empty-value distinction —
    /// `?foo` → `value = None`, `?foo=` → `value = Some("")`.
    #[must_use]
    pub fn pairs(&self) -> QueryPairs<'a> {
        QueryPairs::new(self.bytes)
    }

    /// Deserialize the query into `T` with `application/x-www-form-urlencoded`
    /// semantics: `+` → space, `%XX` → byte, repeated keys collect into a
    /// `Vec<_>` field.
    ///
    /// Bare keys (`?foo`) decode as `foo=""`, matching WHATWG
    /// `URLSearchParams`. This diverges from [`pairs`](Self::pairs)
    /// which keeps the bare-vs-empty distinction — use that iterator
    /// if you need it.
    ///
    /// Fields can borrow from the query bytes when the component already has a
    /// borrowed encoded view: `&'a str` and `Cow<'a, str>` skip the allocation
    /// when the source value has no `+` / `%XX` to decode. When decoding *is*
    /// needed, `&'a str` fails (the decoded bytes don't live in the input)
    /// while `Cow<'a, str>` falls back to `Cow::Owned`. Prefer `Cow<'a, str>`
    /// or `String` for fields that may contain escapes.
    #[cfg(feature = "std")]
    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
    pub fn deserialize<T>(&self) -> Result<T, QueryDeserializeError>
    where
        T: serde::de::Deserialize<'a>,
    {
        match self.as_encoded_str() {
            Cow::Borrowed(encoded) => {
                serde_html_form::from_str(encoded).map_err(QueryDeserializeError)
            }
            Cow::Owned(_) => Err(QueryDeserializeError(
                <serde_html_form::de::Error as serde::de::Error>::custom(
                    "query contains component text that needs encoding before deserialization",
                ),
            )),
        }
    }

    /// The first form-decoded value for the pair named `name`, or `None`
    /// when no pair matches.
    ///
    /// `name` is component text, compared form-decoded on both sides —
    /// `"a b"`, `"a+b"` and `"a%20b"` all address the same name (the same
    /// normalization the path matchers apply to their patterns). A bare
    /// key (`?foo`) yields `Some("")` — the WHATWG convention also used by
    /// [`deserialize`](Self::deserialize); use [`pairs`](Self::pairs) when
    /// the bare-vs-empty distinction matters.
    #[must_use]
    pub fn first_value(self, name: impl IntoUriComponent) -> Option<Cow<'a, str>> {
        self.values(name).next()
    }

    /// Iterator over the form-decoded values of every pair named `name`
    /// (repeated names are legal: `?tag=a&tag=b`). See
    /// [`first_value`](Self::first_value) for the matching and bare-key
    /// rules.
    #[must_use]
    #[expect(
        clippy::needless_pass_by_value,
        reason = "by-value matches IntoUriComponent's signature on sibling matchers; this impl only borrows the input"
    )]
    pub fn values(self, name: impl IntoUriComponent) -> QueryValues<'a> {
        QueryValues {
            pairs: self.pairs(),
            name: form_decode_bytes(&name.as_uri_component_bytes()).into_owned(),
        }
    }

    /// `true` when any pair's form-decoded name equals `name` (bare keys
    /// count). See [`first_value`](Self::first_value) for the matching
    /// rules.
    #[must_use]
    #[expect(
        clippy::needless_pass_by_value,
        reason = "by-value matches IntoUriComponent's signature on sibling matchers; this impl only borrows the input"
    )]
    pub fn contains_name(self, name: impl IntoUriComponent) -> bool {
        let name = name.as_uri_component_bytes();
        let pattern = form_decode_bytes(&name);
        self.pairs()
            .any(|p| form_decode_bytes(p.name_bytes()) == pattern)
    }
}

impl PartialEq for QueryRef<'_> {
    #[inline(always)]
    fn eq(&self, other: &Self) -> bool {
        encoded_query_eq(self.bytes, other.bytes)
    }
}

impl Eq for QueryRef<'_> {}

impl PartialEq<str> for QueryRef<'_> {
    #[inline(always)]
    fn eq(&self, other: &str) -> bool {
        self.eq(&QueryRef::from_raw_str(other))
    }
}

impl PartialEq<&str> for QueryRef<'_> {
    #[inline(always)]
    fn eq(&self, other: &&str) -> bool {
        self.eq(&QueryRef::from_raw_str(other))
    }
}

impl<'a> PartialEq<QueryRef<'a>> for str {
    #[inline(always)]
    fn eq(&self, other: &QueryRef<'a>) -> bool {
        QueryRef::from_raw_str(self).eq(other)
    }
}

impl<'a> PartialEq<QueryRef<'a>> for &str {
    #[inline(always)]
    fn eq(&self, other: &QueryRef<'a>) -> bool {
        QueryRef::from_raw_str(self).eq(other)
    }
}

impl PartialOrd for QueryRef<'_> {
    #[inline(always)]
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for QueryRef<'_> {
    #[inline(always)]
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        encoded_query_cmp(self.bytes, other.bytes)
    }
}

impl Hash for QueryRef<'_> {
    #[inline(always)]
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        hash_encoded_query(state, self.bytes);
    }
}

/// Returned by [`QueryRef::deserialize`] / [`Query::deserialize`] when the
/// query string cannot be converted into the target type — type mismatch,
/// missing required field, malformed encoding, or an escaped value being
/// fed into a non-owning `&str` field.
#[derive(Debug)]
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub struct QueryDeserializeError(serde_html_form::de::Error);

#[cfg(feature = "std")]
impl fmt::Display for QueryDeserializeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "failed to deserialize URI query: {}", self.0)
    }
}

#[cfg(feature = "std")]
impl core::error::Error for QueryDeserializeError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        Some(&self.0)
    }
}

/// One owned `name[=value]` pair, cheap to clone. Produced by
/// [`QueryMut::pop`](super::QueryMut::pop) and
/// [`QueryMut::drain`](super::QueryMut::drain) — popping a pair off a
/// query doesn't copy the byte content (the buffer is refcount-shared
/// with the source).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct QueryPair {
    raw: Bytes,
    /// Byte offset of `=` within `raw`, or `None` for a bare key.
    ///
    /// `u32` because a single key=value pair built via the mutation API
    /// can exceed `MAX_URI_LEN` (the parser-level 16-bit cap applies
    /// only to parsed inputs, not to caller-built queries). `u16` would
    /// silently truncate the offset for pairs whose key crosses 65535
    /// bytes — pinned by the `eq_offset_*` and `huge_pair_*` regression
    /// tests in `parser::tests::query_pairs`.
    eq_at: Option<u32>,
}

impl QueryPair {
    /// Construct from raw `name[=value]` bytes (no leading `&`).
    /// Finds the first `=` once at construction; subsequent accessors
    /// slice without rescanning.
    #[inline]
    #[must_use]
    pub(crate) fn from_raw(raw: Bytes) -> Self {
        let eq_at = memchr::memchr(b'=', &raw).map(|i| i as u32);
        Self { raw, eq_at }
    }

    /// Borrowed view. All inspection methods on `QueryPair` route
    /// through this — single source of truth for the slicing /
    /// decoding logic.
    #[must_use]
    #[inline]
    pub fn view(&self) -> QueryPairRef<'_> {
        QueryPairRef {
            raw: &self.raw,
            eq_at: self.eq_at,
        }
    }

    /// Percent-encoded name.
    #[must_use]
    #[inline]
    pub fn name_encoded(&self) -> Cow<'_, str> {
        self.view().name_encoded()
    }

    /// Name with form-urlencoded decoding: `+` → space, `%XX` → byte.
    #[must_use]
    #[inline]
    pub fn name_decoded(&self) -> Cow<'_, str> {
        self.view().name_decoded()
    }

    /// Percent-encoded value, or `None` for a bare key.
    #[must_use]
    #[inline]
    pub fn value_encoded(&self) -> Option<Cow<'_, str>> {
        self.view().value_encoded()
    }

    /// Value with form-urlencoded decoding (`+` → space, `%XX` → byte),
    /// or `None` for a bare key.
    #[must_use]
    #[inline]
    pub fn value_decoded(&self) -> Option<Cow<'_, str>> {
        self.view().value_decoded()
    }

    /// `true` if the pair has an `=` separator. `?foo=` → `true`; `?foo` → `false`.
    #[must_use]
    #[inline]
    pub fn has_value(&self) -> bool {
        self.view().has_value()
    }
}

impl core::fmt::Display for QueryPair {
    #[inline(always)]
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Display::fmt(&self.view(), f)
    }
}

/// Borrowed `name[=value]` pair view. Yielded by
/// [`QueryRef::pairs`] / [`Query::pairs`].
///
/// Decoded views apply the form-urlencoded convention (`+` → space,
/// `%XX` → byte) — distinct from [`QueryRef::as_decoded_str`] which only
/// percent-decodes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QueryPairRef<'a> {
    raw: &'a [u8],
    /// Byte offset of `=` within `raw`, or `None` for a bare key.
    ///
    /// `u32` because a single key=value pair built via the mutation API
    /// can exceed `MAX_URI_LEN` (the parser-level 16-bit cap applies
    /// only to parsed inputs, not to caller-built queries). `u16` would
    /// silently truncate the offset for pairs whose key crosses 65535
    /// bytes — pinned by the `eq_offset_*` and `huge_pair_*` regression
    /// tests in `parser::tests::query_pairs`.
    eq_at: Option<u32>,
}

impl<'a> QueryPairRef<'a> {
    /// Construct from raw `name[=value]` bytes (no leading `&`).
    #[inline]
    #[must_use]
    pub(crate) fn from_raw(raw: &'a [u8]) -> Self {
        let eq_at = memchr::memchr(b'=', raw).map(|i| i as u32);
        Self { raw, eq_at }
    }

    /// Percent-encoded name.
    #[must_use]
    pub fn name_encoded(self) -> Cow<'a, str> {
        encoded_pair_component(self.name_bytes())
    }

    /// Name with form-urlencoded decoding: `+` → space, `%XX` → byte.
    /// `Cow::Borrowed` when neither escape is present.
    #[must_use]
    pub fn name_decoded(self) -> Cow<'a, str> {
        form_decode(self.name_bytes())
    }

    /// Percent-encoded value, or `None` for a bare key.
    #[must_use]
    pub fn value_encoded(self) -> Option<Cow<'a, str>> {
        self.value_bytes().map(encoded_pair_component)
    }

    /// Value with form-urlencoded decoding (`+` → space, `%XX` → byte),
    /// or `None` for a bare key.
    #[must_use]
    pub fn value_decoded(self) -> Option<Cow<'a, str>> {
        self.value_bytes().map(form_decode)
    }

    /// `true` if the pair has an `=` separator. `?foo=` → `true`; `?foo` → `false`.
    #[must_use]
    pub fn has_value(self) -> bool {
        self.eq_at.is_some()
    }

    /// Allocate an owned [`QueryPair`] copying the raw bytes.
    ///
    /// Named `into_owned` (matching the [`crate::std::borrow::Cow::into_owned`] precedent)
    /// rather than `to_owned` to avoid shadowing the std `ToOwned`
    /// trait method.
    #[must_use]
    pub fn into_owned(self) -> QueryPair {
        QueryPair {
            raw: Bytes::copy_from_slice(self.raw),
            eq_at: self.eq_at,
        }
    }

    /// Raw `name[=value]` bytes of the pair (no leading `&`).
    #[inline(always)]
    pub(super) fn raw_bytes(self) -> &'a [u8] {
        self.raw
    }

    #[inline(always)]
    pub(super) fn name_bytes(self) -> &'a [u8] {
        match self.eq_at {
            Some(i) => &self.raw[..i as usize],
            None => self.raw,
        }
    }

    #[inline(always)]
    pub(super) fn value_bytes(self) -> Option<&'a [u8]> {
        self.eq_at.map(|i| &self.raw[i as usize + 1..])
    }
}

impl core::fmt::Display for QueryPairRef<'_> {
    #[inline(always)]
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write_encoded_query(f, self.raw)
    }
}

/// Iterator over the `name[=value]` pairs of a URI query string. Created by
/// [`QueryRef::pairs`] / [`Query::pairs`].
#[derive(Debug, Clone)]
pub struct QueryPairs<'a> {
    /// Bytes that haven't been processed yet, excluding any `&` that
    /// triggered the previous yield.
    remaining: &'a [u8],
    /// `true` once all fragments have been consumed.
    exhausted: bool,
}

impl<'a> QueryPairs<'a> {
    #[inline]
    fn new(bytes: &'a [u8]) -> Self {
        Self {
            remaining: bytes,
            exhausted: bytes.is_empty(),
        }
    }
}

impl<'a> Iterator for QueryPairs<'a> {
    type Item = QueryPairRef<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if self.exhausted {
                return None;
            }
            // Pull off the next `&`-delimited fragment.
            // `memchr` for SIMD-accelerated boundary search.
            let fragment = if let Some(i) = memchr::memchr(b'&', self.remaining) {
                let frag = &self.remaining[..i];
                self.remaining = &self.remaining[i + 1..];
                frag
            } else {
                let frag = self.remaining;
                self.remaining = &[];
                self.exhausted = true;
                frag
            };

            if fragment.is_empty() {
                // Empty fragment (`&&`, leading `&`, trailing `&`) — skip,
                // matching WHATWG URLSearchParams / serde_html_form behaviour.
                continue;
            }

            return Some(QueryPairRef::from_raw(fragment));
        }
    }
}

impl core::iter::FusedIterator for QueryPairs<'_> {}

/// Iterator over the form-decoded values of every pair with a fixed name.
/// Created by [`QueryRef::values`] / [`Query::values`].
///
/// A bare key (`?foo`) yields `""` — see [`QueryRef::first_value`] for the
/// matching rules.
#[derive(Debug, Clone)]
pub struct QueryValues<'a> {
    pairs: QueryPairs<'a>,
    /// Form-decoded name pattern, decoded once at construction.
    name: Vec<u8>,
}

impl<'a> Iterator for QueryValues<'a> {
    type Item = Cow<'a, str>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let pair = self.pairs.next()?;
            if *form_decode_bytes(pair.name_bytes()) == *self.name {
                return Some(pair.value_decoded().unwrap_or(Cow::Borrowed("")));
            }
        }
    }
}

impl core::iter::FusedIterator for QueryValues<'_> {}

/// Form-urlencoded decode to bytes: `+` → ` `, `%XX` → byte.
///
/// Returns `Cow::Borrowed` when the input contains neither `+` nor `%`.
/// Invalid `%XX` (non-hex or truncated) passes through as a literal `%`.
///
/// Name matching compares these decoded BYTES, not a lossy-UTF-8
/// rendering — lossy decoding collapses every distinct invalid-UTF-8
/// byte to U+FFFD, which would make unrelated names compare equal
/// (mirrors `path::segment_eq`'s rationale).
pub(super) fn form_decode_bytes(input: &[u8]) -> Cow<'_, [u8]> {
    // Fast path: nothing to decode.
    let Some(start) = memchr::memchr2(b'+', b'%', input) else {
        return Cow::Borrowed(input);
    };

    let mut out = Vec::with_capacity(input.len());
    out.extend_from_slice(&input[..start]);

    let mut i = start;
    while i < input.len() {
        match input[i] {
            b'+' => {
                out.push(b' ');
                i += 1;
            }
            b'%' if i + 2 < input.len() => {
                if let Some(byte) = rama_utils::hex::decode_pair(input[i + 1], input[i + 2]) {
                    out.push(byte);
                    i += 3;
                } else {
                    // Malformed `%XX` — emit the `%` literally and move on.
                    out.push(b'%');
                    i += 1;
                }
            }
            b => {
                // Catches trailing `%` with < 2 chars remaining, and every
                // ordinary byte.
                out.push(b);
                i += 1;
            }
        }
    }

    Cow::Owned(out)
}

/// Form-urlencoded decode: `+` → ` `, `%XX` → byte.
///
/// String view over [`form_decode_bytes`]. Invalid UTF-8 in the decoded
/// bytes falls back to U+FFFD.
fn form_decode(input: &[u8]) -> Cow<'_, str> {
    match form_decode_bytes(input) {
        // Safety: parser invariant — query bytes are valid UTF-8, and the
        // borrowed path means no `%XX` / `+` was decoded.
        Cow::Borrowed(bytes) => Cow::Borrowed(unsafe { core::str::from_utf8_unchecked(bytes) }),
        // Happy path: decoded bytes are valid UTF-8 — promote `Vec<u8>` →
        // `String` without re-allocating. Otherwise fall back to lossy.
        Cow::Owned(out) => match String::from_utf8(out) {
            Ok(s) => Cow::Owned(s),
            Err(e) => Cow::Owned(String::from_utf8_lossy(e.as_bytes()).into_owned()),
        },
    }
}

impl fmt::Display for Query {
    #[inline(always)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.view(), f)
    }
}

impl fmt::Display for QueryRef<'_> {
    /// Renders the encoded query bytes (no leading `?`).
    #[inline(always)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_encoded_query(f, self.bytes)
    }
}

impl core::str::FromStr for Query {
    type Err = core::convert::Infallible;

    /// Encode arbitrary input as a [`Query`] — bytes outside
    /// `pchar ∪ {'/', '?'}` get percent-encoded. Infallible because
    /// every input round-trips after encoding; `str::parse` users with
    /// `?`-ladder code can still use this through the `Result` shape.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self {
            bytes: super::encode::encode_query(s),
        })
    }
}

#[cfg(test)]
mod internal_tests {
    //! Direct tests for the private `form_decode` helper. Behavioural
    //! coverage via the public `QueryRef::pairs()` API lives in
    //! `super::super::parser::tests::query_pairs`; these pin the
    //! function-level invariants that don't surface through the iterator.

    use crate::std::borrow::Cow;

    use super::form_decode;

    // ---- form_decode ------------------------------------------------

    #[test]
    fn form_decode_empty_borrows() {
        let out = form_decode(b"");
        assert!(matches!(out, Cow::Borrowed(_)));
        assert_eq!(&*out, "");
    }

    /// Verify the borrowed path is genuinely zero-copy — the returned
    /// `&str` must point at the same address as the input bytes.
    #[test]
    fn form_decode_borrowed_path_is_zero_copy() {
        let input: &[u8] = b"no-escapes-here";
        let out = form_decode(input);
        match out {
            Cow::Borrowed(s) => {
                assert_eq!(s.as_ptr(), input.as_ptr(), "borrowed view re-allocated");
            }
            Cow::Owned(_) => panic!("expected Cow::Borrowed for input without `+` or `%`"),
        }
    }

    /// `%2B` decodes to a literal `+` — the decoder must NOT then
    /// re-interpret that `+` as a space (no double-decoding).
    #[test]
    fn form_decode_pct_2b_is_literal_plus_not_space() {
        assert_eq!(form_decode(b"%2B"), Cow::Borrowed("+"));
        assert_eq!(form_decode(b"a%2Bb"), Cow::Borrowed("a+b"));
    }

    /// `%26` → `&`, `%3D` → `=`. The pair iterator already split on the
    /// raw bytes, so decoded `&`/`=` are inert here.
    #[test]
    fn form_decode_pct_delimiter_bytes() {
        assert_eq!(form_decode(b"%26"), Cow::Borrowed("&"));
        assert_eq!(form_decode(b"%3D"), Cow::Borrowed("="));
        assert_eq!(form_decode(b"a%26b%3Dc"), Cow::Borrowed("a&b=c"));
    }

    /// `%00` produces a null byte in the resulting `String` — Rust
    /// strings tolerate interior NUL.
    #[test]
    fn form_decode_pct_00_null_byte() {
        let out = form_decode(b"a%00b");
        assert_eq!(out.as_bytes(), b"a\x00b");
    }

    /// 3-byte UTF-8: `%E2%82%AC` → `€` (U+20AC).
    #[test]
    fn form_decode_three_byte_utf8() {
        assert_eq!(form_decode(b"%E2%82%AC"), Cow::Borrowed(""));
    }

    /// 4-byte UTF-8: `%F0%9F%98%80` → 😀 (U+1F600).
    #[test]
    fn form_decode_four_byte_utf8() {
        assert_eq!(form_decode(b"%F0%9F%98%80"), Cow::Borrowed("\u{1F600}"));
    }

    /// Truncated multi-byte UTF-8 — lossy decode emits U+FFFD.
    #[test]
    fn form_decode_truncated_utf8_replacement() {
        // `%E2%82` is the first 2 of 3 bytes for `€` — invalid UTF-8.
        let out = form_decode(b"%E2%82");
        assert!(out.contains('\u{FFFD}'), "got {out:?}");
    }

    /// Mixed `+`, `%XX`, and plain bytes in a single input.
    #[test]
    fn form_decode_mixed_input() {
        assert_eq!(
            form_decode(b"hello+world%20%21"),
            Cow::Borrowed("hello world !"),
        );
    }

    /// Long-string sanity check: 4 KB of mixed-escape content decodes
    /// without panicking and produces the expected length.
    #[test]
    fn form_decode_long_string() {
        // Pattern: "a+b%20" repeats; each repeat decodes "a+b%20" (6 bytes)
        // → "a b " (4 bytes).
        const N: usize = 1000;
        let mut input = Vec::with_capacity(6 * N);
        for _ in 0..N {
            input.extend_from_slice(b"a+b%20");
        }
        let out = form_decode(&input);
        assert_eq!(out.len(), 4 * N);
        // Spot-check a couple of windows.
        assert!(out.starts_with("a b a b "));
        assert!(out.ends_with("a b a b "));
    }

    /// Malformed `%XX` sequences (non-hex digits) pass through
    /// literally — including the `%` itself.
    #[test]
    fn form_decode_malformed_pct_literal_passthrough() {
        assert_eq!(form_decode(b"%ZZ"), Cow::Borrowed("%ZZ"));
        assert_eq!(form_decode(b"%G0"), Cow::Borrowed("%G0"));
        assert_eq!(form_decode(b"%-1"), Cow::Borrowed("%-1"));
    }

    /// Trailing `%` with insufficient remaining bytes — literal `%`.
    #[test]
    fn form_decode_trailing_percent_variants() {
        assert_eq!(form_decode(b"%"), Cow::Borrowed("%"));
        assert_eq!(form_decode(b"a%"), Cow::Borrowed("a%"));
        assert_eq!(form_decode(b"a%A"), Cow::Borrowed("a%A"));
    }
}