moq_lite/coding/
encode.rs

1use std::{borrow::Cow, sync::Arc};
2
3use bytes::{Bytes, BytesMut};
4
5pub trait Encode<V>: Sized {
6	// Encode the value to the given writer.
7	// This will panic if the Buf is not large enough; use a Vec or encode_size() to check.
8	fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V);
9
10	// Encode the value to a Bytes buffer.
11	fn encode_bytes(&self, v: V) -> Bytes {
12		let mut buf = BytesMut::new();
13		self.encode(&mut buf, v);
14		buf.freeze()
15	}
16}
17
18impl<V> Encode<V> for bool {
19	fn encode<W: bytes::BufMut>(&self, w: &mut W, _: V) {
20		w.put_u8(*self as u8);
21	}
22}
23
24impl<V> Encode<V> for u8 {
25	fn encode<W: bytes::BufMut>(&self, w: &mut W, _: V) {
26		w.put_u8(*self);
27	}
28}
29
30impl<V> Encode<V> for u16 {
31	fn encode<W: bytes::BufMut>(&self, w: &mut W, _: V) {
32		w.put_u16(*self);
33	}
34}
35
36impl<V> Encode<V> for String {
37	fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V) {
38		self.as_str().encode(w, version)
39	}
40}
41
42impl<V> Encode<V> for &str {
43	fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V) {
44		self.len().encode(w, version);
45		w.put(self.as_bytes());
46	}
47}
48
49impl<V> Encode<V> for i8 {
50	fn encode<W: bytes::BufMut>(&self, w: &mut W, _: V) {
51		// This is not the usual way of encoding negative numbers.
52		// i8 doesn't exist in the draft, but we use it instead of u8 for priority.
53		// A default of 0 is more ergonomic for the user than a default of 128.
54		w.put_u8(((*self as i16) + 128) as u8);
55	}
56}
57
58impl<T: Encode<V>, V: Clone> Encode<V> for &[T] {
59	fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V) {
60		self.len().encode(w, version.clone());
61		for item in self.iter() {
62			item.encode(w, version.clone());
63		}
64	}
65}
66
67impl<V> Encode<V> for Vec<u8> {
68	fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V) {
69		self.len().encode(w, version);
70		w.put_slice(self);
71	}
72}
73
74impl<V> Encode<V> for bytes::Bytes {
75	fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V) {
76		self.len().encode(w, version);
77		w.put_slice(self);
78	}
79}
80
81impl<T: Encode<V>, V> Encode<V> for Arc<T> {
82	fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V) {
83		(**self).encode(w, version);
84	}
85}
86
87impl<V> Encode<V> for Cow<'_, str> {
88	fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V) {
89		self.len().encode(w, version);
90		w.put(self.as_bytes());
91	}
92}