core: add custom traits

This commit is contained in:
Dmitriy Pleshevskiy 2022-07-26 18:14:26 +03:00
parent 67b01b750d
commit 3a234ccc8a
12 changed files with 212 additions and 150 deletions

View file

@ -21,7 +21,7 @@ use estring::{SepVec, EString};
type PlusVec<T> = SepVec<T, '+'>; type PlusVec<T> = SepVec<T, '+'>;
type MulVec<T> = SepVec<T, '*'>; type MulVec<T> = SepVec<T, '*'>;
fn main() -> Result<(), estring::ParseError> { fn main() -> estring::Result<()> {
let res = EString::from("10+5*2+3") let res = EString::from("10+5*2+3")
.parse::<PlusVec<MulVec<f32>>>()? .parse::<PlusVec<MulVec<f32>>>()?
.iter() .iter()
@ -33,14 +33,15 @@ fn main() -> Result<(), estring::ParseError> {
} }
``` ```
You can use custom types as annotations! Just implement `TryFrom<EString>`! You can use custom types as annotations! Just implement
`estring::ParseFragment`!
## Installation ## Installation
**The MSRV is 1.59.0** **The MSRV is 1.59.0**
Add `estring = { version = "0.1", features = ["vec", "number"] }` as a Add `estring = { version = "0.1", features = ["structs"] }` as a dependency in
dependency in `Cargo.toml`. `Cargo.toml`.
`Cargo.toml` example: `Cargo.toml` example:
@ -52,7 +53,7 @@ edition = "2021"
authors = ["Me <user@rust-lang.org>"] authors = ["Me <user@rust-lang.org>"]
[dependencies] [dependencies]
estring = { version = "0.1", features = ["vec", "number"] } estring = { version = "0.1", features = ["structs"] }
``` ```
## License ## License

View file

@ -3,7 +3,7 @@ use estring::{EString, SepVec};
type PlusVec<T> = SepVec<T, '+'>; type PlusVec<T> = SepVec<T, '+'>;
type MulVec<T> = SepVec<T, '*'>; type MulVec<T> = SepVec<T, '*'>;
fn main() -> Result<(), estring::ParseError> { fn main() -> estring::Result<()> {
let res = EString::from("10+5*2+3") let res = EString::from("10+5*2+3")
.parse::<PlusVec<MulVec<f32>>>()? .parse::<PlusVec<MulVec<f32>>>()?
.iter() .iter()

View file

@ -5,7 +5,7 @@ DATABASE_URL=postgres://user:password@localhost:5432/recipes
APP_HOST=http://localhost:3000 APP_HOST=http://localhost:3000
"; ";
fn main() -> Result<(), estring::ParseError> { fn main() -> estring::Result<()> {
EString::from(DOTENV_CONTENT) EString::from(DOTENV_CONTENT)
.parse::<Trim<SepVec<Pair<&str, '=', &str>, '\n'>>>()? .parse::<Trim<SepVec<Pair<&str, '=', &str>, '\n'>>>()?
.iter() .iter()

View file

@ -2,8 +2,73 @@
//! string types //! string types
//! //!
use crate::ParseError; // TODO: add more info and examples.
use std::convert::Infallible; /// Format a value fragment into a ``EString``.
pub trait FormatFragment {
/// Format this type and returns ``EString``.
fn fmt_frag(&self) -> EString;
}
/// Parse a value fragment from a ``EString``.
///
/// ``ParseFragment``s `parse_frag` method is often used imlicitly, through ``EString``s parse.
/// See [parse](EString::parse)s documentation for examples.
///
/// # Examples
///
/// Basic implementation of ``ParseFragment`` on an example ``Point``.
///
/// ```rust
/// use estring::{EString, ParseFragment, Reason};
///
/// #[derive(Debug, PartialEq)]
/// struct Point {
/// x: i32,
/// y: i32,
/// }
///
/// impl ParseFragment for Point {
/// fn parse_frag(es: EString) -> estring::Result<Self> {
/// let orig = es.clone();
/// let (x, y) = es
/// .trim_matches(|p| p == '(' || p == ')')
/// .split_once(',')
/// .ok_or(estring::Error(orig, Reason::Split))?;
///
/// let (x, y) = (EString::from(x), EString::from(y));
/// let x = x.clone().parse::<i32>()
/// .map_err(|_| estring::Error(x, Reason::Parse))?;
/// let y = y.clone().parse::<i32>()
/// .map_err(|_| estring::Error(y, Reason::Parse))?;
///
/// Ok(Point { x, y })
/// }
/// }
///
/// let fragment = EString::from("(1,2)");
/// let res = Point::parse_frag(fragment).unwrap();
/// assert_eq!(res, Point { x: 1, y: 2 })
/// ```
///
pub trait ParseFragment: Sized {
/// Parses a ``EString`` fragment `es` to return a value of this type.
///
/// # Errors
///
/// If parsing is not succeeds, returns ``Error`` inside ``Err`` with original fragment `es`
/// and reason ``Reason``.
///
/// # Examples
///
/// ```rust
/// use estring::{EString, ParseFragment};
///
/// let fragment = EString::from("5");
/// let res = i32::parse_frag(fragment).unwrap();
/// assert_eq!(res, 5);
/// ```
fn parse_frag(es: EString) -> crate::Result<Self>;
}
/// Wrapper under String type. /// Wrapper under String type.
#[derive(Debug, Default, PartialEq, Eq, Clone)] #[derive(Debug, Default, PartialEq, Eq, Clone)]
@ -17,9 +82,8 @@ impl EString {
/// Will return `Err` if estring cannot parse inner fragment /// Will return `Err` if estring cannot parse inner fragment
/// ///
#[inline] #[inline]
pub fn parse<T: TryFrom<EString>>(self) -> Result<T, ParseError> { pub fn parse<T: ParseFragment>(self) -> crate::Result<T> {
let orig = self.0.clone(); T::parse_frag(self)
<T as TryFrom<EString>>::try_from(self).map_err(|_| ParseError(orig))
} }
} }
@ -42,20 +106,23 @@ impl std::ops::Deref for EString {
} }
} }
impl TryFrom<EString> for String { impl ParseFragment for EString {
type Error = Infallible;
#[inline] #[inline]
fn try_from(s: EString) -> Result<Self, Self::Error> { fn parse_frag(value: EString) -> crate::Result<Self> {
Ok(value)
}
}
impl ParseFragment for String {
#[inline]
fn parse_frag(s: EString) -> crate::Result<Self> {
Ok(s.0) Ok(s.0)
} }
} }
impl TryFrom<EString> for &'static str { impl ParseFragment for &'static str {
type Error = Infallible;
#[inline] #[inline]
fn try_from(s: EString) -> Result<Self, Self::Error> { fn parse_frag(s: EString) -> crate::Result<Self> {
Ok(Box::leak(s.0.into_boxed_str())) Ok(Box::leak(s.0.into_boxed_str()))
} }
} }

View file

@ -1,16 +1,31 @@
/// Failed to parse the specified string. use crate::core::EString;
#[derive(Debug)]
pub struct ParseError(pub String);
impl std::fmt::Display for ParseError { /// The error type for operations interacting with ``EString``s fragments.
#[derive(Debug)]
pub struct Error(pub EString, pub Reason);
/// The reason for the failure to parse.
#[derive(Debug, PartialEq, Eq)]
pub enum Reason {
/// Cannot split fragment
Split,
/// Cannot parse fragment
Parse,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, r#"Failed to parse: "{}""#, self.0) write!(
f,
r#"Failed to parse "{:?}" with reason {:?}"#,
self.0, self.1
)
} }
} }
impl std::error::Error for ParseError {} impl std::error::Error for Error {}
impl std::ops::Deref for ParseError { impl std::ops::Deref for Error {
type Target = String; type Target = String;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {

View file

@ -15,7 +15,7 @@
//! type PlusVec<T> = SepVec<T, '+'>; //! type PlusVec<T> = SepVec<T, '+'>;
//! type MulVec<T> = SepVec<T, '*'>; //! type MulVec<T> = SepVec<T, '*'>;
//! //!
//! fn main() -> Result<(), estring::ParseError> { //! fn main() -> estring::Result<()> {
//! let res = EString::from("10+5*2+3") //! let res = EString::from("10+5*2+3")
//! .parse::<PlusVec<MulVec<f32>>>()? //! .parse::<PlusVec<MulVec<f32>>>()?
//! .iter() //! .iter()
@ -32,6 +32,43 @@
#![warn(missing_docs)] #![warn(missing_docs)]
mod error; mod error;
pub use error::{Error, Reason};
/// The type returned by parser methods.
///
/// # Examples
///
/// ```rust
/// use estring::{EString, ParseFragment, Reason};
///
/// #[derive(Debug, PartialEq)]
/// struct Point {
/// x: i32,
/// y: i32,
/// }
///
/// impl ParseFragment for Point {
/// fn parse_frag(es: EString) -> estring::Result<Self> {
/// let orig = es.clone();
/// let (x, y) = es
/// .trim_matches(|p| p == '(' || p == ')')
/// .split_once(',')
/// .ok_or(estring::Error(orig, Reason::Split))?;
///
/// let (x, y) = (EString::from(x), EString::from(y));
/// let x = x.clone().parse::<i32>()
/// .map_err(|_| estring::Error(x, Reason::Parse))?;
/// let y = y.clone().parse::<i32>()
/// .map_err(|_| estring::Error(y, Reason::Parse))?;
///
/// Ok(Point { x, y })
/// }
/// }
///
/// let fragment = EString::from("(1,2)");
/// let res = Point::parse_frag(fragment).unwrap();
/// assert_eq!(res, Point { x: 1, y: 2 })
/// ```
pub type Result<T> = ::std::result::Result<T, Error>;
pub mod core; pub mod core;
pub mod std; pub mod std;
@ -51,4 +88,3 @@ pub mod structs;
pub use structs::*; pub use structs::*;
pub use crate::core::*; pub use crate::core::*;
pub use crate::error::ParseError;

View file

@ -1,4 +1,4 @@
use crate::core::EString; use crate::{core::EString, ParseFragment};
/// Wrapper that allow to trim substring before continue /// Wrapper that allow to trim substring before continue
/// ///
@ -9,7 +9,7 @@ use crate::core::EString;
/// ```rust /// ```rust
/// use estring::{EString, Trim}; /// use estring::{EString, Trim};
/// ///
/// fn main() -> Result<(), estring::ParseError> { /// fn main() -> estring::Result<()> {
/// let res = EString::from(" 99 ").parse::<Trim<i32>>()?; /// let res = EString::from(" 99 ").parse::<Trim<i32>>()?;
/// assert_eq!(res, Trim(99)); /// assert_eq!(res, Trim(99));
/// Ok(()) /// Ok(())
@ -33,16 +33,12 @@ impl<T: std::fmt::Display> std::fmt::Display for Trim<T> {
} }
} }
impl<T> TryFrom<EString> for Trim<T> impl<T> ParseFragment for Trim<T>
where where
T: TryFrom<EString>, T: ParseFragment,
{ {
type Error = (); fn parse_frag(value: EString) -> crate::Result<Self> {
T::parse_frag(EString::from(value.trim())).map(Trim)
fn try_from(value: EString) -> Result<Self, Self::Error> {
T::try_from(EString::from(value.trim()))
.map(Trim)
.map_err(|_| ())
} }
} }
@ -60,7 +56,6 @@ mod tests {
} }
} }
#[cfg(feature = "number")]
#[test] #[test]
fn should_trim_and_convert_to_number() { fn should_trim_and_convert_to_number() {
let estr = EString::from(" 999 "); let estr = EString::from(" 999 ");

View file

@ -1,14 +1,13 @@
use crate::core::EString; use crate::core::{EString, ParseFragment};
use crate::error::{Error, Reason};
impl TryFrom<EString> for bool {
type Error = ();
impl ParseFragment for bool {
#[inline] #[inline]
fn try_from(s: EString) -> Result<Self, Self::Error> { fn parse_frag(s: EString) -> crate::Result<Self> {
match s.to_lowercase().as_str() { match s.to_lowercase().as_str() {
"true" | "t" | "yes" | "y" | "on" | "1" => Ok(true), "true" | "t" | "yes" | "y" | "on" | "1" => Ok(true),
"false" | "f" | "no" | "n" | "off" | "0" | "" => Ok(false), "false" | "f" | "no" | "n" | "off" | "0" | "" => Ok(false),
_ => Err(()), _ => Err(Error(s, Reason::Parse)),
} }
} }
} }
@ -16,7 +15,6 @@ impl TryFrom<EString> for bool {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::ParseError;
#[test] #[test]
fn should_parse_bool_variable() { fn should_parse_bool_variable() {
@ -47,8 +45,9 @@ mod tests {
fn should_throw_parse_error() { fn should_throw_parse_error() {
let estr = EString::from("something"); let estr = EString::from("something");
match estr.parse::<bool>() { match estr.parse::<bool>() {
Err(ParseError(orig)) => { Err(crate::Error(orig, reason)) => {
assert_eq!(orig, String::from("something")); assert_eq!(orig, EString::from("something"));
assert_eq!(reason, crate::Reason::Parse);
} }
_ => unreachable!(), _ => unreachable!(),
}; };

View file

@ -1,15 +1,14 @@
use crate::core::EString; use crate::core::{EString, ParseFragment};
use crate::error::{Error, Reason};
#[doc(hidden)] #[doc(hidden)]
macro_rules! from_env_string_numbers_impl { macro_rules! from_env_string_numbers_impl {
($($ty:ty),+$(,)?) => { ($($ty:ty),+$(,)?) => {
$( $(
impl TryFrom<EString> for $ty { impl ParseFragment for $ty {
type Error = <$ty as std::str::FromStr>::Err;
#[inline] #[inline]
fn try_from(s: EString) -> Result<Self, Self::Error> { fn parse_frag(s: EString) -> crate::Result<Self> {
s.0.parse::<Self>() s.0.parse::<Self>().map_err(|_| Error(s, Reason::Parse))
} }
} }
)+ )+
@ -26,7 +25,6 @@ from_env_string_numbers_impl![
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::ParseError;
#[test] #[test]
fn should_parse_number() { fn should_parse_number() {
@ -51,8 +49,9 @@ mod tests {
fn should_throw_parse_error() { fn should_throw_parse_error() {
let estr = EString::from("-10"); let estr = EString::from("-10");
match estr.parse::<u32>() { match estr.parse::<u32>() {
Err(ParseError(orig)) => { Err(Error(orig, reason)) => {
assert_eq!(orig, String::from("-10")); assert_eq!(orig, EString::from("-10"));
assert_eq!(reason, Reason::Parse);
} }
_ => unreachable!(), _ => unreachable!(),
}; };

View file

@ -1,34 +1,13 @@
//! Contains the implementations to pair tuple type //! Contains the implementations to pair tuple type
//! //!
use crate::core::EString; use crate::core::{EString, ParseFragment};
use crate::{Error, Reason};
use std::fmt::Write; use std::fmt::Write;
/// The error type for operations interacting with parsing tuples. Possibly returned from
/// ``EString::parse``
#[derive(Debug)]
pub enum Error {
/// The specified input string is not split.
Split,
/// The specified substring of the split input string is not parsed
Parse(u8),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::Split => f.write_str("Cannot split input string"),
Error::Parse(n) => write!(f, "Cannot parse {} substring", n),
}
}
}
impl std::error::Error for Error {}
/// Wrapper for pair (A, B) tuple to split string by a separator (`S1`). /// Wrapper for pair (A, B) tuple to split string by a separator (`S1`).
/// ///
/// **NOTE**: Required the enabling of the `tuple` feature. /// **NOTE**: Required the enabling of the `structs` feature.
/// ///
/// # Examples /// # Examples
/// ///
@ -37,7 +16,7 @@ impl std::error::Error for Error {}
/// ///
/// type EqPair<A, B> = Pair<A, '=', B>; /// type EqPair<A, B> = Pair<A, '=', B>;
/// ///
/// fn main() -> Result<(), estring::ParseError> { /// fn main() -> estring::Result<()> {
/// let res = EString::from("one=two=free").parse::<EqPair<&str, &str>>()?; /// let res = EString::from("one=two=free").parse::<EqPair<&str, &str>>()?;
/// assert_eq!(res, Pair("one", "two=free")); /// assert_eq!(res, Pair("one", "two=free"));
/// Ok(()) /// Ok(())
@ -66,19 +45,22 @@ where
} }
} }
impl<A, const S1: char, B> TryFrom<EString> for Pair<A, S1, B> impl<A, const S1: char, B> ParseFragment for Pair<A, S1, B>
where where
A: TryFrom<EString>, A: ParseFragment,
B: TryFrom<EString>, B: ParseFragment,
{ {
type Error = Error; fn parse_frag(value: EString) -> crate::Result<Self> {
value
fn try_from(value: EString) -> Result<Self, Self::Error> { .clone()
value.split_once(S1).ok_or(Error::Split).and_then(|(a, b)| { .split_once(S1)
let a = A::try_from(EString::from(a)).map_err(|_| Error::Parse(0))?; .ok_or(Error(value, Reason::Split))
let b = B::try_from(EString::from(b)).map_err(|_| Error::Parse(1))?; .and_then(|(a, b)| {
Ok(Self(a, b)) let (a, b) = (EString::from(a), EString::from(b));
}) let a = A::parse_frag(a.clone()).map_err(|_| Error(a, Reason::Parse))?;
let b = B::parse_frag(b.clone()).map_err(|_| Error(b, Reason::Parse))?;
Ok(Self(a, b))
})
} }
} }

View file

@ -1,12 +1,12 @@
//! Contains the implementations to vec type //! Contains the implementations to vec type
//! //!
use crate::core::EString; use crate::core::{EString, ParseFragment};
use std::fmt::Write; use std::fmt::Write;
/// Wrapper for ``Vec`` to split string by a separator (`SEP`). /// Wrapper for ``Vec`` to split string by a separator (`SEP`).
/// ///
/// **NOTE**: Required the enabling of the `vec` feature. /// **NOTE**: Required the enabling of the `structs` feature.
/// ///
/// # Examples /// # Examples
/// ///
@ -15,7 +15,7 @@ use std::fmt::Write;
/// ///
/// type CommaVec<T> = SepVec<T, ','>; /// type CommaVec<T> = SepVec<T, ','>;
/// ///
/// fn main() -> Result<(), estring::ParseError> { /// fn main() -> estring::Result<()> {
/// let res = EString::from("1,2,3").parse::<CommaVec<u8>>()?; /// let res = EString::from("1,2,3").parse::<CommaVec<u8>>()?;
/// assert_eq!(*res, vec![1, 2, 3]); /// assert_eq!(*res, vec![1, 2, 3]);
/// Ok(()) /// Ok(())
@ -56,19 +56,17 @@ where
} }
} }
impl<T, const SEP: char> TryFrom<EString> for SepVec<T, SEP> impl<T, const SEP: char> ParseFragment for SepVec<T, SEP>
where where
T: TryFrom<EString> + std::fmt::Display, T: ParseFragment,
{ {
type Error = T::Error; fn parse_frag(value: EString) -> crate::Result<Self> {
fn try_from(value: EString) -> Result<Self, Self::Error> {
let inner = value let inner = value
.split(SEP) .split(SEP)
.map(str::trim) .map(str::trim)
.map(EString::from) .map(EString::from)
.map(T::try_from) .map(T::parse_frag)
.collect::<Result<Vec<_>, _>>()?; .collect::<crate::Result<Vec<_>>>()?;
Ok(Self(inner)) Ok(Self(inner))
} }
} }
@ -76,7 +74,7 @@ where
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::ParseError; use crate::{Error, Reason};
const COMMA: char = ','; const COMMA: char = ',';
const SEMI: char = ';'; const SEMI: char = ';';
@ -134,8 +132,9 @@ d,e";
fn should_throw_parse_vec_error() { fn should_throw_parse_vec_error() {
let estr = EString::from("1,2,3,4,5"); let estr = EString::from("1,2,3,4,5");
match estr.parse::<SemiVec<i32>>() { match estr.parse::<SemiVec<i32>>() {
Err(ParseError(orig)) => { Err(Error(orig, reason)) => {
assert_eq!(orig, String::from("1,2,3,4,5")); assert_eq!(orig, EString::from("1,2,3,4,5"));
assert_eq!(reason, Reason::Parse);
} }
_ => unreachable!(), _ => unreachable!(),
}; };

View file

@ -1,44 +1,21 @@
//! Contains the implementations to parse triple-tuple type //! Contains the implementations to parse triple-tuple type
//! //!
use crate::core::EString; use super::Pair;
use crate::core::{EString, ParseFragment};
use std::fmt::Write; use std::fmt::Write;
/// The error type for operations interacting with parsing tuples. Possibly returned from
/// ``EString::parse``
#[derive(Debug)]
pub enum Error {
/// The specified input string is not split.
Split,
/// The specified substring of the split input string is not parsed
Parse(u8),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::Split => f.write_str("Cannot split input string"),
Error::Parse(n) => write!(f, "Cannot parse {} substring", n),
}
}
}
impl std::error::Error for Error {}
/// Wrapper for trio (A, B, C) tuple to split string by separators (`S1` and `S2`). /// Wrapper for trio (A, B, C) tuple to split string by separators (`S1` and `S2`).
/// ///
/// **NOTE**: Required the enabling of the `tuple` feature. /// **NOTE**: Required the enabling of the `structs` feature.
/// ///
/// # Examples /// # Examples
/// ///
/// ```rust /// ```rust
/// use estring::{Trio, EString}; /// use estring::{Trio, EString};
/// ///
/// type EqTrio<A, B, C> = Trio<A, '=', B, '=', C>; /// fn main() -> estring::Result<()> {
/// /// let res = EString::from("one+two=free").parse::<Trio<&str, '+', &str, '=', &str>>()?;
/// fn main() -> Result<(), estring::ParseError> {
/// let res = EString::from("one=two=free").parse::<EqTrio<&str, &str, &str>>()?;
/// assert_eq!(res, Trio("one", "two", "free")); /// assert_eq!(res, Trio("one", "two", "free"));
/// Ok(()) /// Ok(())
/// } /// }
@ -69,22 +46,15 @@ where
} }
} }
impl<A, const S1: char, B, const S2: char, C> TryFrom<EString> for Trio<A, S1, B, S2, C> impl<A, const S1: char, B, const S2: char, C> ParseFragment for Trio<A, S1, B, S2, C>
where where
A: TryFrom<EString>, A: ParseFragment,
B: TryFrom<EString>, B: ParseFragment,
C: TryFrom<EString>, C: ParseFragment,
{ {
type Error = Error; fn parse_frag(value: EString) -> crate::Result<Self> {
Pair::<A, S1, EString>::parse_frag(value).and_then(|Pair(a, rest)| {
fn try_from(value: EString) -> Result<Self, Self::Error> { Pair::<B, S2, C>::parse_frag(rest).map(|Pair(b, c)| Self(a, b, c))
value.split_once(S1).ok_or(Error::Split).and_then(|(a, b)| {
let a = A::try_from(EString::from(a)).map_err(|_| Error::Parse(0))?;
b.split_once(S2).ok_or(Error::Split).and_then(|(b, c)| {
let b = B::try_from(EString::from(b)).map_err(|_| Error::Parse(1))?;
let c = C::try_from(EString::from(c)).map_err(|_| Error::Parse(2))?;
Ok(Self(a, b, c))
})
}) })
} }
} }
@ -92,7 +62,6 @@ where
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::structs::SepVec;
#[test] #[test]
fn should_parse_into_trio() { fn should_parse_into_trio() {