Skip to content

Commit

Permalink
Add parse_length helper
Browse files Browse the repository at this point in the history
  • Loading branch information
maurolacy committed Oct 4, 2021
1 parent 0fa5124 commit 30913b7
Showing 1 changed file with 12 additions and 18 deletions.
30 changes: 12 additions & 18 deletions packages/storage-plus/src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,18 +121,22 @@ impl KeyDeserialize for TimestampKey {
}
}

fn parse_length(value: &[u8]) -> StdResult<usize> {
Ok(u16::from_be_bytes(
value
.try_into()
.map_err(|_| StdError::generic_err("Could not read 2 byte length"))?,
)
.into())
}

impl<T: KeyDeserialize, U: KeyDeserialize> KeyDeserialize for (T, U) {
type Output = (T::Output, U::Output);

#[inline(always)]
fn from_vec(mut value: Vec<u8>) -> StdResult<Self::Output> {
let mut tu = value.split_off(2);
let t_len = u16::from_be_bytes(
value
.as_slice()
.try_into()
.map_err(|err: TryFromSliceError| StdError::generic_err(err.to_string()))?,
) as usize;
let t_len = parse_length(&value)?;
let u = tu.split_off(t_len);

Ok((T::from_vec(tu)?, U::from_vec(u)?))
Expand All @@ -145,21 +149,11 @@ impl<T: KeyDeserialize, U: KeyDeserialize, V: KeyDeserialize> KeyDeserialize for
#[inline(always)]
fn from_vec(mut value: Vec<u8>) -> StdResult<Self::Output> {
let mut tuv = value.split_off(2);
let t_len = u16::from_be_bytes(
value
.as_slice()
.try_into()
.map_err(|err: TryFromSliceError| StdError::generic_err(err.to_string()))?,
) as usize;
let t_len = parse_length(&value)?;
let mut len_uv = tuv.split_off(t_len);

let mut uv = len_uv.split_off(2);
let u_len = u16::from_be_bytes(
len_uv
.as_slice()
.try_into()
.map_err(|err: TryFromSliceError| StdError::generic_err(err.to_string()))?,
) as usize;
let u_len = parse_length(&len_uv)?;
let v = uv.split_off(u_len);

Ok((T::from_vec(tuv)?, U::from_vec(uv)?, V::from_vec(v)?))
Expand Down

0 comments on commit 30913b7

Please sign in to comment.