postcard_schema/schema/
owned.rs

1//! Owned Schema version
2
3use super::{DataModelType, DataModelVariant, NamedType, NamedValue, NamedVariant};
4use serde::{Deserialize, Serialize};
5
6#[cfg(all(not(feature = "use-std"), feature = "alloc"))]
7extern crate alloc;
8
9#[cfg(feature = "use-std")]
10use std::{boxed::Box, collections::HashSet, string::String, vec::Vec};
11
12#[cfg(all(not(feature = "use-std"), feature = "alloc"))]
13use alloc::{
14    boxed::Box,
15    string::{String, ToString},
16    vec::Vec,
17};
18
19// ---
20
21/// The owned version of [`NamedType`]
22#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
23pub struct OwnedNamedType {
24    /// The name of this type
25    pub name: String,
26    /// The type
27    pub ty: OwnedDataModelType,
28}
29
30impl OwnedNamedType {
31    /// Convert an [OwnedNamedType] to a pseudo-Rust type format
32    pub fn to_pseudocode(&self) -> String {
33        let mut buf = String::new();
34        super::fmt::fmt_owned_nt_to_buf(self, &mut buf, true);
35        buf
36    }
37
38    /// Collect all types used recursively by this type
39    #[cfg(feature = "use-std")]
40    pub fn all_used_types(&self) -> HashSet<OwnedNamedType> {
41        let mut buf = HashSet::new();
42        super::fmt::discover_tys(self, &mut buf);
43        buf
44    }
45}
46
47impl core::fmt::Display for OwnedNamedType {
48    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
49        let pc = self.to_pseudocode();
50        f.write_str(&pc)
51    }
52}
53
54impl From<&NamedType> for OwnedNamedType {
55    fn from(value: &NamedType) -> Self {
56        Self {
57            name: value.name.to_string(),
58            ty: value.ty.into(),
59        }
60    }
61}
62
63impl crate::Schema for OwnedNamedType {
64    const SCHEMA: &'static NamedType = &NamedType {
65        name: "OwnedNamedType",
66        ty: &DataModelType::Schema,
67    };
68}
69
70// ---
71
72/// The owned version of [`DataModelType`]
73#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
74pub enum OwnedDataModelType {
75    /// The `bool` Serde Data Model Type
76    Bool,
77
78    /// The `i8` Serde Data Model Type
79    I8,
80
81    /// The `u8` Serde Data Model Type
82    U8,
83
84    /// A variably encoded i16
85    I16,
86
87    /// A variably encoded i32
88    I32,
89
90    /// A variably encoded i64
91    I64,
92
93    /// A variably encoded i128
94    I128,
95
96    /// A variably encoded u16
97    U16,
98
99    /// A variably encoded u32
100    U32,
101
102    /// A variably encoded u64
103    U64,
104
105    /// A variably encoded u128
106    U128,
107
108    /// A variably encoded usize
109    Usize,
110
111    /// A variably encoded isize
112    Isize,
113
114    /// The `f32` Serde Data Model Type
115    F32,
116
117    /// The `f64 Serde Data Model Type
118    F64,
119
120    /// The `char` Serde Data Model Type
121    Char,
122
123    /// The `String` Serde Data Model Type
124    String,
125
126    /// The `&[u8]` Serde Data Model Type
127    ByteArray,
128
129    /// The `Option<T>` Serde Data Model Type
130    Option(Box<OwnedNamedType>),
131
132    /// The `()` Serde Data Model Type
133    Unit,
134
135    /// The "unit struct" Serde Data Model Type
136    UnitStruct,
137
138    /// The "newtype struct" Serde Data Model Type
139    NewtypeStruct(Box<OwnedNamedType>),
140
141    /// The "Sequence" Serde Data Model Type
142    Seq(Box<OwnedNamedType>),
143
144    /// The "Tuple" Serde Data Model Type
145    Tuple(Vec<OwnedNamedType>),
146
147    /// The "Tuple Struct" Serde Data Model Type
148    TupleStruct(Vec<OwnedNamedType>),
149
150    /// The "Map" Serde Data Model Type
151    Map {
152        /// The map "Key" type
153        key: Box<OwnedNamedType>,
154        /// The map "Value" type
155        val: Box<OwnedNamedType>,
156    },
157
158    /// The "Struct" Serde Data Model Type
159    Struct(Vec<OwnedNamedValue>),
160
161    /// The "Enum" Serde Data Model Type (which contains any of the "Variant" types)
162    Enum(Vec<OwnedNamedVariant>),
163
164    /// A NamedType/OwnedNamedType
165    Schema,
166}
167
168impl From<&DataModelType> for OwnedDataModelType {
169    fn from(other: &DataModelType) -> Self {
170        match other {
171            DataModelType::Bool => Self::Bool,
172            DataModelType::I8 => Self::I8,
173            DataModelType::U8 => Self::U8,
174            DataModelType::I16 => Self::I16,
175            DataModelType::I32 => Self::I32,
176            DataModelType::I64 => Self::I64,
177            DataModelType::I128 => Self::I128,
178            DataModelType::U16 => Self::U16,
179            DataModelType::U32 => Self::U32,
180            DataModelType::U64 => Self::U64,
181            DataModelType::U128 => Self::U128,
182            DataModelType::Usize => Self::Usize,
183            DataModelType::Isize => Self::Isize,
184            DataModelType::F32 => Self::F32,
185            DataModelType::F64 => Self::F64,
186            DataModelType::Char => Self::Char,
187            DataModelType::String => Self::String,
188            DataModelType::ByteArray => Self::ByteArray,
189            DataModelType::Option(o) => Self::Option(Box::new((*o).into())),
190            DataModelType::Unit => Self::Unit,
191            DataModelType::UnitStruct => Self::UnitStruct,
192            DataModelType::NewtypeStruct(nts) => Self::NewtypeStruct(Box::new((*nts).into())),
193            DataModelType::Seq(s) => Self::Seq(Box::new((*s).into())),
194            DataModelType::Tuple(t) => Self::Tuple(t.iter().map(|i| (*i).into()).collect()),
195            DataModelType::TupleStruct(ts) => {
196                Self::TupleStruct(ts.iter().map(|i| (*i).into()).collect())
197            }
198            DataModelType::Map { key, val } => Self::Map {
199                key: Box::new((*key).into()),
200                val: Box::new((*val).into()),
201            },
202            DataModelType::Struct(s) => Self::Struct(s.iter().map(|i| (*i).into()).collect()),
203            DataModelType::Enum(e) => Self::Enum(e.iter().map(|i| (*i).into()).collect()),
204            DataModelType::Schema => Self::Schema,
205        }
206    }
207}
208
209// ---
210
211/// The owned version of [`DataModelVariant`]
212#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
213pub enum OwnedDataModelVariant {
214    /// The "unit variant" Serde Data Model Type
215    UnitVariant,
216    /// The "newtype variant" Serde Data Model Type
217    NewtypeVariant(Box<OwnedNamedType>),
218    /// The "Tuple Variant" Serde Data Model Type
219    TupleVariant(Vec<OwnedNamedType>),
220    /// The "Struct Variant" Serde Data Model Type
221    StructVariant(Vec<OwnedNamedValue>),
222}
223
224impl From<&DataModelVariant> for OwnedDataModelVariant {
225    fn from(value: &DataModelVariant) -> Self {
226        match value {
227            DataModelVariant::UnitVariant => Self::UnitVariant,
228            DataModelVariant::NewtypeVariant(d) => Self::NewtypeVariant(Box::new((*d).into())),
229            DataModelVariant::TupleVariant(d) => {
230                Self::TupleVariant(d.iter().map(|i| (*i).into()).collect())
231            }
232            DataModelVariant::StructVariant(d) => {
233                Self::StructVariant(d.iter().map(|i| (*i).into()).collect())
234            }
235        }
236    }
237}
238
239// ---
240
241/// The owned version of [`NamedValue`]
242#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
243pub struct OwnedNamedValue {
244    /// The name of this value
245    pub name: String,
246    /// The type of this value
247    pub ty: OwnedNamedType,
248}
249
250impl From<&NamedValue> for OwnedNamedValue {
251    fn from(value: &NamedValue) -> Self {
252        Self {
253            name: value.name.to_string(),
254            ty: value.ty.into(),
255        }
256    }
257}
258
259// ---
260
261/// The owned version of [`NamedVariant`]
262#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
263pub struct OwnedNamedVariant {
264    /// The name of this variant
265    pub name: String,
266    /// The type of this variant
267    pub ty: OwnedDataModelVariant,
268}
269
270impl From<&NamedVariant> for OwnedNamedVariant {
271    fn from(value: &NamedVariant) -> Self {
272        Self {
273            name: value.name.to_string(),
274            ty: value.ty.into(),
275        }
276    }
277}