tinc/private/
well_known.rs

1use core::fmt;
2use std::collections::{BTreeMap, HashMap};
3use std::marker::PhantomData;
4use std::mem::ManuallyDrop;
5
6use base64::Engine;
7use serde::ser::{SerializeMap, SerializeSeq};
8use serde::{Deserialize, Serialize};
9
10use super::{DeserializeContent, DeserializeHelper, Expected, Tracker, TrackerDeserializer, TrackerFor};
11
12pub struct WellKnownTracker<T>(PhantomData<T>);
13
14impl<T> std::fmt::Debug for WellKnownTracker<T> {
15    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16        write!(f, "WellKnownTracker<{}>", std::any::type_name::<T>())
17    }
18}
19
20impl<T: Expected> Expected for WellKnownTracker<T> {
21    fn expecting(formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
22        T::expecting(formatter)
23    }
24}
25
26impl<T> Default for WellKnownTracker<T> {
27    fn default() -> Self {
28        Self(PhantomData)
29    }
30}
31
32impl<T: Default + Expected> Tracker for WellKnownTracker<T> {
33    type Target = T;
34
35    fn allow_duplicates(&self) -> bool {
36        false
37    }
38}
39
40impl TrackerFor for prost_types::Struct {
41    type Tracker = WellKnownTracker<prost_types::Struct>;
42}
43
44impl Expected for prost_types::Struct {
45    fn expecting(formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
46        write!(formatter, "struct")
47    }
48}
49
50impl TrackerFor for prost_types::ListValue {
51    type Tracker = WellKnownTracker<prost_types::ListValue>;
52}
53
54impl Expected for prost_types::ListValue {
55    fn expecting(formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
56        write!(formatter, "list")
57    }
58}
59
60impl TrackerFor for prost_types::Timestamp {
61    type Tracker = WellKnownTracker<prost_types::Timestamp>;
62}
63
64impl Expected for prost_types::Timestamp {
65    fn expecting(formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
66        write!(formatter, "timestamp")
67    }
68}
69
70impl TrackerFor for prost_types::Duration {
71    type Tracker = WellKnownTracker<prost_types::Duration>;
72}
73
74impl Expected for prost_types::Duration {
75    fn expecting(formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
76        write!(formatter, "duration")
77    }
78}
79
80impl TrackerFor for prost_types::Value {
81    type Tracker = WellKnownTracker<prost_types::Value>;
82}
83
84impl Expected for prost_types::Value {
85    fn expecting(formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
86        write!(formatter, "value")
87    }
88}
89
90impl TrackerFor for () {
91    type Tracker = WellKnownTracker<()>;
92}
93
94impl Expected for () {
95    fn expecting(formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
96        write!(formatter, "empty object")
97    }
98}
99
100impl<'de, T> serde::de::DeserializeSeed<'de> for DeserializeHelper<'_, WellKnownTracker<T>>
101where
102    T: WellKnownAlias + Default + Expected,
103    T::Helper: serde::Deserialize<'de>,
104{
105    type Value = ();
106
107    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
108    where
109        D: serde::Deserializer<'de>,
110    {
111        let value: T::Helper = serde::Deserialize::deserialize(deserializer)?;
112        *self.value = T::reverse_cast(value);
113        Ok(())
114    }
115}
116
117impl<'de, T> TrackerDeserializer<'de> for WellKnownTracker<T>
118where
119    T: WellKnownAlias + Default + Expected,
120    T::Helper: serde::Deserialize<'de>,
121{
122    fn deserialize<D>(&mut self, value: &mut Self::Target, deserializer: D) -> Result<(), D::Error>
123    where
124        D: DeserializeContent<'de>,
125    {
126        deserializer.deserialize_seed(DeserializeHelper { tracker: self, value })
127    }
128}
129
130#[repr(transparent)]
131pub struct List(pub prost_types::ListValue);
132
133impl From<prost_types::ListValue> for List {
134    fn from(value: prost_types::ListValue) -> Self {
135        Self(value)
136    }
137}
138
139impl From<List> for prost_types::ListValue {
140    fn from(value: List) -> Self {
141        value.0
142    }
143}
144
145#[repr(transparent)]
146pub struct Struct(pub prost_types::Struct);
147
148impl From<prost_types::Struct> for Struct {
149    fn from(value: prost_types::Struct) -> Self {
150        Self(value)
151    }
152}
153
154impl From<Struct> for prost_types::Struct {
155    fn from(value: Struct) -> Self {
156        value.0
157    }
158}
159
160#[repr(transparent)]
161pub struct Value(pub prost_types::Value);
162
163impl From<prost_types::Value> for Value {
164    fn from(value: prost_types::Value) -> Self {
165        Self(value)
166    }
167}
168
169#[repr(transparent)]
170pub struct Timestamp(pub prost_types::Timestamp);
171
172impl From<prost_types::Timestamp> for Timestamp {
173    fn from(value: prost_types::Timestamp) -> Self {
174        Self(value)
175    }
176}
177
178#[repr(transparent)]
179pub struct Duration(pub prost_types::Duration);
180
181impl From<prost_types::Duration> for Duration {
182    fn from(value: prost_types::Duration) -> Self {
183        Self(value)
184    }
185}
186
187#[repr(transparent)]
188pub struct Empty(pub ());
189
190impl From<()> for Empty {
191    fn from(value: ()) -> Self {
192        Self(value)
193    }
194}
195
196impl From<Empty> for () {
197    fn from(value: Empty) -> Self {
198        value.0
199    }
200}
201
202impl<'de> serde::Deserialize<'de> for List {
203    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
204    where
205        D: serde::Deserializer<'de>,
206    {
207        struct Visitor;
208
209        impl<'de> serde::de::Visitor<'de> for Visitor {
210            type Value = List;
211
212            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
213                formatter.write_str("a list")
214            }
215
216            fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
217            where
218                V: serde::de::SeqAccess<'de>,
219            {
220                let mut values = Vec::new();
221
222                while let Some(value) = visitor.next_element::<Value>()? {
223                    values.push(value.0);
224                }
225
226                Ok(List(prost_types::ListValue { values }))
227            }
228        }
229
230        deserializer.deserialize_any(Visitor)
231    }
232}
233
234impl serde::Serialize for List {
235    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
236    where
237        S: serde::Serializer,
238    {
239        let mut seq = serializer.serialize_seq(Some(self.0.values.len()))?;
240
241        for value in self.0.values.iter() {
242            seq.serialize_element(WellKnownAlias::cast_ref(value))?;
243        }
244
245        seq.end()
246    }
247}
248
249impl<'de> serde::Deserialize<'de> for Struct {
250    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
251    where
252        D: serde::Deserializer<'de>,
253    {
254        struct Visitor;
255
256        impl<'de> serde::de::Visitor<'de> for Visitor {
257            type Value = Struct;
258
259            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
260                formatter.write_str("a struct")
261            }
262
263            fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
264            where
265                V: serde::de::MapAccess<'de>,
266            {
267                let mut fields = BTreeMap::new();
268
269                while let Some((key, value)) = visitor.next_entry::<String, Value>()? {
270                    fields.insert(key, value.0);
271                }
272
273                Ok(Struct(prost_types::Struct { fields }))
274            }
275        }
276
277        deserializer.deserialize_map(Visitor)
278    }
279}
280
281impl serde::Serialize for Struct {
282    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
283    where
284        S: serde::Serializer,
285    {
286        let mut map = serializer.serialize_map(Some(self.0.fields.len()))?;
287
288        for (key, value) in self.0.fields.iter() {
289            map.serialize_key(key)?;
290            map.serialize_value(WellKnownAlias::cast_ref(value))?;
291        }
292
293        map.end()
294    }
295}
296
297impl<'de> serde::Deserialize<'de> for Value {
298    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
299    where
300        D: serde::Deserializer<'de>,
301    {
302        struct Visitor;
303
304        macro_rules! visit_number {
305            ($visit_fn:ident, $ty:ty) => {
306                fn $visit_fn<E>(self, v: $ty) -> Result<Self::Value, E>
307                where
308                    E: serde::de::Error,
309                {
310                    Ok(Value(prost_types::Value {
311                        kind: Some(prost_types::value::Kind::NumberValue(v as f64)),
312                    }))
313                }
314            };
315        }
316
317        impl<'de> serde::de::Visitor<'de> for Visitor {
318            type Value = Value;
319
320            visit_number!(visit_f32, f32);
321
322            visit_number!(visit_f64, f64);
323
324            visit_number!(visit_i8, i8);
325
326            visit_number!(visit_i16, i16);
327
328            visit_number!(visit_i32, i32);
329
330            visit_number!(visit_i64, i64);
331
332            visit_number!(visit_u8, u8);
333
334            visit_number!(visit_u16, u16);
335
336            visit_number!(visit_u32, u32);
337
338            visit_number!(visit_u64, u64);
339
340            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
341                formatter.write_str("a value")
342            }
343
344            fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
345            where
346                E: serde::de::Error,
347            {
348                Ok(Value(prost_types::Value {
349                    kind: Some(prost_types::value::Kind::BoolValue(v)),
350                }))
351            }
352
353            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
354            where
355                E: serde::de::Error,
356            {
357                Ok(Value(prost_types::Value {
358                    kind: Some(prost_types::value::Kind::StringValue(v)),
359                }))
360            }
361
362            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
363            where
364                E: serde::de::Error,
365            {
366                self.visit_string(v.to_string())
367            }
368
369            fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
370            where
371                E: serde::de::Error,
372            {
373                self.visit_str(v)
374            }
375
376            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
377            where
378                A: serde::de::MapAccess<'de>,
379            {
380                let Struct(value) = Struct::deserialize(serde::de::value::MapAccessDeserializer::new(map))?;
381
382                Ok(Value(prost_types::Value {
383                    kind: Some(prost_types::value::Kind::StructValue(value)),
384                }))
385            }
386
387            fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
388            where
389                A: serde::de::SeqAccess<'de>,
390            {
391                let List(value) = List::deserialize(serde::de::value::SeqAccessDeserializer::new(seq))?;
392
393                Ok(Value(prost_types::Value {
394                    kind: Some(prost_types::value::Kind::ListValue(value)),
395                }))
396            }
397
398            fn visit_none<E>(self) -> Result<Self::Value, E>
399            where
400                E: serde::de::Error,
401            {
402                Ok(Value(prost_types::Value {
403                    kind: Some(prost_types::value::Kind::NullValue(prost_types::NullValue::NullValue as i32)),
404                }))
405            }
406
407            fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
408            where
409                D: serde::de::Deserializer<'de>,
410            {
411                deserializer.deserialize_any(self)
412            }
413
414            fn visit_unit<E>(self) -> Result<Self::Value, E>
415            where
416                E: serde::de::Error,
417            {
418                self.visit_none()
419            }
420
421            fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
422            where
423                D: serde::Deserializer<'de>,
424            {
425                deserializer.deserialize_any(self)
426            }
427        }
428
429        deserializer.deserialize_any(Visitor)
430    }
431}
432
433impl serde::Serialize for Value {
434    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
435    where
436        S: serde::Serializer,
437    {
438        match &self.0.kind {
439            None | Some(prost_types::value::Kind::NullValue(_)) => serializer.serialize_none(),
440            Some(prost_types::value::Kind::NumberValue(value)) => serializer.serialize_f64(*value),
441            Some(prost_types::value::Kind::StringValue(value)) => serializer.serialize_str(value),
442            Some(prost_types::value::Kind::BoolValue(value)) => serializer.serialize_bool(*value),
443            Some(prost_types::value::Kind::StructValue(value)) => WellKnownAlias::cast_ref(value).serialize(serializer),
444            Some(prost_types::value::Kind::ListValue(value)) => WellKnownAlias::cast_ref(value).serialize(serializer),
445        }
446    }
447}
448
449impl<'de> serde::Deserialize<'de> for Timestamp {
450    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
451    where
452        D: serde::Deserializer<'de>,
453    {
454        struct Visitor;
455
456        impl serde::de::Visitor<'_> for Visitor {
457            type Value = Timestamp;
458
459            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
460                formatter.write_str("a timestamp")
461            }
462
463            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
464            where
465                E: serde::de::Error,
466            {
467                let timestamp = chrono::DateTime::parse_from_rfc3339(v).map_err(E::custom)?.to_utc();
468
469                Ok(Timestamp(prost_types::Timestamp {
470                    seconds: timestamp.timestamp(),
471                    nanos: timestamp.timestamp_subsec_nanos() as i32,
472                }))
473            }
474        }
475
476        deserializer.deserialize_str(Visitor)
477    }
478}
479
480impl serde::Serialize for Timestamp {
481    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
482    where
483        S: serde::Serializer,
484    {
485        let total_nanos = self.0.seconds * 1_000_000_000 + self.0.nanos as i64;
486        let timestamp = chrono::DateTime::from_timestamp_nanos(total_nanos);
487        serializer.serialize_str(&timestamp.to_rfc3339())
488    }
489}
490
491impl<'de> serde::Deserialize<'de> for Duration {
492    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
493    where
494        D: serde::Deserializer<'de>,
495    {
496        struct Visitor;
497
498        impl serde::de::Visitor<'_> for Visitor {
499            type Value = Duration;
500
501            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
502                formatter.write_str("a duration")
503            }
504
505            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
506            where
507                E: serde::de::Error,
508            {
509                let mut v = v.strip_suffix('s').ok_or_else(|| E::custom("invalid duration format"))?;
510                if v.is_empty() || !v.is_ascii() {
511                    return Err(E::custom("invalid duration format"));
512                }
513
514                let negative = match v.as_bytes()[0] {
515                    b'-' => {
516                        v = &v[1..];
517                        -1
518                    }
519                    b'+' => {
520                        v = &v[1..];
521                        1
522                    }
523                    b'0'..=b'9' => 1,
524                    _ => {
525                        return Err(E::custom("invalid duration format"));
526                    }
527                };
528
529                if v.is_empty() || !v.as_bytes()[0].is_ascii_digit() {
530                    return Err(E::custom("invalid duration format"));
531                }
532
533                let (seconds, nanos) = v.split_once('.').unwrap_or((v, "0"));
534                if nanos.is_empty() || !nanos.as_bytes()[0].is_ascii_digit() {
535                    return Err(E::custom("invalid duration format"));
536                }
537
538                let seconds = seconds.parse::<i64>().map_err(|_| E::custom("invalid duration format"))? * negative as i64;
539                let nanos_size = nanos.len().min(9);
540                // only take the first 9 digits of nanos (we only support nanosecond precision)
541                let nanos = &nanos[..nanos_size];
542                // convert the string to an i32
543                let nanos = nanos.parse::<i32>().map_err(|_| E::custom("invalid duration format"))?;
544
545                // We now need to scale the nanos by the number of digits in the nanos string
546                let multiplier = 10_i32.pow(9 - nanos_size as u32);
547                let nanos = nanos * multiplier * negative;
548
549                Ok(Duration(prost_types::Duration { seconds, nanos }))
550            }
551        }
552
553        deserializer.deserialize_str(Visitor)
554    }
555}
556
557impl serde::Serialize for Duration {
558    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
559    where
560        S: serde::Serializer,
561    {
562        let seconds = self.0.seconds;
563        let nanos = self.0.nanos;
564
565        let mut s = seconds.to_string();
566
567        if nanos != 0 {
568            // Convert nanos to 9-digit zero-padded string
569            let mut buf = [b'0'; 9];
570            let mut n = nanos;
571            let mut i = 9;
572            let mut first_non_zero = None;
573            while n != 0 && i > 0 {
574                i -= 1;
575                let modulus = n % 10;
576                if modulus != 0 && first_non_zero.is_none() {
577                    first_non_zero = Some(i);
578                }
579                buf[i] = b'0' + (n % 10) as u8;
580                n /= 10;
581            }
582
583            s.push('.');
584            s.push_str(
585                std::str::from_utf8(&buf[..first_non_zero.unwrap_or(8) + 1])
586                    .expect("we just made this buffer it should be valid utf-8"),
587            );
588            s.push('s');
589        } else {
590            s.push('s');
591        }
592
593        serializer.serialize_str(&s)
594    }
595}
596
597impl<'de> serde::Deserialize<'de> for Empty {
598    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
599    where
600        D: serde::Deserializer<'de>,
601    {
602        struct Visitor;
603
604        impl<'de> serde::de::Visitor<'de> for Visitor {
605            type Value = Empty;
606
607            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
608                formatter.write_str("an empty value")
609            }
610
611            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
612            where
613                A: serde::de::SeqAccess<'de>,
614            {
615                if seq.next_element::<serde::de::IgnoredAny>()?.is_some() {
616                    return Err(serde::de::Error::custom("expected empty sequence"));
617                }
618
619                Ok(Empty(()))
620            }
621
622            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
623            where
624                A: serde::de::MapAccess<'de>,
625            {
626                if map.next_key::<serde::de::IgnoredAny>()?.is_some() {
627                    return Err(serde::de::Error::custom("expected empty map"));
628                }
629
630                Ok(Empty(()))
631            }
632
633            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
634            where
635                E: serde::de::Error,
636            {
637                if v.is_empty() {
638                    return Ok(Empty(()));
639                }
640                Err(E::custom("expected empty string"))
641            }
642
643            fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
644            where
645                D: serde::Deserializer<'de>,
646            {
647                deserializer.deserialize_any(self)
648            }
649
650            fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
651            where
652                E: serde::de::Error,
653            {
654                if v.is_empty() {
655                    return Ok(Empty(()));
656                }
657
658                Err(E::custom("expected empty bytes"))
659            }
660
661            fn visit_unit<E>(self) -> Result<Self::Value, E>
662            where
663                E: serde::de::Error,
664            {
665                Ok(Empty(()))
666            }
667
668            fn visit_none<E>(self) -> Result<Self::Value, E>
669            where
670                E: serde::de::Error,
671            {
672                Ok(Empty(()))
673            }
674        }
675
676        deserializer.deserialize_any(Visitor)
677    }
678}
679
680impl serde::Serialize for Empty {
681    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
682    where
683        S: serde::Serializer,
684    {
685        serializer.serialize_map(Some(0))?.end()
686    }
687}
688
689/// # Safety
690/// This trait is marked as unsafe because the implementator
691/// must ensure that Helper has the same layout & memory representation as Self.
692pub(crate) unsafe trait WellKnownAlias: Sized {
693    type Helper: Sized;
694
695    fn reverse_cast(value: Self::Helper) -> Self {
696        const {
697            assert!(std::mem::size_of::<Self>() == std::mem::size_of::<Self::Helper>());
698            assert!(std::mem::align_of::<Self>() == std::mem::align_of::<Self::Helper>());
699        };
700
701        let mut value = ManuallyDrop::new(value);
702        // Safety: this is safe given that the `unsafe trait`'s precondition is held.
703        let casted = unsafe { &mut *(&mut value as *mut _ as *mut ManuallyDrop<Self>) };
704        // Safety: this is safe because we never access value again and value is a `ManuallyDrop`
705        // which means it will not be deallocated after this scope ends.
706        unsafe { ManuallyDrop::take(casted) }
707    }
708
709    fn cast_ref(value: &Self) -> &Self::Helper {
710        // Safety: this is safe given that the `unsafe trait`'s precondition is held.
711        unsafe { &*(value as *const Self as *const Self::Helper) }
712    }
713}
714
715/// Safety: [`List`] is `#[repr(transparent)]` for [`prost_types::ListValue`]
716unsafe impl WellKnownAlias for prost_types::ListValue {
717    type Helper = List;
718}
719
720/// Safety: [`Struct`] is `#[repr(transparent)]` for [`prost_types::Struct`]
721unsafe impl WellKnownAlias for prost_types::Struct {
722    type Helper = Struct;
723}
724
725/// Safety: [`Value`] is `#[repr(transparent)]` for [`prost_types::Value`]
726unsafe impl WellKnownAlias for prost_types::Value {
727    type Helper = Value;
728}
729
730/// Safety: [`Timestamp`] is `#[repr(transparent)]` for [`prost_types::Timestamp`]
731unsafe impl WellKnownAlias for prost_types::Timestamp {
732    type Helper = Timestamp;
733}
734
735/// Safety: [`Duration`] is `#[repr(transparent)]` for [`prost_types::Duration`]
736unsafe impl WellKnownAlias for prost_types::Duration {
737    type Helper = Duration;
738}
739
740/// Safety: [`Empty`] is `#[repr(transparent)]` for `()`
741unsafe impl WellKnownAlias for () {
742    type Helper = Empty;
743}
744
745/// Safety: If `T` is a [`SerializeWellKnown`] type, then its safe to cast `Option<T>` to `Option<T::Helper>`.
746unsafe impl<T: WellKnownAlias> WellKnownAlias for Option<T> {
747    type Helper = Option<T::Helper>;
748}
749
750/// Safety: If `T` is a [`SerializeWellKnown`] type, then its safe to cast `Vec<T>` to `Vec<T::Helper>`.
751unsafe impl<T: WellKnownAlias> WellKnownAlias for Vec<T> {
752    type Helper = Vec<T::Helper>;
753}
754
755/// Safety: `V` is a [`SerializeWellKnown`] type, then its safe to cast `BTreeMap<K, V>` to `BTreeMap<K, V::Helper>`.
756unsafe impl<K, V: WellKnownAlias> WellKnownAlias for BTreeMap<K, V> {
757    type Helper = BTreeMap<K, V::Helper>;
758}
759
760/// Safety: `V` is a [`SerializeWellKnown`] type, then its safe to cast `HashMap<K, V>` to `HashMap<K, V::Helper>`.
761unsafe impl<K, V: WellKnownAlias, S> WellKnownAlias for HashMap<K, V, S> {
762    type Helper = HashMap<K, V::Helper, S>;
763}
764
765#[repr(transparent)]
766pub(crate) struct Bytes<T>(T);
767
768/// Safety: [`Bytes<T>`] is `#[repr(transparent)]` for [`T`]
769unsafe impl WellKnownAlias for Vec<u8> {
770    type Helper = Bytes<Self>;
771}
772
773/// Safety: [`Bytes<T>`] is `#[repr(transparent)]` for [`T`]
774unsafe impl WellKnownAlias for bytes::Bytes {
775    type Helper = Bytes<Self>;
776}
777
778impl<T: AsRef<[u8]>> serde::Serialize for Bytes<T> {
779    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
780    where
781        S: serde::Serializer,
782    {
783        serializer.serialize_str(&base64::engine::general_purpose::STANDARD.encode(&self.0))
784    }
785}
786
787#[allow(private_bounds)]
788pub fn serialize_well_known<V, S>(value: &V, serializer: S) -> Result<S::Ok, S::Error>
789where
790    V: WellKnownAlias,
791    V::Helper: serde::Serialize,
792    S: serde::Serializer,
793{
794    V::cast_ref(value).serialize(serializer)
795}
796
797#[cfg(test)]
798#[cfg_attr(coverage_nightly, coverage(off))]
799mod tests {
800    use super::*;
801
802    #[test]
803    fn test_duration_deserialize() {
804        let cases = [
805            // Basic positive and negative cases
806            ("1s", prost_types::Duration { seconds: 1, nanos: 0 }),
807            ("-1s", prost_types::Duration { seconds: -1, nanos: 0 }),
808            // Zero cases
809            ("0s", prost_types::Duration { seconds: 0, nanos: 0 }),
810            ("-0s", prost_types::Duration { seconds: 0, nanos: 0 }),
811            // Positive fractions
812            (
813                "0.5s",
814                prost_types::Duration {
815                    seconds: 0,
816                    nanos: 500_000_000,
817                },
818            ),
819            (
820                "1.5s",
821                prost_types::Duration {
822                    seconds: 1,
823                    nanos: 500_000_000,
824                },
825            ),
826            ("0.000000001s", prost_types::Duration { seconds: 0, nanos: 1 }),
827            ("0.000000123s", prost_types::Duration { seconds: 0, nanos: 123 }),
828            (
829                "0.999999999s",
830                prost_types::Duration {
831                    seconds: 0,
832                    nanos: 999_999_999,
833                },
834            ),
835            ("1.000000001s", prost_types::Duration { seconds: 1, nanos: 1 }),
836            (
837                "1.234567890s",
838                prost_types::Duration {
839                    seconds: 1,
840                    nanos: 234_567_890,
841                },
842            ),
843            // Negative fractions
844            (
845                "-0.5s",
846                prost_types::Duration {
847                    seconds: 0,
848                    nanos: -500_000_000,
849                },
850            ),
851            (
852                "-1.5s",
853                prost_types::Duration {
854                    seconds: -1,
855                    nanos: -500_000_000,
856                },
857            ),
858            ("-0.000000001s", prost_types::Duration { seconds: 0, nanos: -1 }),
859            ("-0.000000123s", prost_types::Duration { seconds: 0, nanos: -123 }),
860            (
861                "-0.999999999s",
862                prost_types::Duration {
863                    seconds: 0,
864                    nanos: -999_999_999,
865                },
866            ),
867            ("-1.000000001s", prost_types::Duration { seconds: -1, nanos: -1 }),
868            (
869                "-1.234567890s",
870                prost_types::Duration {
871                    seconds: -1,
872                    nanos: -234_567_890,
873                },
874            ),
875            // Large positive integers
876            ("1000s", prost_types::Duration { seconds: 1000, nanos: 0 }),
877            (
878                "3155695200s",
879                prost_types::Duration {
880                    seconds: 3155695200,
881                    nanos: 0,
882                },
883            ), // 100 years
884            (
885                "1000000000s",
886                prost_types::Duration {
887                    seconds: 1_000_000_000,
888                    nanos: 0,
889                },
890            ),
891            (
892                "9223372036s",
893                prost_types::Duration {
894                    seconds: 9223372036,
895                    nanos: 0,
896                },
897            ),
898            // Large negative integers
899            (
900                "-1000s",
901                prost_types::Duration {
902                    seconds: -1000,
903                    nanos: 0,
904                },
905            ),
906            (
907                "-3155695200s",
908                prost_types::Duration {
909                    seconds: -3155695200,
910                    nanos: 0,
911                },
912            ), // -100 years
913            (
914                "-1000000000s",
915                prost_types::Duration {
916                    seconds: -1_000_000_000,
917                    nanos: 0,
918                },
919            ),
920            (
921                "-9223372036s",
922                prost_types::Duration {
923                    seconds: -9223372036,
924                    nanos: 0,
925                },
926            ),
927            // Large positive fractions
928            (
929                "3155695200.987654321s",
930                prost_types::Duration {
931                    seconds: 3155695200,
932                    nanos: 987_654_321,
933                },
934            ),
935            (
936                "1000000000.123456789s",
937                prost_types::Duration {
938                    seconds: 1_000_000_000,
939                    nanos: 123_456_789,
940                },
941            ),
942            (
943                "9223372036.854775807s",
944                prost_types::Duration {
945                    seconds: 9223372036,
946                    nanos: 854_775_807,
947                },
948            ),
949            (
950                "9223372036.999999999s",
951                prost_types::Duration {
952                    seconds: 9223372036,
953                    nanos: 999_999_999,
954                },
955            ),
956            // Large negative fractions
957            (
958                "-3155695200.987654321s",
959                prost_types::Duration {
960                    seconds: -3155695200,
961                    nanos: -987_654_321,
962                },
963            ),
964            (
965                "-1000000000.123456789s",
966                prost_types::Duration {
967                    seconds: -1_000_000_000,
968                    nanos: -123_456_789,
969                },
970            ),
971            (
972                "-9223372036.854775807s",
973                prost_types::Duration {
974                    seconds: -9223372036,
975                    nanos: -854_775_807,
976                },
977            ),
978            (
979                "-9223372036.999999999s",
980                prost_types::Duration {
981                    seconds: -9223372036,
982                    nanos: -999_999_999,
983                },
984            ),
985            // Near-boundary handling
986            (
987                "9223372036.854775807s",
988                prost_types::Duration {
989                    seconds: 9223372036,
990                    nanos: 854_775_807,
991                },
992            ),
993            (
994                "-9223372036.854775807s",
995                prost_types::Duration {
996                    seconds: -9223372036,
997                    nanos: -854_775_807,
998                },
999            ),
1000            (
1001                "9223372036.999999999s",
1002                prost_types::Duration {
1003                    seconds: 9223372036,
1004                    nanos: 999_999_999,
1005                },
1006            ),
1007            (
1008                "-9223372036.999999999s",
1009                prost_types::Duration {
1010                    seconds: -9223372036,
1011                    nanos: -999_999_999,
1012                },
1013            ),
1014            // Exact integers with max precision
1015            ("1.000000000s", prost_types::Duration { seconds: 1, nanos: 0 }),
1016            ("-1.000000000s", prost_types::Duration { seconds: -1, nanos: 0 }),
1017            ("0.000000000s", prost_types::Duration { seconds: 0, nanos: 0 }),
1018            ("-0.000000000s", prost_types::Duration { seconds: 0, nanos: 0 }),
1019            // Various decimal precision levels
1020            (
1021                "1.2s",
1022                prost_types::Duration {
1023                    seconds: 1,
1024                    nanos: 200_000_000,
1025                },
1026            ),
1027            (
1028                "1.23s",
1029                prost_types::Duration {
1030                    seconds: 1,
1031                    nanos: 230_000_000,
1032                },
1033            ),
1034            (
1035                "1.234s",
1036                prost_types::Duration {
1037                    seconds: 1,
1038                    nanos: 234_000_000,
1039                },
1040            ),
1041            (
1042                "1.2345s",
1043                prost_types::Duration {
1044                    seconds: 1,
1045                    nanos: 234_500_000,
1046                },
1047            ),
1048            (
1049                "1.23456s",
1050                prost_types::Duration {
1051                    seconds: 1,
1052                    nanos: 234_560_000,
1053                },
1054            ),
1055            (
1056                "1.234567s",
1057                prost_types::Duration {
1058                    seconds: 1,
1059                    nanos: 234_567_000,
1060                },
1061            ),
1062            (
1063                "1.2345678s",
1064                prost_types::Duration {
1065                    seconds: 1,
1066                    nanos: 234_567_800,
1067                },
1068            ),
1069            (
1070                "1.23456789s",
1071                prost_types::Duration {
1072                    seconds: 1,
1073                    nanos: 234_567_890,
1074                },
1075            ),
1076            (
1077                "1.234567891s",
1078                prost_types::Duration {
1079                    seconds: 1,
1080                    nanos: 234_567_891,
1081                },
1082            ),
1083            // this will be truncated to 1.23456789s
1084            (
1085                "1.2345678901s",
1086                prost_types::Duration {
1087                    seconds: 1,
1088                    nanos: 234_567_890,
1089                },
1090            ),
1091            (
1092                "1.23456789055s",
1093                prost_types::Duration {
1094                    seconds: 1,
1095                    nanos: 234_567_890,
1096                },
1097            ),
1098        ];
1099
1100        for (idx, (input, expected)) in cases.into_iter().enumerate() {
1101            let Duration(duration) = Duration::deserialize(serde_json::Value::String(input.to_string())).unwrap();
1102            assert_eq!(duration, expected, "case {idx} failed with input {input}");
1103        }
1104    }
1105
1106    #[test]
1107    fn test_duration_deserialize_error() {
1108        let error_cases = [
1109            // Completely invalid strings
1110            ("", "invalid duration format"),
1111            ("abc", "invalid duration format"),
1112            ("randomtext", "invalid duration format"),
1113            ("1second", "invalid duration format"),
1114            ("s1", "invalid duration format"),
1115            ("1.23", "invalid duration format"),
1116            ("1 s", "invalid duration format"),
1117            ("s", "invalid duration format"),
1118            ("1.s", "invalid duration format"),
1119            ("1.0.s", "invalid duration format"),
1120            // Invalid number formats
1121            ("1..0s", "invalid duration format"),
1122            ("1..s", "invalid duration format"),
1123            ("-1..0s", "invalid duration format"),
1124            ("-1..s", "invalid duration format"),
1125            (".1s", "invalid duration format"),
1126            ("-.1s", "invalid duration format"),
1127            ("1.s", "invalid duration format"),
1128            ("-1.s", "invalid duration format"),
1129            ("1.0.0s", "invalid duration format"),
1130            ("1.0.s", "invalid duration format"),
1131            // Invalid negative signs
1132            ("--1s", "invalid duration format"),
1133            ("-s", "invalid duration format"),
1134            ("--0.5s", "invalid duration format"),
1135            // Incorrect use of decimal points
1136            ("1..s", "invalid duration format"),
1137            ("-1..s", "invalid duration format"),
1138            ("0..0s", "invalid duration format"),
1139            ("0.0.0s", "invalid duration format"),
1140            ("1.0.0s", "invalid duration format"),
1141            // Missing unit
1142            ("1", "invalid duration format"),
1143            ("0.5", "invalid duration format"),
1144            ("-0.5", "invalid duration format"),
1145            ("1.", "invalid duration format"),
1146            ("-1.", "invalid duration format"),
1147            // Extra characters
1148            ("1sabc", "invalid duration format"),
1149            ("-1sabc", "invalid duration format"),
1150            ("1.0sabc", "invalid duration format"),
1151            ("0.5sab", "invalid duration format"),
1152            ("-0.5sxyz", "invalid duration format"),
1153            // Misplaced 's' character
1154            ("1s1s", "invalid duration format"),
1155            ("1.0ss", "invalid duration format"),
1156            ("-1s1", "invalid duration format"),
1157            ("-0.5s0.5s", "invalid duration format"),
1158            // Multiple decimals
1159            ("1.1.1s", "invalid duration format"),
1160            ("-1.1.1s", "invalid duration format"),
1161            ("0.1.1s", "invalid duration format"),
1162            ("-0.1.1s", "invalid duration format"),
1163            // Overflow beyond maximum supported range
1164            ("9223372036854775808s", "invalid duration format"), // One more than i64::MAX
1165            ("-9223372036854775809s", "invalid duration format"), // One less than i64::MIN
1166            ("10000000000000000000.0s", "invalid duration format"), // Excessively large number
1167            ("-10000000000000000000.0s", "invalid duration format"), // Excessively large negative number
1168            // Non-numeric characters in numbers
1169            ("1a.0s", "invalid duration format"),
1170            ("1.0as", "invalid duration format"),
1171            ("-1.a0s", "invalid duration format"),
1172            ("1.0a0s", "invalid duration format"),
1173            ("1a0s", "invalid duration format"),
1174            // Empty fraction part
1175            ("1.s", "invalid duration format"),
1176            ("-1.s", "invalid duration format"),
1177            // Invalid leading/trailing spaces
1178            (" 1s", "invalid duration format"),
1179            ("1s ", "invalid duration format"),
1180            ("- 1s", "invalid duration format"),
1181            ("1s s", "invalid duration format"),
1182            ("1 .0s", "invalid duration format"),
1183            // Misuse of signs
1184            ("1.+0s", "invalid duration format"),
1185            ("-+1s", "invalid duration format"),
1186            ("+-1s", "invalid duration format"),
1187            ("--1.0s", "invalid duration format"),
1188        ];
1189
1190        for (idx, (input, error)) in error_cases.into_iter().enumerate() {
1191            let result = Duration::deserialize(serde_json::Value::String(input.to_string()));
1192            match result {
1193                Ok(_) => panic!("case {idx} {input} should not be deserialized"),
1194                Err(e) => assert_eq!(e.to_string(), error, "case {idx} has bad error: {input}"),
1195            }
1196        }
1197    }
1198}