1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
use std::borrow::Cow;

use nom::{
    branch::alt,
    bytes::complete::tag,
    character::complete::digit0,
    combinator::recognize,
    sequence::{delimited, pair, separated_pair},
    IResult,
};

/// Statistics Cookie Object
#[cfg_attr(test, derive(PartialEq))]
#[cfg_attr(feature = "ser", derive(serde::Serialize))]
#[derive(Debug, Clone)]
pub struct Cookie<'a> {
    /// Full cookie value
    pub value: Cow<'a, str>,
}

impl Cookie<'_> {
    pub(crate) fn parse(input: &str) -> Option<(&str, Cookie)> {
        parse_internal(input).ok()
    }

    pub fn into_owned(self) -> Cookie<'static> {
        Cookie {
            value: self.value.into_owned().into(),
        }
    }
}

#[inline]
fn parse_internal(input: &str) -> IResult<&str, Cookie, ()> {
    let (input, value) = recognize(delimited(
        tag("["),
        alt((
            separated_pair(digit0, tag("/"), digit0),
            pair(digit0, tag("%")),
        )),
        tag("]"),
    ))(input)?;

    Ok((
        input,
        Cookie {
            value: value.into(),
        },
    ))
}

#[test]
fn parse() {
    assert_eq!(
        Cookie::parse("[1/10]"),
        Some((
            "",
            Cookie {
                value: "[1/10]".into()
            }
        ))
    );
    assert_eq!(
        Cookie::parse("[1/1000]"),
        Some((
            "",
            Cookie {
                value: "[1/1000]".into()
            }
        ))
    );
    assert_eq!(
        Cookie::parse("[10%]"),
        Some((
            "",
            Cookie {
                value: "[10%]".into()
            }
        ))
    );
    assert_eq!(
        Cookie::parse("[%]"),
        Some((
            "",
            Cookie {
                value: "[%]".into()
            }
        ))
    );
    assert_eq!(
        Cookie::parse("[/]"),
        Some((
            "",
            Cookie {
                value: "[/]".into()
            }
        ))
    );
    assert_eq!(
        Cookie::parse("[100/]"),
        Some((
            "",
            Cookie {
                value: "[100/]".into()
            }
        ))
    );
    assert_eq!(
        Cookie::parse("[/100]"),
        Some((
            "",
            Cookie {
                value: "[/100]".into()
            }
        ))
    );

    assert!(Cookie::parse("[10% ]").is_none());
    assert!(Cookie::parse("[1//100]").is_none());
    assert!(Cookie::parse("[1\\100]").is_none());
    assert!(Cookie::parse("[10%%]").is_none());
}