musli/descriptive/
en.rs

1use core::fmt;
2use core::marker::PhantomData;
3
4use crate::en::{
5    Encode, Encoder, EntriesEncoder, EntryEncoder, MapEncoder, SequenceEncoder, VariantEncoder,
6};
7use crate::hint::{MapHint, SequenceHint};
8use crate::int::continuation as c;
9use crate::storage::en::StorageEncoder;
10use crate::writer::BufWriter;
11use crate::{Context, Options, Writer};
12
13use super::integer_encoding::{encode_typed_signed, encode_typed_unsigned};
14use super::tag::{
15    F32, F64, I8, I16, I32, I64, I128, ISIZE, Kind, Mark, Tag, U8, U16, U32, U64, U128, USIZE,
16};
17
18const VARIANT: Tag = Tag::from_mark(Mark::Variant);
19
20/// A very simple encoder.
21pub struct SelfEncoder<const OPT: Options, W, C, M> {
22    cx: C,
23    writer: W,
24    _marker: PhantomData<M>,
25}
26
27impl<const OPT: Options, W, C, M> SelfEncoder<OPT, W, C, M> {
28    /// Construct a new fixed width message encoder.
29    #[inline]
30    pub(crate) fn new(cx: C, writer: W) -> Self {
31        Self {
32            cx,
33            writer,
34            _marker: PhantomData,
35        }
36    }
37}
38
39pub struct SelfPackEncoder<const OPT: Options, W, C, M>
40where
41    C: Context,
42{
43    cx: C,
44    writer: W,
45    buffer: BufWriter<C::Allocator>,
46    _marker: PhantomData<M>,
47}
48
49impl<const OPT: Options, W, C, M> SelfPackEncoder<OPT, W, C, M>
50where
51    C: Context,
52{
53    /// Construct a new fixed width message encoder.
54    #[inline]
55    pub(crate) fn new(cx: C, writer: W) -> Self {
56        Self {
57            cx,
58            writer,
59            buffer: BufWriter::new(cx.alloc()),
60            _marker: PhantomData,
61        }
62    }
63}
64
65#[crate::trait_defaults(crate)]
66impl<const OPT: Options, W, C, M> Encoder for SelfEncoder<OPT, W, C, M>
67where
68    W: Writer,
69    C: Context,
70    M: 'static,
71{
72    type Cx = C;
73    type Error = C::Error;
74    type Mode = M;
75    type EncodePack = SelfPackEncoder<OPT, W, C, M>;
76    type EncodeSome = Self;
77    type EncodeSequence = Self;
78    type EncodeMap = Self;
79    type EncodeMapEntries = Self;
80    type EncodeVariant = Self;
81    type EncodeSequenceVariant = Self;
82    type EncodeMapVariant = Self;
83
84    #[inline]
85    fn cx(&self) -> Self::Cx {
86        self.cx
87    }
88
89    #[inline]
90    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        write!(f, "type supported by the descriptive encoder")
92    }
93
94    #[inline]
95    fn encode<T>(self, value: T) -> Result<(), Self::Error>
96    where
97        T: Encode<Self::Mode>,
98    {
99        value.encode(self)
100    }
101
102    #[inline]
103    fn encode_empty(mut self) -> Result<(), Self::Error> {
104        self.writer
105            .write_byte(self.cx, Tag::from_mark(Mark::Unit).byte())?;
106        Ok(())
107    }
108
109    #[inline]
110    fn encode_pack(self) -> Result<Self::EncodePack, Self::Error> {
111        Ok(SelfPackEncoder::new(self.cx, self.writer))
112    }
113
114    #[inline]
115    fn encode_array<const N: usize>(self, array: &[u8; N]) -> Result<(), Self::Error> {
116        self.encode_bytes(array)
117    }
118
119    #[inline]
120    fn encode_bytes(mut self, bytes: &[u8]) -> Result<(), Self::Error> {
121        encode_prefix::<OPT, _, _>(self.cx, self.writer.borrow_mut(), Kind::Bytes, bytes.len())?;
122        self.writer.write_bytes(self.cx, bytes)?;
123        Ok(())
124    }
125
126    #[inline]
127    fn encode_bytes_vectored<I>(mut self, len: usize, vectors: I) -> Result<(), Self::Error>
128    where
129        I: IntoIterator<Item: AsRef<[u8]>>,
130    {
131        encode_prefix::<OPT, _, _>(self.cx, self.writer.borrow_mut(), Kind::Bytes, len)?;
132
133        for bytes in vectors {
134            self.writer.write_bytes(self.cx, bytes.as_ref())?;
135        }
136
137        Ok(())
138    }
139
140    #[inline]
141    fn encode_string(mut self, string: &str) -> Result<(), Self::Error> {
142        encode_prefix::<OPT, _, _>(
143            self.cx,
144            self.writer.borrow_mut(),
145            Kind::String,
146            string.len(),
147        )?;
148        self.writer.write_bytes(self.cx, string.as_bytes())?;
149        Ok(())
150    }
151
152    #[inline]
153    fn encode_bool(mut self, value: bool) -> Result<(), Self::Error> {
154        const TRUE: Tag = Tag::from_mark(Mark::True);
155        const FALSE: Tag = Tag::from_mark(Mark::False);
156
157        self.writer
158            .write_byte(self.cx, if value { TRUE } else { FALSE }.byte())
159    }
160
161    #[inline]
162    fn encode_char(mut self, value: char) -> Result<(), Self::Error> {
163        const CHAR: Tag = Tag::from_mark(Mark::Char);
164        self.writer.write_byte(self.cx, CHAR.byte())?;
165        c::encode(self.cx, self.writer.borrow_mut(), value as u32)
166    }
167
168    #[inline]
169    fn encode_u8(mut self, value: u8) -> Result<(), Self::Error> {
170        encode_typed_unsigned(self.cx, self.writer.borrow_mut(), U8, value)
171    }
172
173    #[inline]
174    fn encode_u16(mut self, value: u16) -> Result<(), Self::Error> {
175        encode_typed_unsigned(self.cx, self.writer.borrow_mut(), U16, value)
176    }
177
178    #[inline]
179    fn encode_u32(mut self, value: u32) -> Result<(), Self::Error> {
180        encode_typed_unsigned(self.cx, self.writer.borrow_mut(), U32, value)
181    }
182
183    #[inline]
184    fn encode_u64(mut self, value: u64) -> Result<(), Self::Error> {
185        encode_typed_unsigned(self.cx, self.writer.borrow_mut(), U64, value)
186    }
187
188    #[inline]
189    fn encode_u128(mut self, value: u128) -> Result<(), Self::Error> {
190        encode_typed_unsigned(self.cx, self.writer.borrow_mut(), U128, value)
191    }
192
193    #[inline]
194    fn encode_i8(mut self, value: i8) -> Result<(), Self::Error> {
195        encode_typed_signed(self.cx, self.writer.borrow_mut(), I8, value)
196    }
197
198    #[inline]
199    fn encode_i16(mut self, value: i16) -> Result<(), Self::Error> {
200        encode_typed_signed(self.cx, self.writer.borrow_mut(), I16, value)
201    }
202
203    #[inline]
204    fn encode_i32(mut self, value: i32) -> Result<(), Self::Error> {
205        encode_typed_signed(self.cx, self.writer.borrow_mut(), I32, value)
206    }
207
208    #[inline]
209    fn encode_i64(mut self, value: i64) -> Result<(), Self::Error> {
210        encode_typed_signed(self.cx, self.writer.borrow_mut(), I64, value)
211    }
212
213    #[inline]
214    fn encode_i128(mut self, value: i128) -> Result<(), Self::Error> {
215        encode_typed_signed(self.cx, self.writer.borrow_mut(), I128, value)
216    }
217
218    #[inline]
219    fn encode_f32(mut self, value: f32) -> Result<(), Self::Error> {
220        encode_typed_unsigned(self.cx, self.writer.borrow_mut(), F32, value.to_bits())
221    }
222
223    #[inline]
224    fn encode_f64(mut self, value: f64) -> Result<(), Self::Error> {
225        encode_typed_unsigned(self.cx, self.writer.borrow_mut(), F64, value.to_bits())
226    }
227
228    #[inline]
229    fn encode_usize(mut self, value: usize) -> Result<(), Self::Error> {
230        encode_typed_unsigned(self.cx, self.writer.borrow_mut(), USIZE, value)
231    }
232
233    #[inline]
234    fn encode_isize(mut self, value: isize) -> Result<(), Self::Error> {
235        encode_typed_signed(self.cx, self.writer.borrow_mut(), ISIZE, value)
236    }
237
238    #[inline]
239    fn encode_some(mut self) -> Result<Self::EncodeSome, Self::Error> {
240        const SOME: Tag = Tag::from_mark(Mark::Some);
241        self.writer.write_byte(self.cx, SOME.byte())?;
242        Ok(self)
243    }
244
245    #[inline]
246    fn encode_none(mut self) -> Result<(), Self::Error> {
247        const NONE: Tag = Tag::from_mark(Mark::None);
248        self.writer.write_byte(self.cx, NONE.byte())?;
249        Ok(())
250    }
251
252    #[inline]
253    fn encode_sequence(
254        mut self,
255        hint: impl SequenceHint,
256    ) -> Result<Self::EncodeSequence, Self::Error> {
257        let size = hint.require(self.cx)?;
258        encode_prefix::<OPT, _, _>(self.cx, self.writer.borrow_mut(), Kind::Sequence, size)?;
259        Ok(self)
260    }
261
262    #[inline]
263    fn encode_map(mut self, hint: impl MapHint) -> Result<Self::EncodeMap, Self::Error> {
264        let size = hint.require(self.cx)?;
265        encode_prefix::<OPT, _, _>(self.cx, self.writer.borrow_mut(), Kind::Map, size)?;
266        Ok(self)
267    }
268
269    #[inline]
270    fn encode_map_entries(
271        mut self,
272        hint: impl MapHint,
273    ) -> Result<Self::EncodeMapEntries, Self::Error> {
274        let size = hint.require(self.cx)?;
275        encode_prefix::<OPT, _, _>(self.cx, self.writer.borrow_mut(), Kind::Map, size)?;
276        Ok(self)
277    }
278
279    #[inline]
280    fn encode_variant(mut self) -> Result<Self::EncodeVariant, Self::Error> {
281        self.writer.write_byte(self.cx, VARIANT.byte())?;
282        Ok(self)
283    }
284
285    #[inline]
286    fn encode_unit_variant<T>(self, tag: &T) -> Result<(), Self::Error>
287    where
288        T: ?Sized + Encode<Self::Mode>,
289    {
290        let mut variant = self.encode_variant()?;
291        variant.encode_tag()?.encode(tag)?;
292        variant.encode_data()?.encode_empty()?;
293        VariantEncoder::finish_variant(variant)?;
294        Ok(())
295    }
296
297    #[inline]
298    fn encode_sequence_variant<T>(
299        mut self,
300        tag: &T,
301        hint: impl SequenceHint,
302    ) -> Result<Self::EncodeSequenceVariant, Self::Error>
303    where
304        T: ?Sized + Encode<Self::Mode>,
305    {
306        self.writer.write_byte(self.cx, VARIANT.byte())?;
307        SelfEncoder::<OPT, _, _, M>::new(self.cx, self.writer.borrow_mut()).encode(tag)?;
308        self.encode_sequence(hint)
309    }
310
311    #[inline]
312    fn encode_map_variant<T>(
313        mut self,
314        tag: &T,
315        hint: impl MapHint,
316    ) -> Result<Self::EncodeMapVariant, Self::Error>
317    where
318        T: ?Sized + Encode<Self::Mode>,
319    {
320        self.writer.write_byte(self.cx, VARIANT.byte())?;
321        SelfEncoder::<OPT, _, _, M>::new(self.cx, self.writer.borrow_mut()).encode(tag)?;
322        self.encode_map(hint)
323    }
324}
325
326impl<const OPT: Options, W, C, M> SequenceEncoder for SelfPackEncoder<OPT, W, C, M>
327where
328    W: Writer,
329    C: Context,
330    M: 'static,
331{
332    type Cx = C;
333    type Error = C::Error;
334    type Mode = M;
335    type EncodeNext<'this>
336        = StorageEncoder<OPT, true, &'this mut BufWriter<C::Allocator>, C, M>
337    where
338        Self: 'this;
339
340    #[inline]
341    fn cx(&self) -> Self::Cx {
342        self.cx
343    }
344
345    #[inline]
346    fn encode_next(&mut self) -> Result<Self::EncodeNext<'_>, Self::Error> {
347        Ok(StorageEncoder::new(self.cx, &mut self.buffer))
348    }
349
350    #[inline]
351    fn finish_sequence(mut self) -> Result<(), Self::Error> {
352        let buffer = self.buffer.into_inner();
353        encode_prefix::<OPT, _, _>(self.cx, self.writer.borrow_mut(), Kind::Bytes, buffer.len())?;
354        self.writer.extend(self.cx, buffer)?;
355        Ok(())
356    }
357}
358
359impl<const OPT: Options, W, C, M> SequenceEncoder for SelfEncoder<OPT, W, C, M>
360where
361    W: Writer,
362    C: Context,
363    M: 'static,
364{
365    type Cx = C;
366    type Error = C::Error;
367    type Mode = M;
368    type EncodeNext<'this>
369        = SelfEncoder<OPT, W::Mut<'this>, C, M>
370    where
371        Self: 'this;
372
373    #[inline]
374    fn cx(&self) -> Self::Cx {
375        self.cx
376    }
377
378    #[inline]
379    fn encode_next(&mut self) -> Result<Self::EncodeNext<'_>, Self::Error> {
380        Ok(SelfEncoder::new(self.cx, self.writer.borrow_mut()))
381    }
382
383    #[inline]
384    fn finish_sequence(self) -> Result<(), Self::Error> {
385        Ok(())
386    }
387}
388
389impl<const OPT: Options, W, C, M> MapEncoder for SelfEncoder<OPT, W, C, M>
390where
391    W: Writer,
392    C: Context,
393    M: 'static,
394{
395    type Cx = C;
396    type Error = C::Error;
397    type Mode = M;
398    type EncodeEntry<'this>
399        = SelfEncoder<OPT, W::Mut<'this>, C, M>
400    where
401        Self: 'this;
402
403    #[inline]
404    fn cx(&self) -> Self::Cx {
405        self.cx
406    }
407
408    #[inline]
409    fn encode_entry(&mut self) -> Result<Self::EncodeEntry<'_>, Self::Error> {
410        Ok(SelfEncoder::new(self.cx, self.writer.borrow_mut()))
411    }
412
413    #[inline]
414    fn finish_map(self) -> Result<(), Self::Error> {
415        Ok(())
416    }
417}
418
419impl<const OPT: Options, W, C, M> EntryEncoder for SelfEncoder<OPT, W, C, M>
420where
421    W: Writer,
422    C: Context,
423    M: 'static,
424{
425    type Cx = C;
426    type Error = C::Error;
427    type Mode = M;
428    type EncodeKey<'this>
429        = SelfEncoder<OPT, W::Mut<'this>, C, M>
430    where
431        Self: 'this;
432    type EncodeValue<'this>
433        = SelfEncoder<OPT, W::Mut<'this>, C, M>
434    where
435        Self: 'this;
436
437    #[inline]
438    fn cx(&self) -> Self::Cx {
439        self.cx
440    }
441
442    #[inline]
443    fn encode_key(&mut self) -> Result<Self::EncodeKey<'_>, Self::Error> {
444        Ok(SelfEncoder::new(self.cx, self.writer.borrow_mut()))
445    }
446
447    #[inline]
448    fn encode_value(&mut self) -> Result<Self::EncodeValue<'_>, Self::Error> {
449        Ok(SelfEncoder::new(self.cx, self.writer.borrow_mut()))
450    }
451
452    #[inline]
453    fn finish_entry(self) -> Result<(), Self::Error> {
454        Ok(())
455    }
456}
457
458impl<const OPT: Options, W, C, M> EntriesEncoder for SelfEncoder<OPT, W, C, M>
459where
460    W: Writer,
461    C: Context,
462    M: 'static,
463{
464    type Cx = C;
465    type Error = C::Error;
466    type Mode = M;
467    type EncodeEntryKey<'this>
468        = SelfEncoder<OPT, W::Mut<'this>, C, M>
469    where
470        Self: 'this;
471    type EncodeEntryValue<'this>
472        = SelfEncoder<OPT, W::Mut<'this>, C, M>
473    where
474        Self: 'this;
475
476    #[inline]
477    fn cx(&self) -> Self::Cx {
478        self.cx
479    }
480
481    #[inline]
482    fn encode_entry_key(&mut self) -> Result<Self::EncodeEntryKey<'_>, Self::Error> {
483        Ok(SelfEncoder::new(self.cx, self.writer.borrow_mut()))
484    }
485
486    #[inline]
487    fn encode_entry_value(&mut self) -> Result<Self::EncodeEntryValue<'_>, Self::Error> {
488        Ok(SelfEncoder::new(self.cx, self.writer.borrow_mut()))
489    }
490
491    #[inline]
492    fn finish_entries(self) -> Result<(), Self::Error> {
493        Ok(())
494    }
495}
496
497impl<const OPT: Options, W, C, M> VariantEncoder for SelfEncoder<OPT, W, C, M>
498where
499    W: Writer,
500    C: Context,
501    M: 'static,
502{
503    type Cx = C;
504    type Error = C::Error;
505    type Mode = M;
506    type EncodeTag<'this>
507        = SelfEncoder<OPT, W::Mut<'this>, C, M>
508    where
509        Self: 'this;
510    type EncodeData<'this>
511        = SelfEncoder<OPT, W::Mut<'this>, C, M>
512    where
513        Self: 'this;
514
515    #[inline]
516    fn cx(&self) -> Self::Cx {
517        self.cx
518    }
519
520    #[inline]
521    fn encode_tag(&mut self) -> Result<Self::EncodeTag<'_>, Self::Error> {
522        Ok(SelfEncoder::new(self.cx, self.writer.borrow_mut()))
523    }
524
525    #[inline]
526    fn encode_data(&mut self) -> Result<Self::EncodeData<'_>, Self::Error> {
527        Ok(SelfEncoder::new(self.cx, self.writer.borrow_mut()))
528    }
529
530    #[inline]
531    fn finish_variant(self) -> Result<(), Self::Error> {
532        Ok(())
533    }
534}
535
536/// Encode a length prefix.
537#[inline]
538fn encode_prefix<const OPT: Options, W, C>(
539    cx: C,
540    mut writer: W,
541    kind: Kind,
542    len: usize,
543) -> Result<(), C::Error>
544where
545    W: Writer,
546    C: Context,
547{
548    let (tag, embedded) = Tag::with_len(kind, len);
549    writer.write_byte(cx, tag.byte())?;
550
551    if !embedded {
552        crate::int::encode_usize::<_, _, OPT>(cx, writer, len)?;
553    }
554
555    Ok(())
556}