Skip to content

Commit

Permalink
Factor out ShortU16 deser vistor logic to helper
Browse files Browse the repository at this point in the history
  • Loading branch information
t-nelson committed Aug 14, 2020

Verified

This commit was signed with the committer’s verified signature.
1 parent 5ab33a9 commit 1a69d03
Showing 1 changed file with 30 additions and 9 deletions.
39 changes: 30 additions & 9 deletions sdk/src/short_vec.rs
Original file line number Diff line number Diff line change
@@ -38,6 +38,26 @@ impl Serialize for ShortU16 {
}
}

enum VisitResult {
Done(usize, usize),
More(usize, usize),
Err,
}

fn visit_byte(elem: u8, len: usize, size: usize) -> VisitResult {
let len = len | (elem as usize & 0x7f) << (size * 7);
let size = size + 1;
let more = elem as usize & 0x80 == 0x80;

if size > 3 || len > size_of::<u16>() + 1 {
VisitResult::Err
} else if more {
VisitResult::More(len, size)
} else {
VisitResult::Done(len, size)
}
}

struct ShortLenVisitor;

impl<'de> Visitor<'de> for ShortLenVisitor {
@@ -58,15 +78,16 @@ impl<'de> Visitor<'de> for ShortLenVisitor {
.next_element()?
.ok_or_else(|| de::Error::invalid_length(size, &self))?;

len |= (elem as usize & 0x7f) << (size * 7);
size += 1;

if elem as usize & 0x80 == 0 {
break;
}

if size > size_of::<u16>() + 1 {
return Err(de::Error::invalid_length(size, &self));
match visit_byte(elem, len, size) {
VisitResult::Done(l, _) => {
len = l;
break;
}
VisitResult::More(l, s) => {
len = l;
size = s;
}
VisitResult::Err => return Err(de::Error::invalid_length(size + 1, &self)),
}
}

0 comments on commit 1a69d03

Please sign in to comment.