specta_serde/phased.rs
1use std::marker::PhantomData;
2
3use specta::{
4 Type, Types,
5 datatype::{DataType, Reference},
6};
7
8/// Declares an explicit serialize/deserialize type pair for Specta output.
9///
10/// This is primarily used with `#[specta(type = ...)]` when serde attributes
11/// cause the wire shape to differ by direction.
12///
13/// - `Serialize` is the type used for serialization output.
14/// - `Deserialize` is the type accepted for deserialization input.
15///
16/// When both phases resolve to the same Specta datatype, this collapses to that
17/// single type. When they differ, `PhasesFormat` can split the graph into
18/// `*_Serialize` and `*_Deserialize` variants.
19///
20/// ```rust
21/// # use specta::Type;
22/// #[derive(Type)]
23/// struct OneOrMany {
24/// #[specta(type = specta_serde::Phased<Vec<String>, String>)]
25/// value: Vec<String>,
26/// }
27/// ```
28pub struct Phased<Serialize, Deserialize>(PhantomData<(Serialize, Deserialize)>);
29
30#[derive(Debug, Clone, PartialEq, Eq, Hash)]
31pub(crate) struct PhasedTy {
32 pub(crate) serialize: DataType,
33 pub(crate) deserialize: DataType,
34}
35
36/// Builds an explicit phased [`DataType`] from precomputed serialize and deserialize shapes.
37pub fn phased(serialize: DataType, deserialize: DataType) -> DataType {
38 if serialize == deserialize {
39 serialize
40 } else {
41 DataType::Reference(Reference::opaque(PhasedTy {
42 serialize,
43 deserialize,
44 }))
45 }
46}
47
48impl<Serialize: Type, Deserialize: Type> Type for Phased<Serialize, Deserialize> {
49 fn definition(types: &mut Types) -> DataType {
50 let serialize = types.define::<Serialize>();
51 let deserialize = types.define::<Deserialize>();
52
53 phased(serialize, deserialize)
54 }
55}