better_url/util/
byte_set.rs1use crate::prelude::*;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub struct ByteSet(pub [bool; 256]);
12
13impl ByteSet {
14 pub const fn new() -> Self {
16 Self([false; 256])
17 }
18
19 pub const fn contains(self, b: u8) -> bool {
21 self.0[b as usize]
22 }
23
24
25
26 pub const fn add(mut self, b: u8) -> Self {
28 self.0[b as usize] = true;
29 self
30 }
31
32 pub const fn add_many(mut self, bs: &[u8]) -> Self {
34 let mut i = 0;
35
36 while i < bs.len() {
37 self = self.add(bs[i]);
38 i += 1;
39 }
40
41 self
42 }
43
44
45
46 pub const fn remove(mut self, b: u8) -> Self {
48 self.0[b as usize] = false;
49
50 self
51 }
52
53 pub const fn remove_many(mut self, bs: &[u8]) -> Self {
55 let mut i = 0;
56
57 while i < bs.len() {
58 self = self.remove(bs[i]);
59 i += 1;
60 }
61
62 self
63 }
64
65
66
67 pub const fn merge(mut self, other: Self) -> Self {
69 let mut i = 0;
70 while i < 256 {
71 self.0[i] |= other.0[i];
72 i += 1;
73 }
74 self
75 }
76
77 pub const fn invert(mut self) -> Self {
79 let mut i = 0;
80 while i < 256 {
81 self.0[i] = !self.0[i];
82 i += 1;
83 }
84 self
85 }
86
87
88
89 pub const fn add_non_ascii(mut self) -> Self {
91 let mut i = 128;
92 while i < 256 {
93 self.0[i] = true;
94 i += 1;
95 }
96 self
97 }
98
99 pub const fn remove_non_ascii(mut self) -> Self {
101 let mut i = 128;
102 while i < 256 {
103 self.0[i] = false;
104 i += 1;
105 }
106 self
107 }
108}
109
110impl Default for ByteSet {
111 fn default() -> Self {
112 Self::new()
113 }
114}
115
116pub const FORBIDDEN_HOST_INPUT : ByteSet = ByteSet::new().add_many(b"\x00\t\n\r #/:<>?@[\\]^|");
117pub const FORBIDDEN_DOMAIN_SEGMENT_INPUT : ByteSet = FORBIDDEN_DOMAIN_SEGMENTS_INPUT.add(b'.');
118pub const FORBIDDEN_DOMAIN_SEGMENTS_INPUT: ByteSet = FORBIDDEN_HOST_INPUT.merge(C0.into_inner().remove_non_ascii()).add(b'%');
119pub const FORBIDDEN_DOMAIN_HOST_INPUT : ByteSet = FORBIDDEN_DOMAIN_SEGMENTS_INPUT;
120
121pub const FORBIDDEN_HOST_LITERAL : ByteSet = FORBIDDEN_HOST_INPUT .add_non_ascii().add_many(b"ABCDEFGHIJKLMNOPQRSTUVWXYZ");
122pub const FORBIDDEN_DOMAIN_SEGMENT_LITERAL : ByteSet = FORBIDDEN_DOMAIN_SEGMENT_INPUT .add_non_ascii().add_many(b"ABCDEFGHIJKLMNOPQRSTUVWXYZ");
123pub const FORBIDDEN_DOMAIN_SEGMENTS_LITERAL: ByteSet = FORBIDDEN_DOMAIN_SEGMENTS_INPUT.add_non_ascii().add_many(b"ABCDEFGHIJKLMNOPQRSTUVWXYZ");
124pub const FORBIDDEN_DOMAIN_HOST_LITERAL : ByteSet = FORBIDDEN_DOMAIN_HOST_INPUT .add_non_ascii().add_many(b"ABCDEFGHIJKLMNOPQRSTUVWXYZ");
125
126pub const FORBIDDEN_IPV4_DEC_INPUT: ByteSet = ByteSet::new().add_many(b"0123456789." ).invert();
127pub const FORBIDDEN_IPV4_INPUT : ByteSet = ByteSet::new().add_many(b"0123456789.abcdefABCDEFxX").invert();