Compare commits

..

No commits in common. "85fbf7c9e85e27e3f617f80c5b3bd19daea1ae54" and "43af123801bacd8bd3c0971059dab596fa78bcdb" have entirely different histories.

9 changed files with 28 additions and 275 deletions

View file

@ -12,17 +12,11 @@ estring = "0.1"
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
## [Documentation](https://docs.rs/estring) ## Getting started
For more details, see [examples].
[examples]: https://github.com/pleshevskiy/estring/tree/main/examples
## Usage
```rust ```rust
use estring::{SepVec, EString}; use estring::{SepVec, EString};

View file

@ -2,51 +2,11 @@
//! string types //! string types
//! //!
/// Format this type and wrap into ``EString``. // TODO: add more info and examples.
/// /// Format a value fragment into a ``EString``.
/// ``ToEString``s `to_estring` method is often used implicitly, through ``EString``s from. pub trait FormatFragment {
///
/// # 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``. /// 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``. /// Parse a value fragment from a ``EString``.
@ -110,54 +70,11 @@ pub trait ParseFragment: Sized {
fn parse_frag(es: EString) -> crate::Result<Self>; fn parse_frag(es: EString) -> crate::Result<Self>;
} }
/// Wrapper under ``String`` type. /// 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)] #[derive(Debug, Default, PartialEq, Eq, Clone)]
pub struct EString(pub String); 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 { 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. /// Parses this inner string into another type.
/// ///
/// `parse` can parse into any type that implements the ``ParseFragment`` trait. /// `parse` can parse into any type that implements the ``ParseFragment`` trait.
@ -193,11 +110,11 @@ impl EString {
impl<T> From<T> for EString impl<T> From<T> for EString
where where
T: ToEString, T: std::fmt::Display,
{ {
#[inline] #[inline]
fn from(val: T) -> Self { fn from(val: T) -> Self {
val.to_estring() Self(val.to_string())
} }
} }
@ -212,36 +129,22 @@ impl std::ops::Deref for EString {
impl ParseFragment for EString { impl ParseFragment for EString {
#[inline] #[inline]
fn parse_frag(es: EString) -> crate::Result<Self> { fn parse_frag(value: EString) -> crate::Result<Self> {
Ok(es) Ok(value)
} }
} }
impl ParseFragment for String { impl ParseFragment for String {
#[inline] #[inline]
fn parse_frag(es: EString) -> crate::Result<Self> { fn parse_frag(s: EString) -> crate::Result<Self> {
Ok(es.0) Ok(s.0)
}
}
impl ToEString for String {
#[inline]
fn to_estring(&self) -> EString {
EString(self.clone())
} }
} }
impl ParseFragment for &'static str { impl ParseFragment for &'static str {
#[inline] #[inline]
fn parse_frag(es: EString) -> crate::Result<Self> { fn parse_frag(s: EString) -> crate::Result<Self> {
Ok(Box::leak(es.0.into_boxed_str())) Ok(Box::leak(s.0.into_boxed_str()))
}
}
impl<'a> ToEString for &'a str {
#[inline]
fn to_estring(&self) -> EString {
EString((*self).to_string())
} }
} }

View file

@ -1,4 +1,4 @@
use crate::core::{EString, ParseFragment, ToEString}; use crate::{core::EString, ParseFragment};
/// Wrapper that allow to trim substring before continue /// Wrapper that allow to trim substring before continue
/// ///
@ -42,15 +42,6 @@ where
} }
} }
impl<T> ToEString for Trim<T>
where
T: ToEString,
{
fn to_estring(&self) -> EString {
self.0.to_estring()
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;

View file

@ -1,4 +1,4 @@
use crate::core::{EString, ParseFragment, ToEString}; use crate::core::{EString, ParseFragment};
use crate::error::{Error, Reason}; use crate::error::{Error, Reason};
impl ParseFragment for bool { impl ParseFragment for bool {
@ -12,13 +12,6 @@ impl ParseFragment for bool {
} }
} }
impl ToEString for bool {
#[inline]
fn to_estring(&self) -> EString {
EString(self.to_string())
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -59,10 +52,4 @@ mod tests {
_ => 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")));
}
} }

View file

@ -1,4 +1,4 @@
use crate::core::{EString, ParseFragment, ToEString}; use crate::core::{EString, ParseFragment};
use crate::error::{Error, Reason}; use crate::error::{Error, Reason};
#[doc(hidden)] #[doc(hidden)]
@ -11,13 +11,6 @@ macro_rules! from_env_string_numbers_impl {
s.0.parse::<Self>().map_err(|_| Error(s, Reason::Parse)) s.0.parse::<Self>().map_err(|_| Error(s, Reason::Parse))
} }
} }
impl ToEString for $ty {
#[inline]
fn to_estring(&self) -> EString {
EString(self.to_string())
}
}
)+ )+
}; };
} }
@ -63,11 +56,4 @@ mod tests {
_ => unreachable!(), _ => 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")));
}
} }

View file

@ -1,16 +1,4 @@
use crate::core::{EString, ParseFragment, ToEString}; use crate::core::{EString, ParseFragment};
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> impl<T> ParseFragment for Option<T>
where where
@ -32,7 +20,7 @@ mod tests {
#[test] #[test]
fn should_parse_empty_string_as_none() { fn should_parse_empty_string_as_none() {
let estr = EString::new(); let estr = EString::from("");
match estr.parse::<Option<i32>>() { match estr.parse::<Option<i32>>() {
Ok(res) => assert_eq!(res, None), Ok(res) => assert_eq!(res, None),
_ => unreachable!(), _ => unreachable!(),
@ -56,10 +44,4 @@ mod tests {
_ => unreachable!(), _ => unreachable!(),
} }
} }
#[test]
fn should_format_option() {
assert_eq!(None::<i32>.to_estring(), EString::new());
assert_eq!(Some(99).to_estring(), EString(String::from("99")));
}
} }

View file

@ -1,7 +1,7 @@
//! Contains the implementations to pair tuple type //! Contains the implementations to pair tuple type
//! //!
use crate::core::{EString, ParseFragment, ToEString}; use crate::core::{EString, ParseFragment};
use crate::{Error, Reason}; use crate::{Error, Reason};
use std::fmt::Write; use std::fmt::Write;
@ -39,25 +39,13 @@ where
B: std::fmt::Display, B: std::fmt::Display,
{ {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}{}{}", self.0, S1, self.1) f.write_str(&self.0.to_string())?;
f.write_char(S1)?;
f.write_str(&self.1.to_string())
} }
} }
impl<A, B, const S1: char> ToEString for Pair<A, S1, B> impl<A, const S1: char, B> ParseFragment 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 where
A: ParseFragment, A: ParseFragment,
B: ParseFragment, B: ParseFragment,
@ -114,12 +102,4 @@ hello=bar",
_ => unreachable!(), _ => unreachable!(),
}; };
} }
#[test]
fn should_format_pair() {
let pair = Pair::<_, '+', _>(1, 2);
assert_eq!(pair.clone().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

@ -1,7 +1,7 @@
//! Contains the implementations to vec type //! Contains the implementations to vec type
//! //!
use crate::core::{EString, ParseFragment, ToEString}; use crate::core::{EString, ParseFragment};
use std::fmt::Write; use std::fmt::Write;
/// Wrapper for ``Vec`` to split string by a separator (`SEP`). /// Wrapper for ``Vec`` to split string by a separator (`SEP`).
@ -51,32 +51,11 @@ where
f.write_char(SEP)?; f.write_char(SEP)?;
} }
write!(f, "{}", part) f.write_str(&part.to_string())
}) })
} }
} }
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> impl<T, const SEP: char> ParseFragment for SepVec<T, SEP>
where where
T: ParseFragment, T: ParseFragment,
@ -95,7 +74,6 @@ where
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::Pair;
use crate::{Error, Reason}; use crate::{Error, Reason};
const COMMA: char = ','; const COMMA: char = ',';
@ -161,14 +139,4 @@ d,e";
_ => unreachable!(), _ => 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")));
}
} }

View file

@ -2,7 +2,7 @@
//! //!
use super::Pair; use super::Pair;
use crate::core::{EString, ParseFragment, ToEString}; use crate::core::{EString, ParseFragment};
use std::fmt::Write; use std::fmt::Write;
/// Wrapper for trio (A, B, C) tuple to split string by separators (`S1` and `S2`). /// Wrapper for trio (A, B, C) tuple to split string by separators (`S1` and `S2`).
@ -46,29 +46,6 @@ 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> impl<A, const S1: char, B, const S2: char, C> ParseFragment for Trio<A, S1, B, S2, C>
where where
A: ParseFragment, A: ParseFragment,
@ -114,19 +91,4 @@ mod tests {
_ => unreachable!(), _ => 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"))
);
}
} }