bitcode_lightyear_patch/serde/
mod.rs

1use crate::{Buffer, Error, Result};
2use serde::{de::DeserializeOwned, Serialize};
3use std::fmt::Display;
4
5pub mod de;
6pub mod ser;
7
8/// Serializes a `T:` [`Serialize`] into a [`Vec<u8>`].
9///
10/// **Warning:** The format is incompatible with [`decode`][`crate::decode`] and subject to change between versions.
11// #[cfg_attr(doc, doc(cfg(feature = "serde")))]
12pub fn serialize<T: ?Sized>(t: &T) -> Result<Vec<u8>>
13where
14    T: Serialize,
15{
16    Ok(Buffer::new().serialize(t)?.to_vec())
17}
18
19/// Deserializes a [`&[u8]`][`prim@slice`] into an instance of `T:` [`Deserialize`][`serde::Deserialize`].
20///
21/// **Warning:** The format is incompatible with [`encode`][`crate::encode`] and subject to change between versions.
22// #[cfg_attr(doc, doc(cfg(feature = "serde")))]
23pub fn deserialize<T>(bytes: &[u8]) -> Result<T>
24where
25    T: DeserializeOwned,
26{
27    Buffer::new().deserialize(bytes)
28}
29
30impl Buffer {
31    /// Serializes a `T:` [`Serialize`] into a [`&[u8]`][`prim@slice`]. Can reuse the buffer's
32    /// allocations.
33    ///
34    /// Even if you call `to_vec` on the [`&[u8]`][`prim@slice`], it's still more efficient than
35    /// [`serialize`].
36    ///
37    /// **Warning:** The format is incompatible with [`decode`][`Buffer::decode`] and subject to change between versions.
38    // #[cfg_attr(doc, doc(cfg(feature = "serde")))]
39    pub fn serialize<T: ?Sized>(&mut self, t: &T) -> Result<&[u8]>
40    where
41        T: Serialize,
42    {
43        ser::serialize_internal(&mut self.0, t)
44    }
45
46    /// Deserializes a [`&[u8]`][`prim@slice`] into an instance of `T:` [`Deserialize`][`serde::Deserialize`]. Can reuse
47    /// the buffer's allocations.
48    ///
49    /// **Warning:** The format is incompatible with [`encode`][`Buffer::encode`] and subject to change between versions.
50    // #[cfg_attr(doc, doc(cfg(feature = "serde")))]
51    pub fn deserialize<T>(&mut self, bytes: &[u8]) -> Result<T>
52    where
53        T: DeserializeOwned,
54    {
55        de::deserialize_internal(&mut self.0, bytes)
56    }
57}
58
59impl serde::ser::Error for Error {
60    fn custom<T>(_msg: T) -> Self
61    where
62        T: Display,
63    {
64        #[cfg(debug_assertions)]
65        return Self(crate::E::Custom(_msg.to_string()));
66        #[cfg(not(debug_assertions))]
67        Self(())
68    }
69}
70
71impl serde::de::Error for Error {
72    fn custom<T>(_msg: T) -> Self
73    where
74        T: Display,
75    {
76        #[cfg(debug_assertions)]
77        return Self(crate::E::Custom(_msg.to_string()));
78        #[cfg(not(debug_assertions))]
79        Self(())
80    }
81}