use aws_smithy_types::{Blob, DateTime};
macro_rules! delegate_method {
($($(#[$meta:meta])* $wrapper_name:ident => $encoder_name:ident($($param_name:ident : $param_type:ty),*);)+) => {
$(
pub fn $wrapper_name(&mut self, $($param_name: $param_type),*) -> &mut Self {
self.encoder.$encoder_name($($param_name)*).expect(INFALLIBLE_WRITE);
self
}
)+
};
}
#[derive(Debug, Clone)]
pub struct Encoder {
encoder: minicbor::Encoder<Vec<u8>>,
}
const INFALLIBLE_WRITE: &str = "write failed";
impl Encoder {
pub fn new(writer: Vec<u8>) -> Self {
Self {
encoder: minicbor::Encoder::new(writer),
}
}
delegate_method! {
begin_map => begin_map();
str => str(x: &str);
boolean => bool(x: bool);
byte => i8(x: i8);
short => i16(x: i16);
integer => i32(x: i32);
long => i64(x: i64);
float => f32(x: f32);
double => f64(x: f64);
null => null();
end => end();
}
pub fn blob(&mut self, x: &Blob) -> &mut Self {
self.encoder.bytes(x.as_ref()).expect(INFALLIBLE_WRITE);
self
}
pub fn array(&mut self, len: usize) -> &mut Self {
self.encoder
.array(len.try_into().expect("`usize` to `u64` conversion failed"))
.expect(INFALLIBLE_WRITE);
self
}
pub fn map(&mut self, len: usize) -> &mut Self {
self.encoder
.map(len.try_into().expect("`usize` to `u64` conversion failed"))
.expect(INFALLIBLE_WRITE);
self
}
pub fn timestamp(&mut self, x: &DateTime) -> &mut Self {
self.encoder
.tag(minicbor::data::Tag::from(
minicbor::data::IanaTag::Timestamp,
))
.expect(INFALLIBLE_WRITE);
self.encoder.f64(x.as_secs_f64()).expect(INFALLIBLE_WRITE);
self
}
pub fn into_writer(self) -> Vec<u8> {
self.encoder.into_writer()
}
}