Add `usize` parsing

next
Sayan Nandan 2 years ago
parent 59c681e787
commit 7f3d3cb05e
No known key found for this signature in database
GPG Key ID: 8BC07A0A4D41DD52

@ -31,6 +31,7 @@ use core::marker::PhantomData;
#[cfg(test)]
mod tests;
/// A parser for Skyhash 2.0
pub struct Parser<'a> {
end: *const u8,
cursor: *const u8,
@ -98,6 +99,7 @@ impl<'a> Parser<'a> {
// higher level abstractions
impl<'a> Parser<'a> {
/// Attempt to read `len` bytes
fn read_until(&mut self, len: usize) -> ParseResult<UnsafeSlice> {
if self.has_remaining(len) {
unsafe {
@ -110,6 +112,7 @@ impl<'a> Parser<'a> {
Err(ParseError::NotEnough)
}
}
/// Attempt to read a byte slice terminated by an LF
fn read_line(&mut self) -> ParseResult<UnsafeSlice> {
let start_ptr = self.cursor_ptr();
unsafe {
@ -125,4 +128,27 @@ impl<'a> Parser<'a> {
}
}
}
fn read_usize(&mut self) -> ParseResult<usize> {
let line = self.read_line()?;
let bytes = unsafe {
// UNSAFE(@ohsayan): We just extracted the slice
line.as_slice()
};
let mut ret = 0usize;
for byte in bytes {
if byte.is_ascii_digit() {
ret = match ret.checked_mul(10) {
Some(r) => r,
None => return Err(ParseError::DatatypeParseFailure),
};
ret = match ret.checked_add((byte - b'0') as _) {
Some(r) => r,
None => return Err(ParseError::DatatypeParseFailure),
};
} else {
return Err(ParseError::DatatypeParseFailure);
}
}
Ok(ret)
}
}

@ -196,6 +196,7 @@ fn exhausted_with_incr() {
}
}
// not_exhausted
#[test]
fn not_exhausted() {
for src in slices() {
@ -238,6 +239,7 @@ fn ensure_zero_reads(parser: &mut Parser) {
}
}
// read_until
#[test]
fn read_until_empty() {
let b = v!(b"");
@ -303,6 +305,7 @@ fn slices_lf_with_len() -> IterPacketWithLen {
get_slices_with_len(slices_lf())
}
// read_line
#[test]
fn read_line_special_case_only_lf() {
let b = v!(b"\n");
@ -334,9 +337,9 @@ fn read_line() {
}
// now, we attempt to read which should work
ensure_zero_reads(&mut parser);
// now, we attempt to read another line which should fail
assert_eq!(parser.read_line().unwrap_err(), ParseError::NotEnough);
}
// now, we attempt to read another line which should fail
assert_eq!(parser.read_line().unwrap_err(), ParseError::NotEnough);
// ensure that cursor is at end
unsafe {
assert_eq!(parser.cursor_ptr(), src.as_ptr().add(len));

Loading…
Cancel
Save