Skip to main content

ic_wire/evolution/
declaration.rs

1//! Typed carriers for the explicit extension declarations.
2
3use super::{Extensions, OpaqueOpen, ReadContext, Recoverable, RecoveryContext, WriteContext};
4use crate::Error;
5use core::marker::PhantomData;
6use serde::{Deserialize, Deserializer, Serialize, Serializer};
7
8/// The final extension block of an evolvable record, with the associated set
9/// of field IDs retained in the Rust type.
10pub struct ExtensionSlot<'a, T>(Extensions<'a>, PhantomData<fn() -> T>);
11
12impl<T> Copy for ExtensionSlot<'_, T> {}
13
14impl<T> Clone for ExtensionSlot<'_, T> {
15    fn clone(&self) -> Self {
16        *self
17    }
18}
19
20impl<'a, T> ExtensionSlot<'a, T> {
21    /// Wrap an already prepared or decoded extension block.
22    #[doc(hidden)]
23    #[must_use]
24    pub const fn from_raw(block: Extensions<'a>) -> Self {
25        Self(block, PhantomData)
26    }
27
28    /// Access the low-level block for an explicit projection.
29    #[doc(hidden)]
30    #[must_use]
31    pub const fn into_raw(self) -> Extensions<'a> {
32        self.0
33    }
34}
35
36impl<T> Serialize for ExtensionSlot<'_, T> {
37    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
38        self.0.serialize(serializer)
39    }
40}
41
42impl<'de: 'a, 'a, T> Deserialize<'de> for ExtensionSlot<'a, T> {
43    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
44        Extensions::deserialize(deserializer).map(Self::from_raw)
45    }
46}
47
48/// An open variant carrying the declaration of the cases the reader knows.
49/// Set `REQUIRED` to propagate unknown tags to the nearest recovering scope.
50pub struct OpenSlot<'a, T, const REQUIRED: bool = false>(OpaqueOpen<'a>, PhantomData<fn() -> T>);
51
52impl<T, const REQUIRED: bool> Copy for OpenSlot<'_, T, REQUIRED> {}
53
54impl<T, const REQUIRED: bool> Clone for OpenSlot<'_, T, REQUIRED> {
55    fn clone(&self) -> Self {
56        *self
57    }
58}
59
60impl<'a, T, const REQUIRED: bool> OpenSlot<'a, T, REQUIRED> {
61    /// Wrap an already prepared or decoded open variant.
62    #[doc(hidden)]
63    #[must_use]
64    pub const fn from_raw(open: OpaqueOpen<'a>) -> Self {
65        Self(open, PhantomData)
66    }
67
68    /// Access the low-level variant for an explicit projection.
69    #[doc(hidden)]
70    #[must_use]
71    pub const fn into_raw(self) -> OpaqueOpen<'a> {
72        self.0
73    }
74}
75
76impl<T, const REQUIRED: bool> Serialize for OpenSlot<'_, T, REQUIRED> {
77    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
78        self.0.serialize(serializer)
79    }
80}
81
82impl<'de: 'a, 'a, T, const REQUIRED: bool> Deserialize<'de> for OpenSlot<'a, T, REQUIRED> {
83    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
84        OpaqueOpen::deserialize(deserializer).map(Self::from_raw)
85    }
86}
87
88/// An optional, length-bounded payload that can recover an unknown required case.
89pub struct RecoverSlot<'a, T>(Recoverable<'a>, PhantomData<fn() -> T>);
90
91impl<T> Copy for RecoverSlot<'_, T> {}
92
93impl<T> Clone for RecoverSlot<'_, T> {
94    fn clone(&self) -> Self {
95        *self
96    }
97}
98
99impl<'a, T> RecoverSlot<'a, T> {
100    /// Construct an absent branch.
101    #[must_use]
102    pub const fn absent() -> Self {
103        Self(Recoverable::absent(), PhantomData)
104    }
105
106    /// Prepare a present branch in the supplied scratch.
107    /// # Errors
108    /// Returns the first resource, encoding or scratch refusal.
109    pub fn write(
110        context: &WriteContext<'_>,
111        value: &T,
112        scratch: &'a mut [u8],
113    ) -> Result<Self, Error>
114    where
115        T: Serialize,
116    {
117        Recoverable::write(context, value, scratch).map(|branch| Self(branch, PhantomData))
118    }
119
120    /// Project the branch through its nearest recovery scope.
121    /// # Errors
122    /// Returns a resource or payload failure. A marked unknown required tag
123    /// yields absence after the projection checks the remaining known parts.
124    pub fn project<R>(
125        self,
126        context: &ReadContext<'_>,
127        project: impl FnOnce(T, &RecoveryContext<'_>) -> Result<R, Error>,
128    ) -> Result<Option<R>, Error>
129    where
130        T: Deserialize<'a>,
131    {
132        self.0.project(context, project)
133    }
134}
135
136impl<T> Serialize for RecoverSlot<'_, T> {
137    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
138        self.0.serialize(serializer)
139    }
140}
141
142impl<'de: 'a, 'a, T> Deserialize<'de> for RecoverSlot<'a, T> {
143    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
144        Recoverable::deserialize(deserializer).map(|branch| Self(branch, PhantomData))
145    }
146}
147
148#[cfg(feature = "derive")]
149pub use ic_wire_derive::Evolve;
150
151#[doc(hidden)]
152pub mod __private {
153    pub use alloc::vec::Vec;
154
155    /// Describe the root projected by a generated typed method adapter.
156    #[cfg(feature = "typescript")]
157    pub trait EvolvingSchema {
158        fn describe(
159            context: &mut crate::typescript::SchemaContext,
160        ) -> Result<serde_json::Value, crate::typescript::GenerationError>;
161    }
162}
163
164#[cfg(feature = "typescript")]
165mod schema {
166    use super::{ExtensionSlot, OpenSlot, RecoverSlot};
167    use crate::typescript::{
168        __private::{Value, json},
169        GenerationError, SchemaContext, Wire,
170    };
171    /// Return metadata for the fields held in an extension declaration.
172    #[doc(hidden)]
173    pub trait ExtensionLayout {
174        fn extension_fields(context: &mut SchemaContext) -> Result<Value, GenerationError>;
175    }
176
177    /// Return metadata for the cases held in an open variant declaration.
178    #[doc(hidden)]
179    pub trait OpenLayout {
180        fn open_cases(context: &mut SchemaContext) -> Result<Value, GenerationError>;
181    }
182
183    /// Confirm that the final member of an extension record is a typed carrier.
184    #[doc(hidden)]
185    pub trait SchemaFields {
186        fn extension_fields(context: &mut SchemaContext) -> Result<Value, GenerationError>;
187    }
188
189    impl<T: ExtensionLayout> SchemaFields for ExtensionSlot<'_, T> {
190        fn extension_fields(context: &mut SchemaContext) -> Result<Value, GenerationError> {
191            T::extension_fields(context)
192        }
193    }
194
195    impl<T: OpenLayout, const REQUIRED: bool> Wire for OpenSlot<'_, T, REQUIRED> {
196        fn schema(context: &mut SchemaContext) -> Result<Value, GenerationError> {
197            let cases = T::open_cases(context)?;
198            if REQUIRED {
199                Ok(json!({"k":"open-variant","variants":cases,"required":true}))
200            } else {
201                Ok(json!({"k":"open-variant","variants":cases}))
202            }
203        }
204    }
205
206    impl<T: Wire> Wire for RecoverSlot<'_, T> {
207        fn schema(context: &mut SchemaContext) -> Result<Value, GenerationError> {
208            Ok(json!({"k":"recover","item":context.describe::<T>()?}))
209        }
210    }
211}
212
213#[cfg(feature = "typescript")]
214pub use schema::{ExtensionLayout, OpenLayout, SchemaFields};
215
216/// Emit a generated schema implementation when the runtime supplies schema tooling.
217#[cfg(feature = "typescript")]
218#[doc(hidden)]
219#[macro_export]
220macro_rules! __wire_evolution_schema {
221    ($schema:item) => {
222        $schema
223    };
224}
225
226/// Drop generated schema metadata from codec-only consumers.
227#[cfg(not(feature = "typescript"))]
228#[doc(hidden)]
229#[macro_export]
230macro_rules! __wire_evolution_schema {
231    ($schema:item) => {};
232}