musli_core/hint/
map_hint.rs

1use crate::de::SizeHint;
2use crate::Context;
3
4mod sealed {
5    pub trait Sealed {}
6    impl<T, M> Sealed for crate::__priv::EncodeMapHint<'_, T, M> where T: ?Sized {}
7    impl Sealed for usize {}
8    impl Sealed for Option<usize> {}
9}
10
11/// A size hint passed in when encoding or decoding a map.
12pub trait MapHint: Sized + self::sealed::Sealed {
13    /// Get an optional map hint.
14    fn get(self) -> Option<usize>;
15
16    /// Require a map hint or raise an error indicating that the format doesn't
17    /// support maps of unknown size if one is not present.
18    #[inline]
19    fn require<C>(self, cx: C) -> Result<usize, C::Error>
20    where
21        C: Context,
22    {
23        let Some(size) = self.get() else {
24            return Err(cx.message("Format cannot handle maps with an unknown number of entries"));
25        };
26
27        Ok(size)
28    }
29
30    /// Coerce into a [`SizeHint`].
31    #[inline]
32    fn size_hint(self) -> SizeHint {
33        match self.get() {
34            Some(size) => SizeHint::exact(size),
35            None => SizeHint::any(),
36        }
37    }
38}
39
40impl MapHint for usize {
41    #[inline]
42    fn get(self) -> Option<usize> {
43        Some(self)
44    }
45
46    #[inline]
47    fn require<C>(self, _: C) -> Result<usize, C::Error>
48    where
49        C: Context,
50    {
51        Ok(self)
52    }
53
54    #[inline]
55    fn size_hint(self) -> SizeHint {
56        SizeHint::exact(self)
57    }
58}
59
60impl MapHint for Option<usize> {
61    #[inline]
62    fn get(self) -> Option<usize> {
63        self
64    }
65}