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

Merged
merged 2 commits into from
Dec 8, 2024

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
Copy link
Collaborator

@Geal Geal left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

great, thanks

Copy link

codspeed-hq bot commented Dec 8, 2024

CodSpeed Performance Report

Merging #1762 will improve performances by 13.57%

Comparing AMDmi3:iusize-parsers (9f5b6f3) with main (ebb9e47)

Summary

⚡ 1 improvements
✅ 23 untouched benchmarks

Benchmarks breakdown

Benchmark main AMDmi3:iusize-parsers Change
number 244.2 ns 215 ns +13.57%

@Geal Geal merged commit 9745930 into rust-bakery:main Dec 8, 2024
17 checks passed
@AMDmi3 AMDmi3 deleted the iusize-parsers branch December 8, 2024 14:08
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.

2 participants