css_parse/
comparison.rs

1use crate::{Parse, Parser, Result, T, ToCursors, diagnostics};
2
3/// This enum represents a set of comparison operators, used in Ranged Media Features (see
4/// [RangedFeature][crate::RangedFeature]), and could be used in other parts of a CSS-alike language. This isn't a
5/// strictly standard part of CSS, but is provided for convenience.
6///
7/// [Comparison] is defined as:
8///
9/// ```md
10/// <comparison>
11///  │├──╮─ "="  ─╭──┤│
12///      ├─ "<"  ─┤
13///      ├─ "<=" ─┤
14///      ├─ ">"  ─┤
15///      ╰─ ">=" ─╯
16/// ```
17///
18#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize), serde(tag = "type"))]
20pub enum Comparison {
21	LessThan(T![<]),
22	GreaterThan(T![>]),
23	GreaterThanEqual(T![>=]),
24	LessThanEqual(T![<=]),
25	Equal(T![=]),
26}
27
28impl<'a> Parse<'a> for Comparison {
29	fn parse(p: &mut Parser<'a>) -> Result<Comparison> {
30		let c = p.peek_next();
31		match c.token().char() {
32			Some('=') => p.parse::<T![=]>().map(Comparison::Equal),
33			Some('>') => {
34				if p.peek::<T![>=]>() {
35					p.parse::<T![>=]>().map(Comparison::GreaterThanEqual)
36				} else {
37					p.parse::<T![>]>().map(Comparison::GreaterThan)
38				}
39			}
40			Some('<') => {
41				if p.peek::<T![<=]>() {
42					p.parse::<T![<=]>().map(Comparison::LessThanEqual)
43				} else {
44					p.parse::<T![<]>().map(Comparison::LessThan)
45				}
46			}
47			Some(char) => Err(diagnostics::UnexpectedDelim(char, p.next()))?,
48			_ => Err(diagnostics::Unexpected(p.next()))?,
49		}
50	}
51}
52
53impl ToCursors for Comparison {
54	fn to_cursors(&self, s: &mut impl crate::CursorSink) {
55		match self {
56			Self::LessThan(c) => ToCursors::to_cursors(c, s),
57			Self::GreaterThan(c) => ToCursors::to_cursors(c, s),
58			Self::GreaterThanEqual(c) => ToCursors::to_cursors(c, s),
59			Self::LessThanEqual(c) => ToCursors::to_cursors(c, s),
60			Self::Equal(c) => ToCursors::to_cursors(c, s),
61		}
62	}
63}