Compare commits
19 commits
parse-trai
...
main
Author | SHA1 | Date | |
---|---|---|---|
8814c6ef14 | |||
81202b9d57 | |||
039a0dd630 | |||
aecd3f9543 | |||
af55a8a31e | |||
e9f77c203f | |||
b13a510fb7 | |||
7d215c876f | |||
984e0c8fbf | |||
85fbf7c9e8 | |||
7ed5ee68e8 | |||
d921f9fab2 | |||
ed5d7be035 | |||
43af123801 | |||
38e035037c | |||
62e38ccf6f | |||
103c8f9249 | |||
aad84aac62 | |||
3a234ccc8a |
17 changed files with 715 additions and 66 deletions
5
Cargo.lock
generated
5
Cargo.lock
generated
|
@ -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"
|
||||
|
|
|
@ -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"
|
||||
|
|
75
README.md
75
README.md
|
@ -1,19 +1,45 @@
|
|||
# EString
|
||||
|
||||
[![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)
|
||||
[![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/l/estring?style=flat-square)](https://github.com/pleshevskiy/estring/LICENSE)
|
||||
[![unsafe forbidden](https://img.shields.io/badge/unsafe-forbidden-success.svg?style=flat-square)](https://github.com/rust-secure-code/safety-dance/)
|
||||
[![Matrix](https://img.shields.io/matrix/enve_team:matrix.org?label=matrix&style=flat-square)](https://matrix.to/#/!yZalHbWfGRWOMaetSn:matrix.org?via=matrix.org)
|
||||
[![docs.rs](https://img.shields.io/docsrs/estring?style=flat-square)](https://docs.rs/estring)
|
||||
[![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)
|
||||
![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.
|
||||
|
||||
This package was originally designed for [enve]
|
||||
This package was originally designed for [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
|
||||
use estring::{SepVec, EString};
|
||||
|
@ -33,29 +59,30 @@ 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.
|
||||
|
||||
## Installation
|
||||
```rust
|
||||
use estring::{Aggregate, EString, Product, SepVec, Sum};
|
||||
|
||||
**The MSRV is 1.59.0**
|
||||
type PlusVec<T> = SepVec<T, '+'>;
|
||||
type MulVec<T> = SepVec<T, '*'>;
|
||||
|
||||
Add `estring = { version = "0.1", features = ["structs"] }` as a dependency in
|
||||
`Cargo.toml`.
|
||||
fn main() -> estring::Result<()> {
|
||||
let res = EString::from("10+5*2+3")
|
||||
.parse::<Sum<PlusVec<Product<MulVec<f32>>>>>()?
|
||||
.agg();
|
||||
|
||||
`Cargo.toml` example:
|
||||
|
||||
```toml
|
||||
[package]
|
||||
name = "my-crate"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
authors = ["Me <user@rust-lang.org>"]
|
||||
|
||||
[dependencies]
|
||||
estring = { version = "0.1", features = ["structs"] }
|
||||
assert_eq!(res, 23.0);
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
## 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
|
||||
|
||||
**MIT**. See [LICENSE](https://github.com/pleshevskiy/estring/LICENSE) to see
|
||||
|
|
|
@ -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(())
|
||||
|
|
|
@ -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
92
src/agg/product.rs
Normal 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
90
src/agg/sum.rs
Normal 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);
|
||||
}
|
||||
}
|
176
src/core.rs
176
src/core.rs
|
@ -2,11 +2,51 @@
|
|||
//! string types
|
||||
//!
|
||||
|
||||
// TODO: add more info and examples.
|
||||
/// Format a value fragment into a ``EString``.
|
||||
pub trait FormatFragment {
|
||||
/// Format this type and wrap into ``EString``.
|
||||
///
|
||||
/// ``ToEString``’s `to_estring` method is often used implicitly, through ``EString``’s from.
|
||||
///
|
||||
/// # 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``.
|
||||
fn fmt_frag(&self) -> 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;
|
||||
}
|
||||
|
||||
/// Parse a value fragment from a ``EString``.
|
||||
|
@ -70,11 +110,77 @@ pub trait ParseFragment: Sized {
|
|||
fn parse_frag(es: EString) -> crate::Result<Self>;
|
||||
}
|
||||
|
||||
/// Wrapper under String type.
|
||||
// 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]
|
||||
pub fn new() -> Self {
|
||||
Self(String::new())
|
||||
}
|
||||
|
||||
/// Parses this inner string into another type.
|
||||
///
|
||||
/// `parse` can parse into any type that implements the ``ParseFragment`` trait.
|
||||
|
@ -110,11 +216,11 @@ impl EString {
|
|||
|
||||
impl<T> From<T> for EString
|
||||
where
|
||||
T: std::fmt::Display,
|
||||
T: ToEString,
|
||||
{
|
||||
#[inline]
|
||||
fn from(val: T) -> Self {
|
||||
Self(val.to_string())
|
||||
val.to_estring()
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -129,22 +235,66 @@ impl std::ops::Deref for EString {
|
|||
|
||||
impl ParseFragment for EString {
|
||||
#[inline]
|
||||
fn parse_frag(value: EString) -> crate::Result<Self> {
|
||||
Ok(value)
|
||||
fn parse_frag(es: EString) -> crate::Result<Self> {
|
||||
Ok(es)
|
||||
}
|
||||
}
|
||||
|
||||
#[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(s: EString) -> crate::Result<Self> {
|
||||
Ok(s.0)
|
||||
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(s: EString) -> crate::Result<Self> {
|
||||
Ok(Box::leak(s.0.into_boxed_str()))
|
||||
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]
|
||||
}
|
||||
}
|
||||
|
||||
|
|
42
src/lib.rs
42
src/lib.rs
|
@ -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)]
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
use crate::{core::EString, ParseFragment};
|
||||
use crate::core::{EString, ParseFragment, ToEString};
|
||||
|
||||
/// Wrapper that allow to trim substring before continue
|
||||
///
|
||||
|
@ -42,6 +42,15 @@ where
|
|||
}
|
||||
}
|
||||
|
||||
impl<T> ToEString for Trim<T>
|
||||
where
|
||||
T: ToEString,
|
||||
{
|
||||
fn to_estring(&self) -> EString {
|
||||
self.0.to_estring()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
|
@ -3,6 +3,4 @@
|
|||
|
||||
mod bool;
|
||||
mod number;
|
||||
|
||||
pub use self::bool::*;
|
||||
pub use number::*;
|
||||
mod option;
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
use crate::core::{EString, ParseFragment};
|
||||
use crate::core::{EString, ParseFragment, ToEString};
|
||||
use crate::error::{Error, Reason};
|
||||
|
||||
impl ParseFragment for bool {
|
||||
|
@ -12,6 +12,23 @@ impl ParseFragment for bool {
|
|||
}
|
||||
}
|
||||
|
||||
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)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
@ -52,4 +69,10 @@ mod tests {
|
|||
_ => unreachable!(),
|
||||
};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_format_bool() {
|
||||
assert_eq!(true.to_estring(), EString(String::from("true")));
|
||||
assert_eq!(false.to_estring(), EString(String::from("false")));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
use crate::core::{EString, ParseFragment};
|
||||
use crate::core::{EString, ParseFragment, ToEString};
|
||||
use crate::error::{Error, Reason};
|
||||
|
||||
#[doc(hidden)]
|
||||
|
@ -11,6 +11,23 @@ macro_rules! from_env_string_numbers_impl {
|
|||
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]
|
||||
}
|
||||
}
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
@ -56,4 +73,11 @@ mod tests {
|
|||
_ => 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
77
src/std/option.rs
Normal 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")));
|
||||
}
|
||||
}
|
|
@ -1,7 +1,7 @@
|
|||
//! Contains the implementations to pair tuple type
|
||||
//!
|
||||
|
||||
use crate::core::{EString, ParseFragment};
|
||||
use crate::core::{EString, ParseFragment, ToEString};
|
||||
use crate::{Error, Reason};
|
||||
use std::fmt::Write;
|
||||
|
||||
|
@ -39,13 +39,25 @@ where
|
|||
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())
|
||||
write!(f, "{}{}{}", self.0, S1, self.1)
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, const S1: char, B> ParseFragment for Pair<A, S1, B>
|
||||
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,
|
||||
|
@ -102,4 +114,12 @@ 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")));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
//! Contains the implementations to vec type
|
||||
//!
|
||||
|
||||
use crate::core::{EString, ParseFragment};
|
||||
use crate::core::{EString, ParseFragment, ToEString};
|
||||
use std::fmt::Write;
|
||||
|
||||
/// Wrapper for ``Vec`` to split string by a separator (`SEP`).
|
||||
|
@ -51,11 +51,32 @@ where
|
|||
f.write_char(SEP)?;
|
||||
}
|
||||
|
||||
f.write_str(&part.to_string())
|
||||
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,
|
||||
|
@ -71,16 +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() {
|
||||
|
@ -139,4 +171,28 @@ d,e";
|
|||
_ => 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]);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
//!
|
||||
|
||||
use super::Pair;
|
||||
use crate::core::{EString, ParseFragment};
|
||||
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`).
|
||||
|
@ -46,6 +46,29 @@ where
|
|||
}
|
||||
}
|
||||
|
||||
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,
|
||||
|
@ -91,4 +114,19 @@ mod tests {
|
|||
_ => 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"))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
Reference in a new issue