Skip to main content

messagepack_core/decode/
int.rs

1use super::{DecodeBorrowed, Error};
2use crate::{formats::Format, io::IoRead};
3
4impl<'de> DecodeBorrowed<'de> for u8 {
5    type Value = Self;
6
7    fn decode_borrowed_with_format<R>(
8        format: Format,
9        reader: &mut R,
10    ) -> core::result::Result<Self::Value, Error<R::Error>>
11    where
12        R: IoRead<'de>,
13    {
14        match format {
15            Format::PositiveFixInt(v) => Ok(v),
16            Format::Uint8 => {
17                let b = reader.read_slice(1).map_err(Error::Io)?;
18                let v: [u8; 1] = b.as_bytes().try_into().map_err(|_| Error::UnexpectedEof)?;
19                Ok(v[0])
20            }
21            _ => Err(Error::UnexpectedFormat),
22        }
23    }
24}
25
26impl<'de> DecodeBorrowed<'de> for i8 {
27    type Value = Self;
28
29    fn decode_borrowed_with_format<R>(
30        format: Format,
31        reader: &mut R,
32    ) -> core::result::Result<Self::Value, Error<R::Error>>
33    where
34        R: IoRead<'de>,
35    {
36        match format {
37            Format::Int8 => {
38                let b = reader.read_slice(1).map_err(Error::Io)?;
39                let v: [u8; 1] = b.as_bytes().try_into().map_err(|_| Error::UnexpectedEof)?;
40                Ok(v[0] as i8)
41            }
42            Format::NegativeFixInt(v) => Ok(v),
43            _ => Err(Error::UnexpectedFormat),
44        }
45    }
46}
47
48macro_rules! impl_decode_int {
49    ($ty:ty,$format:path) => {
50        impl<'de> DecodeBorrowed<'de> for $ty {
51            type Value = Self;
52
53            fn decode_borrowed_with_format<R>(
54                format: Format,
55                reader: &mut R,
56            ) -> core::result::Result<Self::Value, Error<R::Error>>
57            where
58                R: IoRead<'de>,
59            {
60                match format {
61                    $format => {
62                        const SIZE: usize = core::mem::size_of::<$ty>();
63                        let bytes = reader.read_slice(SIZE).map_err(Error::Io)?;
64                        let slice = bytes.as_bytes();
65                        let data: [u8; SIZE] =
66                            slice.try_into().map_err(|_| Error::UnexpectedEof)?;
67                        let val = <$ty>::from_be_bytes(data);
68                        Ok(val)
69                    }
70                    _ => Err(Error::UnexpectedFormat),
71                }
72            }
73        }
74    };
75}
76
77impl_decode_int!(u16, Format::Uint16);
78impl_decode_int!(u32, Format::Uint32);
79impl_decode_int!(u64, Format::Uint64);
80impl_decode_int!(i16, Format::Int16);
81impl_decode_int!(i32, Format::Int32);
82impl_decode_int!(i64, Format::Int64);
83
84impl<'de> DecodeBorrowed<'de> for u128 {
85    type Value = Self;
86
87    fn decode_borrowed_with_format<R>(
88        format: Format,
89        reader: &mut R,
90    ) -> core::result::Result<Self::Value, Error<R::Error>>
91    where
92        R: IoRead<'de>,
93    {
94        let val = u64::decode_borrowed_with_format(format, reader)?;
95        Ok(Self::from(val))
96    }
97}
98
99impl<'de> DecodeBorrowed<'de> for i128 {
100    type Value = Self;
101
102    fn decode_borrowed_with_format<R>(
103        format: Format,
104        reader: &mut R,
105    ) -> core::result::Result<Self::Value, Error<R::Error>>
106    where
107        R: IoRead<'de>,
108    {
109        let val = i64::decode_borrowed_with_format(format, reader)?;
110        Ok(Self::from(val))
111    }
112}
113
114impl<'de> DecodeBorrowed<'de> for usize {
115    type Value = Self;
116
117    fn decode_borrowed_with_format<R>(
118        format: Format,
119        reader: &mut R,
120    ) -> core::result::Result<Self::Value, Error<R::Error>>
121    where
122        R: IoRead<'de>,
123    {
124        let val = u64::decode_borrowed_with_format(format, reader)?;
125        usize::try_from(val).map_err(|_| Error::InvalidData)
126    }
127}
128
129impl<'de> DecodeBorrowed<'de> for isize {
130    type Value = Self;
131
132    fn decode_borrowed_with_format<R>(
133        format: Format,
134        reader: &mut R,
135    ) -> core::result::Result<Self::Value, Error<R::Error>>
136    where
137        R: IoRead<'de>,
138    {
139        let val = i64::decode_borrowed_with_format(format, reader)?;
140        isize::try_from(val).map_err(|_| Error::InvalidData)
141    }
142}
143
144macro_rules! impl_nonzero_int {
145    ($ty:ty) => {
146        impl<'de> DecodeBorrowed<'de> for core::num::NonZero<$ty> {
147            type Value = Self;
148
149            fn decode_borrowed_with_format<R>(
150                format: Format,
151                reader: &mut R,
152            ) -> core::result::Result<Self::Value, Error<R::Error>>
153            where
154                R: IoRead<'de>,
155            {
156                let val = <$ty>::decode_borrowed_with_format(format, reader)?;
157                Self::new(val).ok_or(Error::InvalidData)
158            }
159        }
160    };
161}
162impl_nonzero_int!(u8);
163impl_nonzero_int!(u16);
164impl_nonzero_int!(u32);
165impl_nonzero_int!(u64);
166impl_nonzero_int!(usize);
167impl_nonzero_int!(i8);
168impl_nonzero_int!(i16);
169impl_nonzero_int!(i32);
170impl_nonzero_int!(i64);
171impl_nonzero_int!(isize);
172
173macro_rules! impl_atomic_int {
174    ($ty:ty, $base:ty) => {
175        impl<'de> DecodeBorrowed<'de> for $ty {
176            type Value = Self;
177
178            fn decode_borrowed_with_format<R>(
179                format: Format,
180                reader: &mut R,
181            ) -> Result<Self::Value, Error<R::Error>>
182            where
183                R: IoRead<'de>,
184            {
185                let val = <$base>::decode_borrowed_with_format(format, reader)?;
186                Ok(Self::new(val))
187            }
188        }
189    };
190}
191impl_atomic_int!(core::sync::atomic::AtomicU8, u8);
192impl_atomic_int!(core::sync::atomic::AtomicU16, u16);
193impl_atomic_int!(core::sync::atomic::AtomicU32, u32);
194impl_atomic_int!(core::sync::atomic::AtomicU64, u64);
195impl_atomic_int!(core::sync::atomic::AtomicUsize, usize);
196impl_atomic_int!(core::sync::atomic::AtomicI8, i8);
197impl_atomic_int!(core::sync::atomic::AtomicI16, i16);
198impl_atomic_int!(core::sync::atomic::AtomicI32, i32);
199impl_atomic_int!(core::sync::atomic::AtomicI64, i64);
200impl_atomic_int!(core::sync::atomic::AtomicIsize, isize);
201
202#[cfg(test)]
203mod tests {
204    use crate::decode::Decode;
205
206    #[test]
207    fn decode_u8_fix_pos_int() {
208        // FixPosInt
209        let buf: &[u8] = &[0x00];
210        let mut r = crate::io::SliceReader::new(buf);
211        let decoded = u8::decode(&mut r).unwrap();
212        let expect = u8::MIN;
213        assert_eq!(decoded, expect);
214        assert_eq!(r.rest().len(), 0);
215
216        let buf: &[u8] = &[0x7f];
217        let mut r = crate::io::SliceReader::new(buf);
218        let decoded = u8::decode(&mut r).unwrap();
219        let expect = 0x7f;
220        assert_eq!(decoded, expect);
221        assert_eq!(r.rest().len(), 0);
222    }
223
224    #[test]
225    fn decode_u8() {
226        // Uint8
227        let buf: &[u8] = &[0xcc, 0x00];
228        let mut r = crate::io::SliceReader::new(buf);
229        let decoded = u8::decode(&mut r).unwrap();
230        let expect = u8::MIN;
231        assert_eq!(decoded, expect);
232        assert_eq!(r.rest().len(), 0);
233
234        let buf: &[u8] = &[0xcc, 0xff];
235        let mut r = crate::io::SliceReader::new(buf);
236        let decoded = u8::decode(&mut r).unwrap();
237        let expect = u8::MAX;
238        assert_eq!(decoded, expect);
239        assert_eq!(r.rest().len(), 0);
240    }
241
242    #[test]
243    fn decode_u16() {
244        // Uint16
245        let buf: &[u8] = &[0xcd, 0x00, 0x00];
246        let mut r = crate::io::SliceReader::new(buf);
247        let decoded = u16::decode(&mut r).unwrap();
248        let expect = u16::MIN;
249        assert_eq!(decoded, expect);
250        assert_eq!(r.rest().len(), 0);
251
252        let buf: &[u8] = &[0xcd, 0x12, 0x34];
253        let mut r = crate::io::SliceReader::new(buf);
254        let decoded = u16::decode(&mut r).unwrap();
255        let expect = 0x1234;
256        assert_eq!(decoded, expect);
257        assert_eq!(r.rest().len(), 0);
258
259        let buf: &[u8] = &[0xcd, 0xff, 0xff];
260        let mut r = crate::io::SliceReader::new(buf);
261        let decoded = u16::decode(&mut r).unwrap();
262        let expect = u16::MAX;
263        assert_eq!(decoded, expect);
264        assert_eq!(r.rest().len(), 0);
265    }
266
267    #[test]
268    fn decode_u32() {
269        // Uint32
270        let buf: &[u8] = &[0xce, 0x00, 0x00, 0x00, 0x00];
271        let mut r = crate::io::SliceReader::new(buf);
272        let decoded = u32::decode(&mut r).unwrap();
273        let expect = u32::MIN;
274        assert_eq!(decoded, expect);
275        assert_eq!(r.rest().len(), 0);
276
277        let buf: &[u8] = &[0xce, 0x12, 0x34, 0x56, 0x78];
278        let mut r = crate::io::SliceReader::new(buf);
279        let decoded = u32::decode(&mut r).unwrap();
280        let expect = 0x12345678;
281        assert_eq!(decoded, expect);
282        assert_eq!(r.rest().len(), 0);
283
284        let buf: &[u8] = &[0xce, 0xff, 0xff, 0xff, 0xff];
285        let mut r = crate::io::SliceReader::new(buf);
286        let decoded = u32::decode(&mut r).unwrap();
287        let expect = u32::MAX;
288        assert_eq!(decoded, expect);
289        assert_eq!(r.rest().len(), 0);
290    }
291
292    #[test]
293    fn decode_u64() {
294        // Uint64
295        let buf: &[u8] = &[0xcf, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
296        let mut r = crate::io::SliceReader::new(buf);
297        let decoded = u64::decode(&mut r).unwrap();
298        let expect = u64::MIN;
299        assert_eq!(decoded, expect);
300        assert_eq!(r.rest().len(), 0);
301
302        let buf: &[u8] = &[0xcf, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78];
303        let mut r = crate::io::SliceReader::new(buf);
304        let decoded = u64::decode(&mut r).unwrap();
305        let expect = 0x1234567812345678;
306        assert_eq!(decoded, expect);
307        assert_eq!(r.rest().len(), 0);
308
309        let buf: &[u8] = &[0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
310        let mut r = crate::io::SliceReader::new(buf);
311        let decoded = u64::decode(&mut r).unwrap();
312        let expect = u64::MAX;
313        assert_eq!(decoded, expect);
314        assert_eq!(r.rest().len(), 0);
315    }
316
317    #[test]
318    fn decode_i8_fix_neg_int() {
319        // FixNegInt
320        let buf: &[u8] = &[0xff];
321        let mut r = crate::io::SliceReader::new(buf);
322        let decoded = i8::decode(&mut r).unwrap();
323        let expect = -1;
324        assert_eq!(decoded, expect);
325        assert_eq!(r.rest().len(), 0);
326
327        let buf: &[u8] = &[0xe0];
328        let mut r = crate::io::SliceReader::new(buf);
329        let decoded = i8::decode(&mut r).unwrap();
330        let expect = -32;
331        assert_eq!(decoded, expect);
332        assert_eq!(r.rest().len(), 0);
333    }
334
335    #[test]
336    fn decode_i8() {
337        // Int8
338        let buf: &[u8] = &[0xd0, 0x80];
339        let mut r = crate::io::SliceReader::new(buf);
340        let decoded = i8::decode(&mut r).unwrap();
341        let expect = i8::MIN;
342        assert_eq!(decoded, expect);
343        assert_eq!(r.rest().len(), 0);
344
345        let buf: &[u8] = &[0xd0, 0x7f];
346        let mut r = crate::io::SliceReader::new(buf);
347        let decoded = i8::decode(&mut r).unwrap();
348        let expect = i8::MAX;
349        assert_eq!(decoded, expect);
350        assert_eq!(r.rest().len(), 0);
351    }
352
353    #[test]
354    fn decode_i16() {
355        // Int16
356        let buf: &[u8] = &[0xd1, 0x80, 0x00];
357        let mut r = crate::io::SliceReader::new(buf);
358        let decoded = i16::decode(&mut r).unwrap();
359        let expect = i16::MIN;
360        assert_eq!(decoded, expect);
361        assert_eq!(r.rest().len(), 0);
362
363        let buf: &[u8] = &[0xd1, 0x7f, 0xff];
364        let mut r = crate::io::SliceReader::new(buf);
365        let decoded = i16::decode(&mut r).unwrap();
366        let expect = i16::MAX;
367        assert_eq!(decoded, expect);
368        assert_eq!(r.rest().len(), 0);
369    }
370
371    #[test]
372    fn decode_i32() {
373        // Int16
374        let buf: &[u8] = &[0xd2, 0x80, 0x00, 0x00, 0x00];
375        let mut r = crate::io::SliceReader::new(buf);
376        let decoded = i32::decode(&mut r).unwrap();
377        let expect = i32::MIN;
378        assert_eq!(decoded, expect);
379        assert_eq!(r.rest().len(), 0);
380
381        let buf: &[u8] = &[0xd2, 0x7f, 0xff, 0xff, 0xff];
382        let mut r = crate::io::SliceReader::new(buf);
383        let decoded = i32::decode(&mut r).unwrap();
384        let expect = i32::MAX;
385        assert_eq!(decoded, expect);
386        assert_eq!(r.rest().len(), 0);
387    }
388
389    #[test]
390    fn decode_i64() {
391        // Int16
392        let buf: &[u8] = &[0xd3, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
393        let mut r = crate::io::SliceReader::new(buf);
394        let decoded = i64::decode(&mut r).unwrap();
395        let expect = i64::MIN;
396        assert_eq!(decoded, expect);
397        assert_eq!(r.rest().len(), 0);
398
399        let buf: &[u8] = &[0xd3, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
400        let mut r = crate::io::SliceReader::new(buf);
401        let decoded = i64::decode(&mut r).unwrap();
402        let expect = i64::MAX;
403        assert_eq!(decoded, expect);
404        assert_eq!(r.rest().len(), 0);
405    }
406}