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 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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
//! A Set API based on a prefix array, this module contains the [`PrefixArraySet`] type.
#[cfg(any(test, feature = "std"))]
extern crate std;
extern crate alloc;
use alloc::{borrow::ToOwned, vec::Vec};
use core::{borrow::Borrow, fmt, ops::Deref};
mod iter;
pub use iter::{Drain, IntoIter, Iter};
use crate::shared::{PrefixBorrowed, PrefixOwned, ScratchSpace};
/// A generic search-by-prefix array designed to find strings with common prefixes in `O(log n)` time, and easily search on subslices to refine a previous search.
///
/// The generic parameter is mainly in place so that `&'a str`, `String`, and `&'static str` may all be used for the backing storage.
/// It is a logical error for an implementer of `AsRef<str>` to return different data across multiple calls while it remains in this container.
/// Doing so renders the datastructure useless (but will NOT cause UB).
///
/// The main downside of a [`PrefixArraySet`] over a trie type datastructure is that insertions have a significant `O(n)` cost,
/// so if you are adding multiple values over the lifetime of the [`PrefixArraySet`] it may become less efficient overall than a traditional tree.
#[derive(PartialEq, Eq)]
pub struct PrefixArraySet<K: Borrow<str>>(pub(crate) Vec<K>);
impl<K: Borrow<str> + fmt::Debug> fmt::Debug for PrefixArraySet<K> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "PrefixArraySet")?;
f.debug_set().entries(self.iter()).finish()
}
}
// Manually impl to get clone_from
impl<K: Borrow<str> + Clone> Clone for PrefixArraySet<K> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
fn clone_from(&mut self, other: &Self) {
self.0.clone_from(&other.0);
}
}
impl<K: Borrow<str>> Default for PrefixArraySet<K> {
fn default() -> Self {
PrefixArraySet::new()
}
}
impl<K: Borrow<str>> PrefixArraySet<K> {
/// Create a new empty [`PrefixArraySet`].
///
/// This function will not allocate anything.
#[must_use]
pub const fn new() -> Self {
Self(Vec::new())
}
/// Creates a new empty [`PrefixArraySet`] with space for at least `capacity` elements.
///
/// See [`Vec::with_capacity`] for additional notes.
///
/// # Panics:
/// Panics if the new capacity exceeds `isize::MAX` bytes.
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
Self(Vec::with_capacity(capacity))
}
/// Reserves capacity for at least `additional` more elements to be inserted, the collection may reserve additional space as a speculative optimization.
/// Does nothing if capacity is already sufficient.
///
/// See [`Vec::reserve`] for additional notes.
///
/// # Panics:
/// Panics if the new capacity exceeds `isize::MAX` bytes.
pub fn reserve(&mut self, additional: usize) {
self.0.reserve(additional);
}
/// Reserves the minimum capacity to append `additional` more elements. Or, will not speculatively over-allocate like [`reserve`][PrefixArraySet::reserve].
/// Does nothing if capacity is already sufficient.
///
/// See [`Vec::reserve_exact`] for additional notes.
///
/// # Panics:
/// Panics if the new capacity exceeds `isize::MAX` bytes.
pub fn reserve_exact(&mut self, additional: usize) {
self.0.reserve_exact(additional);
}
/// Creates a new [`PrefixArraySet`] from a `Vec<K>`, removing any duplicate keys.
///
/// This operation is `O(n log n)`.
#[must_use]
pub fn from_vec_lossy(v: Vec<K>) -> Self {
Self::from_vec_lossy_impl(v)
}
/// Inserts the given K into the [`PrefixArraySet`], returning true if the key was not already in the set
///
/// This operation is `O(n)`.
pub fn insert(&mut self, key: K) -> bool {
self.insert_impl(key).is_none()
}
/// Adds a value to the set, replacing the existing value, if any, that is equal to the given one.
/// Returns the replaced value.
pub fn replace(&mut self, key: K) -> Option<K> {
// This functionality is not shared in PrefixOwned so we will make it ourself
match (self.0).binary_search_by_key(&key.borrow(), |s| s.borrow()) {
Ok(idx) => Some(core::mem::replace(&mut (self.0)[idx], key)),
Err(idx) => {
self.0.insert(idx, key);
None
}
}
}
/// Removes all values with the prefix provided, shifting the array in the process to account for the empty space.
///
/// This operation is `O(n)`.
///
/// # Examples
/// ```rust
/// # use prefix_array::PrefixArraySet;
/// let mut set = PrefixArraySet::from_iter(["a", "b", "c"]);
///
/// set.drain_all_with_prefix("b");
///
/// assert_eq!(set.to_vec(), &["a", "c"]);
/// ```
pub fn drain_all_with_prefix<'a>(&'a mut self, prefix: &str) -> Drain<'a, K> {
let range = self.find_all_with_prefix_idx_impl(prefix);
Drain(self.0.drain(range))
}
/// Drains all elements of the [`PrefixArraySet`], returning them in an iterator.
/// Keeps the backing allocation intact, unlike [`IntoIter`].
///
/// When this iterator is dropped it drops all remaining elements.
pub fn drain(&mut self) -> Drain<K> {
Drain(self.0.drain(..))
}
/// Removes the value that matches the given key, returning true if it was present in the set
///
/// This operation is `O(log n)` if the key was not found, and `O(n)` if it was.
pub fn remove(&mut self, key: &str) -> bool {
self.remove_entry_impl(key).is_some()
}
/// Returns the total capacity that the [`PrefixArraySet`] has.
#[must_use]
pub fn capacity(&self) -> usize {
self.0.capacity()
}
/// Clears the [`PrefixArraySet`], removing all values.
///
/// Capacity will not be freed.
pub fn clear(&mut self) {
self.0.clear();
}
/// Shrinks the capacity of this collection as much as possible.
///
/// Additional capacity may still be left over after this operation.
pub fn shrink_to_fit(&mut self) {
self.0.shrink_to_fit();
}
/// Shrinks the capacity of this collection with a lower limit. It will drop down no lower than the supplied limit.
///
/// If the current capacity is less than the lower limit, this is a no-op.
pub fn shrink_to(&mut self, min_capacity: usize) {
self.0.shrink_to(min_capacity);
}
/// Extends the collection with items from an iterator, this is functionally equivalent to the
/// `Extend` implementation and carries the same edge cases, but it allows passing a scratch
/// space to potentially avoid reallocations when calling `extend_with` multiple times.
pub fn extend_with<I>(&mut self, scratch: &mut ScratchSpace<Self>, iter: I)
where
I: IntoIterator<Item = K>,
{
self.extend_with_impl(&mut scratch.0, iter);
}
/// Makes a `PrefixArraySet` from an iterator in which all key items are unique
fn from_unique_iter<T: IntoIterator<Item = K>>(v: T) -> Self {
Self::from_unique_iter_impl(v)
}
}
impl<K: Borrow<str>> Extend<K> for PrefixArraySet<K> {
/// Extends the [`PrefixArraySet`] with more values, skipping updating any duplicates.
///
/// It is currently unspecified if two identical values are given, who are not already in the set, which value will be kept.
///
/// This operation is `O(n + k log k)` where k is the number of elements in the iterator.
fn extend<T>(&mut self, iter: T)
where
T: IntoIterator<Item = K>,
{
self.extend_with(&mut ScratchSpace::new(), iter);
}
}
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl<K: Borrow<str>, H> From<std::collections::HashSet<K, H>> for PrefixArraySet<K> {
/// Performs a lossless conversion from a `HashSet<K>` to a `PrefixArraySet<K>` in `O(n log n)` time.
fn from(v: std::collections::HashSet<K, H>) -> Self {
Self::from_unique_iter(v)
}
}
impl<K: Borrow<str>> From<alloc::collections::BTreeSet<K>> for PrefixArraySet<K> {
/// Performs a lossless conversion from a `BTreeSet<K>` to a `PrefixArraySet<K>` in `O(n log n)` time.
fn from(v: alloc::collections::BTreeSet<K>) -> Self {
Self::from_unique_iter(v)
}
}
impl<K: Borrow<str>> From<PrefixArraySet<K>> for Vec<K> {
fn from(v: PrefixArraySet<K>) -> Vec<K> {
v.0
}
}
impl<K: Borrow<str>> Deref for PrefixArraySet<K> {
type Target = SetSubSlice<K>;
fn deref(&self) -> &Self::Target {
SetSubSlice::cast_from_slice_core(&self.0)
}
}
impl<K: Borrow<str>> core::borrow::Borrow<SetSubSlice<K>> for PrefixArraySet<K> {
fn borrow(&self) -> &SetSubSlice<K> {
self
}
}
impl<K: Borrow<str> + Clone> ToOwned for SetSubSlice<K> {
type Owned = PrefixArraySet<K>;
fn to_owned(&self) -> PrefixArraySet<K> {
// here we can assert the invariants were upheld
PrefixArraySet(self.to_vec())
}
fn clone_into(&self, target: &mut PrefixArraySet<K>) {
self.0.clone_into(&mut target.0);
}
}
impl<K: Borrow<str> + fmt::Debug> fmt::Debug for SetSubSlice<K> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "SetSubSlice")?;
f.debug_set().entries(self.iter()).finish()
}
}
/// A subslice of a [`PrefixArraySet`] in which all items contain a common prefix (which may be the unit prefix `""`).
///
/// The [`SetSubSlice`] does not store what that common prefix is for performance reasons (but it can be computed, see: [`SetSubSlice::common_prefix`]), it is up to the user to keep track of.
// SAFETY: this type must remain repr(transparent) to map::SubSlice<K, ()> for from_map_slice invariants
#[repr(transparent)]
#[derive(PartialEq, Eq)]
pub struct SetSubSlice<K: Borrow<str>>(pub(crate) [K]);
impl<K: Borrow<str>> SetSubSlice<K> {
/// creates a ref to Self from a ref to backing storage
// bypass lint level
#[allow(unsafe_code)]
pub(crate) fn cast_from_slice_core(v: &[K]) -> &Self {
// SAFETY: this type is repr(transparent), and the lifetimes are both &'a
unsafe { &*(v as *const [K] as *const SetSubSlice<K>) }
}
// bypass lint level
#[allow(unsafe_code)]
pub(crate) fn cast_from_slice_mut_core(v: &mut [K]) -> &mut Self {
// SAFETY: this type is repr(transparent), and the lifetimes are both &'a
unsafe { &mut *(v as *mut [K] as *mut SetSubSlice<K>) }
}
/// Returns an iterator over all of the elements of this [`SetSubSlice`]
pub fn iter(&self) -> Iter<K> {
Iter(self.0.iter())
}
/// Creates an owned copy of this [`SetSubSlice`] as a [`Vec`].
/// If you wish to preserve [`PrefixArraySet`] semantics consider using [`ToOwned`] instead.
pub fn to_vec(&self) -> Vec<K>
where
K: Clone,
{
self.0.to_vec()
}
/// Returns the `SetSubSlice` where all `K` have the same prefix `prefix`.
///
/// Will return an empty array if there are no matches.
///
/// This operation is `O(log n)`
///
/// # Examples
/// ```rust
/// # use prefix_array::PrefixArraySet;
/// let set = PrefixArraySet::from_iter(["foo", "bar", "baz"]);
///
/// assert_eq!(set.find_all_with_prefix("b").to_vec(), vec!["bar", "baz"]);
/// ```
pub fn find_all_with_prefix<'a>(&'a self, prefix: &str) -> &'a Self {
let range = self.find_all_with_prefix_idx_impl(prefix);
self.reslice(range)
}
/// Compute the common prefix of this [`SetSubSlice`] from the data.
/// Will return an empty string if this subslice is empty.
///
/// Note that this may be more specific than what was searched for, i/e:
/// ```rust
/// # use prefix_array::PrefixArraySet;
/// let arr = PrefixArraySet::from_iter(["12346", "12345", "12341"]);
/// // Common prefix is *computed*, so even though we only
/// // searched for "12" we got something more specific
/// assert_eq!(arr.find_all_with_prefix("12").common_prefix(), "1234");
/// ```
///
/// This operation is `O(1)`, but it is not computationally free.
pub fn common_prefix(&self) -> &str {
self.common_prefix_impl()
}
/// Returns whether this [`SetSubSlice`] contains the given key
///
/// This operation is `O(log n)`.
pub fn contains(&self, key: &str) -> bool {
self.contains_key_impl(key)
}
/// Returns whether this [`SetSubSlice`] is empty
pub const fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Returns the length of this [`SetSubSlice`]
pub const fn len(&self) -> usize {
self.0.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
#[test]
fn submatches() {
let parray = PrefixArraySet::from_vec_lossy(vec![
"abcde", "234234", "among", "we", "weed", "who", "what", "why", "abde", "abch",
"america",
]);
assert_eq!(
&["abcde", "abch", "abde"],
&*parray.find_all_with_prefix("ab").to_vec()
);
assert_eq!("ab", parray.find_all_with_prefix("ab").common_prefix());
let mut parraysingle = PrefixArraySet::from_vec_lossy(vec!["abcde"]);
assert_eq!("abcde", parraysingle.to_vec()[0]);
assert_eq!(
&["abcde"],
&*parraysingle.find_all_with_prefix("a").to_vec()
);
assert!(parraysingle.find_all_with_prefix("b").is_empty());
_ = parraysingle.drain_all_with_prefix("a");
assert!(parraysingle.is_empty());
}
#[test]
fn is_eq() {
let arr1 = PrefixArraySet::from_iter(["abcde", "among"]);
let arr2 = PrefixArraySet::from_iter(["abcde", "among"]);
assert_eq!(arr1, arr2);
let arr3 = PrefixArraySet::new();
assert_ne!(&*arr3, &*arr2);
}
}