aws_multipart_upload/codec/
json_writer.rs

1use crate::AWS_MIN_PART_SIZE;
2use crate::client::part::PartBody;
3use crate::codec::PartEncoder;
4
5use bytes::BufMut as _;
6use serde::Serialize;
7use std::ops::DerefMut;
8
9/// `JsonLinesEncoder` implements `PartEncoder` by writing lines of JSON to the
10/// part.
11#[derive(Debug, Clone)]
12pub struct JsonLinesEncoder {
13    writer: PartBody,
14}
15
16impl JsonLinesEncoder {
17    /// Create a `JsonLinesEncoder`.
18    pub fn new() -> Self {
19        Self::default()
20    }
21}
22
23impl Default for JsonLinesEncoder {
24    fn default() -> Self {
25        Self {
26            writer: PartBody::with_capacity(AWS_MIN_PART_SIZE.as_u64() as usize),
27        }
28    }
29}
30
31impl<Item: Serialize> PartEncoder<Item> for JsonLinesEncoder {
32    type Error = serde_json::Error;
33
34    fn restore(&self) -> Result<Self, Self::Error> {
35        let capacity = self.writer.capacity();
36        Ok(Self {
37            writer: PartBody::with_capacity(capacity),
38        })
39    }
40
41    fn encode(&mut self, item: Item) -> Result<usize, Self::Error> {
42        let it = serde_json::to_vec(&item)?;
43        let bytes = it.len();
44        self.writer.deref_mut().reserve(bytes + 1);
45        self.writer.deref_mut().put(it.as_ref());
46        self.writer.deref_mut().put_u8(b'\n');
47        Ok(bytes + 1)
48    }
49
50    fn flush(&mut self) -> Result<(), Self::Error> {
51        Ok(())
52    }
53
54    fn into_body(self) -> Result<PartBody, Self::Error> {
55        Ok(self.writer)
56    }
57}