aws_multipart_upload/codec/
mod.rs

1//! Encoding data in the body of a part upload request.
2//!
3//! This module defines `PartEncoder` and a few select implementations.
4//! `PartEncoder` describes how an item should be written as bytes to a part
5//! upload request body.
6use crate::client::part::PartBody;
7
8use bytes::BufMut;
9
10#[cfg(feature = "csv")]
11#[cfg_attr(docsrs, doc(cfg(feature = "csv")))]
12mod csv_writer;
13#[cfg(feature = "csv")]
14#[cfg_attr(docsrs, doc(cfg(feature = "csv")))]
15pub use csv_writer::CsvEncoder;
16
17mod error;
18pub use error::{EncodeError, EncodeErrorKind};
19
20mod json_writer;
21pub use json_writer::JsonLinesEncoder;
22
23mod lines_writer;
24pub use lines_writer::LinesEncoder;
25
26/// Encoding for items in a part of a multipart upload.
27pub trait PartEncoder<Item> {
28    /// The type of value returned when encoding items is not successful.
29    type Error: EncodeError;
30
31    /// Restore this encoder's state for a new upload.
32    fn restore(&self) -> Result<Self, Self::Error>
33    where
34        Self: Sized;
35
36    /// Encode this item in the part, returning the number of bytes written.
37    fn encode(&mut self, item: Item) -> Result<usize, Self::Error>;
38
39    /// Flush the items in any internal buffer.
40    fn flush(&mut self) -> Result<(), Self::Error>;
41
42    /// Convert the encoder to a `PartBody`.
43    fn into_body(self) -> Result<PartBody, Self::Error>;
44
45    /// Clear the encoder to prepare for a new part.
46    ///
47    /// Override this method to provide an alternative means of building the
48    /// encoder in between uploads if, for example if preparing for a new part is
49    /// different than preparing for a new upload.
50    fn clear(&self) -> Result<Self, Self::Error>
51    where
52        Self: Sized,
53    {
54        self.restore()
55    }
56}
57
58impl<T: AsRef<[u8]>> PartEncoder<T> for PartBody {
59    type Error = std::convert::Infallible;
60
61    fn restore(&self) -> Result<Self, Self::Error> {
62        let capacity = self.capacity();
63        Ok(Self::with_capacity(capacity))
64    }
65
66    fn encode(&mut self, item: T) -> Result<usize, Self::Error> {
67        let buf = item.as_ref();
68        let bytes = buf.len();
69        self.reserve(bytes);
70        self.put(buf);
71        Ok(bytes)
72    }
73
74    fn flush(&mut self) -> Result<(), Self::Error> {
75        Ok(())
76    }
77
78    fn into_body(self) -> Result<PartBody, Self::Error> {
79        Ok(self)
80    }
81}