FromBStr

Trait FromBStr 

Source
pub trait FromBStr: Sized {
    type Err;

    // Required method
    fn from_bstr(s: &[u8]) -> Result<Self, Self::Err>;
}
Expand description

Parse a value from a string

FromBStr’s from_bstr method is often used implicitly, through [u8]’s parse method. See parse’s documentation for examples.

FromBStr does not have a lifetime parameter, and so you can only parse types that do not contain a lifetime parameter themselves. In other words, you can parse an i32 with FromBStr, but not a &i32. You can parse a struct that contains an i32, but not one that contains an &i32.

§Examples

Basic implementation of FromBStr on an example Point type:

use bstr_parse::*;

#[derive(Debug, PartialEq)]
struct Point {
    x: i32,
    y: i32
}

impl FromBStr for Point {
    type Err = ParseIntError;

    fn from_bstr(s: &[u8]) -> Result<Self, Self::Err> {
        let coords: Vec<&[u8]> = s.split(|&p| p == b'(' || p == b')' || p == b',')
                                 .skip_while(|s| s.is_empty())
                                 .take_while(|s| !s.is_empty())
                                 .collect();

        let x_frombstr = coords[0].parse::<i32>()?;
        let y_frombstr = coords[1].parse::<i32>()?;

        Ok(Point { x: x_frombstr, y: y_frombstr })
    }
}

let p = Point::from_bstr(b"(1,2)");
assert_eq!(p.unwrap(), Point{ x: 1, y: 2} )

Required Associated Types§

Source

type Err

The associated error which can be returned from parsing.

Required Methods§

Source

fn from_bstr(s: &[u8]) -> Result<Self, Self::Err>

Parses a string s to return a value of this type.

If parsing succeeds, return the value inside Ok, otherwise when the string is ill-formatted return an error specific to the inside Err. The error type is specific to implementation of the trait.

§Examples

Basic usage with i32, a type that implements FromBStr:

use bstr_parse::*;

let s = b"5";
let x = i32::from_bstr(s).unwrap();

assert_eq!(5, x);

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl FromBStr for i8

Source§

impl FromBStr for i16

Source§

impl FromBStr for i32

Source§

impl FromBStr for i64

Source§

impl FromBStr for i128

Source§

impl FromBStr for isize

Source§

impl FromBStr for u8

Source§

impl FromBStr for u16

Source§

impl FromBStr for u32

Source§

impl FromBStr for u64

Source§

impl FromBStr for u128

Source§

impl FromBStr for usize

Implementors§