test_fuzz_internal/
serde_format.rs

1use serde::{Serialize, de::DeserializeOwned};
2use std::io::Read;
3
4#[cfg(any(serde_default, feature = "__serde_bincode"))]
5const BYTE_LIMIT: usize = 1024 * 1024 * 1024;
6
7// smoelius: I can't find any guidance on how to choose this size. 2048 is used in the `loopback`
8// test in the `postcard` repository:
9// https://github.com/jamesmunns/postcard/blob/03865c2b7d694d000c0457e8cfaf4ff1b128ed81/tests/loopback.rs#L191
10#[cfg(feature = "__serde_postcard")]
11const SLIDING_BUFFER_SIZE: usize = 2048;
12
13#[allow(clippy::vec_init_then_push)]
14#[must_use]
15pub fn as_feature() -> &'static str {
16    let mut formats = vec![];
17
18    #[cfg(any(serde_default, feature = "__serde_bincode"))]
19    formats.push("serde_bincode");
20
21    #[cfg(feature = "__serde_postcard")]
22    formats.push("serde_postcard");
23
24    assert!(
25        formats.len() <= 1,
26        "Multiple serde formats selected: {formats:?}"
27    );
28
29    formats.pop().expect("No serde format selected")
30}
31
32pub fn serialize<T: Serialize>(args: &T) -> Vec<u8> {
33    #[cfg(any(serde_default, feature = "__serde_bincode"))]
34    return {
35        // smoelius: From
36        // https://github.com/bincode-org/bincode/blob/c44b5e364e7084cdbabf9f94b63a3c7f32b8fb68/src/lib.rs#L102-L103 :
37        // /// **Warning:** the default configuration used by [`bincode::serialize`] is not
38        // /// the same as that used by the `DefaultOptions` struct. ...
39        // The point is that `bincode::serialize(..)` and `bincode::options().serialize(..)` use
40        // different encodings, even though the latter uses "default" options.
41        // smoelius: With the upgrade to Bincode 2.0, the preceding comments may no longer be
42        // applicable.
43        let config = bincode::config::standard().with_limit::<BYTE_LIMIT>();
44        bincode::serde::encode_to_vec(args, config).unwrap()
45    };
46
47    #[cfg(feature = "__serde_postcard")]
48    return {
49        let mut data = Vec::new();
50        postcard::to_io(args, &mut data).unwrap();
51        data
52    };
53}
54
55#[allow(unused_mut)]
56pub fn deserialize<T: DeserializeOwned, R: Read>(mut reader: R) -> Option<T> {
57    #[cfg(any(serde_default, feature = "__serde_bincode"))]
58    return {
59        let config = bincode::config::standard().with_limit::<BYTE_LIMIT>();
60        bincode::serde::decode_from_std_read(&mut reader, config).ok()
61    };
62
63    #[cfg(feature = "__serde_postcard")]
64    return {
65        let mut buff = [0; SLIDING_BUFFER_SIZE];
66        postcard::from_io((reader, &mut buff))
67            .map(|(value, _)| value)
68            .ok()
69    };
70}