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 MulVec<T> = SepVec<T, '*'>;
fn main() -> Result<(), estring::ParseError> {
fn main() -> estring::Result<()> {
let res = EString::from("10+5*2+3")
.parse::<PlusVec<MulVec<f32>>>()?
.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
**The MSRV is 1.59.0**
Add `estring = { version = "0.1", features = ["vec", "number"] }` as a
dependency in `Cargo.toml`.
Add `estring = { version = "0.1", features = ["structs"] }` as a dependency in
`Cargo.toml`.
`Cargo.toml` example:
@ -52,7 +53,7 @@ edition = "2021"
authors = ["Me <user@rust-lang.org>"]
[dependencies]
estring = { version = "0.1", features = ["vec", "number"] }
estring = { version = "0.1", features = ["structs"] }
```
## License

View File

@ -3,7 +3,7 @@ use estring::{EString, SepVec};
type PlusVec<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")
.parse::<PlusVec<MulVec<f32>>>()?
.iter()

View File

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

View File

@ -2,8 +2,73 @@
//! string types
//!
use crate::ParseError;
use std::convert::Infallible;
// TODO: add more info and examples.
/// 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.
#[derive(Debug, Default, PartialEq, Eq, Clone)]
@ -17,9 +82,8 @@ impl EString {
/// Will return `Err` if estring cannot parse inner fragment
///
#[inline]
pub fn parse<T: TryFrom<EString>>(self) -> Result<T, ParseError> {
let orig = self.0.clone();
<T as TryFrom<EString>>::try_from(self).map_err(|_| ParseError(orig))
pub fn parse<T: ParseFragment>(self) -> crate::Result<T> {
T::parse_frag(self)
}
}
@ -42,20 +106,23 @@ impl std::ops::Deref for EString {
}
}
impl TryFrom<EString> for String {
type Error = Infallible;
impl ParseFragment for EString {
#[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)
}
}
impl TryFrom<EString> for &'static str {
type Error = Infallible;
impl ParseFragment for &'static str {
#[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()))
}
}

View File

@ -1,16 +1,31 @@
/// Failed to parse the specified string.
#[derive(Debug)]
pub struct ParseError(pub String);
use crate::core::EString;
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 {
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;
fn deref(&self) -> &Self::Target {

View File

@ -15,7 +15,7 @@
//! type PlusVec<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")
//! .parse::<PlusVec<MulVec<f32>>>()?
//! .iter()
@ -32,6 +32,43 @@
#![warn(missing_docs)]
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 std;
@ -51,4 +88,3 @@ pub mod structs;
pub use structs::*;
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
///
@ -9,7 +9,7 @@ use crate::core::EString;
/// ```rust
/// use estring::{EString, Trim};
///
/// fn main() -> Result<(), estring::ParseError> {
/// fn main() -> estring::Result<()> {
/// let res = EString::from(" 99 ").parse::<Trim<i32>>()?;
/// assert_eq!(res, Trim(99));
/// 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
T: TryFrom<EString>,
T: ParseFragment,
{
type Error = ();
fn try_from(value: EString) -> Result<Self, Self::Error> {
T::try_from(EString::from(value.trim()))
.map(Trim)
.map_err(|_| ())
fn parse_frag(value: EString) -> crate::Result<Self> {
T::parse_frag(EString::from(value.trim())).map(Trim)
}
}
@ -60,7 +56,6 @@ mod tests {
}
}
#[cfg(feature = "number")]
#[test]
fn should_trim_and_convert_to_number() {
let estr = EString::from(" 999 ");

View File

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

View File

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

View File

@ -1,34 +1,13 @@
//! Contains the implementations to pair tuple type
//!
use crate::core::EString;
use crate::core::{EString, ParseFragment};
use crate::{Error, Reason};
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`).
///
/// **NOTE**: Required the enabling of the `tuple` feature.
/// **NOTE**: Required the enabling of the `structs` feature.
///
/// # Examples
///
@ -37,7 +16,7 @@ impl std::error::Error for Error {}
///
/// 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>>()?;
/// assert_eq!(res, Pair("one", "two=free"));
/// 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
A: TryFrom<EString>,
B: TryFrom<EString>,
A: ParseFragment,
B: ParseFragment,
{
type Error = Error;
fn try_from(value: EString) -> Result<Self, Self::Error> {
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))?;
let b = B::try_from(EString::from(b)).map_err(|_| Error::Parse(1))?;
Ok(Self(a, b))
})
fn parse_frag(value: EString) -> crate::Result<Self> {
value
.clone()
.split_once(S1)
.ok_or(Error(value, Reason::Split))
.and_then(|(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
//!
use crate::core::EString;
use crate::core::{EString, ParseFragment};
use std::fmt::Write;
/// 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
///
@ -15,7 +15,7 @@ use std::fmt::Write;
///
/// type CommaVec<T> = SepVec<T, ','>;
///
/// fn main() -> Result<(), estring::ParseError> {
/// fn main() -> estring::Result<()> {
/// let res = EString::from("1,2,3").parse::<CommaVec<u8>>()?;
/// assert_eq!(*res, vec![1, 2, 3]);
/// 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
T: TryFrom<EString> + std::fmt::Display,
T: ParseFragment,
{
type Error = T::Error;
fn try_from(value: EString) -> Result<Self, Self::Error> {
fn parse_frag(value: EString) -> crate::Result<Self> {
let inner = value
.split(SEP)
.map(str::trim)
.map(EString::from)
.map(T::try_from)
.collect::<Result<Vec<_>, _>>()?;
.map(T::parse_frag)
.collect::<crate::Result<Vec<_>>>()?;
Ok(Self(inner))
}
}
@ -76,7 +74,7 @@ where
#[cfg(test)]
mod tests {
use super::*;
use crate::ParseError;
use crate::{Error, Reason};
const COMMA: char = ',';
const SEMI: char = ';';
@ -134,8 +132,9 @@ d,e";
fn should_throw_parse_vec_error() {
let estr = EString::from("1,2,3,4,5");
match estr.parse::<SemiVec<i32>>() {
Err(ParseError(orig)) => {
assert_eq!(orig, String::from("1,2,3,4,5"));
Err(Error(orig, reason)) => {
assert_eq!(orig, EString::from("1,2,3,4,5"));
assert_eq!(reason, Reason::Parse);
}
_ => unreachable!(),
};

View File

@ -1,44 +1,21 @@
//! Contains the implementations to parse triple-tuple type
//!
use crate::core::EString;
use super::Pair;
use crate::core::{EString, ParseFragment};
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`).
///
/// **NOTE**: Required the enabling of the `tuple` feature.
/// **NOTE**: Required the enabling of the `structs` feature.
///
/// # Examples
///
/// ```rust
/// use estring::{Trio, EString};
///
/// type EqTrio<A, B, C> = Trio<A, '=', B, '=', C>;
///
/// fn main() -> Result<(), estring::ParseError> {
/// let res = EString::from("one=two=free").parse::<EqTrio<&str, &str, &str>>()?;
/// fn main() -> estring::Result<()> {
/// let res = EString::from("one+two=free").parse::<Trio<&str, '+', &str, '=', &str>>()?;
/// assert_eq!(res, Trio("one", "two", "free"));
/// 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
A: TryFrom<EString>,
B: TryFrom<EString>,
C: TryFrom<EString>,
A: ParseFragment,
B: ParseFragment,
C: ParseFragment,
{
type Error = Error;
fn try_from(value: EString) -> Result<Self, Self::Error> {
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))
})
fn parse_frag(value: EString) -> crate::Result<Self> {
Pair::<A, S1, EString>::parse_frag(value).and_then(|Pair(a, rest)| {
Pair::<B, S2, C>::parse_frag(rest).map(|Pair(b, c)| Self(a, b, c))
})
}
}
@ -92,7 +62,6 @@ where
#[cfg(test)]
mod tests {
use super::*;
use crate::structs::SepVec;
#[test]
fn should_parse_into_trio() {