use crate::{
error::ParseResult,
parse::{Parse, ParseOffsetInput},
};
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Copy)]
pub struct Ws<T>(pub T);
impl<T> Ws<T> {
#[must_use]
pub fn into_inner(self) -> T {
self.0
}
#[must_use]
pub fn inner(&self) -> &T {
&self.0
}
pub fn new(value: T) -> Self {
Self(value)
}
}
impl<T> std::ops::Deref for Ws<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T: PartialEq<T>> PartialEq<T> for Ws<T> {
fn eq(&self, other: &T) -> bool {
&self.0 == other
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Copy)]
pub struct Spaced<T>(pub T);
impl<T> Spaced<T> {
#[must_use]
pub fn new(value: T) -> Self {
Self(value)
}
#[must_use]
pub fn into_inner(self) -> T {
self.0
}
#[must_use]
pub fn inner(&self) -> &T {
&self.0
}
}
impl<T> std::ops::Deref for Spaced<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T: PartialEq<T>> PartialEq<T> for Spaced<T> {
fn eq(&self, other: &T) -> bool {
&self.0 == other
}
}
pub type PaddedWs<T> = Spaced<T>;
impl<'a, I, T> Parse<'a, I> for Ws<T>
where
I: crate::input::Input<'a>,
T: Parse<'a, I>,
{
#[inline]
fn parse_with_context(
input: I,
context: &mut crate::parse::ParseOffsetContext,
) -> ParseResult<(Self, I)> {
let (value, rest) = T::parse_with_context(input.trim_start(), context)?;
Ok((Self(value), rest))
}
}
impl<'a, I, T> Parse<'a, I> for Spaced<T>
where
I: crate::input::Input<'a>,
T: Parse<'a, I>,
{
#[inline]
fn parse_with_context(
input: I,
context: &mut crate::parse::ParseOffsetContext,
) -> ParseResult<(Self, I)> {
let (value, rest) = T::parse_with_context(input.trim_start(), context)?;
Ok((Self(value), rest.trim_start()))
}
}
pub trait WsExt: Sized {
type Whitespaced;
fn parse_ws<'a, I>(input: I) -> ParseResult<(Self::Whitespaced, I)>
where
I: ParseOffsetInput<'a>,
Self::Whitespaced: Parse<'a, I>,
{
Self::Whitespaced::parse(input)
}
}
impl<T> WsExt for T {
type Whitespaced = Ws<T>;
}
pub trait SpacedExt: Sized {
type Spaced;
fn parse_spaced<'a, I>(input: I) -> ParseResult<(Self::Spaced, I)>
where
I: ParseOffsetInput<'a>,
Self::Spaced: Parse<'a, I>,
{
Self::Spaced::parse(input)
}
}
impl<T> SpacedExt for T {
type Spaced = Spaced<T>;
}
#[cfg(test)]
mod tests {
use crate::{
combinators::ws::{Spaced, SpacedExt, Ws},
parse::Parse,
};
#[test]
fn ws_consumes_leading_whitespace() {
let (parsed, rest) = Ws::<i64>::parse(" 42 tail").unwrap();
assert_eq!(parsed.into_inner(), 42);
assert_eq!(rest, " tail");
}
#[test]
fn spaced_trims_both_sides() {
let (parsed, rest) = Spaced::<i64>::parse(" 42 tail").unwrap();
assert_eq!(parsed.into_inner(), 42);
assert_eq!(rest, "tail");
}
#[test]
fn spaced_extension_trait_is_available() {
let (parsed, rest) = i64::parse_spaced(" 7 ").unwrap();
assert_eq!(parsed, 7);
assert_eq!(rest, "");
}
}