moq_transfork/coding/
encode.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use std::{sync::Arc, time};

use super::Sizer;

pub trait Encode: Sized {
	// Encode the value to the given writer.
	// This will panic if the Buf is not large enough; use a Vec or encode_size() to check.
	fn encode<W: bytes::BufMut>(&self, w: &mut W);

	// Return the size of the encoded value
	// Implementations can override this to provide a more efficient implementation
	fn encode_size(&self) -> usize {
		let mut sizer = Sizer::default();
		self.encode(&mut sizer);
		sizer.size
	}
}

impl Encode for u8 {
	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
		w.put_u8(*self);
	}
}

impl Encode for String {
	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
		self.as_str().encode(w)
	}
}

impl Encode for &str {
	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
		self.len().encode(w);
		w.put(self.as_bytes());
	}
}

impl Encode for time::Duration {
	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
		let v: u64 = self.as_millis().try_into().expect("duration too large");
		v.encode(w);
	}
}

impl Encode for i8 {
	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
		// This is not the usual way of encoding negative numbers.
		// i8 doesn't exist in the draft, but we use it instead of u8 for priority.
		// A default of 0 is more ergonomic for the user than a default of 128.
		w.put_u8(((*self as i16) + 128) as u8);
	}
}

impl<T: Encode> Encode for &[T] {
	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
		self.len().encode(w);
		for item in self.iter() {
			item.encode(w);
		}
	}
}

impl<T: Encode> Encode for Vec<T> {
	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
		self.len().encode(w);
		for item in self.iter() {
			item.encode(w);
		}
	}
}

impl Encode for bytes::Bytes {
	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
		self.len().encode(w);
		w.put_slice(self);
	}
}

impl<T: Encode> Encode for Arc<T> {
	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
		(**self).encode(w);
	}
}