Skip to content

Commit f99b175

Browse files
started on decode for u16
1 parent fdf0baa commit f99b175

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

amqp-type/src/fixed_width/ushort.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,37 @@
11
use crate::serde::encode::{Encode, Encoded};
2+
use crate::serde::decode::Decode;
3+
4+
const BYTE_LEN: usize = 2;
25

36
impl Encode for u16 {
47
fn encode(&self) -> Encoded {
58
Encoded::new_fixed(0x60, self.to_be_bytes().to_vec())
69
}
710
}
811

12+
impl Decode for u16 {
13+
fn can_decode(iter: impl Iterator<Item = u8>) -> bool {
14+
match iter.peekable().peek() {
15+
Some(0x60) => true,
16+
_ => false
17+
}
18+
}
19+
20+
fn try_decode(mut iter: impl Iterator<Item = u8>) -> Result<Self, crate::error::AppError>
21+
where
22+
Self: Sized {
23+
let mut val_bytes = [0; BYTE_LEN];
24+
let con = iter.next();
25+
let mut index = 0;
26+
for b in iter.take(BYTE_LEN) {
27+
val_bytes[index] = b;
28+
index += 1;
29+
}
30+
Ok(u16::from_be_bytes(val_bytes))
31+
}
32+
}
33+
34+
935
#[cfg(test)]
1036
mod test {
1137

@@ -16,4 +42,23 @@ mod test {
1642
let val: u16 = 16;
1743
assert_eq!(val.encode().constructor(), 0x60);
1844
}
45+
46+
47+
#[test]
48+
fn can_deocde_returns_true_if_constructor_is_valid() {
49+
let val = vec![0x60, 0x41];
50+
assert_eq!(u16::can_decode(val.into_iter()), true);
51+
}
52+
53+
#[test]
54+
fn can_decode_return_false_if_constructor_is_invalid() {
55+
let val = vec![0x61];
56+
assert_eq!(u16::can_decode(val.into_iter()), false);
57+
}
58+
59+
#[test]
60+
fn try_decode_returns_correct_value() {
61+
let val = vec![0x60, 0x00, 0x10];
62+
assert_eq!(u16::try_decode(val.into_iter()).unwrap(), 16)
63+
}
1964
}

0 commit comments

Comments
 (0)