moq_transfork/coding/
encode.rsuse std::{sync::Arc, time};
use super::Sizer;
pub trait Encode: Sized {
fn encode<W: bytes::BufMut>(&self, w: &mut W);
fn encode_size(&self) -> usize {
let mut sizer = Sizer::default();
self.encode(&mut sizer);
sizer.size
}
}
impl Encode for u8 {
fn encode<W: bytes::BufMut>(&self, w: &mut W) {
w.put_u8(*self);
}
}
impl Encode for String {
fn encode<W: bytes::BufMut>(&self, w: &mut W) {
self.as_str().encode(w)
}
}
impl Encode for &str {
fn encode<W: bytes::BufMut>(&self, w: &mut W) {
self.len().encode(w);
w.put(self.as_bytes());
}
}
impl Encode for time::Duration {
fn encode<W: bytes::BufMut>(&self, w: &mut W) {
let v: u64 = self.as_millis().try_into().expect("duration too large");
v.encode(w);
}
}
impl Encode for i8 {
fn encode<W: bytes::BufMut>(&self, w: &mut W) {
w.put_u8(((*self as i16) + 128) as u8);
}
}
impl<T: Encode> Encode for &[T] {
fn encode<W: bytes::BufMut>(&self, w: &mut W) {
self.len().encode(w);
for item in self.iter() {
item.encode(w);
}
}
}
impl<T: Encode> Encode for Vec<T> {
fn encode<W: bytes::BufMut>(&self, w: &mut W) {
self.len().encode(w);
for item in self.iter() {
item.encode(w);
}
}
}
impl Encode for bytes::Bytes {
fn encode<W: bytes::BufMut>(&self, w: &mut W) {
self.len().encode(w);
w.put_slice(self);
}
}
impl<T: Encode> Encode for Arc<T> {
fn encode<W: bytes::BufMut>(&self, w: &mut W) {
(**self).encode(w);
}
}