oni_comb_parser_rs/utils/
set.rs1use std::cmp::{PartialEq, PartialOrd};
2use std::ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive};
3use std::str;
4
5pub trait Set<T> {
7 fn contains(&self, elem: &T) -> bool;
9
10 fn to_str(&self) -> &str {
12 "<set>"
13 }
14}
15
16impl<T: PartialEq> Set<T> for [T] {
17 fn contains(&self, elem: &T) -> bool {
18 (self as &[T]).contains(elem)
19 }
20}
21
22impl Set<char> for str {
23 fn contains(&self, elem: &char) -> bool {
24 (self as &str).contains(*elem)
25 }
26
27 fn to_str(&self) -> &str {
28 self
29 }
30}
31
32impl<T> Set<T> for RangeFull {
34 fn contains(&self, _: &T) -> bool {
35 true
36 }
37
38 fn to_str(&self) -> &str {
39 ".."
40 }
41}
42
43impl<T: PartialOrd + Copy> Set<T> for Range<T> {
45 fn contains(&self, elem: &T) -> bool {
46 self.start <= *elem && self.end > *elem
47 }
48}
49
50impl<T: PartialOrd + Copy> Set<T> for RangeInclusive<T> {
52 fn contains(&self, elem: &T) -> bool {
53 self.start() <= elem && self.end() >= elem
54 }
55}
56
57impl<T: PartialOrd + Copy> Set<T> for RangeFrom<T> {
59 fn contains(&self, elem: &T) -> bool {
60 self.start <= *elem
61 }
62}
63
64impl<T: PartialOrd + Copy> Set<T> for RangeTo<T> {
66 fn contains(&self, elem: &T) -> bool {
67 self.end > *elem
68 }
69}
70
71impl<T: PartialOrd + Copy> Set<T> for RangeToInclusive<T> {
73 fn contains(&self, elem: &T) -> bool {
74 self.end >= *elem
75 }
76}
77
78macro_rules! impl_set_for_array {
79 ( $($n:expr),+ ) => {
80 $(
81 impl Set<u8> for [u8; $n] {
82 fn contains(&self, elem: &u8) -> bool {
83 (self as &[u8]).contains(elem)
84 }
85
86 fn to_str(&self) -> &str {
87 str::from_utf8(self).unwrap_or("<byte array>")
88 }
89 }
90 )+
91 };
92}
93
94impl_set_for_array!(
95 0, 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,
96 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,
97 61, 62, 63, 64
98);