third_party_rust_cxx/syntax/set.rs

137 lines
3.0 KiB
Rust
Raw Normal View History

2020-10-04 02:42:16 +00:00
use std::fmt::{self, Debug};
2019-10-20 18:51:12 +00:00
use std::slice;
pub use self::ordered::OrderedSet;
2020-11-04 03:30:38 +00:00
pub use self::unordered::UnorderedSet;
2019-10-20 18:51:12 +00:00
mod ordered {
2020-11-04 03:30:38 +00:00
use super::{Iter, UnorderedSet};
use std::borrow::Borrow;
use std::hash::Hash;
2019-10-20 18:51:12 +00:00
pub struct OrderedSet<T> {
2020-11-04 03:30:38 +00:00
set: UnorderedSet<T>,
vec: Vec<T>,
2019-10-20 18:51:12 +00:00
}
impl<'a, T> OrderedSet<&'a T>
2020-10-04 06:48:06 +00:00
where
T: Hash + Eq,
2020-10-04 06:48:06 +00:00
{
pub fn new() -> Self {
OrderedSet {
2020-11-04 03:30:38 +00:00
set: UnorderedSet::new(),
vec: Vec::new(),
}
}
pub fn insert(&mut self, value: &'a T) -> bool {
let new = self.set.insert(value);
if new {
self.vec.push(value);
}
new
}
pub fn contains<Q>(&self, value: &Q) -> bool
where
&'a T: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
self.set.contains(value)
}
pub fn get<Q>(&self, value: &Q) -> Option<&'a T>
where
&'a T: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
self.set.get(value).copied()
}
}
2019-10-20 18:51:12 +00:00
2020-12-21 06:05:11 +00:00
impl<'a, T> OrderedSet<&'a T> {
pub fn is_empty(&self) -> bool {
self.vec.is_empty()
}
pub fn iter(&self) -> Iter<'_, 'a, T> {
Iter(self.vec.iter())
}
}
impl<'s, 'a, T> IntoIterator for &'s OrderedSet<&'a T> {
type Item = &'a T;
type IntoIter = Iter<'s, 'a, T>;
fn into_iter(self) -> Self::IntoIter {
2020-12-21 06:05:11 +00:00
self.iter()
}
2019-10-20 18:51:12 +00:00
}
}
2020-11-04 03:30:38 +00:00
mod unordered {
use std::borrow::Borrow;
use std::collections::HashSet;
use std::hash::Hash;
// Wrapper prohibits accidentally introducing iteration over the set, which
// could lead to nondeterministic generated code.
pub struct UnorderedSet<T>(HashSet<T>);
impl<T> UnorderedSet<T>
where
T: Hash + Eq,
{
pub fn new() -> Self {
UnorderedSet(HashSet::new())
}
pub fn insert(&mut self, value: T) -> bool {
self.0.insert(value)
}
pub fn contains<Q>(&self, value: &Q) -> bool
where
T: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
self.0.contains(value)
}
pub fn get<Q>(&self, value: &Q) -> Option<&T>
where
T: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
self.0.get(value)
}
pub fn retain(&mut self, f: impl FnMut(&T) -> bool) {
self.0.retain(f);
}
2020-11-04 03:30:38 +00:00
}
}
2019-10-20 18:51:12 +00:00
pub struct Iter<'s, 'a, T>(slice::Iter<'s, &'a T>);
impl<'s, 'a, T> Iterator for Iter<'s, 'a, T> {
type Item = &'a T;
2019-10-20 18:51:12 +00:00
fn next(&mut self) -> Option<Self::Item> {
self.0.next().copied()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
2019-10-20 18:51:12 +00:00
}
2020-10-04 02:42:16 +00:00
impl<'a, T> Debug for OrderedSet<&'a T>
where
T: Debug,
{
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.debug_set().entries(self).finish()
}
}