Compare commits

..

29 commits

Author SHA1 Message Date
8814c6ef14
chore: cleanup unused imports 2022-07-28 14:42:51 +03:00
81202b9d57
bump version 2022-07-28 14:37:00 +03:00
039a0dd630
doc: add examples to readme 2022-07-28 14:36:09 +03:00
aecd3f9543 agg: add product struct 2022-07-28 10:09:41 +00:00
af55a8a31e agg: fix typo, add docs 2022-07-28 09:36:55 +00:00
e9f77c203f agg: add aggregatable trait 2022-07-28 09:36:55 +00:00
b13a510fb7 agg: add draft logic for aggregation 2022-07-28 09:36:55 +00:00
7d215c876f
doc: update version in readme 2022-07-27 18:54:20 +03:00
984e0c8fbf
bump version 2022-07-27 16:29:56 +03:00
85fbf7c9e8 core: format doc 2022-07-27 13:28:00 +00:00
7ed5ee68e8 core: fix changes in doc 2022-07-27 13:28:00 +00:00
d921f9fab2 core: implement to_estring for each type 2022-07-27 13:28:00 +00:00
ed5d7be035
doc: add documentation section 2022-07-27 11:44:17 +03:00
43af123801
doc: improve readme 2022-07-27 10:45:38 +03:00
38e035037c chore: add test with custom type 2022-07-26 20:42:01 +00:00
62e38ccf6f std: implement ParseFragment for Option
Closes #17
2022-07-26 20:42:01 +00:00
103c8f9249 chore: declare EqTrio in global scope 2022-07-26 15:55:23 +00:00
aad84aac62 chore: add more docs 2022-07-26 15:55:23 +00:00
3a234ccc8a core: add custom traits 2022-07-26 15:55:23 +00:00
brxken128
67b01b750d structs: add trio 2022-07-26 10:49:18 +00:00
d3ceb11057 chore: reimport mods 2022-07-25 19:57:40 +00:00
91d2652027 refac: restructure modules
Closes #20
2022-07-25 19:57:40 +00:00
f54b99984e
doc: add 2021 edition to installation section 2022-07-25 13:33:11 +03:00
b93c4efaa7
doc: fix the MSRV 2022-07-25 13:32:05 +03:00
13c7bcd04d
bump msrv 2022-07-25 13:31:13 +03:00
79937e86eb
doc: add build badge 2022-07-25 13:23:33 +03:00
92296599e5
ci: add github actions
Closes #2
2022-07-25 13:22:13 +03:00
a63449111e core/low: add trim type 2022-07-24 21:18:09 +00:00
299c77245d doc: change enve url 2022-07-24 21:18:09 +00:00
26 changed files with 1418 additions and 481 deletions

106
.github/workflows/ci.yml vendored Normal file
View file

@ -0,0 +1,106 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
env:
CARGO_TERM_COLOR: always
jobs:
tests:
strategy:
fail-fast: false
matrix:
os:
- ubuntu-latest
- macos-latest
- windows-latest
rust:
- 1.59.0 # msrv
- stable
- beta
- nightly
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- name: Restore cargo cache
uses: actions/cache@v2.1.7
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ matrix.os }}-cargo-${{ matrix.rust }}-${{ hashFiles('Cargo.lock') }}
- name: Toolchain
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: ${{ matrix.rust }}
override: true
- name: Run tests
uses: actions-rs/cargo@v1
with:
command: test
args: --all-features --verbose
clippy:
name: clippy (ubuntu-latest, stable)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
components: clippy
- name: Restore cargo cache
uses: actions/cache@v2.1.7
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-stable-${{ hashFiles('Cargo.lock') }}
- name: Check clippy
uses: actions-rs/cargo@v1
with:
command: clippy
args: -- -D warnings
fmt:
name: fmt (ubuntu-latest, stable)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
components: rustfmt
- name: Restore cargo cache
uses: actions/cache@v2.1.7
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-stable-${{ hashFiles('Cargo.lock') }}
- name: Check format
uses: actions-rs/cargo@v1
with:
command: fmt
args: --all -- --check

2
Cargo.lock generated
View file

@ -4,4 +4,4 @@ version = 3
[[package]] [[package]]
name = "estring" name = "estring"
version = "0.1.2" version = "0.3.0"

View file

@ -1,19 +1,15 @@
[package] [package]
name = "estring" name = "estring"
description = "A simple way to parse a string using type annotations" description = "A simple way to parse a string using type annotations"
version = "0.1.2" version = "0.3.0"
edition = "2018" edition = "2021"
authors = ["Dmitriy Pleshevskiy <dmitriy@ideascup.me>"] authors = ["Dmitriy Pleshevskiy <dmitriy@ideascup.me>"]
readme = "README.md" readme = "README.md"
repository = "https://github.com/pleshevskiy/estring" repository = "https://github.com/pleshevskiy/estring"
license = "MIT" license = "MIT"
keywords = ["parsing", "type", "annotations", "customizable"] keywords = ["parsing", "type", "annotations", "customizable"]
categories = ["data-structures", "parsing"] categories = ["data-structures", "parsing"]
rust-version = "1.59.0"
# rust-version = "1.51.0" # The first version of Cargo that supports this field is 1.56.0
[package.metadata]
msrv = "1.51.0"
[package.metadata.docs.rs] [package.metadata.docs.rs]
all-features = true all-features = true
@ -21,12 +17,9 @@ all-features = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[features] [features]
prim = ["number", "bool"]
number = []
bool = []
vec = []
tuple = []
low-level = [] low-level = []
aggs = []
structs = []
[dependencies] [dependencies]
@ -35,8 +28,8 @@ maintenance = { status = "actively-developed" }
[[example]] [[example]]
name = "calc" name = "calc"
required-features = ["vec", "number"] required-features = ["structs", "aggs"]
[[example]] [[example]]
name = "dotenv" name = "dotenv"
required-features = ["vec", "tuple", "low-level"] required-features = ["structs", "low-level"]

View file

@ -1,18 +1,45 @@
# EString # EString
[![docs.rs](https://img.shields.io/docsrs/estring?style=flat-square)](https://docs.rs/estring)
[![Crates.io](https://img.shields.io/crates/v/estring?style=flat-square)](https://crates.io/crates/estring) [![Crates.io](https://img.shields.io/crates/v/estring?style=flat-square)](https://crates.io/crates/estring)
[![Crates.io](https://img.shields.io/crates/l/estring?style=flat-square)](https://github.com/pleshevskiy/estring/LICENSE) [![docs.rs](https://img.shields.io/docsrs/estring?style=flat-square)](https://docs.rs/estring)
[![unsafe forbidden](https://img.shields.io/badge/unsafe-forbidden-success.svg?style=flat-square)](https://github.com/rust-secure-code/safety-dance/) [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/pleshevskiy/estring/CI?label=tests&logo=github&style=flat-square)](https://github.com/pleshevskiy/estring/actions/workflows/ci.yml)
[![Matrix](https://img.shields.io/matrix/enve_team:matrix.org?label=matrix&style=flat-square)](https://matrix.to/#/!yZalHbWfGRWOMaetSn:matrix.org?via=matrix.org) ![The MSRV](https://img.shields.io/badge/MSRV-1.59.0-red.svg)
```toml
[dependencies]
estring = "0.3"
```
A simple way to parse a string using type annotations. A simple way to parse a string using type annotations.
This package was originally designed for [enve] This package was originally designed for [enve].
[enve]: https://github.com/pleshevskiy/enve [enve]: https://github.com/pleshevskiy/enve
## Getting started ## [Documentation](https://docs.rs/estring)
For more details, see [examples].
[examples]: https://github.com/pleshevskiy/estring/tree/main/examples
## Usage
Basic
```rust
use estring::EString;
fn main() -> estring::Result<()> {
let res: i32 = EString::from("10").parse()?;
assert_eq!(res, 10);
Ok(())
}
```
You can use predefined structs like `SepVec` if you enable the `structs`
feature.
Note: You can use custom types as annotations! Just implement `ParseFragment`!
```rust ```rust
use estring::{SepVec, EString}; use estring::{SepVec, EString};
@ -20,7 +47,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()
@ -32,27 +59,30 @@ fn main() -> Result<(), estring::ParseError> {
} }
``` ```
You can use custom types as annotations! Just implement `TryFrom<EString>`! You can also use predefined aggregators if you enable the `aggs` feature.
## Installation ```rust
use estring::{Aggregate, EString, Product, SepVec, Sum};
**The MSRV is 1.51.0** type PlusVec<T> = SepVec<T, '+'>;
type MulVec<T> = SepVec<T, '*'>;
Add `estring = { version = "0.1", features = ["vec", "number"] }` as a fn main() -> estring::Result<()> {
dependency in `Cargo.toml`. let res = EString::from("10+5*2+3")
.parse::<Sum<PlusVec<Product<MulVec<f32>>>>>()?
.agg();
`Cargo.toml` example: assert_eq!(res, 23.0);
Ok(())
```toml }
[package]
name = "my-crate"
version = "0.1.0"
authors = ["Me <user@rust-lang.org>"]
[dependencies]
estring = { version = "0.1", features = ["vec", "number"] }
``` ```
## Contact Us
Join us in:
[![Matrix](https://img.shields.io/badge/matrix-%23enve_team:matrix.org-blueviolet.svg?style=flat-square)](https://matrix.to/#/#enve_team:matrix.org)
## License ## License
**MIT**. See [LICENSE](https://github.com/pleshevskiy/estring/LICENSE) to see **MIT**. See [LICENSE](https://github.com/pleshevskiy/estring/LICENSE) to see

View file

@ -1,14 +1,12 @@
use estring::{EString, SepVec}; use estring::{Aggregate, EString, Product, SepVec, Sum};
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::<Sum<PlusVec<Product<MulVec<f32>>>>>()?
.iter() .agg();
.map(|m| m.iter().product::<f32>())
.sum::<f32>();
assert_eq!(res, 23.0); assert_eq!(res, 23.0);
Ok(()) Ok(())

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()

8
src/agg.rs Normal file
View file

@ -0,0 +1,8 @@
//! This module will contain aggregate functions (Sum, Product, etc)
//!
mod product;
mod sum;
pub use product::*;
pub use sum::*;

92
src/agg/product.rs Normal file
View file

@ -0,0 +1,92 @@
use crate::{Aggregatable, Aggregate, EString, ParseFragment};
/// Aggregate struct, that can multiply inner aggregatable [items](Aggregatable::items) if
/// [``Aggregatable::Item``] implements [``std::iter::Product``](std::iter::Product)
///
/// # Examples
///
/// ```rust
/// use estring::{Aggregate, EString, SepVec, Product};
/// let res = EString::from("1*2*3*4")
/// .parse::<Product<SepVec<i32, '*'>>>()
/// .unwrap()
/// .agg();
/// assert_eq!(res, 24);
/// ```
#[derive(Debug, PartialEq, Eq)]
pub struct Product<T>(pub T);
impl<T> ParseFragment for Product<T>
where
T: ParseFragment,
{
fn parse_frag(es: EString) -> crate::Result<Self> {
T::parse_frag(es).map(Self)
}
}
impl<R, T> Aggregate for Product<T>
where
R: std::iter::Product,
T: Aggregatable<Item = R>,
{
type Target = R;
fn agg(self) -> Self::Target {
self.0.items().into_iter().product()
}
}
impl<R, T> Aggregatable for Product<T>
where
R: std::iter::Product,
T: Aggregatable<Item = R>,
{
type Item = R;
fn items(self) -> Vec<Self::Item> {
vec![self.agg()]
}
}
#[cfg(test)]
mod tests {
use crate::SepVec;
use super::*;
type CommaVec<T> = SepVec<T, ','>;
type MulVec<T> = SepVec<T, '*'>;
#[test]
fn should_parse_vec() {
let es = EString::from("1,2,3");
match es.parse::<Product<CommaVec<i32>>>() {
Ok(res) => assert_eq!(res, Product(CommaVec::from(vec![1, 2, 3]))),
_ => unreachable!(),
}
}
#[test]
fn should_aggregate_vector() {
let es = EString::from("1,2,3");
let expr = es.parse::<Product<CommaVec<i32>>>().unwrap();
assert_eq!(expr.agg(), 6);
}
#[test]
fn should_aggregate_vector_with_inner_vector() {
let es = EString::from("1*2,2,3");
let expr = es.parse::<Product<CommaVec<MulVec<i32>>>>().unwrap();
assert_eq!(expr.agg(), 12);
}
#[test]
fn should_aggregate_vector_with_inner_aggregation() {
let es = EString::from("1*2,2,3");
let expr = es
.parse::<Product<CommaVec<Product<MulVec<i32>>>>>()
.unwrap();
assert_eq!(expr.agg(), 12);
}
}

90
src/agg/sum.rs Normal file
View file

@ -0,0 +1,90 @@
use crate::{Aggregatable, Aggregate, EString, ParseFragment};
/// Aggregate struct, that can sum inner aggregatable [items](Aggregatable::items) if
/// [``Aggregatable::Item``] implements [``std::iter::Sum``](std::iter::Sum)
///
/// # Examples
///
/// ```rust
/// use estring::{Aggregate, EString, SepVec, Sum};
/// let res = EString::from("1+2+3+4")
/// .parse::<Sum<SepVec<i32, '+'>>>()
/// .unwrap()
/// .agg();
/// assert_eq!(res, 10);
/// ```
#[derive(Debug, PartialEq, Eq)]
pub struct Sum<T>(pub T);
impl<T> ParseFragment for Sum<T>
where
T: ParseFragment,
{
fn parse_frag(es: EString) -> crate::Result<Self> {
T::parse_frag(es).map(Self)
}
}
impl<R, T> Aggregate for Sum<T>
where
R: std::iter::Sum,
T: Aggregatable<Item = R>,
{
type Target = R;
fn agg(self) -> Self::Target {
self.0.items().into_iter().sum()
}
}
impl<R, T> Aggregatable for Sum<T>
where
R: std::iter::Sum,
T: Aggregatable<Item = R>,
{
type Item = R;
fn items(self) -> Vec<Self::Item> {
vec![self.agg()]
}
}
#[cfg(test)]
mod tests {
use crate::SepVec;
use super::*;
type CommaVec<T> = SepVec<T, ','>;
type PlusVec<T> = SepVec<T, '+'>;
#[test]
fn should_parse_vec() {
let es = EString::from("1,2,3");
match es.parse::<Sum<CommaVec<i32>>>() {
Ok(res) => assert_eq!(res, Sum(CommaVec::from(vec![1, 2, 3]))),
_ => unreachable!(),
}
}
#[test]
fn should_aggregate_vector() {
let es = EString::from("1,2,3");
let expr = es.parse::<Sum<CommaVec<i32>>>().unwrap();
assert_eq!(expr.agg(), 6);
}
#[test]
fn should_aggregate_vector_with_inner_vector() {
let es = EString::from("1+2,2,3");
let expr = es.parse::<Sum<CommaVec<PlusVec<i32>>>>().unwrap();
assert_eq!(expr.agg(), 8);
}
#[test]
fn should_aggregate_vector_with_inner_aggregation() {
let es = EString::from("1+2,2,3");
let expr = es.parse::<Sum<CommaVec<Sum<PlusVec<i32>>>>>().unwrap();
assert_eq!(expr.agg(), 8);
}
}

View file

@ -1,54 +1,226 @@
//! Contains the ``EString`` type, as well as the basic implementation of conversions to //! Contains the ``EString`` type, as well as the basic implementation of conversions to
//! string types //! string types
//! //!
#[cfg(any(feature = "number", feature = "bool"))]
pub mod prim;
#[cfg(any(feature = "number", feature = "bool"))]
pub use prim::*;
#[cfg(feature = "vec")] /// Format this type and wrap into ``EString``.
pub mod vec; ///
#[cfg(feature = "vec")] /// ``ToEString``s `to_estring` method is often used implicitly, through ``EString``s from.
pub use vec::*; ///
/// # Examples
///
/// Basic implementation of ``ToEString`` on an example ``Point``.
///
/// ```rust
/// use std::fmt::Write;
/// use estring::{EString, ToEString};
///
/// #[derive(Debug, PartialEq)]
/// struct Point {
/// x: i32,
/// y: i32,
/// }
///
/// impl ToEString for Point {
/// fn to_estring(&self) -> EString {
/// let mut res = String::new();
/// write!(res, "({},{})", self.x, self.y)
/// .ok()
/// .expect("Cannot format Point into EString");
/// EString(res)
/// }
/// }
///
/// let point = Point { x: 1, y: 2 };
/// assert_eq!(point.to_estring(), EString::from("(1,2)"));
/// ```
///
pub trait ToEString {
/// Format this type and returns ``EString``.
///
/// # Examples
///
/// ```rust
/// use estring::{EString, ToEString};
///
/// let i = 5;
/// let five = EString::from(5);
/// assert_eq!(five, i.to_estring());
/// ```
fn to_estring(&self) -> EString;
}
#[cfg(feature = "tuple")] /// Parse a value fragment from a ``EString``.
pub mod tuple; ///
#[cfg(feature = "tuple")] /// ``ParseFragment``s `parse_frag` method is often used implicitly, through ``EString``s parse.
pub use tuple::*; /// See [parse](EString::parse)s documentation for examples.
///
#[cfg(feature = "low-level")] /// # Examples
pub mod low; ///
#[cfg(feature = "low-level")] /// Basic implementation of ``ParseFragment`` on an example ``Point``.
pub use low::*; ///
/// ```rust
use crate::ParseError; /// use estring::{EString, ParseFragment, Reason};
use std::convert::{Infallible, TryFrom}; ///
/// #[derive(Debug, PartialEq)]
/// Wrapper under String type. /// struct Point {
#[derive(Debug, Default, PartialEq, Eq, Clone)] /// x: i32,
pub struct EString(pub String); /// y: i32,
/// }
impl EString { ///
/// Parses inner string by type annotations and returns result. /// 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 /// # Errors
/// ///
/// Will return `Err` if estring cannot parse inner fragment /// 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>;
}
// TODO: add example
/// Trait to represent structures that can act as aggregators.
///
/// The `agg` method works with data that has already been parsed. For this reason, **this trait
/// should never fail**.
pub trait Aggregate {
/// The resulting type after aggregation.
type Target: ?Sized;
/// Aggregates the value.
fn agg(self) -> Self::Target;
}
// TODO: add example
/// Trait to represent structures that can iterate values for the aggregator.
pub trait Aggregatable {
/// The type of the elements being iterated over.
type Item;
/// Returns Vec of aggregatable values
fn items(self) -> Vec<Self::Item>;
}
/// Wrapper under ``String`` type.
///
/// # Examples
///
/// You can create a ``EString`` from a any type that implement ``ToEString`` with ``EString::from``
///
/// ```rust
/// # use estring::EString;
/// let hello = EString::from("Hello, world");
/// let num = EString::from("999");
/// ```
///
/// You can use ``ToEString::to_estring`` directly on the type.
///
/// ```rust
/// # use estring::ToEString;
/// let some_opt = Some(999).to_estring();
/// let none_opt = None::<i32>.to_estring();
/// ```
///
#[derive(Debug, Default, PartialEq, Eq, Clone)]
pub struct EString(pub String);
impl std::fmt::Display for EString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl EString {
/// Creates a new empty ``EString``.
///
/// This will not allocate any inital buffer.
///
/// # Examples
///
/// Basic usage:
///
/// ```rust
/// # use estring::EString;
/// let s = EString::new();
/// ```
#[must_use]
#[inline] #[inline]
pub fn parse<T: TryFrom<EString>>(self) -> Result<T, ParseError> { pub fn new() -> Self {
let orig = self.0.clone(); Self(String::new())
<T as TryFrom<EString>>::try_from(self).map_err(|_| ParseError(orig)) }
/// Parses this inner string into another type.
///
/// `parse` can parse into any type that implements the ``ParseFragment`` trait.
///
/// # Errors
///
/// Will return `Err` if estring cannot parse inner fragment into the desired type.
///
/// # Examples
///
/// Basic usage
///
/// ```rust
/// # use estring::{EString, ParseFragment};
/// let fragment = EString::from("5");
/// let res = i32::parse_frag(fragment);
/// assert_eq!(res, Ok(5));
/// ```
///
/// Failing to parse:
///
/// ```rust
/// # use estring::{EString, ParseFragment, Error, Reason};
/// let fragment = EString::from("j");
/// let res = i32::parse_frag(fragment.clone());
/// assert_eq!(res, Err(Error(fragment, Reason::Parse)));
/// ```
#[inline]
pub fn parse<T: ParseFragment>(self) -> crate::Result<T> {
T::parse_frag(self)
} }
} }
impl<T> From<T> for EString impl<T> From<T> for EString
where where
T: std::fmt::Display, T: ToEString,
{ {
#[inline] #[inline]
fn from(val: T) -> Self { fn from(val: T) -> Self {
Self(val.to_string()) val.to_estring()
} }
} }
@ -61,21 +233,68 @@ 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(es: EString) -> crate::Result<Self> {
Ok(s.0) Ok(es)
} }
} }
impl TryFrom<EString> for &'static str { #[cfg(feature = "aggs")]
type Error = Infallible; impl Aggregatable for EString {
type Item = Self;
#[inline] #[inline]
fn try_from(s: EString) -> Result<Self, Self::Error> { fn items(self) -> Vec<Self::Item> {
Ok(Box::leak(s.0.into_boxed_str())) vec![self]
}
}
impl ParseFragment for String {
#[inline]
fn parse_frag(es: EString) -> crate::Result<Self> {
Ok(es.0)
}
}
impl ToEString for String {
#[inline]
fn to_estring(&self) -> EString {
EString(self.clone())
}
}
#[cfg(feature = "aggs")]
impl Aggregatable for String {
type Item = Self;
#[inline]
fn items(self) -> Vec<Self::Item> {
vec![self]
}
}
impl ParseFragment for &'static str {
#[inline]
fn parse_frag(es: EString) -> crate::Result<Self> {
Ok(Box::leak(es.0.into_boxed_str()))
}
}
impl<'a> ToEString for &'a str {
#[inline]
fn to_estring(&self) -> EString {
EString((*self).to_string())
}
}
#[cfg(feature = "aggs")]
impl<'a> Aggregatable for &'a str {
type Item = Self;
#[inline]
fn items(self) -> Vec<Self::Item> {
vec![self]
} }
} }

View file

@ -1,14 +0,0 @@
//! Contains the implementations to primitive types (number, boolean)
//!
//! **NOTE**: Require the enabling of the same-name features
//!
#[cfg(feature = "bool")]
mod bool;
#[cfg(feature = "bool")]
pub use self::bool::*;
#[cfg(feature = "number")]
mod number;
#[cfg(feature = "number")]
pub use self::number::*;

View file

@ -1,62 +0,0 @@
use crate::core::EString;
use std::convert::TryFrom;
#[doc(hidden)]
macro_rules! from_env_string_numbers_impl {
($($ty:ty),+$(,)?) => {
$(
#[cfg(feature = "number")]
impl TryFrom<EString> for $ty {
type Error = <$ty as std::str::FromStr>::Err;
#[inline]
fn try_from(s: EString) -> Result<Self, Self::Error> {
s.0.parse::<Self>()
}
}
)+
};
}
#[rustfmt::skip]
from_env_string_numbers_impl![
i8, i16, i32, i64, i128, isize,
u8, u16, u32, u64, u128, usize,
f32, f64
];
#[cfg(test)]
mod tests {
use super::*;
use crate::ParseError;
#[test]
fn should_parse_number() {
let estr = EString::from("-10");
match estr.parse::<i32>() {
Ok(res) => assert_eq!(res, -10),
_ => unreachable!(),
};
}
#[test]
fn should_parse_float_number() {
let estr = EString::from("-0.15");
match estr.parse::<f32>() {
#[allow(clippy::float_cmp)]
Ok(res) => assert_eq!(res, -0.15),
_ => unreachable!(),
};
}
#[test]
fn should_throw_parse_error() {
let estr = EString::from("-10");
match estr.parse::<u32>() {
Err(ParseError(orig)) => {
assert_eq!(orig, String::from("-10"));
}
_ => unreachable!(),
};
}
}

View file

@ -1,132 +0,0 @@
//! Contains the implementations to tuple type
//!
//! **NOTE**: Require the enabling of the `tuple` features
//!
use crate::core::EString;
use std::convert::TryFrom;
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.
///
/// # Examples
///
/// ```rust
/// use estring::{Pair, EString};
///
/// type EqPair<A, B> = Pair<A, '=', B>;
///
/// fn main() -> Result<(), estring::ParseError> {
/// let res = EString::from("one=two=free").parse::<EqPair<&str, &str>>()?;
/// assert_eq!(res, Pair("one", "two=free"));
/// Ok(())
/// }
/// ```
///
#[derive(Debug, PartialEq, Clone)]
pub struct Pair<A, const S1: char, B>(pub A, pub B);
impl<A, B, const S1: char> From<(A, B)> for Pair<A, S1, B> {
#[inline]
fn from((a, b): (A, B)) -> Self {
Self(a, b)
}
}
impl<A, B, const S1: char> std::fmt::Display for Pair<A, S1, B>
where
A: std::fmt::Display,
B: std::fmt::Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0.to_string())?;
f.write_char(S1)?;
f.write_str(&self.1.to_string())
}
}
impl<A, const S1: char, B> TryFrom<EString> for Pair<A, S1, B>
where
A: TryFrom<EString>,
B: TryFrom<EString>,
{
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))
})
}
}
#[cfg(test)]
mod tests {
use super::*;
type EqPair<A, B> = Pair<A, '=', B>;
#[test]
fn should_parse_into_pair() {
let estr = EString::from("hello=world=hello");
match estr.parse::<EqPair<&str, &str>>() {
Ok(res) => assert_eq!((res.0, res.1), ("hello", "world=hello")),
_ => unreachable!(),
};
}
#[test]
fn should_parse_rest_as_pair() {
let estr = EString::from("hello=world=hello");
match estr.parse::<EqPair<&str, EqPair<&str, &str>>>() {
Ok(res) => assert_eq!(res, Pair("hello", Pair("world", "hello"))),
_ => unreachable!(),
};
}
#[cfg(feature = "number")]
mod vec {
use crate::SepVec;
use super::*;
type LineVec<T> = SepVec<T, '\n'>;
#[test]
fn should_parse_vec_of_pairs() {
let estr = EString::from(
"foo=bar
hello=bar",
);
match estr.parse::<LineVec<EqPair<&str, &str>>>() {
Ok(res) => assert_eq!(res, SepVec(vec![Pair("foo", "bar"), Pair("hello", "bar"),])),
_ => unreachable!(),
};
}
}
}

View file

@ -1,151 +0,0 @@
//! Contains the implementations to vec type
//!
//! **NOTE**: Require the enabling of the `vec` features
//!
use crate::core::EString;
use std::convert::TryFrom;
use std::fmt::Write;
/// Wrapper for ``Vec`` to split string by a separator (`SEP`).
///
/// **NOTE**: Required the enabling of the `vec` feature.
///
/// # Examples
///
/// ```rust
/// use estring::{SepVec, EString};
///
/// type CommaVec<T> = SepVec<T, ','>;
///
/// fn main() -> Result<(), estring::ParseError> {
/// let res = EString::from("1,2,3").parse::<CommaVec<u8>>()?;
/// assert_eq!(*res, vec![1, 2, 3]);
/// Ok(())
/// }
/// ```
///
#[derive(Debug, PartialEq, Clone)]
pub struct SepVec<T, const SEP: char>(pub Vec<T>);
impl<T, const SEP: char> std::ops::Deref for SepVec<T, SEP> {
type Target = Vec<T>;
#[inline]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T, const SEP: char> From<Vec<T>> for SepVec<T, SEP> {
#[inline]
fn from(vec: Vec<T>) -> Self {
Self(vec)
}
}
impl<T, const SEP: char> std::fmt::Display for SepVec<T, SEP>
where
T: std::fmt::Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.iter().enumerate().try_for_each(|(i, part)| {
if i != 0 {
f.write_char(SEP)?;
}
f.write_str(&part.to_string())
})
}
}
impl<T, const SEP: char> TryFrom<EString> for SepVec<T, SEP>
where
T: TryFrom<EString> + std::fmt::Display,
{
type Error = T::Error;
fn try_from(value: EString) -> Result<Self, Self::Error> {
let inner = value
.split(SEP)
.map(str::trim)
.map(EString::from)
.map(T::try_from)
.collect::<Result<Vec<_>, _>>()?;
Ok(Self(inner))
}
}
#[cfg(test)]
mod tests {
use super::*;
const COMMA: char = ',';
const SEMI: char = ';';
type CommaVec<T> = SepVec<T, COMMA>;
type SemiVec<T> = SepVec<T, SEMI>;
#[test]
fn should_parse_into_vec() {
let estr = EString::from("a,b,c,d,e");
match estr.parse::<CommaVec<&str>>() {
Ok(res) => assert_eq!(*res, vec!["a", "b", "c", "d", "e"]),
_ => unreachable!(),
};
}
#[test]
fn should_trim_identations_before_parsing() {
let input = "
a , b, c,
d,e";
let estr = EString::from(input);
match estr.parse::<CommaVec<&str>>() {
Ok(res) => assert_eq!(*res, vec!["a", "b", "c", "d", "e"]),
_ => unreachable!(),
};
}
#[test]
fn should_parse_into_vector_of_vectors() {
let estr = EString::from("a,b; c,d,e; f,g");
match estr.parse::<SemiVec<CommaVec<&str>>>() {
Ok(res) => assert_eq!(
res,
SemiVec::from(vec![
CommaVec::from(vec!["a", "b"]),
CommaVec::from(vec!["c", "d", "e"]),
CommaVec::from(vec!["f", "g"])
])
),
_ => unreachable!(),
};
}
#[cfg(feature = "number")]
mod numbers {
use super::*;
use crate::ParseError;
#[test]
fn should_parse_into_num_vec() {
let estr = EString::from("1,2,3,4,5");
match estr.parse::<CommaVec<i32>>() {
Ok(res) => assert_eq!(*res, vec![1, 2, 3, 4, 5]),
_ => unreachable!(),
};
}
#[test]
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"));
}
_ => unreachable!(),
};
}
}
}

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, PartialEq, Eq)]
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

@ -7,7 +7,23 @@
//! //!
//! [enve]: https://github.com/pleshevskiy/enve //! [enve]: https://github.com/pleshevskiy/enve
//! //!
//! ## Getting started //! ## Usage
//!
//! Basic
//!
//! ```rust
//! use estring::EString;
//!
//! fn main() -> estring::Result<()> {
//! let res: i32 = EString::from("10").parse()?;
//! assert_eq!(res, 10);
//! Ok(())
//! }
//! ```
//!
//! You can use predefined structs like ``SepVec`` if you enable `structs` feature.
//!
//! Note: You can use custom types as annotations! Just implement ``ParseFragment``!
//! //!
//! ```rust //! ```rust
//! use estring::{SepVec, EString}; //! use estring::{SepVec, EString};
@ -15,7 +31,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()
@ -27,12 +43,88 @@
//! } //! }
//! ``` //! ```
//! //!
//! You can also use predefined aggregators if you enable `aggs` feature.
//!
//! ```rust
//! use estring::{Aggregate, EString, Product, SepVec, Sum};
//!
//! type PlusVec<T> = SepVec<T, '+'>;
//! type MulVec<T> = SepVec<T, '*'>;
//!
//! fn main() -> estring::Result<()> {
//! let res = EString::from("10+5*2+3")
//! .parse::<Sum<PlusVec<Product<MulVec<f32>>>>>()?
//! .agg();
//!
//! assert_eq!(res, 23.0);
//! Ok(())
//! }
//! ```
//!
//! ---
//!
//! For more details, see [examples].
//!
//! [examples]: https://github.com/pleshevskiy/estring/tree/main/examples
//!
#![deny(clippy::pedantic)] #![deny(clippy::pedantic)]
#![allow(clippy::module_name_repetitions)] #![allow(clippy::module_name_repetitions)]
#![warn(missing_docs)] #![warn(missing_docs)]
pub mod core;
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 std;
#[cfg(feature = "aggs")]
pub mod agg;
#[cfg(feature = "aggs")]
pub use agg::*;
#[cfg(feature = "low-level")]
pub mod low;
#[cfg(feature = "low-level")]
pub use low::*;
#[cfg(feature = "structs")]
pub mod structs;
#[cfg(feature = "structs")]
pub use structs::*;
pub use crate::core::*; pub use crate::core::*;
pub use crate::error::ParseError;

View file

@ -1,9 +1,4 @@
use crate::core::EString; use crate::core::{EString, ParseFragment, ToEString};
use std::convert::TryFrom;
//===========================================================================//
// TRIM //
//===========================================================================//
/// Wrapper that allow to trim substring before continue /// Wrapper that allow to trim substring before continue
/// ///
@ -14,7 +9,7 @@ use std::convert::TryFrom;
/// ```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(())
@ -38,16 +33,21 @@ 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> { impl<T> ToEString for Trim<T>
T::try_from(EString::from(value.trim())) where
.map(Trim) T: ToEString,
.map_err(|_| ()) {
fn to_estring(&self) -> EString {
self.0.to_estring()
} }
} }
@ -65,7 +65,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 ");

6
src/std.rs Normal file
View file

@ -0,0 +1,6 @@
//! Contains implementations for standard types (`bool`, numbers, `Option`, etc.)
//!
mod bool;
mod number;
mod option;

View file

@ -1,23 +1,37 @@
use crate::core::EString; use crate::core::{EString, ParseFragment, ToEString};
use std::convert::TryFrom; 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)),
} }
} }
} }
impl ToEString for bool {
#[inline]
fn to_estring(&self) -> EString {
EString(self.to_string())
}
}
#[cfg(feature = "aggs")]
impl crate::core::Aggregatable for bool {
type Item = Self;
#[inline]
fn items(self) -> Vec<Self::Item> {
vec![self]
}
}
#[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() {
@ -48,10 +62,17 @@ 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!(),
}; };
} }
#[test]
fn should_format_bool() {
assert_eq!(true.to_estring(), EString(String::from("true")));
assert_eq!(false.to_estring(), EString(String::from("false")));
}
} }

83
src/std/number.rs Normal file
View file

@ -0,0 +1,83 @@
use crate::core::{EString, ParseFragment, ToEString};
use crate::error::{Error, Reason};
#[doc(hidden)]
macro_rules! from_env_string_numbers_impl {
($($ty:ty),+$(,)?) => {
$(
impl ParseFragment for $ty {
#[inline]
fn parse_frag(s: EString) -> crate::Result<Self> {
s.0.parse::<Self>().map_err(|_| Error(s, Reason::Parse))
}
}
impl ToEString for $ty {
#[inline]
fn to_estring(&self) -> EString {
EString(self.to_string())
}
}
#[cfg(feature = "aggs")]
impl crate::core::Aggregatable for $ty {
type Item = Self;
#[inline]
fn items(self) -> Vec<Self::Item> {
vec![self]
}
}
)+
};
}
#[rustfmt::skip]
from_env_string_numbers_impl![
i8, i16, i32, i64, i128, isize,
u8, u16, u32, u64, u128, usize,
f32, f64
];
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_parse_number() {
let estr = EString::from("-10");
match estr.parse::<i32>() {
Ok(res) => assert_eq!(res, -10),
_ => unreachable!(),
};
}
#[test]
fn should_parse_float_number() {
let estr = EString::from("-0.15");
match estr.parse::<f32>() {
#[allow(clippy::float_cmp)]
Ok(res) => assert_eq!(res, -0.15),
_ => unreachable!(),
};
}
#[test]
fn should_throw_parse_error() {
let estr = EString::from("-10");
match estr.parse::<u32>() {
Err(Error(orig, reason)) => {
assert_eq!(orig, EString::from("-10"));
assert_eq!(reason, Reason::Parse);
}
_ => unreachable!(),
};
}
#[test]
fn should_format_number() {
assert_eq!((-1).to_estring(), EString(String::from("-1")));
assert_eq!(10.to_estring(), EString(String::from("10")));
assert_eq!(1.1.to_estring(), EString(String::from("1.1")));
}
}

77
src/std/option.rs Normal file
View file

@ -0,0 +1,77 @@
use crate::core::{EString, ParseFragment, ToEString};
impl<T> ToEString for Option<T>
where
T: ToEString,
{
fn to_estring(&self) -> EString {
match self {
Some(inner) => inner.to_estring(),
None => EString::new(),
}
}
}
impl<T> ParseFragment for Option<T>
where
T: ParseFragment,
{
fn parse_frag(es: EString) -> crate::Result<Self> {
if es.is_empty() {
Ok(None)
} else {
es.parse().map(Some)
}
}
}
#[cfg(feature = "aggs")]
impl<T> crate::core::Aggregatable for Option<T>
where
T: crate::core::Aggregatable,
{
type Item = T::Item;
fn items(self) -> Vec<Self::Item> {
self.map(T::items).unwrap_or_default()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::structs::Pair;
#[test]
fn should_parse_empty_string_as_none() {
let estr = EString::new();
match estr.parse::<Option<i32>>() {
Ok(res) => assert_eq!(res, None),
_ => unreachable!(),
}
}
#[test]
fn should_parse_number_as_some() {
let estr = EString::from("99");
match estr.parse::<Option<i32>>() {
Ok(res) => assert_eq!(res, Some(99)),
_ => unreachable!(),
}
}
#[test]
fn should_parse_pair() {
let estr = EString::from("1+2");
match estr.parse::<Option<Pair<i32, '+', i32>>>() {
Ok(res) => assert_eq!(res, Some(Pair(1, 2))),
_ => unreachable!(),
}
}
#[test]
fn should_format_option() {
assert_eq!(None::<i32>.to_estring(), EString::new());
assert_eq!(Some(99).to_estring(), EString(String::from("99")));
}
}

12
src/structs.rs Normal file
View file

@ -0,0 +1,12 @@
//! Contains the predefined types (``SepVec``, ``Pair``, etc.)
//!
//! **NOTE**: Require the enabling the `structs` feature.
//!
mod pair;
mod sep_vec;
mod trio;
pub use pair::*;
pub use sep_vec::*;
pub use trio::*;

125
src/structs/pair.rs Normal file
View file

@ -0,0 +1,125 @@
//! Contains the implementations to pair tuple type
//!
use crate::core::{EString, ParseFragment, ToEString};
use crate::{Error, Reason};
use std::fmt::Write;
/// Wrapper for pair (A, B) tuple to split string by a separator (`S1`).
///
/// **NOTE**: Required the enabling of the `structs` feature.
///
/// # Examples
///
/// ```rust
/// use estring::{Pair, EString};
///
/// type EqPair<A, B> = Pair<A, '=', B>;
///
/// fn main() -> estring::Result<()> {
/// let res = EString::from("one=two=free").parse::<EqPair<&str, &str>>()?;
/// assert_eq!(res, Pair("one", "two=free"));
/// Ok(())
/// }
/// ```
///
#[derive(Debug, PartialEq, Clone)]
pub struct Pair<A, const S1: char, B>(pub A, pub B);
impl<A, B, const S1: char> From<(A, B)> for Pair<A, S1, B> {
#[inline]
fn from((a, b): (A, B)) -> Self {
Self(a, b)
}
}
impl<A, B, const S1: char> std::fmt::Display for Pair<A, S1, B>
where
A: std::fmt::Display,
B: std::fmt::Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}{}{}", self.0, S1, self.1)
}
}
impl<A, B, const S1: char> ToEString for Pair<A, S1, B>
where
A: ToEString,
B: ToEString,
{
fn to_estring(&self) -> EString {
let mut res = String::new();
write!(res, "{}{}{}", self.0.to_estring(), S1, self.1.to_estring())
.ok()
.expect("Cannot parse Pair to EString");
EString(res)
}
}
impl<A, B, const S1: char> ParseFragment for Pair<A, S1, B>
where
A: ParseFragment,
B: ParseFragment,
{
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))
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::structs::SepVec;
type EqPair<A, B> = Pair<A, '=', B>;
#[test]
fn should_parse_into_pair() {
let estr = EString::from("hello=world=hello");
match estr.parse::<EqPair<&str, &str>>() {
Ok(res) => assert_eq!((res.0, res.1), ("hello", "world=hello")),
_ => unreachable!(),
};
}
#[test]
fn should_parse_rest_as_pair() {
let estr = EString::from("hello=world=hello");
match estr.parse::<EqPair<&str, EqPair<&str, &str>>>() {
Ok(res) => assert_eq!(res, Pair("hello", Pair("world", "hello"))),
_ => unreachable!(),
};
}
type LineVec<T> = SepVec<T, '\n'>;
#[test]
fn should_parse_vec_of_pairs() {
let estr = EString::from(
"foo=bar
hello=bar",
);
match estr.parse::<LineVec<EqPair<&str, &str>>>() {
Ok(res) => assert_eq!(res, SepVec(vec![Pair("foo", "bar"), Pair("hello", "bar"),])),
_ => unreachable!(),
};
}
#[test]
fn should_format_pair() {
let pair = Pair::<_, '+', _>(1, 2);
assert_eq!(pair.to_estring(), EString(String::from("1+2")));
let pair_in_pair = Pair::<_, '=', _>(3, pair);
assert_eq!(pair_in_pair.to_estring(), EString(String::from("3=1+2")));
}
}

198
src/structs/sep_vec.rs Normal file
View file

@ -0,0 +1,198 @@
//! Contains the implementations to vec type
//!
use crate::core::{EString, ParseFragment, ToEString};
use std::fmt::Write;
/// Wrapper for ``Vec`` to split string by a separator (`SEP`).
///
/// **NOTE**: Required the enabling of the `structs` feature.
///
/// # Examples
///
/// ```rust
/// use estring::{SepVec, EString};
///
/// type CommaVec<T> = SepVec<T, ','>;
///
/// fn main() -> estring::Result<()> {
/// let res = EString::from("1,2,3").parse::<CommaVec<u8>>()?;
/// assert_eq!(*res, vec![1, 2, 3]);
/// Ok(())
/// }
/// ```
///
#[derive(Debug, PartialEq, Clone)]
pub struct SepVec<T, const SEP: char>(pub Vec<T>);
impl<T, const SEP: char> std::ops::Deref for SepVec<T, SEP> {
type Target = Vec<T>;
#[inline]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T, const SEP: char> From<Vec<T>> for SepVec<T, SEP> {
#[inline]
fn from(vec: Vec<T>) -> Self {
Self(vec)
}
}
impl<T, const SEP: char> std::fmt::Display for SepVec<T, SEP>
where
T: std::fmt::Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.iter().enumerate().try_for_each(|(i, part)| {
if i != 0 {
f.write_char(SEP)?;
}
write!(f, "{}", part)
})
}
}
impl<T, const SEP: char> ToEString for SepVec<T, SEP>
where
T: ToEString,
{
fn to_estring(&self) -> EString {
self.0
.iter()
.enumerate()
.try_fold(String::new(), |mut res, (i, part)| {
if i != 0 {
res.write_char(SEP).ok()?;
}
write!(res, "{}", part.to_estring()).ok()?;
Some(res)
})
.map(EString)
.expect("Cannot format SepVec ${self.0} to EString")
}
}
impl<T, const SEP: char> ParseFragment for SepVec<T, SEP>
where
T: ParseFragment,
{
fn parse_frag(value: EString) -> crate::Result<Self> {
let inner = value
.split(SEP)
.map(str::trim)
.map(EString::from)
.map(T::parse_frag)
.collect::<crate::Result<Vec<_>>>()?;
Ok(Self(inner))
}
}
#[cfg(feature = "aggs")]
impl<T, const SEP: char> crate::core::Aggregatable for SepVec<T, SEP>
where
T: crate::core::Aggregatable,
{
type Item = T::Item;
fn items(self) -> Vec<Self::Item> {
self.0.into_iter().flat_map(T::items).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Aggregatable;
use crate::Pair;
use crate::{Error, Reason};
type CommaVec<T> = SepVec<T, ','>;
type SemiVec<T> = SepVec<T, ';'>;
#[test]
fn should_parse_into_vec() {
let estr = EString::from("a,b,c,d,e");
match estr.parse::<CommaVec<&str>>() {
Ok(res) => assert_eq!(*res, vec!["a", "b", "c", "d", "e"]),
_ => unreachable!(),
};
}
#[test]
fn should_trim_identations_before_parsing() {
let input = "
a , b, c,
d,e";
let estr = EString::from(input);
match estr.parse::<CommaVec<&str>>() {
Ok(res) => assert_eq!(*res, vec!["a", "b", "c", "d", "e"]),
_ => unreachable!(),
};
}
#[test]
fn should_parse_into_vector_of_vectors() {
let estr = EString::from("a,b; c,d,e; f,g");
match estr.parse::<SemiVec<CommaVec<&str>>>() {
Ok(res) => assert_eq!(
res,
SemiVec::from(vec![
CommaVec::from(vec!["a", "b"]),
CommaVec::from(vec!["c", "d", "e"]),
CommaVec::from(vec!["f", "g"])
])
),
_ => unreachable!(),
};
}
#[test]
fn should_parse_into_num_vec() {
let estr = EString::from("1,2,3,4,5");
match estr.parse::<CommaVec<i32>>() {
Ok(res) => assert_eq!(*res, vec![1, 2, 3, 4, 5]),
_ => unreachable!(),
};
}
#[test]
fn should_throw_parse_vec_error() {
let estr = EString::from("1,2,3,4,5");
match estr.parse::<SemiVec<i32>>() {
Err(Error(orig, reason)) => {
assert_eq!(orig, EString::from("1,2,3,4,5"));
assert_eq!(reason, Reason::Parse);
}
_ => unreachable!(),
};
}
#[test]
fn should_format_vec() {
type PlusPair<T> = Pair<T, '+', T>;
let vec = SepVec::<_, ','>::from(vec![1, 2, 3]);
assert_eq!(vec.to_estring(), EString(String::from("1,2,3")));
let vec = SepVec::<_, ','>::from(vec![PlusPair::from((1, 2)), PlusPair::from((3, 4))]);
assert_eq!(vec.to_estring(), EString(String::from("1+2,3+4")));
}
#[test]
fn should_returns_aggregatable_items() {
let estr = EString::from("1,2,3,4,5");
let res = estr.parse::<CommaVec<i32>>().unwrap();
assert_eq!(res.items(), vec![1, 2, 3, 4, 5]);
}
#[test]
fn should_returns_flatten_aggregatable_items() {
let estr = EString::from("1,2; 3,4,5; 6,7");
let res = estr.parse::<SemiVec<CommaVec<i32>>>().unwrap();
assert_eq!(res.items(), vec![1, 2, 3, 4, 5, 6, 7]);
}
}

132
src/structs/trio.rs Normal file
View file

@ -0,0 +1,132 @@
//! Contains the implementations to parse triple-tuple type
//!
use super::Pair;
use crate::core::{EString, ParseFragment, ToEString};
use std::fmt::Write;
/// Wrapper for trio (A, B, C) tuple to split string by separators (`S1` and `S2`).
///
/// **NOTE**: Required the enabling of the `structs` feature.
///
/// # Examples
///
/// ```rust
/// use estring::{Trio, EString};
///
/// fn main() -> estring::Result<()> {
/// let res = EString::from("one+two=free").parse::<Trio<&str, '+', &str, '=', &str>>()?;
/// assert_eq!(res, Trio("one", "two", "free"));
/// Ok(())
/// }
/// ```
///
#[derive(Debug, PartialEq, Clone)]
pub struct Trio<A, const S1: char, B, const S2: char, C>(pub A, pub B, pub C);
impl<A, B, C, const S1: char, const S2: char> From<(A, B, C)> for Trio<A, S1, B, S2, C> {
#[inline]
fn from((a, b, c): (A, B, C)) -> Self {
Self(a, b, c)
}
}
impl<A, B, C, const S1: char, const S2: char> std::fmt::Display for Trio<A, S1, B, S2, C>
where
A: std::fmt::Display,
B: std::fmt::Display,
C: std::fmt::Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0.to_string())?;
f.write_char(S1)?;
f.write_str(&self.1.to_string())?;
f.write_char(S2)?;
f.write_str(&self.2.to_string())
}
}
impl<A, B, C, const S1: char, const S2: char> ToEString for Trio<A, S1, B, S2, C>
where
A: ToEString,
B: ToEString,
C: ToEString,
{
fn to_estring(&self) -> EString {
let mut res = String::new();
write!(
res,
"{}{}{}{}{}",
self.0.to_estring(),
S1,
self.1.to_estring(),
S2,
self.2.to_estring()
)
.ok()
.expect("Cannot parse Pair to EString");
EString(res)
}
}
impl<A, const S1: char, B, const S2: char, C> ParseFragment for Trio<A, S1, B, S2, C>
where
A: ParseFragment,
B: ParseFragment,
C: ParseFragment,
{
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))
})
}
}
#[cfg(test)]
mod tests {
use super::*;
type EqTrio<A, B, C> = Trio<A, '=', B, '=', C>;
#[test]
fn should_parse_into_trio() {
let estr = EString::from("hello=world=hello");
match estr.parse::<EqTrio<&str, &str, &str>>() {
Ok(res) => assert_eq!((res.0, res.1, res.2), ("hello", "world", "hello")),
_ => unreachable!(),
};
}
#[test]
fn should_parse_into_trio_with_alternate_delims() {
let estr = EString::from("hello-world^hello");
match estr.parse::<Trio<&str, '-', &str, '^', &str>>() {
Ok(res) => assert_eq!((res.0, res.1, res.2), ("hello", "world", "hello")),
_ => unreachable!(),
};
}
#[test]
fn should_parse_rest_as_trio() {
let estr = EString::from("hello=world=hello=world=hello");
match estr.parse::<EqTrio<&str, &str, EqTrio<&str, &str, &str>>>() {
Ok(res) => assert_eq!(res, Trio("hello", "world", Trio("hello", "world", "hello"))),
_ => unreachable!(),
};
}
#[test]
fn should_format_trio() {
let trio = Trio::<_, '+', _, '-', _>::from(("foo", "baz", "bar"));
assert_eq!(
trio.clone().to_estring(),
EString(String::from("foo+baz-bar"))
);
let trio_in_trio = Trio::<_, '*', _, '=', _>::from(("foo", "baz", trio));
assert_eq!(
trio_in_trio.clone().to_estring(),
EString(String::from("foo*baz=foo+baz-bar"))
);
}
}