Skip to content

Instantly share code, notes, and snippets.

@ian-p-cooke
Last active July 4, 2018 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ian-p-cooke/d3d737c260a41bbb78d7e4acabce6000 to your computer and use it in GitHub Desktop.
Save ian-p-cooke/d3d737c260a41bbb78d7e4acabce6000 to your computer and use it in GitHub Desktop.
example parser with nom
#[macro_use]
extern crate nom;
use std::str;
use nom::{digit, recognize_float, space, line_ending, IResult};
use nom::types::CompleteStr;
#[derive(Debug)]
struct FloatRecord {
timestamp: u64,
tx: f32,
ty: f32,
tz: f32,
qx: f32,
qy: f32,
qz: f32,
qw: f32,
}
pub fn float_cs(input: CompleteStr) -> IResult<CompleteStr,f32> {
flat_map!(input, call!(recognize_float), parse_to!(f32))
}
named!(
timestamp<CompleteStr, u64>,
map_res!(digit, |s: CompleteStr| { str::parse::<u64>(s.0) })
);
named!(float_record<CompleteStr, FloatRecord>,
do_parse!(
timestamp: timestamp >>
space >>
tx: float_cs >>
space >>
ty: float_cs >>
space >>
tz: float_cs >>
space >>
qx: float_cs >>
space >>
qy: float_cs >>
space >>
qz: float_cs >>
space >>
qw: float_cs >>
alt!(line_ending|eof!()) >>
(FloatRecord{ timestamp, tx, ty, tz, qx, qy, qz, qw })
)
);
fn main() {
let input = CompleteStr("1 0 0 -2.25 0 0 0 1
2 0.000466347 0.00895357 -2.24935 -0.00101358 0.00052453 -0.000231475 0.999999
3 -0.000154972 -0.000102997 -2.25066 -0.00465149 0.000380752 0.000400181 0.999998");
let ( remaining, record ) = float_record(input).unwrap();
println!("{:?}", record);
let ( remaining, record ) = float_record(remaining).unwrap();
println!("{:?}", record);
let ( _remaining, record ) = float_record(remaining).unwrap();
println!("{:?}", record);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment