spacetimedb_sats/
satn.rs

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