Sha256: cdac92fb14afb75cba9d6b8f568e272a630b2cfb9f096b76c91909a3cd016869

Contents?: true

Size: 1.39 KB

Versions: 38

Compression:

Stored size: 1.39 KB

Contents

use nom::branch::alt;
use nom::bytes::complete::tag;
use nom::character::streaming::digit1 as digit;
use nom::combinator::{map, map_res, opt, recognize};
use nom::sequence::{delimited, pair};
use nom::IResult;

use std::str;
use std::str::FromStr;

fn unsigned_float(i: &[u8]) -> IResult<&[u8], f32> {
  let float_bytes = recognize(alt((
    delimited(digit, tag("."), opt(digit)),
    delimited(opt(digit), tag("."), digit),
  )));
  let float_str = map_res(float_bytes, str::from_utf8);
  map_res(float_str, FromStr::from_str)(i)
}

fn float(i: &[u8]) -> IResult<&[u8], f32> {
  map(
    pair(opt(alt((tag("+"), tag("-")))), unsigned_float),
    |(sign, value)| {
      sign
        .and_then(|s| if s[0] == b'-' { Some(-1f32) } else { None })
        .unwrap_or(1f32)
        * value
    },
  )(i)
}

#[test]
fn unsigned_float_test() {
  assert_eq!(unsigned_float(&b"123.456;"[..]), Ok((&b";"[..], 123.456)));
  assert_eq!(unsigned_float(&b"0.123;"[..]), Ok((&b";"[..], 0.123)));
  assert_eq!(unsigned_float(&b"123.0;"[..]), Ok((&b";"[..], 123.0)));
  assert_eq!(unsigned_float(&b"123.;"[..]), Ok((&b";"[..], 123.0)));
  assert_eq!(unsigned_float(&b".123;"[..]), Ok((&b";"[..], 0.123)));
}

#[test]
fn float_test() {
  assert_eq!(float(&b"123.456;"[..]), Ok((&b";"[..], 123.456)));
  assert_eq!(float(&b"+123.456;"[..]), Ok((&b";"[..], 123.456)));
  assert_eq!(float(&b"-123.456;"[..]), Ok((&b";"[..], -123.456)));
}

Version data entries

38 entries across 38 versions & 1 rubygems

Version Path
wasmtime-29.0.0 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs
wasmtime-28.0.0 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs
wasmtime-27.0.0 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs
wasmtime-26.0.0 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs
wasmtime-25.0.2 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs
wasmtime-25.0.1 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs
wasmtime-25.0.0 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs
wasmtime-24.0.0 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs
wasmtime-23.0.2 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs
wasmtime-22.0.0 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs
wasmtime-21.0.1 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs
wasmtime-20.0.2 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs
wasmtime-20.0.0 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs
wasmtime-18.0.3 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs
wasmtime-17.0.1 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs
wasmtime-17.0.0 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs
wasmtime-16.0.0 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs
wasmtime-15.0.1 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs
wasmtime-15.0.0 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs
wasmtime-14.0.4 ./ext/cargo-vendor/nom-7.1.3/tests/float.rs