Function procspawn::serde::in_ipc_mode

source ·
pub fn in_ipc_mode() -> bool
Expand description

Checks if serde is in IPC mode.

This can be used to customize the serialization behavior of custom types for IPC specific purposes. This is useful when a type has a regular serialization/deserialization behavior but you want to use a cheaper one when procspawn is used.

An example of this can be a type that abstracts over an mmap. It might want to serialize the raw bytes under normal circumstances but for IPC purposes might want to instead serialize the underlying file path and reopen the mmap on the other side.

This function returns true whenever procspawn is attempting to serialize and deserialize but never anytime else. Internally this is implemented as a thread local.

Examples found in repository?
examples/custom-serialization.rs (line 37)
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        if procspawn::serde::in_ipc_mode() {
            println!("serialize in ipc mode");
            self.path.serialize(serializer)
        } else {
            println!("serialize in normal mode");
            MyBytesHelper {
                path: Cow::Borrowed(&self.path),
                bytes: Cow::Borrowed(&self.bytes),
            }
            .serialize(serializer)
        }
    }
}

impl<'de> Deserialize<'de> for MyBytes {
    fn deserialize<D>(deserializer: D) -> Result<MyBytes, D::Error>
    where
        D: Deserializer<'de>,
    {
        if procspawn::serde::in_ipc_mode() {
            println!("deserialize in ipc mode");
            let path = PathBuf::deserialize(deserializer)?;
            MyBytes::open(path).map_err(D::Error::custom)
        } else {
            println!("deserialize in normal mode");
            let helper = MyBytesHelper::deserialize(deserializer)?;
            Ok(MyBytes {
                path: helper.path.into_owned(),
                bytes: helper.bytes.into_owned(),
            })
        }
    }