str-reader 0.1.2

Simple reader/parser for formatted strings.
Documentation
  • Coverage
  • 93.55%
    29 out of 31 items documented1 out of 29 items with examples
  • Size
  • Source code size: 15.65 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.95 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 9s Average build duration of successful builds.
  • all releases: 9s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • operutka/str-reader
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • operutka

String reader

Crates.io MIT licensed Build Status

Zero-allocation string reader. The string reader can be used to parse all kinds of values from strings. It can be used for construction of traditional lexical analyzers for example. It is useful in situation when you need to parse simple formatted strings but regular expressions are too heavy-weight.

Example

Parsing HTTP response header:

use std::num::ParseIntError;

use str_reader::{ParseError, StringReader};

/// Parse the first line of an HTTP response header.
fn parse_http_response_line(line: &str) -> Result<(u16, &str), HttpParseError> {
    let mut reader = StringReader::new(line);

    reader.match_str("HTTP/")?;

    match reader.read_word() {
        "1.0" => (),
        "1.1" => (),
        _ => return Err(HttpParseError),
    }

    let status_code = reader.read_u16()?;

    Ok((status_code, reader.as_str().trim()))
}

#[derive(Debug)]
struct HttpParseError;

impl From<ParseError> for HttpParseError {
    fn from(_: ParseError) -> Self {
        Self
    }
}

impl From<ParseIntError> for HttpParseError {
    fn from(_: ParseIntError) -> Self {
        Self
    }
}

let (status_code, status_msg) = parse_http_response_line("HTTP/1.1 404 Not Found").unwrap();

assert_eq!(status_code, 404);
assert_eq!(status_msg, "Not Found");