moq_lite/coding/
encode.rs1use std::{borrow::Cow, sync::Arc};
2
3use bytes::{Bytes, BytesMut};
4
5pub trait Encode<V>: Sized {
7 fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V);
11
12 fn encode_bytes(&self, v: V) -> Bytes {
16 let mut buf = BytesMut::new();
17 self.encode(&mut buf, v);
18 buf.freeze()
19 }
20}
21
22impl<V> Encode<V> for bool {
23 fn encode<W: bytes::BufMut>(&self, w: &mut W, _: V) {
24 w.put_u8(*self as u8);
25 }
26}
27
28impl<V> Encode<V> for u8 {
29 fn encode<W: bytes::BufMut>(&self, w: &mut W, _: V) {
30 w.put_u8(*self);
31 }
32}
33
34impl<V> Encode<V> for u16 {
35 fn encode<W: bytes::BufMut>(&self, w: &mut W, _: V) {
36 w.put_u16(*self);
37 }
38}
39
40impl<V> Encode<V> for String {
41 fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V) {
42 self.as_str().encode(w, version)
43 }
44}
45
46impl<V> Encode<V> for &str {
47 fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V) {
48 self.len().encode(w, version);
49 w.put(self.as_bytes());
50 }
51}
52
53impl<V> Encode<V> for i8 {
54 fn encode<W: bytes::BufMut>(&self, w: &mut W, _: V) {
55 w.put_u8(((*self as i16) + 128) as u8);
59 }
60}
61
62impl<T: Encode<V>, V: Clone> Encode<V> for &[T] {
63 fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V) {
64 self.len().encode(w, version.clone());
65 for item in self.iter() {
66 item.encode(w, version.clone());
67 }
68 }
69}
70
71impl<V> Encode<V> for Vec<u8> {
72 fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V) {
73 self.len().encode(w, version);
74 w.put_slice(self);
75 }
76}
77
78impl<V> Encode<V> for bytes::Bytes {
79 fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V) {
80 self.len().encode(w, version);
81 w.put_slice(self);
82 }
83}
84
85impl<T: Encode<V>, V> Encode<V> for Arc<T> {
86 fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V) {
87 (**self).encode(w, version);
88 }
89}
90
91impl<V> Encode<V> for Cow<'_, str> {
92 fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V) {
93 self.len().encode(w, version);
94 w.put(self.as_bytes());
95 }
96}