BurntSushi / bstr

A string type for Rust that is not required to be valid UTF-8.
Other
745 stars 51 forks source link

Adds FromStr for BString #170

Closed FilipAndersson245 closed 6 months ago

FilipAndersson245 commented 7 months ago

This PR adds FromStr for BString. I had a use case where I wanted to call parse on a regex to extract BString values,

So now you can do this

let s: BString = "abc".parse().unwrap();
FilipAndersson245 commented 6 months ago

@BurntSushi ping

BurntSushi commented 6 months ago

I had a use case where I wanted to call parse on a regex to extract BString values

Can you please show a code example of this? It isn't clear why this requires a FromStr impl.

Overall, I'm not so sure about this. It seems awfully strange. There's no real parsing going on here, and std itself does not have a impl FromStr for Vec<u8> impl itself.

FilipAndersson245 commented 6 months ago

I had a use case where I wanted to call parse on a regex to extract BString values

Can you please show a code example of this? It isn't clear why this requires a FromStr impl.

Overall, I'm not so sure about this. It seems awfully strange. There's no real parsing going on here, and std itself does not have a impl FromStr for Vec<u8> impl itself.

currently I'm using this feature when parsing a regex of some amount of parameters. It did work if I used String instead of Bstr and with this change it works for BStr aswell

#[macro_export]
macro_rules! capture_regex {
    ($fn_name:ident = $regex:literal, $($capture:ty),* $(,)?) => {
        fn $fn_name(input: &[u8]) -> $crate::Result<( $($capture),* )> {
            static RE: $crate::OnceCell<$crate::regex::bytes::Regex> = $crate::OnceCell::new();
            let regex = RE.get_or_try_init(|| $crate::regex::bytes::Regex::new($regex))?;
            let captures = regex
                .captures(input)
                .ok_or_else(|| $crate::eyre!("No captures was found"))?;
            let mut iter = captures.iter();
            $crate::ensure!(iter.next().is_some(), "No captures was found");

            Ok(($(
                std::str::from_utf8(
                    iter.next()
                        .ok_or_else(|| $crate::eyre!("Insuffisint amount of"))?
                        .ok_or_else(|| $crate::eyre!("No match found"))?
                        .as_bytes(),
                )?
                .parse::<$capture>()?
            ),*))
        }
    }
}

And as String implement FromString I don't think it would be that weird if Bstring also did it.

BurntSushi commented 6 months ago

OK, this PR is on crates.io in bstr 1.8.0.