sudachi/
pos.rs

1/*
2 *  Copyright (c) 2021 Works Applications Co., Ltd.
3 *
4 *  Licensed under the Apache License, Version 2.0 (the "License");
5 *  you may not use this file except in compliance with the License.
6 *  You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 *   Unless required by applicable law or agreed to in writing, software
11 *  distributed under the License is distributed on an "AS IS" BASIS,
12 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 *  See the License for the specific language governing permissions and
14 *  limitations under the License.
15 */
16
17use crate::util::fxhash::FxBuildHasher;
18use std::collections::HashSet;
19
20#[derive(Clone)]
21pub struct PosMatcher {
22    ids: HashSet<u16, FxBuildHasher>,
23}
24
25impl PosMatcher {
26    pub fn new<I: IntoIterator<Item = u16>>(pos: I) -> Self {
27        let iter = pos.into_iter();
28        let (min_size, max_size) = iter.size_hint();
29        let size = max_size.unwrap_or(min_size);
30        let mut ids = HashSet::with_capacity_and_hasher(size, FxBuildHasher::default());
31        ids.extend(iter);
32        Self { ids }
33    }
34
35    #[inline]
36    pub fn matches_id(&self, pos_id: u16) -> bool {
37        self.ids.contains(&pos_id)
38    }
39
40    pub fn num_entries(&self) -> usize {
41        self.ids.len()
42    }
43
44    pub fn entries(&self) -> impl Iterator<Item = u16> + '_ {
45        self.ids.iter().cloned()
46    }
47
48    pub fn union(&self, other: &PosMatcher) -> PosMatcher {
49        let mut ids = self.ids.clone();
50        ids.extend(other.ids.iter());
51        PosMatcher { ids }
52    }
53
54    pub fn intersection(&self, other: &PosMatcher) -> PosMatcher {
55        let mut ids = self.ids.clone();
56        ids.retain(|id| other.ids.contains(id));
57        PosMatcher { ids }
58    }
59
60    pub fn difference(&self, other: &PosMatcher) -> PosMatcher {
61        let mut ids = self.ids.clone();
62        ids.retain(|id| !other.ids.contains(id));
63        PosMatcher { ids }
64    }
65}