moq_lite/coding/
parameters.rs

1use std::collections::HashMap;
2
3use crate::coding::*;
4
5const MAX_PARAMS: u64 = 64;
6
7#[derive(Default, Debug, Clone)]
8pub struct Parameters(HashMap<u64, Vec<u8>>);
9
10impl Decode for Parameters {
11	fn decode<R: bytes::Buf>(mut r: &mut R) -> Result<Self, DecodeError> {
12		let mut map = HashMap::new();
13
14		// I hate this encoding so much; let me encode my role and get on with my life.
15		let count = u64::decode(r)?;
16		if count > MAX_PARAMS {
17			return Err(DecodeError::TooMany);
18		}
19
20		for _ in 0..count {
21			let kind = u64::decode(r)?;
22			if map.contains_key(&kind) {
23				return Err(DecodeError::Duplicate);
24			}
25
26			let data = Vec::<u8>::decode(&mut r)?;
27			map.insert(kind, data);
28		}
29
30		Ok(Parameters(map))
31	}
32}
33
34impl Encode for Parameters {
35	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
36		self.0.len().encode(w);
37
38		for (kind, value) in self.0.iter() {
39			kind.encode(w);
40			value.encode(w);
41		}
42	}
43}
44
45impl Parameters {
46	pub fn get(&self, kind: u64) -> Option<&Vec<u8>> {
47		self.0.get(&kind)
48	}
49
50	pub fn set(&mut self, kind: u64, value: Vec<u8>) {
51		self.0.insert(kind, value);
52	}
53}