spacetimedb_sats/
satn.rs

1use crate::{
2    algebraic_value::ser::ValueSerializer,
3    ser::{self, Serialize},
4    ProductType,
5};
6use crate::{i256, u256};
7use core::fmt;
8use core::fmt::Write as _;
9use derive_more::{From, Into};
10
11/// An extension trait for [`Serialize`] providing formatting methods.
12pub trait Satn: ser::Serialize {
13    /// Formats the value using the SATN data format into the formatter `f`.
14    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
15        Writer::with(f, |f| self.serialize(SatnFormatter { f }))?;
16        Ok(())
17    }
18
19    /// Formats the value using the postgres SATN(SatnFormatter { f }, /* AlgebraicType */) formatter `f`.
20    fn fmt_psql(&self, f: &mut fmt::Formatter, ty: &ProductType) -> fmt::Result {
21        Writer::with(f, |f| {
22            self.serialize(PsqlFormatter {
23                fmt: SatnFormatter { f },
24                ty,
25            })
26        })?;
27        Ok(())
28    }
29
30    /// Formats the value using the SATN data format into the returned `String`.
31    fn to_satn(&self) -> String {
32        Wrapper::from_ref(self).to_string()
33    }
34
35    /// Pretty prints the value using the SATN data format into the returned `String`.
36    fn to_satn_pretty(&self) -> String {
37        format!("{:#}", Wrapper::from_ref(self))
38    }
39}
40
41impl<T: ser::Serialize + ?Sized> Satn for T {}
42
43/// A wrapper around a `T: Satn`
44/// providing `Display` and `Debug` implementations
45/// that uses the SATN formatting for `T`.
46#[repr(transparent)]
47pub struct Wrapper<T: ?Sized>(pub T);
48
49impl<T: ?Sized> Wrapper<T> {
50    /// Converts `&T` to `&Wrapper<T>`.
51    pub fn from_ref(t: &T) -> &Self {
52        // SAFETY: `repr(transparent)` turns the ABI of `T`
53        // into the same as `Self` so we can also cast `&T` to `&Self`.
54        unsafe { &*(t as *const T as *const Self) }
55    }
56}
57
58impl<T: Satn + ?Sized> fmt::Display for Wrapper<T> {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        self.0.fmt(f)
61    }
62}
63
64impl<T: Satn + ?Sized> fmt::Debug for Wrapper<T> {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        self.0.fmt(f)
67    }
68}
69
70/// A wrapper around a `T: Satn`
71/// providing `Display` and `Debug` implementations
72/// that uses postgres SATN formatting for `T`.
73pub struct PsqlWrapper<'a, T: ?Sized> {
74    pub ty: &'a ProductType,
75    pub value: T,
76}
77
78impl<T: ?Sized> PsqlWrapper<'_, T> {
79    /// Converts `&T` to `&PsqlWrapper<T>`.
80    pub fn from_ref(t: &T) -> &Self {
81        // SAFETY: `repr(transparent)` turns the ABI of `T`
82        // into the same as `Self` so we can also cast `&T` to `&Self`.
83        unsafe { &*(t as *const T as *const Self) }
84    }
85}
86
87impl<T: Satn + ?Sized> fmt::Display for PsqlWrapper<'_, T> {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        self.value.fmt_psql(f, self.ty)
90    }
91}
92
93impl<T: Satn + ?Sized> fmt::Debug for PsqlWrapper<'_, T> {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        self.value.fmt_psql(f, self.ty)
96    }
97}
98
99/// Wraps a writer for formatting lists separated by `SEP` into it.
100struct EntryWrapper<'a, 'f, const SEP: char> {
101    /// The writer we're formatting into.
102    fmt: Writer<'a, 'f>,
103    /// Whether there were any fields.
104    /// Initially `false` and then `true` after calling [`.entry(..)`](EntryWrapper::entry).
105    has_fields: bool,
106}
107
108impl<'a, 'f, const SEP: char> EntryWrapper<'a, 'f, SEP> {
109    /// Constructs the entry wrapper using the writer `fmt`.
110    fn new(fmt: Writer<'a, 'f>) -> Self {
111        Self { fmt, has_fields: false }
112    }
113
114    /// Formats another entry in the larger structure.
115    ///
116    /// The formatting for the element / entry itself is provided by the function `entry`.
117    fn entry(&mut self, entry: impl FnOnce(Writer) -> fmt::Result) -> fmt::Result {
118        let res = (|| match &mut self.fmt {
119            Writer::Pretty(f) => {
120                if !self.has_fields {
121                    f.write_char('\n')?;
122                }
123                f.state.indent += 1;
124                entry(Writer::Pretty(f.as_mut()))?;
125                f.write_char(SEP)?;
126                f.write_char('\n')?;
127                f.state.indent -= 1;
128                Ok(())
129            }
130            Writer::Normal(f) => {
131                if self.has_fields {
132                    f.write_char(SEP)?;
133                    f.write_char(' ')?;
134                }
135                entry(Writer::Normal(f))
136            }
137        })();
138        self.has_fields = true;
139        res
140    }
141}
142
143/// An implementation of [`fmt::Write`] supporting indented and non-idented formatting.
144enum Writer<'a, 'f> {
145    /// Uses the standard library's formatter i.e. plain formatting.
146    Normal(&'a mut fmt::Formatter<'f>),
147    /// Uses indented formatting.
148    Pretty(IndentedWriter<'a, 'f>),
149}
150
151impl<'f> Writer<'_, 'f> {
152    /// Provided with a formatter `f`, runs `func` provided with a `Writer`.
153    fn with<R>(f: &mut fmt::Formatter<'_>, func: impl FnOnce(Writer<'_, '_>) -> R) -> R {
154        let mut state;
155        // We use `alternate`, i.e., the `#` flag to let the user trigger pretty printing.
156        let f = if f.alternate() {
157            state = IndentState {
158                indent: 0,
159                on_newline: true,
160            };
161            Writer::Pretty(IndentedWriter { f, state: &mut state })
162        } else {
163            Writer::Normal(f)
164        };
165        func(f)
166    }
167
168    /// Returns a sub-writer without moving `self`.
169    fn as_mut(&mut self) -> Writer<'_, 'f> {
170        match self {
171            Writer::Normal(f) => Writer::Normal(f),
172            Writer::Pretty(f) => Writer::Pretty(f.as_mut()),
173        }
174    }
175}
176
177/// A formatter that adds decoration atop of the standard library's formatter.
178struct IndentedWriter<'a, 'f> {
179    f: &'a mut fmt::Formatter<'f>,
180    state: &'a mut IndentState,
181}
182
183/// The indentation state.
184struct IndentState {
185    /// Number of tab indentations to make.
186    indent: u32,
187    /// Whether we were last on a newline.
188    on_newline: bool,
189}
190
191impl<'f> IndentedWriter<'_, 'f> {
192    /// Returns a sub-writer without moving `self`.
193    fn as_mut(&mut self) -> IndentedWriter<'_, 'f> {
194        IndentedWriter {
195            f: self.f,
196            state: self.state,
197        }
198    }
199}
200
201impl fmt::Write for IndentedWriter<'_, '_> {
202    fn write_str(&mut self, s: &str) -> fmt::Result {
203        for s in s.split_inclusive('\n') {
204            if self.state.on_newline {
205                // Indent 4 characters times the indentation level.
206                for _ in 0..self.state.indent {
207                    self.f.write_str("    ")?;
208                }
209            }
210
211            self.state.on_newline = s.ends_with('\n');
212            self.f.write_str(s)?;
213        }
214        Ok(())
215    }
216}
217
218impl fmt::Write for Writer<'_, '_> {
219    fn write_str(&mut self, s: &str) -> fmt::Result {
220        match self {
221            Writer::Normal(f) => f.write_str(s),
222            Writer::Pretty(f) => f.write_str(s),
223        }
224    }
225}
226
227/// Provides the SATN data format implementing [`Serializer`](ser::Serializer).
228struct SatnFormatter<'a, 'f> {
229    /// The sink / writer / output / formatter.
230    f: Writer<'a, 'f>,
231}
232
233/// An error occured during serialization to the SATS data format.
234#[derive(From, Into)]
235struct SatnError(fmt::Error);
236
237impl ser::Error for SatnError {
238    fn custom<T: fmt::Display>(_msg: T) -> Self {
239        Self(fmt::Error)
240    }
241}
242
243impl SatnFormatter<'_, '_> {
244    /// Writes `args` formatted to `self`.
245    #[inline(always)]
246    fn write_fmt(&mut self, args: fmt::Arguments) -> Result<(), SatnError> {
247        self.f.write_fmt(args)?;
248        Ok(())
249    }
250}
251
252impl<'a, 'f> ser::Serializer for SatnFormatter<'a, 'f> {
253    type Ok = ();
254    type Error = SatnError;
255    type SerializeArray = ArrayFormatter<'a, 'f>;
256    type SerializeSeqProduct = SeqFormatter<'a, 'f>;
257    type SerializeNamedProduct = NamedFormatter<'a, 'f>;
258
259    fn serialize_bool(mut self, v: bool) -> Result<Self::Ok, Self::Error> {
260        write!(self, "{v}")
261    }
262    fn serialize_u8(mut self, v: u8) -> Result<Self::Ok, Self::Error> {
263        write!(self, "{v}")
264    }
265    fn serialize_u16(mut self, v: u16) -> Result<Self::Ok, Self::Error> {
266        write!(self, "{v}")
267    }
268    fn serialize_u32(mut self, v: u32) -> Result<Self::Ok, Self::Error> {
269        write!(self, "{v}")
270    }
271    fn serialize_u64(mut self, v: u64) -> Result<Self::Ok, Self::Error> {
272        write!(self, "{v}")
273    }
274    fn serialize_u128(mut self, v: u128) -> Result<Self::Ok, Self::Error> {
275        write!(self, "{v}")
276    }
277    fn serialize_u256(mut self, v: u256) -> Result<Self::Ok, Self::Error> {
278        write!(self, "{v}")
279    }
280    fn serialize_i8(mut self, v: i8) -> Result<Self::Ok, Self::Error> {
281        write!(self, "{v}")
282    }
283    fn serialize_i16(mut self, v: i16) -> Result<Self::Ok, Self::Error> {
284        write!(self, "{v}")
285    }
286    fn serialize_i32(mut self, v: i32) -> Result<Self::Ok, Self::Error> {
287        write!(self, "{v}")
288    }
289    fn serialize_i64(mut self, v: i64) -> Result<Self::Ok, Self::Error> {
290        write!(self, "{v}")
291    }
292    fn serialize_i128(mut self, v: i128) -> Result<Self::Ok, Self::Error> {
293        write!(self, "{v}")
294    }
295    fn serialize_i256(mut self, v: i256) -> Result<Self::Ok, Self::Error> {
296        write!(self, "{v}")
297    }
298    fn serialize_f32(mut self, v: f32) -> Result<Self::Ok, Self::Error> {
299        write!(self, "{v}")
300    }
301    fn serialize_f64(mut self, v: f64) -> Result<Self::Ok, Self::Error> {
302        write!(self, "{v}")
303    }
304
305    fn serialize_str(mut self, v: &str) -> Result<Self::Ok, Self::Error> {
306        write!(self, "\"{}\"", v)
307    }
308
309    fn serialize_bytes(mut self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
310        write!(self, "0x{}", hex::encode(v))
311    }
312
313    fn serialize_array(mut self, _len: usize) -> Result<Self::SerializeArray, Self::Error> {
314        write!(self, "[")?; // Closed via `.end()`.
315        Ok(ArrayFormatter {
316            f: EntryWrapper::new(self.f),
317        })
318    }
319
320    fn serialize_seq_product(self, len: usize) -> Result<Self::SerializeSeqProduct, Self::Error> {
321        // Delegate to named products handling of element formatting.
322        self.serialize_named_product(len).map(|inner| SeqFormatter { inner })
323    }
324
325    fn serialize_named_product(mut self, _len: usize) -> Result<Self::SerializeNamedProduct, Self::Error> {
326        write!(self, "(")?; // Closed via `.end()`.
327        Ok(NamedFormatter {
328            f: EntryWrapper::new(self.f),
329            idx: 0,
330        })
331    }
332
333    fn serialize_variant<T: ser::Serialize + ?Sized>(
334        mut self,
335        _tag: u8,
336        name: Option<&str>,
337        value: &T,
338    ) -> Result<Self::Ok, Self::Error> {
339        write!(self, "(")?;
340        EntryWrapper::<','>::new(self.f.as_mut()).entry(|mut f| {
341            if let Some(name) = name {
342                write!(f, "{}", name)?;
343            }
344            write!(f, " = ")?;
345            value.serialize(SatnFormatter { f })?;
346            Ok(())
347        })?;
348        write!(self, ")")
349    }
350
351    unsafe fn serialize_bsatn(self, ty: &crate::AlgebraicType, bsatn: &[u8]) -> Result<Self::Ok, Self::Error> {
352        // TODO(Centril): Consider instead deserializing the `bsatn` through a
353        // deserializer that serializes into `self` directly.
354
355        // First convert the BSATN to an `AlgebraicValue`.
356        // SAFETY: Forward caller requirements of this method to that we are calling.
357        let res = unsafe { ValueSerializer.serialize_bsatn(ty, bsatn) };
358        let value = res.unwrap_or_else(|x| match x {});
359
360        // Then serialize that.
361        value.serialize(self)
362    }
363
364    unsafe fn serialize_bsatn_in_chunks<'c, I: Clone + Iterator<Item = &'c [u8]>>(
365        self,
366        ty: &crate::AlgebraicType,
367        total_bsatn_len: usize,
368        bsatn: I,
369    ) -> Result<Self::Ok, Self::Error> {
370        // TODO(Centril): Unlike above, in this case we must at minimum concatenate `bsatn`
371        // before we can do the piping mentioned above, but that's better than
372        // serializing to `AlgebraicValue` first, so consider that.
373
374        // First convert the BSATN to an `AlgebraicValue`.
375        // SAFETY: Forward caller requirements of this method to that we are calling.
376        let res = unsafe { ValueSerializer.serialize_bsatn_in_chunks(ty, total_bsatn_len, bsatn) };
377        let value = res.unwrap_or_else(|x| match x {});
378
379        // Then serialize that.
380        value.serialize(self)
381    }
382
383    unsafe fn serialize_str_in_chunks<'c, I: Clone + Iterator<Item = &'c [u8]>>(
384        self,
385        total_len: usize,
386        string: I,
387    ) -> Result<Self::Ok, Self::Error> {
388        // First convert the `string` to an `AlgebraicValue`.
389        // SAFETY: Forward caller requirements of this method to that we are calling.
390        let res = unsafe { ValueSerializer.serialize_str_in_chunks(total_len, string) };
391        let value = res.unwrap_or_else(|x| match x {});
392
393        // Then serialize that.
394        // This incurs a very minor cost of branching on `AlgebraicValue::String`.
395        value.serialize(self)
396    }
397}
398
399/// Defines the SATN formatting for arrays.
400struct ArrayFormatter<'a, 'f> {
401    /// The formatter for each element separating elements by a `,`.
402    f: EntryWrapper<'a, 'f, ','>,
403}
404
405impl ser::SerializeArray for ArrayFormatter<'_, '_> {
406    type Ok = ();
407    type Error = SatnError;
408
409    fn serialize_element<T: ser::Serialize + ?Sized>(&mut self, elem: &T) -> Result<(), Self::Error> {
410        self.f.entry(|f| elem.serialize(SatnFormatter { f }).map_err(|e| e.0))?;
411        Ok(())
412    }
413
414    fn end(mut self) -> Result<Self::Ok, Self::Error> {
415        write!(self.f.fmt, "]")?;
416        Ok(())
417    }
418}
419
420/// Provides the data format for unnamed products for SATN.
421struct SeqFormatter<'a, 'f> {
422    /// Delegates to the named format.
423    inner: NamedFormatter<'a, 'f>,
424}
425
426impl ser::SerializeSeqProduct for SeqFormatter<'_, '_> {
427    type Ok = ();
428    type Error = SatnError;
429
430    fn serialize_element<T: ser::Serialize + ?Sized>(&mut self, elem: &T) -> Result<(), Self::Error> {
431        ser::SerializeNamedProduct::serialize_element(&mut self.inner, None, elem)
432    }
433
434    fn end(self) -> Result<Self::Ok, Self::Error> {
435        ser::SerializeNamedProduct::end(self.inner)
436    }
437}
438
439/// Provides the data format for named products for SATN.
440struct NamedFormatter<'a, 'f> {
441    /// The formatter for each element separating elements by a `,`.
442    f: EntryWrapper<'a, 'f, ','>,
443    /// The index of the element.
444    idx: usize,
445}
446
447impl ser::SerializeNamedProduct for NamedFormatter<'_, '_> {
448    type Ok = ();
449    type Error = SatnError;
450
451    fn serialize_element<T: ser::Serialize + ?Sized>(
452        &mut self,
453        name: Option<&str>,
454        elem: &T,
455    ) -> Result<(), Self::Error> {
456        let res = self.f.entry(|mut f| {
457            // Format the name or use the index if unnamed.
458            if let Some(name) = name {
459                write!(f, "{}", name)?;
460            } else {
461                write!(f, "{}", self.idx)?;
462            }
463            write!(f, " = ")?;
464            elem.serialize(SatnFormatter { f })?;
465            Ok(())
466        });
467        self.idx += 1;
468        res?;
469        Ok(())
470    }
471
472    fn end(mut self) -> Result<Self::Ok, Self::Error> {
473        write!(self.f.fmt, ")")?;
474        Ok(())
475    }
476}
477
478/// Provides the data format for named products for `SQL`.
479struct PsqlNamedFormatter<'a, 'f> {
480    /// The formatter for each element separating elements by a `,`.
481    f: EntryWrapper<'a, 'f, ','>,
482    /// The index of the element.
483    idx: usize,
484    /// If is not [Self::is_bytes_or_special] to control if we start with `(`
485    start: bool,
486    /// For checking [Self::is_bytes_or_special]
487    ty: &'a ProductType,
488    /// If the current element is a special type.
489    is_special: bool,
490}
491
492impl ser::SerializeNamedProduct for PsqlNamedFormatter<'_, '_> {
493    type Ok = ();
494    type Error = SatnError;
495
496    fn serialize_element<T: Satn + ser::Serialize + ?Sized>(
497        &mut self,
498        name: Option<&str>,
499        elem: &T,
500    ) -> Result<(), Self::Error> {
501        // For binary data, output in `hex` format and skip the tagging of each value
502        self.is_special = ProductType::is_special_tag(name.unwrap_or_default());
503        self.f.entry(|mut f| {
504            if !self.is_special {
505                if self.start {
506                    write!(f, "(")?; // Closed v
507                    self.start = false;
508                }
509                // Format the name or use the index if unnamed.
510                if let Some(name) = name {
511                    write!(f, "{}", name)?;
512                } else {
513                    write!(f, "{}", self.idx)?;
514                }
515                write!(f, " = ")?;
516            }
517
518            elem.serialize(PsqlFormatter {
519                fmt: SatnFormatter { f },
520                ty: self.ty,
521            })?;
522
523            if !self.is_special {
524                self.idx += 1;
525            }
526            Ok(())
527        })?;
528
529        Ok(())
530    }
531
532    fn end(mut self) -> Result<Self::Ok, Self::Error> {
533        if !self.is_special {
534            write!(self.f.fmt, ")")?;
535        }
536        Ok(())
537    }
538}
539
540/// Provides the data format for unnamed products for `SQL`.
541struct PsqlSeqFormatter<'a, 'f> {
542    /// Delegates to the named format.
543    inner: PsqlNamedFormatter<'a, 'f>,
544}
545
546impl ser::SerializeSeqProduct for PsqlSeqFormatter<'_, '_> {
547    type Ok = ();
548    type Error = SatnError;
549
550    fn serialize_element<T: ser::Serialize + ?Sized>(&mut self, elem: &T) -> Result<(), Self::Error> {
551        ser::SerializeNamedProduct::serialize_element(&mut self.inner, None, elem)
552    }
553
554    fn end(self) -> Result<Self::Ok, Self::Error> {
555        ser::SerializeNamedProduct::end(self.inner)
556    }
557}
558
559/// An implementation of [`Serializer`](ser::Serializer) for `SQL` output.
560struct PsqlFormatter<'a, 'f> {
561    fmt: SatnFormatter<'a, 'f>,
562    ty: &'a ProductType,
563}
564
565impl<'a, 'f> ser::Serializer for PsqlFormatter<'a, 'f> {
566    type Ok = ();
567    type Error = SatnError;
568    type SerializeArray = ArrayFormatter<'a, 'f>;
569    type SerializeSeqProduct = PsqlSeqFormatter<'a, 'f>;
570    type SerializeNamedProduct = PsqlNamedFormatter<'a, 'f>;
571
572    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
573        self.fmt.serialize_bool(v)
574    }
575    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
576        self.fmt.serialize_u8(v)
577    }
578    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
579        self.fmt.serialize_u16(v)
580    }
581    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
582        self.fmt.serialize_u32(v)
583    }
584    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
585        self.fmt.serialize_u64(v)
586    }
587    fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
588        self.fmt.serialize_u128(v)
589    }
590    fn serialize_u256(self, v: u256) -> Result<Self::Ok, Self::Error> {
591        self.fmt.serialize_u256(v)
592    }
593    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
594        self.fmt.serialize_i8(v)
595    }
596    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
597        self.fmt.serialize_i16(v)
598    }
599    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
600        self.fmt.serialize_i32(v)
601    }
602    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
603        self.fmt.serialize_i64(v)
604    }
605    fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
606        self.fmt.serialize_i128(v)
607    }
608    fn serialize_i256(self, v: i256) -> Result<Self::Ok, Self::Error> {
609        self.fmt.serialize_i256(v)
610    }
611    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
612        self.fmt.serialize_f32(v)
613    }
614    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
615        self.fmt.serialize_f64(v)
616    }
617
618    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
619        self.fmt.serialize_str(v)
620    }
621
622    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
623        self.fmt.serialize_bytes(v)
624    }
625
626    fn serialize_array(self, len: usize) -> Result<Self::SerializeArray, Self::Error> {
627        self.fmt.serialize_array(len)
628    }
629
630    fn serialize_seq_product(self, len: usize) -> Result<Self::SerializeSeqProduct, Self::Error> {
631        Ok(PsqlSeqFormatter {
632            inner: self.serialize_named_product(len)?,
633        })
634    }
635
636    fn serialize_named_product(self, _len: usize) -> Result<Self::SerializeNamedProduct, Self::Error> {
637        Ok(PsqlNamedFormatter {
638            f: EntryWrapper::new(self.fmt.f),
639            idx: 0,
640            start: true,
641            ty: self.ty,
642            is_special: false,
643        })
644    }
645
646    fn serialize_variant<T: ser::Serialize + ?Sized>(
647        self,
648        tag: u8,
649        name: Option<&str>,
650        value: &T,
651    ) -> Result<Self::Ok, Self::Error> {
652        self.fmt.serialize_variant(tag, name, value)
653    }
654
655    unsafe fn serialize_bsatn(self, ty: &crate::AlgebraicType, bsatn: &[u8]) -> Result<Self::Ok, Self::Error> {
656        // SAFETY: Forward caller requirements of this method to that we are calling.
657        unsafe { self.fmt.serialize_bsatn(ty, bsatn) }
658    }
659
660    unsafe fn serialize_bsatn_in_chunks<'c, I: Clone + Iterator<Item = &'c [u8]>>(
661        self,
662        ty: &crate::AlgebraicType,
663        total_bsatn_len: usize,
664        bsatn: I,
665    ) -> Result<Self::Ok, Self::Error> {
666        // SAFETY: Forward caller requirements of this method to that we are calling.
667        unsafe { self.fmt.serialize_bsatn_in_chunks(ty, total_bsatn_len, bsatn) }
668    }
669
670    unsafe fn serialize_str_in_chunks<'c, I: Clone + Iterator<Item = &'c [u8]>>(
671        self,
672        total_len: usize,
673        string: I,
674    ) -> Result<Self::Ok, Self::Error> {
675        // SAFETY: Forward caller requirements of this method to that we are calling.
676        unsafe { self.fmt.serialize_str_in_chunks(total_len, string) }
677    }
678}