Skip to content

Commit

Permalink
add NumberAny::from_bytes, tests
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelcolvin committed Sep 17, 2024
1 parent 5e4c945 commit e38b1bd
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 11 deletions.
20 changes: 9 additions & 11 deletions crates/jiter/src/number_decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,18 +143,16 @@ impl TryFrom<&[u8]> for NumberAny {
type Error = JsonError;

fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
let first = *value.first().ok_or_else(|| json_error!(InvalidNumber, 0))?;
let (int_parse, index) = IntParse::parse(value, 0, first)?;
let (number, index) = match int_parse {
IntParse::Int(int) => (Self::Int(int), index),
IntParse::Float => {
let (f, index) = NumberFloat::decode(value, 0, first, false)?;
(Self::Float(f), index)
}
_ => return json_err!(InvalidNumber, index),
};
Self::from_bytes(value, false)
}
}

impl NumberAny {
pub fn from_bytes(data: &[u8], allow_inf_nan: bool) -> Result<Self, JsonError> {
let first = *data.first().ok_or_else(|| json_error!(InvalidNumber, 0))?;
let (number, index) = Self::decode(data, 0, first, allow_inf_nan)?;

if index == value.len() {
if index == data.len() {
Ok(number)
} else {
json_err!(InvalidNumber, index)
Expand Down
21 changes: 21 additions & 0 deletions crates/jiter/tests/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1467,11 +1467,32 @@ fn test_number_any_try_from_bytes() {
let e = NumberAny::try_from(b"0123".as_ref()).unwrap_err();
assert_eq!(e.to_string(), "invalid number at index 1");

let e = NumberAny::try_from(b"NaN".as_ref()).unwrap_err();
assert_eq!(e.to_string(), "expected value at index 0");

let too_long = "9".repeat(4309);
let e = NumberAny::try_from(too_long.as_bytes()).unwrap_err();
assert_eq!(e.to_string(), "number out of range at index 4301");
}

#[test]
fn test_number_any_try_from_bytes_allow() {
let n = NumberAny::from_bytes(b"123", true).unwrap();
assert_eq!(n, NumberAny::Int(NumberInt::Int(123)));

let e = NumberAny::from_bytes(b"x23", true).unwrap_err();
assert_eq!(e.to_string(), "invalid number at index 0");

let n = NumberAny::from_bytes(b"NaN", true).unwrap();
assert_eq!(format!("{n:?}"), "Float(NaN)");

let n = NumberAny::from_bytes(b"Infinity", true).unwrap();
assert_eq!(format!("{n:?}"), "Float(inf)");

let e = NumberAny::from_bytes(b"NaN", false).unwrap_err();
assert_eq!(e.to_string(), "expected value at index 0");
}

#[test]
fn jiter_skip_whole_object() {
let mut jiter = Jiter::new(br#"{"x": 1}"#);
Expand Down

0 comments on commit e38b1bd

Please sign in to comment.