specta/datatype/
object.rs

1use crate::{DataType, NamedDataType, NamedDataTypeItem};
2
3/// A field in an [`ObjectType`].
4#[derive(Debug, Clone, PartialEq)]
5#[allow(missing_docs)]
6pub struct ObjectField {
7    pub key: &'static str,
8    pub optional: bool,
9    pub flatten: bool,
10    pub ty: DataType,
11}
12
13/// Type of an object.
14/// Could be from a struct or named enum variant.
15#[derive(Debug, Clone, PartialEq, Default)]
16#[allow(missing_docs)]
17pub struct ObjectType {
18    pub generics: Vec<&'static str>,
19    pub fields: Vec<ObjectField>,
20    pub tag: Option<&'static str>,
21}
22
23impl ObjectType {
24    /// Convert a [`ObjectType`] to an anonymous [`DataType`].
25    pub fn to_anonymous(self) -> DataType {
26        DataType::Object(self)
27    }
28
29    /// Convert a [`ObjectType`] to a named [`NamedDataType`].
30    ///
31    /// This can easily be converted to a [`DataType`] by putting it inside the [DataType::Named] variant.
32    pub fn to_named(self, name: &'static str) -> NamedDataType {
33        NamedDataType {
34            name,
35            sid: None,
36            impl_location: None,
37            comments: &[],
38            export: None,
39            deprecated: None,
40            item: NamedDataTypeItem::Object(self),
41        }
42    }
43}
44
45impl From<ObjectType> for DataType {
46    fn from(t: ObjectType) -> Self {
47        t.to_anonymous()
48    }
49}