moq_lite/coding/
encode.rs1use std::{borrow::Cow, sync::Arc};
2
3pub trait Encode: Sized {
4 fn encode<W: bytes::BufMut>(&self, w: &mut W);
7}
8
9impl Encode for bool {
10 fn encode<W: bytes::BufMut>(&self, w: &mut W) {
11 w.put_u8(*self as u8);
12 }
13}
14
15impl Encode for u8 {
16 fn encode<W: bytes::BufMut>(&self, w: &mut W) {
17 w.put_u8(*self);
18 }
19}
20
21impl Encode for u16 {
22 fn encode<W: bytes::BufMut>(&self, w: &mut W) {
23 w.put_u16(*self);
24 }
25}
26
27impl Encode for String {
28 fn encode<W: bytes::BufMut>(&self, w: &mut W) {
29 self.as_str().encode(w)
30 }
31}
32
33impl Encode for &str {
34 fn encode<W: bytes::BufMut>(&self, w: &mut W) {
35 self.len().encode(w);
36 w.put(self.as_bytes());
37 }
38}
39
40impl Encode for std::time::Duration {
41 fn encode<W: bytes::BufMut>(&self, w: &mut W) {
42 let v: u64 = self.as_micros().try_into().expect("duration too large");
43 v.encode(w);
44 }
45}
46
47impl Encode for i8 {
48 fn encode<W: bytes::BufMut>(&self, w: &mut W) {
49 w.put_u8(((*self as i16) + 128) as u8);
53 }
54}
55
56impl<T: Encode> Encode for &[T] {
57 fn encode<W: bytes::BufMut>(&self, w: &mut W) {
58 self.len().encode(w);
59 for item in self.iter() {
60 item.encode(w);
61 }
62 }
63}
64
65impl Encode for Vec<u8> {
66 fn encode<W: bytes::BufMut>(&self, w: &mut W) {
67 self.len().encode(w);
68 w.put_slice(self);
69 }
70}
71
72impl Encode for bytes::Bytes {
73 fn encode<W: bytes::BufMut>(&self, w: &mut W) {
74 self.len().encode(w);
75 w.put_slice(self);
76 }
77}
78
79impl<T: Encode> Encode for Arc<T> {
80 fn encode<W: bytes::BufMut>(&self, w: &mut W) {
81 (**self).encode(w);
82 }
83}
84
85impl Encode for Cow<'_, str> {
86 fn encode<W: bytes::BufMut>(&self, w: &mut W) {
87 self.len().encode(w);
88 w.put(self.as_bytes());
89 }
90}