Skip to main content

postcard_schema_ng/schema/
owned.rs

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