character_set/insert/
mod.rs1use std::ops::{Range, RangeInclusive};
2
3use ucd_trie::Error;
4
5use crate::CharacterSet;
6
7pub const UNICODE_MAX: u32 = 0x110000;
8
9#[derive(Debug, Clone)]
10pub struct InsertAction {
11 pub insert: Vec<RangeInclusive<u32>>,
12 pub error: Option<Error>,
13}
14
15impl CharacterSet {
16 pub fn all() -> Self {
17 Self { all: Box::new([true; UNICODE_MAX as usize]) }
18 }
19 pub fn nil() -> Self {
20 Self { all: Box::new([false; UNICODE_MAX as usize]) }
21 }
22 pub fn include(&mut self, set: impl Into<InsertAction>) -> Result<(), Error> {
23 self.try_insert(set, true)
24 }
25 pub fn exclude(&mut self, set: impl Into<InsertAction>) -> Result<(), Error> {
26 self.try_insert(set, false)
27 }
28 fn try_insert(&mut self, set: impl Into<InsertAction>, result: bool) -> Result<(), Error> {
29 let InsertAction { insert, error } = set.into();
30 if let Some(e) = error {
31 return Err(e);
32 }
33 self.insert(insert, result);
34 Ok(())
35 }
36 fn insert(&mut self, set: Vec<RangeInclusive<u32>>, result: bool) {
37 for range in set {
38 for cp in range {
39 debug_assert!(cp <= UNICODE_MAX);
40 self.all[cp as usize] = result;
41 }
42 }
43 }
44}
45
46impl From<char> for InsertAction {
47 fn from(char: char) -> Self {
48 InsertAction::from(RangeInclusive::new(char, char))
49 }
50}
51
52impl From<RangeInclusive<char>> for InsertAction {
53 fn from(range: RangeInclusive<char>) -> Self {
54 let start = *range.start() as u32;
55 let end = *range.end() as u32;
56 InsertAction { insert: vec![RangeInclusive::new(start, end)], error: None }
57 }
58}
59
60impl From<Range<char>> for InsertAction {
61 fn from(range: Range<char>) -> Self {
62 InsertAction::from(RangeInclusive::new(range.start as u32, range.end as u32 + 1))
63 }
64}
65
66impl From<(char, char)> for InsertAction {
67 fn from(range: (char, char)) -> Self {
68 InsertAction::from(RangeInclusive::new(range.0, range.1))
69 }
70}
71
72impl From<u32> for InsertAction {
73 fn from(char: u32) -> Self {
74 InsertAction::from(RangeInclusive::new(char, char))
75 }
76}
77
78impl From<RangeInclusive<u32>> for InsertAction {
79 fn from(range: RangeInclusive<u32>) -> Self {
80 let mut error = None;
81 let start = *range.start();
82 let end = *range.end();
83 if start > UNICODE_MAX {
84 error = Some(Error::InvalidCodepoint(start))
85 }
86 if end > UNICODE_MAX {
87 error = Some(Error::InvalidCodepoint(end))
88 }
89 InsertAction { insert: vec![RangeInclusive::new(start, end)], error }
90 }
91}
92impl From<Range<u32>> for InsertAction {
93 fn from(range: Range<u32>) -> Self {
94 InsertAction::from(RangeInclusive::new(range.start, range.end + 1))
95 }
96}
97
98impl From<(u32, u32)> for InsertAction {
99 fn from(range: (u32, u32)) -> Self {
100 InsertAction::from(RangeInclusive::new(range.0, range.1))
101 }
102}