musli_json/en/
array_encoder.rs

1use core::mem::take;
2
3use musli::en::SequenceEncoder;
4use musli::Context;
5use musli_utils::Writer;
6
7use super::JsonEncoder;
8
9/// Encoder for a JSON array.
10pub(crate) struct JsonArrayEncoder<'a, W, C: ?Sized> {
11    cx: &'a C,
12    first: bool,
13    end: &'static [u8],
14    writer: W,
15}
16
17impl<'a, W, C> JsonArrayEncoder<'a, W, C>
18where
19    W: Writer,
20    C: ?Sized + Context,
21{
22    #[inline]
23    pub(super) fn new(cx: &'a C, writer: W) -> Result<Self, C::Error> {
24        Self::with_end(cx, writer, b"]")
25    }
26
27    #[inline]
28    pub(super) fn with_end(cx: &'a C, mut writer: W, end: &'static [u8]) -> Result<Self, C::Error> {
29        writer.write_byte(cx, b'[')?;
30
31        Ok(Self {
32            cx,
33            first: true,
34            end,
35            writer,
36        })
37    }
38}
39
40impl<'a, W, C> SequenceEncoder for JsonArrayEncoder<'a, W, C>
41where
42    W: Writer,
43    C: ?Sized + Context,
44{
45    type Cx = C;
46    type Ok = ();
47    type EncodeNext<'this> = JsonEncoder<'a, W::Mut<'this>, C>
48    where
49        Self: 'this;
50
51    #[inline]
52    fn encode_next(&mut self) -> Result<Self::EncodeNext<'_>, C::Error> {
53        if !take(&mut self.first) {
54            self.writer.write_byte(self.cx, b',')?;
55        }
56
57        Ok(JsonEncoder::new(self.cx, self.writer.borrow_mut()))
58    }
59
60    #[inline]
61    fn finish_sequence(mut self) -> Result<Self::Ok, C::Error> {
62        self.writer.write_bytes(self.cx, self.end)
63    }
64}