moq_lite/coding/
encode.rs

1use std::{borrow::Cow, sync::Arc};
2
3pub trait Encode: Sized {
4	// Encode the value to the given writer.
5	// This will panic if the Buf is not large enough; use a Vec or encode_size() to check.
6	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		// This is not the usual way of encoding negative numbers.
50		// i8 doesn't exist in the draft, but we use it instead of u8 for priority.
51		// A default of 0 is more ergonomic for the user than a default of 128.
52		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}