Skip to main content

ic_wire/evolution/
recovery.rs

1//! Explicit optional branches with a bounded, typed recovery scope.
2
3use super::{Error, Field, OpaqueOpen, ReadContext, WriteContext, admit_scope};
4use core::cell::Cell;
5use serde::{Deserialize, Deserializer, Serialize, Serializer};
6use serde_bytes::Bytes;
7
8/// A Postcard option containing a bounded, borrowed Postcard payload.
9///
10/// Absence is the byte zero. Presence is the byte one followed by the byte
11/// length and contents of the payload. A present unit has a zero byte length.
12/// Consumers explicitly project this value to enable recovery.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub struct Recoverable<'a>(Option<&'a [u8]>);
15
16impl<'a> Recoverable<'a> {
17    /// Construct an absent branch.
18    #[must_use]
19    pub const fn absent() -> Self {
20        Self(None)
21    }
22
23    /// Write a present branch payload into caller-owned scratch storage.
24    ///
25    /// # Errors
26    ///
27    /// Returns an allowance, output capacity, or payload serialization error.
28    pub fn write<T: Serialize + ?Sized>(
29        context: &WriteContext<'_>,
30        value: &T,
31        scratch: &'a mut [u8],
32    ) -> Result<Self, Error> {
33        let body = context.child();
34        let size = body.write_once(value, scratch)?;
35        Ok(Self(Some(&scratch[..size])))
36    }
37
38    /// Project a complete branch and map a marked incompatibility to absence.
39    ///
40    /// The projection must check the whole branch, including known siblings
41    /// after an incompatible value, and propagate errors from those checks.
42    ///
43    /// # Errors
44    ///
45    /// Returns a malformed payload, allowance refusal, or projection error.
46    /// Recovery requires a mark from [RecoveryContext::required_open] or
47    /// [RecoveryContext::missing_required].
48    pub fn project<T: Deserialize<'a>, R>(
49        self,
50        context: &ReadContext<'_>,
51        project: impl FnOnce(T, &RecoveryContext<'_>) -> Result<R, Error>,
52    ) -> Result<Option<R>, Error> {
53        let branch = context.child();
54        admit_scope(branch.budget, branch.depth)?;
55        let Some(bytes) = self.0 else {
56            return Ok(None);
57        };
58        let field = Field {
59            bytes,
60            context: branch,
61        };
62        field.project(|value, read| {
63            let incompatible = Cell::new(false);
64            let scope = RecoveryContext {
65                read,
66                incompatible: &incompatible,
67            };
68            let projected = project(value, &scope)?;
69            Ok((!incompatible.get()).then_some(projected))
70        })
71    }
72}
73
74impl Serialize for Recoverable<'_> {
75    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
76        self.0.map(Bytes::new).serialize(serializer)
77    }
78}
79
80impl<'de: 'a, 'a> Deserialize<'de> for Recoverable<'a> {
81    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
82        Option::<&Bytes>::deserialize(deserializer).map(|bytes| Self(bytes.map(AsRef::as_ref)))
83    }
84}
85
86/// Projection scope that records unknown required tags and missing required fields.
87///
88/// Projectors still validate each known descendant. The scope owns only the
89/// compatibility result and borrows the same admission meter as its parent.
90pub struct RecoveryContext<'a> {
91    read: &'a ReadContext<'a>,
92    incompatible: &'a Cell<bool>,
93}
94
95impl RecoveryContext<'_> {
96    /// Check a projection with no enclosing option for a marked incompatibility.
97    ///
98    /// # Errors
99    ///
100    /// Returns a projection error first. Returns [Error::Incompatible] if the
101    /// projection completes with a marked incompatibility outside a recovering
102    /// branch.
103    pub fn check<R>(
104        context: &ReadContext<'_>,
105        project: impl FnOnce(&RecoveryContext<'_>) -> Result<R, Error>,
106    ) -> Result<R, Error> {
107        let incompatible = Cell::new(false);
108        let scope = RecoveryContext {
109            read: context,
110            incompatible: &incompatible,
111        };
112        let value = project(&scope)?;
113        context.budget.check()?;
114        if incompatible.get() {
115            return Err(Error::Incompatible);
116        }
117        Ok(value)
118    }
119
120    /// Borrow the current context for ordinary projection and nested branches.
121    #[must_use]
122    pub const fn read_context(&self) -> &ReadContext<'_> {
123        self.read
124    }
125
126    /// Admit one additional structural level within this scope.
127    ///
128    /// # Errors
129    ///
130    /// Returns the depth or work refusal or a projection error.
131    pub fn nested<R>(
132        &self,
133        project: impl FnOnce(&RecoveryContext<'_>) -> Result<R, Error>,
134    ) -> Result<R, Error> {
135        self.read.nested(|read| {
136            project(&RecoveryContext {
137                read,
138                incompatible: self.incompatible,
139            })
140        })
141    }
142
143    /// Project a known field at its own admitted depth within this scope.
144    ///
145    /// # Errors
146    ///
147    /// Returns a typed field error or a projection error. A field from a
148    /// different admission context is malformed.
149    pub fn project_field<'de, T: Deserialize<'de>, R>(
150        &self,
151        field: Field<'_, 'de>,
152        project: impl FnOnce(T, &RecoveryContext<'_>) -> Result<R, Error>,
153    ) -> Result<R, Error> {
154        if !core::ptr::eq(self.read.budget, field.context.budget) {
155            return Err(Error::Malformed);
156        }
157        field.project(|value, read| {
158            project(
159                value,
160                &RecoveryContext {
161                    read,
162                    incompatible: self.incompatible,
163                },
164            )
165        })
166    }
167
168    /// Mark a missing required extension in the reader's schema.
169    ///
170    /// Call this only after a complete [extension visit](super::Extensions::visit)
171    /// has validated every entry header and known value. Continue projecting
172    /// the remaining known siblings and propagate their errors.
173    pub fn missing_required(&self) {
174        self.incompatible.set(true);
175    }
176
177    /// Map a required open variant and mark a well-formed unknown tag.
178    ///
179    /// Return [None] from the callback only for unknown tags. Known tags must
180    /// check their typed payloads. The result is absent until the enclosing
181    /// projection decides whether it can return the full value.
182    ///
183    /// # Errors
184    ///
185    /// Returns malformed for a zero tag, and propagates allowance and callback
186    /// errors.
187    pub fn required_open<'de, R>(
188        &self,
189        open: OpaqueOpen<'de>,
190        visit: impl FnOnce(u32, Field<'_, 'de>) -> Result<Option<R>, Error>,
191    ) -> Result<Option<R>, Error> {
192        let value = open.visit(self.read, visit)?.ok_or(Error::Malformed)?;
193        if value.is_none() {
194            self.incompatible.set(true);
195        }
196        Ok(value)
197    }
198}