[−][src]Trait bstr_parse::FromBStr
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} )
Associated Types
Loading content...Required methods
pub fn from_bstr(s: &[u8]) -> Result<Self, Self::Err>
[src]
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);