Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for character::*::{isize,usize} parsers #1762

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

AMDmi3
Copy link
Contributor

@AMDmi3 AMDmi3 commented May 10, 2024

Trivial change to add character::{streaming,complete}::{usize,isize} parsers. The use case is to parse item quantities which are later used in nom::multi::count, or to parse values which are intended to index collections without residing to needless casts.

Example use case:

use nom::character::complete::{newline, usize};
use nom::IResult;

fn parse(input: &str) -> IResult<&str, Vec<usize>> {
    let (input, count) = nom::sequence::terminated(usize, newline)(input)?;
    nom::multi::count(
        nom::sequence::terminated(usize, newline), 
        count
    )(input)
}

fn main() {
    assert_eq!(parse("3\n1\n2\n3\n"), Ok(("", vec![1, 2, 3])));
}

Without this change I have to complicate the code with casts:

use nom::character::complete::{newline, u32};
use nom::IResult;

fn parse(input: &str) -> IResult<&str, Vec<usize>> {
    let (input, count) = nom::sequence::terminated(u32, newline)(input)?;
    nom::multi::count(
        nom::sequence::terminated(
            nom::combinator::map(u32, |v| v as usize), 
            newline
        ),
        count as usize,
    )(input)
}

fn main() {
    assert_eq!(parse("3\n1\n2\n3\n"), Ok(("", vec![1, 2, 3])));
}

This change applies to both main and 7.x branches, if accepted please merge to both. Test pass for both branches as well.

@AMDmi3 AMDmi3 requested a review from Geal as a code owner May 10, 2024 23:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant