rama-http-headers 0.3.0

typed http headers for rama
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
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
use std::time::Duration;

use rama_http_types::{HeaderName, HeaderValue};
use rama_utils::collections::NonEmptySmallVec;

use crate::util::{self, IterExt};
use crate::{Error, HeaderDecode, HeaderEncode, TypedHeader};

macro_rules! client_hint {
    (
        #[doc = $ch_doc:literal]
        pub enum ClientHint {
            $(
                #[doc = $doc:literal]
                $name:ident($($str:literal),*),
            )+
        }
    ) => {
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        pub enum ClientHint {
            $(
                #[doc = $doc]
                $name,
            )+
        }

        impl ClientHint {
            #[doc = "Checks if the client hint is low entropy, meaning that it will be send by default."]
            #[must_use] pub fn is_low_entropy(&self) -> bool {
                matches!(self, Self::SaveData | Self::Ua | Self::Mobile | Self::Platform)
            }

            #[inline]
            #[doc = "Attempts to convert a `HeaderName` to a `ClientHint`."]
            pub fn match_header_name(name: &::rama_http_types::HeaderName) -> Option<Self> {
                name.try_into().ok()
            }

            #[doc = "All header-name spellings this client hint answers to, as borrowed `'static` strs: the preferred (`Sec-CH-` prefixed) form first, followed by any legacy bare alias (e.g. `[\"sec-ch-ect\", \"ect\"]`). Allocation-free — the slice is statically promoted."]
            #[must_use] pub fn header_name_strs(&self) -> &'static [&'static str] {
                match self {
                    $(
                        Self::$name => {
                            const NAMES: &[&str] = &[$($str,)+];
                            NAMES
                        },
                    )+
                }
            }

            #[doc = "Return an iterator of all header names for this client hint. Allocation-free."]
            pub fn iter_header_names(&self) -> impl Iterator<Item = ::rama_http_types::HeaderName> {
                self.header_name_strs()
                    .iter()
                    .copied()
                    .map(::rama_http_types::HeaderName::from_static)
            }

            #[doc = "Returns the preferred string representation of the client hint."]
            #[must_use] pub fn as_str(&self) -> &'static str {
                self.header_name_strs()[0]
            }
        }

        rama_utils::macros::error::static_str_error! {
            /// Client Hint Parsing Error
            pub struct ClientHintParsingError;
        }

        impl TryFrom<&str> for ClientHint {
            type Error = ClientHintParsingError;

            fn try_from(name: &str) -> Result<Self, Self::Error> {
                rama_utils::macros::match_ignore_ascii_case_str! {
                    match (name) {
                        $(
                            $($str)|+ => Ok(Self::$name),
                        )+
                        _ => Err(ClientHintParsingError),
                    }
                }
            }
        }

        impl TryFrom<String> for ClientHint {
            type Error = ClientHintParsingError;

            fn try_from(name: String) -> Result<Self, Self::Error> {
                Self::try_from(name.as_str())
            }
        }

        impl TryFrom<::rama_http_types::HeaderName> for ClientHint {
            type Error = ClientHintParsingError;

            fn try_from(name: ::rama_http_types::HeaderName) -> Result<Self, Self::Error> {
                Self::try_from(name.as_str())
            }
        }

        impl TryFrom<&::rama_http_types::HeaderName> for ClientHint {
            type Error = ClientHintParsingError;

            fn try_from(name: &::rama_http_types::HeaderName) -> Result<Self, Self::Error> {
                Self::try_from(name.as_str())
            }
        }

        impl std::str::FromStr for ClientHint {
            type Err = ClientHintParsingError;

            #[inline]
            fn from_str(s: &str) -> Result<Self, Self::Err> {
                Self::try_from(s)
            }
        }

        impl std::fmt::Display for ClientHint {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}", self.as_str())
            }
        }

        impl serde::Serialize for ClientHint {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: serde::Serializer,
            {
                serializer.serialize_str(self.as_str())
            }
        }

        impl<'de> serde::Deserialize<'de> for ClientHint {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                use serde::de::Error;
                let s = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
                Self::try_from(s.as_ref()).map_err(D::Error::custom)
            }
        }

        #[doc = "Returns an iterator over all client hints."]
        pub fn all_client_hints() -> impl Iterator<Item = ClientHint> {
            [
                $(
                    ClientHint::$name,
                )+
            ].into_iter()
        }

        #[doc = "Returns an iterator over all client hint header name strings."]
        pub fn all_client_hint_header_name_strings() -> impl Iterator<Item = &'static str> {
            [
                $(
                    $($str,)+
                )+
            ].into_iter()
        }

        #[doc = "Returns an iterator over all client hint header names."]
        pub fn all_client_hint_header_names() -> impl Iterator<Item = ::rama_http_types::HeaderName> {
            all_client_hint_header_name_strings().map(::rama_http_types::HeaderName::from_static)
        }
    };
}

// NOTE: we are open to contributions to this module,
// e.g. in case you wish typed headers for each or some of these client hint headers,
// we gladly mentor and guide you in the process.

client_hint! {
    #[doc = "Client Hints are a set of HTTP Headers and a JavaScript API that allow web browsers to send detailed information about the client device and browser to web servers. They are designed to be a successor to User-Agent, and provide a standardized way for web servers to optimize content for the client without relying on unreliable user-agent string-based detection or browser fingerprinting techniques."]
    pub enum ClientHint {
        /// Sec-CH-UA represents a user agent's branding and version.
        Ua("sec-ch-ua"),
        /// Sec-CH-UA-Full-Version represents the user agent's full version.
        FullVersion("sec-ch-ua-full-version"),
        /// Sec-CH-UA-Full-Version-List represents the full version for each brand in its brands list.
        FullVersionList("sec-ch-ua-full-version-list"),
        /// Sec-CH-UA-Platform represents the platform on which a given user agent is executing.
        Platform("sec-ch-ua-platform"),
        /// Sec-CH-UA-Platform-Version represents the platform version on which a given user agent is executing.
        PlatformVersion("sec-ch-ua-platform-version"),
        /// Sec-CH-UA-Arch represents the architecture of the platform on which a given user agent is executing.
        Arch("sec-ch-ua-arch"),
        /// Sec-CH-UA-Bitness represents the bitness of the architecture of the platform on which a given user agent is executing.
        Bitness("sec-ch-ua-bitness"),
        /// Sec-CH-UA-WoW64 is used to detect whether or not a user agent binary is running in 32-bit mode on 64-bit Windows.
        Wow64("sec-ch-ua-wow64"),
        /// Sec-CH-UA-Model represents the device on which a given user agent is executing.
        Model("sec-ch-ua-model"),
        /// Sec-CH-UA-Mobile is used to detect whether or not a user agent prefers a «mobile» user experience.
        Mobile("sec-ch-ua-mobile"),
        /// Sec-CH-UA-Form-Factors represents the form-factors of a device, historically represented as a `<deviceCompat>` token in the User-Agent string.
        FormFactor("sec-ch-ua-form-factors"),
        /// Sec-CH-Lang  (or Lang) represents the user's language preference.
        Lang("sec-ch-lang", "lang"),
        /// Sec-CH-Save-Data (or Save-Data) represents the user agent's preference for reduced data usage.
        SaveData("sec-ch-save-data", "save-data"),
        /// Sec-CH-Width gives a server the layout width of the image.
        Width("sec-ch-width"),
        /// Sec-CH-Viewport-Width (or Viewport-Width) is the width of the user's viewport in CSS pixels.
        ViewportWidth("sec-ch-viewport-width", "viewport-width"),
        /// Sec-CH-Viewport-Height represents the user-agent's current viewport height.
        ViewportHeight("sec-ch-viewport-height"),
        /// Sec-CH-DPR (or DPR) reports the ratio of physical pixels to CSS pixels of the user's screen.
        Dpr("sec-ch-dpr", "dpr"),
        /// Sec-CH-Device-Memory (or Device-Memory) reveals the approximate amount of memory the current device has in GiB. Because this information could be used to fingerprint users, the value of Device-Memory is intentionally coarse. Valid values are 0.25, 0.5, 1, 2, 4, and 8.
        DeviceMemory("sec-ch-device-memory", "device-memory"),
        /// Sec-CH-RTT (or RTT) provides the approximate Round Trip Time, in milliseconds, on the application layer. The RTT hint, unlike transport layer RTT, includes server processing time. The value of RTT is rounded to the nearest 25 milliseconds to prevent fingerprinting.
        Rtt("sec-ch-rtt", "rtt"),
        /// Sec-CH-Downlink (or Downlink) expressed in megabits per second (Mbps), reveals the approximate downstream speed of the user's connection. The value is rounded to the nearest multiple of 25 kilobits per second. Because again, fingerprinting.
        Downlink("sec-ch-downlink", "downlink"),
        /// Sec-CH-ECT (or ECT) stands for Effective Connection Type. Its value is one of an enumerated list of connection types, each of which describes a connection within specified ranges of both RTT and Downlink values. Valid values for ECT are 4g, 3g, 2g, and slow-2g.
        Ect("sec-ch-ect", "ect"),
        /// Sec-CH-Prefers-Color-Scheme represents the user's preferred color scheme.
        PrefersColorScheme("sec-ch-prefers-color-scheme"),
        /// Sec-CH-Prefers-Reduced-Motion is used to detect if the user has requested the system minimize the amount of animation or motion it uses.
        PrefersReducedMotion("sec-ch-prefers-reduced-motion"),
        /// Sec-CH-Prefers-Reduced-Transparency is used to detect if the user has requested the system minimize the amount of transparent or translucent layer effects it uses.
        PrefersReducedTransparency("sec-ch-prefers-reduced-transparency"),
        /// Sec-CH-Prefers-Contrast is used to detect if the user has requested that the web content is presented with a higher (or lower) contrast.
        PrefersContrast("sec-ch-prefers-contrast"),
        /// Sec-CH-Forced-Colors is used to detect if the user agent has enabled a forced colors mode where it enforces a user-chosen limited color palette on the page.
        ForcedColors("sec-ch-forced-colors"),
    }
}

// ---------------------------------------------------------------------------
// Client-hint negotiation headers: a server advertises which [`ClientHint`]s
// it wants (`Accept-CH`) and which of those are critical (`Critical-CH`).
//
// Both are flat comma-separated lists of client-hint header names. Each hint is
// advertised under *every* spelling it answers to — the preferred `Sec-CH-`
// form and any legacy bare alias (e.g. both `sec-ch-ect` and `ect`) — so a user
// agent that recognises only one form still sees its slot. Several deployed
// hints (the Network Information set `rtt`/`downlink`/`ect`, `device-memory`,
// `dpr`, `viewport-width`, `save-data`) are only honoured under the bare name,
// so canonical-only advertisement would silently fail to elicit them. Decoding
// accepts any known spelling and normalises it back to the [`ClientHint`].
// ---------------------------------------------------------------------------

/// Encode a hint set as a `", "`-joined list of every header-name spelling each
/// hint answers to (see [`ClientHint::header_name_strs`]). Allocation-free per
/// item. The names are static ASCII tokens and the set is non-empty, so this
/// only ever returns `None` in the unreachable case of an invalid header value.
fn encode_client_hint_names(hints: &NonEmptySmallVec<16, ClientHint>) -> Option<HeaderValue> {
    let mut buf = Vec::new();
    for name in hints
        .iter()
        .flat_map(|h| h.header_name_strs().iter().copied())
    {
        if !buf.is_empty() {
            buf.extend_from_slice(b", ");
        }
        buf.extend_from_slice(name.as_bytes());
    }
    HeaderValue::from_bytes(&buf).ok()
}

macro_rules! client_hint_advert_header {
    (
        #[header(name = $name:ident)]
        $(#[$m:meta])*
        $type:ident
    ) => {
        $(#[$m])*
        #[derive(Clone, Debug, PartialEq, Eq)]
        pub struct $type(pub NonEmptySmallVec<16, ClientHint>);

        impl $type {
            #[doc = concat!("Create a `", stringify!($type), "` advertising a single [`ClientHint`].")]
            #[must_use]
            pub fn new(hint: ClientHint) -> Self {
                Self(NonEmptySmallVec::new(hint))
            }
        }

        impl TypedHeader for $type {
            fn name() -> &'static HeaderName {
                &rama_http_types::header::$name
            }
        }

        impl HeaderDecode for $type {
            fn decode<'i, I>(values: &mut I) -> Result<Self, Error>
            where
                I: Iterator<Item = &'i HeaderValue>,
            {
                util::try_decode_flat_csv_header_values_as_non_empty_smallvec(
                    values,
                    util::FlatCsvSeparator::Comma,
                )
                .map(Self)
                .map_err(|err| {
                    rama_core::telemetry::tracing::debug!(
                        concat!("failed to decode ", stringify!($name), ": {}"),
                        err,
                    );
                    Error::invalid()
                })
            }
        }

        impl HeaderEncode for $type {
            fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) {
                match encode_client_hint_names(&self.0) {
                    Some(value) => values.extend(std::iter::once(value)),
                    None => rama_core::telemetry::tracing::debug!(
                        concat!("failed to encode ", stringify!($name), " client-hint names")
                    ),
                }
            }
        }
    };
}

client_hint_advert_header! {
    #[header(name = ACCEPT_CH)]
    /// `Accept-CH` header, defined in [RFC8942](https://datatracker.ietf.org/doc/html/rfc8942#section-3.1).
    ///
    /// Sent by a server to advertise the set of [`ClientHint`]s it would like
    /// the user agent to send on subsequent requests to the same origin. Each
    /// hint is advertised under *every* spelling it answers to (its preferred
    /// `Sec-CH-` form plus any legacy bare alias); entries that do not map to a
    /// known [`ClientHint`] are rejected on decode.
    ///
    /// # ABNF
    ///
    /// ```text
    /// Accept-CH = #client-hint-name
    /// ```
    ///
    /// # Example
    ///
    /// ```
    /// use rama_utils::collections::non_empty_smallvec;
    /// use rama_http_headers::{AcceptCh, ClientHint};
    ///
    /// let accept_ch = AcceptCh(
    ///     non_empty_smallvec![ClientHint::Ua, ClientHint::Platform, ClientHint::Mobile; 16],
    /// );
    /// ```
    AcceptCh
}

client_hint_advert_header! {
    #[header(name = CRITICAL_CH)]
    /// `Critical-CH` header, defined by the
    /// [Client Hints Infrastructure](https://wicg.github.io/client-hints-infrastructure/#critical-ch).
    ///
    /// Sent alongside [`AcceptCh`] to mark a subset of the advertised
    /// [`ClientHint`]s as *critical*: if the original request was not sent with
    /// these hints, a conforming user agent retries the request before handing
    /// the response to the page. Same wire format as `Accept-CH` (each hint
    /// under every spelling it answers to).
    ///
    /// # ABNF
    ///
    /// ```text
    /// Critical-CH = #client-hint-name
    /// ```
    ///
    /// # Example
    ///
    /// ```
    /// use rama_utils::collections::non_empty_smallvec;
    /// use rama_http_headers::{ClientHint, CriticalCh};
    ///
    /// let critical_ch = CriticalCh(
    ///     non_empty_smallvec![ClientHint::Ua, ClientHint::Platform; 16],
    /// );
    /// ```
    CriticalCh
}

// ---------------------------------------------------------------------------
// Typed value parsers for a subset of the client hints above.
//
// Each parses a single header value with a strict spec, following the same
// typed-header shape rama uses for `Cache-Control`, `Age`, etc. The canonical
// header name matches the preferred (`Sec-CH-` prefixed) form of the matching
// [`ClientHint`] variant, sourced from `rama_http_types::header`.
// ---------------------------------------------------------------------------

/// `Save-Data` client hint: the user agent's preference for reduced data usage.
///
/// Defined by the [Save Data API](https://wicg.github.io/savedata/). The header
/// is sent with the value `on` when the user has opted in to data savings; the
/// canonical "off" state is the *absence* of the header, though an explicit
/// `off` is also accepted on decode (both matched ASCII case-insensitively).
///
/// Corresponds to [`ClientHint::SaveData`]; encoded as `Sec-CH-Save-Data`.
///
/// # Example
///
/// ```
/// use rama_http_headers::SaveData;
///
/// let save_data = SaveData::on();
/// assert!(save_data.is_on());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SaveData(bool);

impl SaveData {
    /// The [`ClientHint`] this typed value parser corresponds to.
    pub const HINT: ClientHint = ClientHint::SaveData;

    /// Create a [`SaveData`] hint from a boolean preference.
    #[must_use]
    pub const fn new(enabled: bool) -> Self {
        Self(enabled)
    }

    /// Create a [`SaveData`] hint requesting reduced data usage (`on`).
    #[must_use]
    pub const fn on() -> Self {
        Self(true)
    }

    /// Create a [`SaveData`] hint with data savings disabled (`off`).
    #[must_use]
    pub const fn off() -> Self {
        Self(false)
    }

    /// Returns `true` if reduced data usage is requested.
    #[must_use]
    pub const fn is_on(self) -> bool {
        self.0
    }
}

impl From<bool> for SaveData {
    fn from(enabled: bool) -> Self {
        Self(enabled)
    }
}

impl From<SaveData> for bool {
    fn from(value: SaveData) -> Self {
        value.0
    }
}

impl TypedHeader for SaveData {
    fn name() -> &'static HeaderName {
        &rama_http_types::header::SEC_CH_SAVE_DATA
    }
}

impl HeaderDecode for SaveData {
    fn decode<'i, I: Iterator<Item = &'i HeaderValue>>(values: &mut I) -> Result<Self, Error> {
        let value = values
            .just_one()
            .and_then(|value| value.to_str().ok())
            .ok_or_else(Error::invalid)?;
        if value.eq_ignore_ascii_case("on") {
            Ok(Self(true))
        } else if value.eq_ignore_ascii_case("off") {
            Ok(Self(false))
        } else {
            Err(Error::invalid())
        }
    }
}

impl HeaderEncode for SaveData {
    fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) {
        let value = if self.0 {
            HeaderValue::from_static("on")
        } else {
            HeaderValue::from_static("off")
        };
        values.extend(std::iter::once(value));
    }
}

/// `Sec-CH-ECT` (Effective Connection Type) client hint.
///
/// Describes the measured network performance as one of an enumerated set of
/// connection profiles, each covering a range of [`Rtt`] and [`Downlink`]
/// values. See the
/// [Network Information API](https://wicg.github.io/netinfo/#dom-effectiveconnectiontype).
///
/// Corresponds to [`ClientHint::Ect`]; encoded as `Sec-CH-ECT`.
///
/// # Example
///
/// ```
/// use rama_http_headers::Ect;
///
/// assert_eq!(Ect::Type4g.as_str(), "4g");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Ect {
    /// `slow-2g`
    Slow2g,
    /// `2g`
    Type2g,
    /// `3g`
    Type3g,
    /// `4g`
    Type4g,
}

impl Ect {
    /// The [`ClientHint`] this typed value parser corresponds to.
    pub const HINT: ClientHint = ClientHint::Ect;

    /// Returns the canonical wire representation of this connection type.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Slow2g => "slow-2g",
            Self::Type2g => "2g",
            Self::Type3g => "3g",
            Self::Type4g => "4g",
        }
    }
}

impl std::fmt::Display for Ect {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl TypedHeader for Ect {
    fn name() -> &'static HeaderName {
        &rama_http_types::header::SEC_CH_ECT
    }
}

impl HeaderDecode for Ect {
    fn decode<'i, I: Iterator<Item = &'i HeaderValue>>(values: &mut I) -> Result<Self, Error> {
        let value = values
            .just_one()
            .and_then(|value| value.to_str().ok())
            .ok_or_else(Error::invalid)?;
        rama_utils::macros::match_ignore_ascii_case_str! {
            match (value) {
                "slow-2g" => Ok(Self::Slow2g),
                "2g" => Ok(Self::Type2g),
                "3g" => Ok(Self::Type3g),
                "4g" => Ok(Self::Type4g),
                _ => Err(Error::invalid()),
            }
        }
    }
}

impl HeaderEncode for Ect {
    fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) {
        values.extend(std::iter::once(HeaderValue::from_static(self.as_str())));
    }
}

/// `Sec-CH-RTT` client hint: the approximate round-trip time on the application
/// layer, modelled as a [`Duration`].
///
/// Unlike transport-layer RTT this includes server processing time. The value
/// is rounded to the nearest 25 ms to limit fingerprinting. See the
/// [Network Information API](https://wicg.github.io/netinfo/#dom-networkinformation-rtt).
///
/// Corresponds to [`ClientHint::Rtt`]; encoded as `Sec-CH-RTT`.
///
/// # Example
///
/// ```
/// use std::time::Duration;
/// use rama_http_headers::Rtt;
///
/// let rtt = Rtt::from_millis(100);
/// assert_eq!(Duration::from(rtt), Duration::from_millis(100));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Rtt(u64);

impl Rtt {
    /// The [`ClientHint`] this typed value parser corresponds to.
    pub const HINT: ClientHint = ClientHint::Rtt;

    /// Create an [`Rtt`] hint from a round-trip time in milliseconds.
    #[must_use]
    pub const fn from_millis(millis: u64) -> Self {
        Self(millis)
    }

    /// Returns the round-trip time in milliseconds.
    #[must_use]
    pub const fn as_millis(self) -> u64 {
        self.0
    }

    /// Returns the round-trip time as a [`Duration`].
    #[must_use]
    pub const fn as_duration(self) -> Duration {
        Duration::from_millis(self.0)
    }
}

impl From<Rtt> for Duration {
    fn from(rtt: Rtt) -> Self {
        rtt.as_duration()
    }
}

impl TypedHeader for Rtt {
    fn name() -> &'static HeaderName {
        &rama_http_types::header::SEC_CH_RTT
    }
}

impl HeaderDecode for Rtt {
    fn decode<'i, I: Iterator<Item = &'i HeaderValue>>(values: &mut I) -> Result<Self, Error> {
        values
            .just_one()
            .and_then(|value| value.to_str().ok())
            .and_then(|s| s.parse::<u64>().ok())
            .map(Self)
            .ok_or_else(Error::invalid)
    }
}

impl HeaderEncode for Rtt {
    fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) {
        values.extend(std::iter::once(self.0.into()));
    }
}

/// `Sec-CH-Downlink` client hint: the approximate downstream speed of the
/// user's connection, in megabits per second (Mbps).
///
/// The value is rounded to the nearest 25 kbps to limit fingerprinting. See the
/// [Network Information API](https://wicg.github.io/netinfo/#dom-networkinformation-downlink).
///
/// Corresponds to [`ClientHint::Downlink`]; encoded as `Sec-CH-Downlink`.
///
/// # Example
///
/// ```
/// use rama_http_headers::Downlink;
///
/// let downlink = Downlink::new(1.6);
/// assert_eq!(downlink.as_mbps(), 1.6);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Downlink(f64);

impl Downlink {
    /// The [`ClientHint`] this typed value parser corresponds to.
    pub const HINT: ClientHint = ClientHint::Downlink;

    /// Create a [`Downlink`] hint from a speed in megabits per second.
    #[must_use]
    pub const fn new(mbps: f64) -> Self {
        Self(mbps)
    }

    /// Returns the downstream speed in megabits per second.
    #[must_use]
    pub const fn as_mbps(self) -> f64 {
        self.0
    }
}

impl From<Downlink> for f64 {
    fn from(downlink: Downlink) -> Self {
        downlink.0
    }
}

impl TypedHeader for Downlink {
    fn name() -> &'static HeaderName {
        &rama_http_types::header::SEC_CH_DOWNLINK
    }
}

impl HeaderDecode for Downlink {
    fn decode<'i, I: Iterator<Item = &'i HeaderValue>>(values: &mut I) -> Result<Self, Error> {
        values
            .just_one()
            .and_then(|value| value.to_str().ok())
            .and_then(|s| s.parse::<f64>().ok())
            .filter(|mbps| mbps.is_finite() && *mbps >= 0.0)
            .map(Self)
            .ok_or_else(Error::invalid)
    }
}

impl HeaderEncode for Downlink {
    fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) {
        values.extend(std::iter::once(util::fmt(self.0)));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_client_hint_ua_from_str() {
        let hint = ClientHint::try_from("Sec-CH-UA").unwrap();
        assert_eq!(hint, ClientHint::Ua);
    }

    #[test]
    fn test_client_hint_ua_from_str_lowercase() {
        let hint = ClientHint::try_from("sec-ch-ua").unwrap();
        assert_eq!(hint, ClientHint::Ua);
    }

    #[test]
    fn test_client_hint_ua_from_str_uppercase() {
        let hint = ClientHint::try_from("SEC-CH-UA").unwrap();
        assert_eq!(hint, ClientHint::Ua);
    }

    #[test]
    fn test_client_hint_ua_from_str_mixedcase() {
        let hint = ClientHint::try_from("Sec-CH-UA").unwrap();
        assert_eq!(hint, ClientHint::Ua);
    }

    #[test]
    fn test_client_hint_low_entropy() {
        let hints = [
            "Sec-CH-UA",
            "Sec-CH-UA-Mobile",
            "Sec-CH-UA-Platform",
            "Save-Data",
            "Sec-CH-Save-Data",
        ];

        for hint in hints {
            let hint = ClientHint::try_from(hint).expect(hint);
            assert!(hint.is_low_entropy());
        }
    }

    #[test]
    fn test_client_hint_high_entropy() {
        let hints = [
            "Sec-CH-UA-Full-Version",
            "Sec-CH-UA-Full-Version-List",
            "Sec-CH-UA-Platform-Version",
            "Sec-CH-UA-Arch",
            "Sec-CH-UA-Bitness",
            "Sec-CH-UA-WoW64",
            "Sec-CH-UA-Model",
            "Sec-CH-UA-Form-Factors",
            "Sec-CH-Width",
            "Sec-CH-Viewport-Width",
            "Sec-CH-Viewport-Height",
            "Sec-CH-DPR",
            "Sec-CH-Device-Memory",
            "Sec-CH-RTT",
            "Sec-CH-Downlink",
            "Sec-CH-ECT",
            "Sec-CH-Prefers-Color-Scheme",
            "Sec-CH-Prefers-Reduced-Motion",
            "Sec-CH-Prefers-Reduced-Transparency",
            "Sec-CH-Prefers-Contrast",
            "Sec-CH-Forced-Colors",
        ];

        for hint in hints {
            let hint = ClientHint::try_from(hint).expect(hint);
            assert!(!hint.is_low_entropy());
        }
    }

    #[test]
    fn test_all_client_hint_header_name_strings_contains_some_hints() {
        let strings = all_client_hint_header_name_strings().collect::<Vec<_>>();
        assert!(strings.contains(&"sec-ch-ua"), "{strings:?}");
    }

    #[test]
    fn test_all_client_hint_header_names() {
        let names = all_client_hint_header_names().collect::<Vec<_>>();
        let strings = all_client_hint_header_name_strings().collect::<Vec<_>>();
        assert_eq!(names.len(), strings.len());
        for (name, string) in names.iter().zip(strings.iter()) {
            assert_eq!(name.as_str(), *string);
        }
    }

    fn decode<T: HeaderDecode>(values: &[&str]) -> Option<T> {
        use crate::HeaderMapExt;
        let mut map = rama_http_types::HeaderMap::new();
        for value in values {
            map.append(T::name(), value.parse().unwrap());
        }
        map.typed_get()
    }

    fn encode<T: HeaderEncode>(header: T) -> String {
        use crate::HeaderMapExt;
        let mut map = rama_http_types::HeaderMap::new();
        map.typed_insert(header);
        map.get(T::name())
            .expect("header set")
            .to_str()
            .unwrap()
            .to_owned()
    }

    #[test]
    fn test_save_data_decode() {
        assert_eq!(decode::<SaveData>(&["on"]), Some(SaveData::on()));
        assert_eq!(decode::<SaveData>(&["ON"]), Some(SaveData::on()));
        assert_eq!(decode::<SaveData>(&["off"]), Some(SaveData::off()));
        assert!(decode::<SaveData>(&["1"]).is_none());
        assert!(decode::<SaveData>(&[""]).is_none());
        assert!(decode::<SaveData>(&["on", "off"]).is_none());
    }

    #[test]
    fn test_save_data_round_trip() {
        assert_eq!(encode(SaveData::on()), "on");
        assert_eq!(encode(SaveData::off()), "off");
        assert_eq!(
            decode::<SaveData>(&[encode(SaveData::on()).as_str()]),
            Some(SaveData::on())
        );
    }

    #[test]
    fn test_ect_decode() {
        assert_eq!(decode::<Ect>(&["slow-2g"]), Some(Ect::Slow2g));
        assert_eq!(decode::<Ect>(&["2g"]), Some(Ect::Type2g));
        assert_eq!(decode::<Ect>(&["3g"]), Some(Ect::Type3g));
        assert_eq!(decode::<Ect>(&["4g"]), Some(Ect::Type4g));
        assert_eq!(decode::<Ect>(&["SLOW-2G"]), Some(Ect::Slow2g));
        assert!(decode::<Ect>(&["5g"]).is_none());
        assert!(decode::<Ect>(&[""]).is_none());
    }

    #[test]
    fn test_ect_round_trip() {
        for ect in [Ect::Slow2g, Ect::Type2g, Ect::Type3g, Ect::Type4g] {
            assert_eq!(decode::<Ect>(&[encode(ect).as_str()]), Some(ect));
        }
    }

    #[test]
    fn test_rtt_decode() {
        assert_eq!(
            decode::<Rtt>(&["100"]).map(Duration::from),
            Some(Duration::from_millis(100)),
        );
        assert_eq!(decode::<Rtt>(&["0"]), Some(Rtt::from_millis(0)));
        assert!(decode::<Rtt>(&["-25"]).is_none());
        assert!(decode::<Rtt>(&["1.5"]).is_none());
        assert!(decode::<Rtt>(&["fast"]).is_none());
    }

    #[test]
    fn test_rtt_round_trip() {
        assert_eq!(encode(Rtt::from_millis(125)), "125");
        assert_eq!(decode::<Rtt>(&["125"]), Some(Rtt::from_millis(125)));
    }

    #[test]
    fn test_downlink_decode() {
        assert_eq!(decode::<Downlink>(&["1.5"]), Some(Downlink::new(1.5)));
        assert_eq!(decode::<Downlink>(&["100"]), Some(Downlink::new(100.0)));
        assert_eq!(decode::<Downlink>(&["0"]), Some(Downlink::new(0.0)));
        assert!(decode::<Downlink>(&["-1"]).is_none());
        assert!(decode::<Downlink>(&["inf"]).is_none());
        assert!(decode::<Downlink>(&["fast"]).is_none());
    }

    #[test]
    fn test_downlink_round_trip() {
        assert_eq!(encode(Downlink::new(1.5)), "1.5");
        assert_eq!(encode(Downlink::new(100.0)), "100");
        assert_eq!(decode::<Downlink>(&["1.5"]), Some(Downlink::new(1.5)));
    }

    #[test]
    fn test_accept_ch_decode() {
        use rama_utils::collections::non_empty_smallvec;

        assert_eq!(
            decode::<AcceptCh>(&["sec-ch-ua, sec-ch-ua-platform, sec-ch-ua-mobile"]),
            Some(AcceptCh(non_empty_smallvec![
                ClientHint::Ua,
                ClientHint::Platform,
                ClientHint::Mobile; 16
            ])),
        );
        // case-insensitive and legacy aliases both map onto the canonical hint
        assert_eq!(
            decode::<AcceptCh>(&["DPR, save-data"]),
            Some(AcceptCh(non_empty_smallvec![
                ClientHint::Dpr,
                ClientHint::SaveData; 16
            ])),
        );
        // multiple header lines fold into a single list
        assert_eq!(
            decode::<AcceptCh>(&["sec-ch-ua", "sec-ch-ua-platform"]),
            Some(AcceptCh(non_empty_smallvec![
                ClientHint::Ua,
                ClientHint::Platform; 16
            ])),
        );
        // an unknown hint poisons the whole list
        assert!(decode::<AcceptCh>(&["sec-ch-ua, not-a-hint"]).is_none());
        assert!(decode::<AcceptCh>(&[""]).is_none());
        assert!(decode::<AcceptCh>(&[]).is_none());
    }

    #[test]
    fn test_accept_ch_round_trip() {
        use rama_utils::collections::non_empty_smallvec;

        let header = AcceptCh(non_empty_smallvec![
            ClientHint::Ua,
            ClientHint::Platform,
            ClientHint::Mobile; 16
        ]);
        assert_eq!(
            encode(header.clone()),
            "sec-ch-ua, sec-ch-ua-platform, sec-ch-ua-mobile",
        );
        assert_eq!(
            decode::<AcceptCh>(&[encode(header.clone()).as_str()]),
            Some(header)
        );
    }

    #[test]
    fn test_critical_ch_round_trip() {
        use rama_utils::collections::non_empty_smallvec;

        let header = CriticalCh(non_empty_smallvec![ClientHint::Ua, ClientHint::Platform; 16]);
        assert_eq!(encode(header.clone()), "sec-ch-ua, sec-ch-ua-platform");
        assert_eq!(
            decode::<CriticalCh>(&[encode(header.clone()).as_str()]),
            Some(header),
        );
    }

    #[test]
    fn test_header_name_strs() {
        // dual-name hints expose the Sec-CH-* form first, then the bare alias
        assert_eq!(ClientHint::Ect.header_name_strs(), &["sec-ch-ect", "ect"]);
        assert_eq!(
            ClientHint::SaveData.header_name_strs(),
            &["sec-ch-save-data", "save-data"]
        );
        // single-name hints expose just the one
        assert_eq!(ClientHint::Ua.header_name_strs(), &["sec-ch-ua"]);
        // `as_str` is always the first (preferred) spelling
        for hint in all_client_hints() {
            assert_eq!(hint.as_str(), hint.header_name_strs()[0]);
            // `iter_header_names` agrees with the str slice
            let names: Vec<_> = hint
                .iter_header_names()
                .map(|n| n.as_str().to_owned())
                .collect();
            assert_eq!(names, hint.header_name_strs());
        }
    }

    #[test]
    fn test_accept_ch_emits_all_aliases() {
        use rama_utils::collections::non_empty_smallvec;

        // every dual-name hint is advertised under BOTH spellings, so a UA that
        // only honours the legacy bare name (e.g. Chrome for the network hints)
        // still sees its slot.
        let header = AcceptCh(non_empty_smallvec![
            ClientHint::SaveData,
            ClientHint::Ect,
            ClientHint::Rtt,
            ClientHint::Downlink; 16
        ]);
        assert_eq!(
            encode(header),
            "sec-ch-save-data, save-data, sec-ch-ect, ect, \
             sec-ch-rtt, rtt, sec-ch-downlink, downlink",
        );
        // and decoding any spelling round-trips back to the hint set
        assert_eq!(
            decode::<AcceptCh>(&["save-data, ect, rtt, downlink"]),
            Some(AcceptCh(non_empty_smallvec![
                ClientHint::SaveData,
                ClientHint::Ect,
                ClientHint::Rtt,
                ClientHint::Downlink; 16
            ])),
        );
    }

    #[test]
    fn test_critical_ch_emits_all_aliases() {
        let header = CriticalCh::new(ClientHint::SaveData);
        assert_eq!(encode(header), "sec-ch-save-data, save-data");
    }

    #[test]
    fn test_typed_value_parsers_match_their_client_hint() {
        assert_eq!(SaveData::HINT, ClientHint::SaveData);
        assert_eq!(Ect::HINT, ClientHint::Ect);
        assert_eq!(Rtt::HINT, ClientHint::Rtt);
        assert_eq!(Downlink::HINT, ClientHint::Downlink);

        // the typed header name must agree with the hint's preferred name
        assert_eq!(SaveData::name().as_str(), SaveData::HINT.as_str());
        assert_eq!(Ect::name().as_str(), Ect::HINT.as_str());
        assert_eq!(Rtt::name().as_str(), Rtt::HINT.as_str());
        assert_eq!(Downlink::name().as_str(), Downlink::HINT.as_str());
    }
}