encode/encoders/
arrayvec.rs1use arrayvec::ArrayString;
2use arrayvec::ArrayVec;
3
4use super::InsufficientSpace;
5use crate::BaseEncoder;
6use crate::ByteEncoder;
7use crate::StrEncoder;
8
9impl<const SIZE: usize> BaseEncoder for ArrayVec<u8, SIZE> {
10 type Error = InsufficientSpace;
11}
12
13impl<const SIZE: usize> ByteEncoder for ArrayVec<u8, SIZE> {
14 #[inline]
15 fn put_slice(&mut self, slice: &[u8]) -> Result<(), Self::Error> {
16 self.try_extend_from_slice(slice)
17 .map_err(|_| InsufficientSpace)
18 }
19
20 #[inline]
21 fn put_byte(&mut self, byte: u8) -> Result<(), Self::Error> {
22 self.try_push(byte).map_err(|_| InsufficientSpace)
23 }
24}
25
26impl<const SIZE: usize> BaseEncoder for ArrayString<SIZE> {
27 type Error = InsufficientSpace;
28}
29
30impl<const SIZE: usize> StrEncoder for ArrayString<SIZE> {
31 #[inline]
32 fn put_str(&mut self, string: &str) -> Result<(), Self::Error> {
33 self.try_push_str(string).map_err(|_| InsufficientSpace)
34 }
35}
36
37#[cfg(test)]
38mod test {
39 use super::*;
40 use crate::Encodable;
41
42 #[test]
43 fn assert_that_encoding_something_into_an_empty_arrayvec_always_fails() {
44 let mut encoder = ArrayVec::<u8, 0>::new();
45 let encodable = "hello";
46 assert!(
47 encodable.encode(&mut encoder).is_err(),
48 "Empty arrays should always fail"
49 );
50 }
51
52 #[test]
53 fn assert_that_arrayvecs_can_be_used_as_encoders() {
54 let mut buf = ArrayVec::<u8, 64>::new();
55 let encodable = ("hello", 0u8);
56
57 encodable.encode(&mut buf).unwrap();
58
59 assert_eq!(buf.len(), 6, "The buffer should contain 5 bytes");
60 assert_eq!(
61 buf.as_slice(),
62 b"hello\0",
63 "The buffer should contain the encoded string"
64 );
65 }
66
67 #[test]
68 fn assert_that_arraystrings_can_be_used_as_str_encoders() {
69 let mut buf = ArrayString::<64>::new();
70 let encodable = "hello";
71
72 encodable.encode(&mut buf).unwrap();
73
74 assert_eq!(buf.len(), 5, "The buffer should contain 5 bytes");
75 assert_eq!(
76 buf.as_str(),
77 "hello",
78 "The buffer should contain the encoded string"
79 );
80 }
81}