Compare commits

..

12 commits

14 changed files with 390 additions and 20 deletions

5
Cargo.lock generated
View file

@ -1,6 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "estring"
version = "0.1.2"
version = "0.3.0"

View file

@ -1,7 +1,7 @@
[package]
name = "estring"
description = "A simple way to parse a string using type annotations"
version = "0.1.2"
version = "0.3.0"
edition = "2021"
authors = ["Dmitriy Pleshevskiy <dmitriy@ideascup.me>"]
readme = "README.md"
@ -28,7 +28,7 @@ maintenance = { status = "actively-developed" }
[[example]]
name = "calc"
required-features = ["structs"]
required-features = ["structs", "aggs"]
[[example]]
name = "dotenv"

View file

@ -7,7 +7,7 @@
```toml
[dependencies]
estring = "0.1"
estring = "0.3"
```
A simple way to parse a string using type annotations.
@ -24,6 +24,23 @@ For more details, see [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
use estring::{SepVec, EString};
@ -42,8 +59,23 @@ fn main() -> estring::Result<()> {
}
```
You can use custom types as annotations! Just implement
`estring::ParseFragment`!
You can also use predefined aggregators if you enable the `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(())
}
```
## Contact Us

View file

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

View file

@ -1,2 +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

@ -23,7 +23,9 @@
/// 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");
/// write!(res, "({},{})", self.x, self.y)
/// .ok()
/// .expect("Cannot format Point into EString");
/// EString(res)
/// }
/// }
@ -108,6 +110,29 @@ pub trait ParseFragment: Sized {
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
@ -215,6 +240,16 @@ impl ParseFragment for EString {
}
}
#[cfg(feature = "aggs")]
impl Aggregatable for EString {
type Item = Self;
#[inline]
fn items(self) -> Vec<Self::Item> {
vec![self]
}
}
impl ParseFragment for String {
#[inline]
fn parse_frag(es: EString) -> crate::Result<Self> {
@ -229,6 +264,16 @@ impl ToEString for String {
}
}
#[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> {
@ -243,6 +288,16 @@ impl<'a> ToEString for &'a str {
}
}
#[cfg(feature = "aggs")]
impl<'a> Aggregatable for &'a str {
type Item = Self;
#[inline]
fn items(self) -> Vec<Self::Item> {
vec![self]
}
}
#[cfg(test)]
mod tests {
use super::*;

View file

@ -7,7 +7,23 @@
//!
//! [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
//! use estring::{SepVec, EString};
@ -27,6 +43,30 @@
//! }
//! ```
//!
//! 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)]
#![allow(clippy::module_name_repetitions)]
#![warn(missing_docs)]

View file

@ -19,6 +19,16 @@ impl ToEString for bool {
}
}
#[cfg(feature = "aggs")]
impl crate::core::Aggregatable for bool {
type Item = Self;
#[inline]
fn items(self) -> Vec<Self::Item> {
vec![self]
}
}
#[cfg(test)]
mod tests {
use super::*;

View file

@ -18,6 +18,16 @@ macro_rules! from_env_string_numbers_impl {
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]
}
}
)+
};
}

View file

@ -25,6 +25,18 @@ where
}
}
#[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::*;

View file

@ -118,7 +118,7 @@ hello=bar",
#[test]
fn should_format_pair() {
let pair = Pair::<_, '+', _>(1, 2);
assert_eq!(pair.clone().to_estring(), EString(String::from("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")));
}

View file

@ -92,17 +92,27 @@ where
}
}
#[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};
const COMMA: char = ',';
const SEMI: char = ';';
type CommaVec<T> = SepVec<T, COMMA>;
type SemiVec<T> = SepVec<T, SEMI>;
type CommaVec<T> = SepVec<T, ','>;
type SemiVec<T> = SepVec<T, ';'>;
#[test]
fn should_parse_into_vec() {
@ -171,4 +181,18 @@ d,e";
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]);
}
}