musli_descriptive/
en.rs

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