Debian Codegraph @

tests/alloc.rs

raw
1 #![allow(clippy::disallowed_names)]
2 #![cfg(feature = "alloc")]
3
4 extern crate alloc;
5
6 mod utils;
7
8 use alloc::borrow::Cow;
9 use alloc::collections::*;
10 #[cfg(not(feature = "serde"))]
11 use alloc::rc::Rc;
12 #[cfg(all(target_has_atomic = "ptr", not(feature = "serde")))]
13 use alloc::sync::Arc;
14 use utils::{the_same, the_same_with_comparer};
15
16 struct Foo {
17 pub a: u32,
18 pub b: u32,
19 }
20
21 impl bincode::Encode for Foo {
22 fn encode<E: bincode::enc::Encoder>(
23 &self,
24 encoder: &mut E,
25 ) -> Result<(), bincode::error::EncodeError> {
26 self.a.encode(encoder)?;
27 self.b.encode(encoder)?;
28 Ok(())
29 }
30 }
31
32 impl<Context> bincode::Decode<Context> for Foo {
33 fn decode<D: bincode::de::Decoder>(
34 decoder: &mut D,
35 ) -> Result<Self, bincode::error::DecodeError> {
36 Ok(Self {
37 a: bincode::Decode::decode(decoder)?,
38 b: bincode::Decode::decode(decoder)?,
39 })
40 }
41 }
42 bincode::impl_borrow_decode!(Foo);
43
44 #[test]
45 fn test_vec() {
46 let vec = bincode::encode_to_vec(Foo { a: 5, b: 10 }, bincode::config::standard()).unwrap();
47 assert_eq!(vec, &[5, 10]);
48
49 let (foo, len): (Foo, usize) =
50 bincode::decode_from_slice(&vec, bincode::config::standard()).unwrap();
51 assert_eq!(foo.a, 5);
52 assert_eq!(foo.b, 10);
53 assert_eq!(len, 2);
54
55 let vec: Vec<u8> = bincode::decode_from_slice(
56 &[4, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4],
57 bincode::config::legacy(),
58 )
59 .unwrap()
60 .0;
61 assert_eq!(vec, &[1, 2, 3, 4]);
62
63 let vec: Vec<Cow<'static, u8>> = bincode::decode_from_slice(
64 &[4, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4],
65 bincode::config::legacy(),
66 )
67 .unwrap()
68 .0;
69 assert_eq!(
70 vec,
71 &[
72 Cow::Borrowed(&1),
73 Cow::Borrowed(&2),
74 Cow::Borrowed(&3),
75 Cow::Borrowed(&4)
76 ]
77 );
78 }
79
80 #[test]
81 fn test_alloc_commons() {
82 the_same::<Vec<u32>>(vec![1, 2, 3, 4, 5]);
83 the_same(String::from("Hello world"));
84 the_same(Box::<u32>::new(5));
85 the_same(Box::<[u32]>::from(vec![1, 2, 3, 4, 5]));
86 the_same(Cow::<u32>::Owned(5));
87 the_same(Cow::<u32>::Borrowed(&5));
88 #[cfg(not(feature = "serde"))]
89 {
90 // Serde doesn't support Rc or Arc
91 the_same(Rc::<u32>::new(5));
92 the_same(Rc::<[u32]>::from(vec![1, 2, 3, 4, 5]));
93
94 #[cfg(target_has_atomic = "ptr")]
95 {
96 the_same(Arc::<u32>::new(5));
97 the_same(Arc::<[u32]>::from(vec![1, 2, 3, 4, 5]));
98 }
99 }
100
101 the_same_with_comparer(
102 {
103 let mut map = BinaryHeap::<u32>::new();
104 map.push(1);
105 map.push(2);
106 map.push(3);
107 map.push(4);
108 map.push(5);
109 map
110 },
111 |a, b| a.iter().collect::<Vec<_>>() == b.iter().collect::<Vec<_>>(),
112 );
113 the_same({
114 let mut map = BTreeMap::<u32, i32>::new();
115 map.insert(5, -5);
116 map
117 });
118 the_same({
119 let mut set = BTreeSet::<u32>::new();
120 set.insert(5);
121 set
122 });
123 the_same({
124 let mut set = VecDeque::<u32>::new();
125 set.push_back(15);
126 set.push_front(5);
127 set
128 });
129 }
130
131 #[test]
132 fn test_container_limits() {
133 use bincode::{error::DecodeError, BorrowDecode, Decode};
134
135 const DECODE_LIMIT: usize = 100_000;
136
137 // for this test we'll create a malformed package of a lot of bytes
138 let test_cases = &[
139 // u64::max_value(), should overflow
140 #[cfg(target_pointer_width = "64")]
141 bincode::encode_to_vec(u64::MAX, bincode::config::standard()).unwrap(),
142 #[cfg(target_pointer_width = "32")]
143 bincode::encode_to_vec(u32::MAX, bincode::config::standard()).unwrap(),
144 // A high value which doesn't overflow, but exceeds the decode limit
145 bincode::encode_to_vec(DECODE_LIMIT as u64, bincode::config::standard()).unwrap(),
146 ];
147
148 fn validate_fail<T: Decode<()> + for<'de> BorrowDecode<'de, ()> + core::fmt::Debug>(
149 slice: &[u8],
150 ) {
151 let result = bincode::decode_from_slice::<T, _>(
152 slice,
153 bincode::config::standard().with_limit::<DECODE_LIMIT>(),
154 );
155
156 let name = core::any::type_name::<T>();
157 match result {
158 Ok(_) => panic!("Decoding {} should fail, it instead succeeded", name),
159 Err(DecodeError::OutsideUsizeRange(_)) if cfg!(target_pointer_width = "32") => {},
160 Err(DecodeError::LimitExceeded) => {},
161 Err(e) => panic!("Expected OutsideUsizeRange (on 32 bit platforms) or LimitExceeded whilst decoding {}, got {:?}", name, e),
162 }
163 }
164
165 for slice in test_cases {
166 validate_fail::<BinaryHeap<i32>>(slice);
167 validate_fail::<BTreeMap<i32, i32>>(slice);
168 validate_fail::<BTreeSet<i32>>(slice);
169 validate_fail::<VecDeque<i32>>(slice);
170 validate_fail::<Vec<i32>>(slice);
171 validate_fail::<String>(slice);
172 #[cfg(feature = "std")]
173 {
174 validate_fail::<std::collections::HashMap<i32, i32>>(slice);
175 validate_fail::<std::collections::HashSet<i32>>(slice);
176 }
177 }
178 }
179
180 #[cfg(target_has_atomic = "ptr")]
181 #[test]
182 fn test_arc_str() {
183 use alloc::sync::Arc;
184
185 let start: Arc<str> = Arc::from("Example String");
186 let mut target = [0u8; 100];
187 let config = bincode::config::standard();
188
189 let len = {
190 let start: Arc<str> = Arc::clone(&start);
191 bincode::encode_into_slice(start, &mut target, config).unwrap()
192 };
193 let slice = &target[..len];
194
195 let decoded: Arc<str> = bincode::borrow_decode_from_slice(slice, config).unwrap().0;
196 assert_eq!(decoded, start);
197 }