moq_lite/coding/
encode.rs

1use std::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 u8 {
10	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
11		w.put_u8(*self);
12	}
13}
14
15impl Encode for String {
16	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
17		self.as_str().encode(w)
18	}
19}
20
21impl Encode for &str {
22	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
23		self.len().encode(w);
24		w.put(self.as_bytes());
25	}
26}
27
28impl Encode for std::time::Duration {
29	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
30		let v: u64 = self.as_micros().try_into().expect("duration too large");
31		v.encode(w);
32	}
33}
34
35impl Encode for i8 {
36	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
37		// This is not the usual way of encoding negative numbers.
38		// i8 doesn't exist in the draft, but we use it instead of u8 for priority.
39		// A default of 0 is more ergonomic for the user than a default of 128.
40		w.put_u8(((*self as i16) + 128) as u8);
41	}
42}
43
44impl<T: Encode> Encode for &[T] {
45	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
46		self.len().encode(w);
47		for item in self.iter() {
48			item.encode(w);
49		}
50	}
51}
52
53impl Encode for Vec<u8> {
54	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
55		self.len().encode(w);
56		w.put_slice(self);
57	}
58}
59
60impl Encode for bytes::Bytes {
61	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
62		self.len().encode(w);
63		w.put_slice(self);
64	}
65}
66
67impl<T: Encode> Encode for Arc<T> {
68	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
69		(**self).encode(w);
70	}
71}