Skip to content

Commit

Permalink
tls_codec: fix deserialization of option (#1125)
Browse files Browse the repository at this point in the history
  • Loading branch information
kkohbrok authored Jun 28, 2023
1 parent 56c6756 commit 409be05
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
6 changes: 3 additions & 3 deletions tls_codec/src/primitives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,13 +95,13 @@ impl<T: Deserialize> Deserialize for Option<T> {
impl<T: DeserializeBytes> DeserializeBytes for Option<T> {
#[inline]
fn tls_deserialize(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
let some_or_none = bytes.first().ok_or(Error::EndOfStream)?;
let (some_or_none, remainder) = <u8 as DeserializeBytes>::tls_deserialize(bytes)?;
match some_or_none {
0 => {
Ok((None, bytes.get(1..).ok_or(Error::EndOfStream)?))
Ok((None, remainder))
},
1 => {
let (element, remainder) = T::tls_deserialize(bytes)?;
let (element, remainder) = T::tls_deserialize(remainder)?;
Ok((Some(element), remainder))
},
_ => Err(Error::DecodingError(alloc::format!("Trying to decode Option<T> with {} for option. It must be 0 for None and 1 for Some.", some_or_none)))
Expand Down
14 changes: 14 additions & 0 deletions tls_codec/tests/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,20 @@ fn deserialize_primitives() {
assert!(u8::tls_deserialize(&mut b).is_err())
}

#[test]
fn deserialize_option_bytes() {
use tls_codec::DeserializeBytes;
for b in [Some(0u8), None] {
let b_encoded = b.tls_serialize_detached().expect("Unable to tls_serialize");
let (b_decoded, remainder) = Option::<u8>::tls_deserialize(&mut b_encoded.as_slice())
.expect("Unable to tls_deserialize");

assert!(remainder.is_empty());

assert_eq!(b_decoded, b);
}
}

#[test]
fn deserialize_bytes_primitives() {
use tls_codec::DeserializeBytes;
Expand Down

0 comments on commit 409be05

Please sign in to comment.