Debian Codegraph @

tests/std.rs

raw
1 #![allow(clippy::disallowed_names)]
2 #![cfg(feature = "std")]
3
4 mod utils;
5
6 use bincode::error::DecodeError;
7 use std::{
8 ffi::CString,
9 io::{Cursor, Seek, SeekFrom},
10 net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6},
11 path::{Path, PathBuf},
12 sync::{Mutex, RwLock},
13 };
14 use utils::the_same;
15
16 use crate::utils::the_same_with_comparer;
17
18 struct Foo {
19 pub a: u32,
20 pub b: u32,
21 }
22
23 impl bincode::Encode for Foo {
24 fn encode<E: bincode::enc::Encoder>(
25 &self,
26 encoder: &mut E,
27 ) -> Result<(), bincode::error::EncodeError> {
28 self.a.encode(encoder)?;
29 self.b.encode(encoder)?;
30 Ok(())
31 }
32 }
33
34 impl<Context> bincode::Decode<Context> for Foo {
35 fn decode<D: bincode::de::Decoder>(
36 decoder: &mut D,
37 ) -> Result<Self, bincode::error::DecodeError> {
38 Ok(Self {
39 a: bincode::Decode::decode(decoder)?,
40 b: bincode::Decode::decode(decoder)?,
41 })
42 }
43 }
44
45 #[test]
46 fn test_std_cursor() {
47 let mut cursor = Cursor::<&[u8]>::new(&[5, 10]);
48 let foo: Foo = bincode::decode_from_std_read(&mut cursor, bincode::config::standard()).unwrap();
49
50 assert_eq!(foo.a, 5);
51 assert_eq!(foo.b, 10);
52 }
53
54 #[test]
55 #[cfg_attr(miri, ignore)] // miri does not like `tempfile`
56 fn test_std_file() {
57 let mut file = tempfile::tempfile().expect("Could not create temp file");
58
59 let bytes_written = bincode::encode_into_std_write(
60 Foo { a: 30, b: 50 },
61 &mut file,
62 bincode::config::standard(),
63 )
64 .unwrap();
65 assert_eq!(bytes_written, 2);
66 file.seek(SeekFrom::Start(0)).unwrap();
67
68 let foo: Foo = bincode::decode_from_std_read(&mut file, bincode::config::standard()).unwrap();
69
70 assert_eq!(foo.a, 30);
71 assert_eq!(foo.b, 50);
72 }
73
74 #[test]
75 fn test_std_commons() {
76 the_same(CString::new("Hello world").unwrap());
77 the_same(PathBuf::from("C:/Program Files/Foo"));
78 the_same(Ipv4Addr::LOCALHOST);
79 the_same(Ipv6Addr::LOCALHOST);
80 the_same(IpAddr::V4(Ipv4Addr::LOCALHOST));
81 the_same(IpAddr::V6(Ipv6Addr::LOCALHOST));
82 the_same(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 12345));
83 the_same(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 12345, 0, 0));
84 the_same(SocketAddr::V4(SocketAddrV4::new(
85 Ipv4Addr::LOCALHOST,
86 12345,
87 )));
88 the_same(SocketAddr::V6(SocketAddrV6::new(
89 Ipv6Addr::LOCALHOST,
90 12345,
91 0,
92 0,
93 )));
94 the_same_with_comparer(Mutex::new("Hello world".to_string()), |a, b| {
95 *a.lock().unwrap() == *b.lock().unwrap()
96 });
97 the_same_with_comparer(RwLock::new("Hello world".to_string()), |a, b| {
98 *a.read().unwrap() == *b.read().unwrap()
99 });
100
101 let mut map = std::collections::HashMap::new();
102 map.insert("Hello".to_owned(), "world".to_owned());
103 map.insert("How".to_owned(), "are".to_owned());
104 map.insert("you".to_owned(), "doing?".to_owned());
105 the_same(map);
106
107 let mut set = std::collections::HashSet::new();
108 set.insert("Hello".to_string());
109 set.insert("World".to_string());
110 the_same(set);
111
112 // HashMap and HashSet with custom hash algorithm
113 type MyBuildHasher = std::hash::BuildHasherDefault<ExampleCustomHasher>;
114 let mut custom_map: std::collections::HashMap<String, String, MyBuildHasher> =
115 Default::default();
116 custom_map.insert("Hello".to_owned(), "world".to_owned());
117 custom_map.insert("How".to_owned(), "are".to_owned());
118 custom_map.insert("you".to_owned(), "doing?".to_owned());
119 the_same(custom_map);
120
121 let mut custom_set: std::collections::HashSet<String, MyBuildHasher> = Default::default();
122 custom_set.insert("Hello".to_string());
123 custom_set.insert("World".to_string());
124 the_same(custom_set);
125
126 // Borrowed values
127 let config = bincode::config::standard();
128 let mut buffer = [0u8; 1024];
129
130 // &CStr
131 let cstr = c"Hello world";
132 let len = bincode::encode_into_slice(cstr, &mut buffer, config).unwrap();
133 let (decoded, len): (CString, usize) =
134 bincode::decode_from_slice(&buffer[..len], config).unwrap();
135 assert_eq!(cstr, decoded.as_c_str());
136 assert_eq!(len, 12);
137
138 // Path
139 let path = Path::new("C:/Program Files/Foo");
140 let len = bincode::encode_into_slice(path, &mut buffer, config).unwrap();
141 let (decoded, len): (&Path, usize) =
142 bincode::borrow_decode_from_slice(&buffer[..len], config).unwrap();
143 assert_eq!(path, decoded);
144 assert_eq!(len, 21);
145 }
146
147 #[test]
148 fn test_system_time_out_of_range() {
149 let input = [0xfd, 0x90, 0x0c, 0xfd, 0xfd, 0x90, 0x0c, 0xfd, 0x90, 0x90];
150
151 let result: Result<(std::time::SystemTime, usize), _> =
152 bincode::decode_from_slice(&input, bincode::config::standard());
153
154 match result {
155 Ok(_) => panic!("Expected the decode to fail, but it succeeded"),
156 Err(DecodeError::InvalidSystemTime { duration }) => {
157 assert_eq!(
158 duration,
159 std::time::Duration::new(10447520527445462160, 144)
160 )
161 }
162 Err(e) => panic!("Expected DecodeError::InvalidSystemTime, got {e:?}"),
163 }
164 }
165
166 /// Simple example of user-defined hasher to test encoding/decoding HashMap and HashSet with custom hash algorithms.
167 #[derive(Copy, Clone, Default)]
168 pub struct ExampleCustomHasher {
169 pub hash: u64,
170 }
171
172 impl std::hash::Hasher for ExampleCustomHasher {
173 fn write(&mut self, value: &[u8]) {
174 for (index, &item) in value.iter().enumerate() {
175 self.hash ^= u64::from(item) << ((index % 8) * 8);
176 }
177 }
178
179 fn finish(&self) -> u64 {
180 self.hash
181 }
182 }
183
184 #[test]
185 fn test_decode_borrow_str_in_array() {
186 let (strs, _): (Vec<&str>, usize) = bincode::borrow_decode_from_slice(
187 &[
188 3, 3, b'a', b'b', b'c', 3, b'd', b'e', b'f', 3, b'g', b'h', b'i',
189 ],
190 bincode::config::standard(),
191 )
192 .unwrap();
193 assert_eq!(strs, vec!["abc", "def", "ghi"]);
194
195 let (strs, _): ([&str; 3], usize) = bincode::borrow_decode_from_slice(
196 &[
197 3, b'a', b'b', b'c', 3, b'd', b'e', b'f', 3, b'g', b'h', b'i',
198 ],
199 bincode::config::standard(),
200 )
201 .unwrap();
202 assert_eq!(strs, ["abc", "def", "ghi"]);
203 }