pub struct BTreeVec<T, const B: usize = 12> { /* private fields */ }Expand description
A growable array (vector) implemented as a B+ tree.
Provides non-amortized O(log n) random accesses, insertions, and removals, and O(n) iteration.
B is the branching factor. It must be at least 3. The standard library
uses a value of 6 for its B-tree structures. Larger values are better when
T is smaller.
Implementations§
source§impl<T> BTreeVec<T>
impl<T> BTreeVec<T>
sourcepub fn new() -> Self
pub fn new() -> Self
Creates a new BTreeVec. Note that this function is implemented
only for the default value of B; see Self::create for an
equivalent that works with all values of B.
source§impl<T, const B: usize> BTreeVec<T, B>
impl<T, const B: usize> BTreeVec<T, B>
sourcepub fn create() -> Self
pub fn create() -> Self
Creates a new BTreeVec. This function exists because
BTreeVec::new is implemented only for the default value of B.
Examples found in repository?
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
pub fn new() -> Self {
Self::create()
}
}
impl<T, const B: usize> BTreeVec<T, B> {
/// Creates a new [`BTreeVec`]. This function exists because
/// [`BTreeVec::new`] is implemented only for the default value of `B`.
pub fn create() -> Self {
assert!(B >= 3);
Self {
root: None,
size: 0,
phantom: PhantomData,
}
}
/// # Safety
///
/// * There must not be any mutable references, including other
/// [`NodeRef`]s where `R` is [`Mutable`], to any data accessible via the
/// returned [`NodeRef`].
///
/// [`Mutable`]: node::Mutable
unsafe fn leaf_for(&self, index: usize) -> (LeafRef<T, B>, usize) {
// SAFETY: Caller guarantees safety.
leaf_for(unsafe { NodeRef::new(self.root.unwrap()) }, index)
}
/// # Safety
///
/// There must be no other references, including [`NodeRef`]s, to any data
/// accessible via the returned [`NodeRef`].
unsafe fn leaf_for_mut(
&mut self,
index: usize,
) -> (LeafRef<T, B, Mutable>, usize) {
// SAFETY: Caller guarantees safety.
leaf_for(unsafe { NodeRef::new_mutable(self.root.unwrap()) }, index)
}
/// Gets the length of the vector.
pub fn len(&self) -> usize {
self.size
}
/// Checks whether the vector is empty.
pub fn is_empty(&self) -> bool {
self.size == 0
}
/// Gets the item at `index`, or [`None`] if no such item exists.
pub fn get(&self, index: usize) -> Option<&T> {
(index < self.size).then(|| {
// SAFETY: `BTreeVec` uses `NodeRef`s in accordance with
// standard borrowing rules, so there are no existing mutable
// references.
let (leaf, index) = unsafe { self.leaf_for(index) };
leaf.into_child(index)
})
}
/// Gets a mutable reference to the item at `index`, or [`None`] if no such
/// item exists.
pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
(index < self.size).then(|| {
// SAFETY: `BTreeVec` uses `NodeRef`s in accordance with
// standard borrowing rules, so there are no existing references.
let (leaf, index) = unsafe { self.leaf_for_mut(index) };
leaf.into_child_mut(index)
})
}
/// Gets the first item in the vector, or [`None`] if the vector is empty.
pub fn first(&self) -> Option<&T> {
self.get(0)
}
/// Gets a mutable reference to the first item in the vector, or [`None`]
/// if the vector is empty.
pub fn first_mut(&mut self) -> Option<&mut T> {
self.get_mut(0)
}
/// Gets the last item in the vector, or [`None`] if the vector is empty.
pub fn last(&self) -> Option<&T> {
self.size.checked_sub(1).and_then(|s| self.get(s))
}
/// Gets a mutable reference to the last item in the vector, or [`None`] if
/// the vector is empty.
pub fn last_mut(&mut self) -> Option<&mut T> {
self.size.checked_sub(1).and_then(move |s| self.get_mut(s))
}
/// Inserts `item` at `index`.
///
/// # Panics
///
/// Panics if `index` is greater than [`self.len()`](Self::len).
pub fn insert(&mut self, index: usize, item: T) {
assert!(index <= self.size);
self.root
.get_or_insert_with(|| LeafRef::alloc().into_prefix().as_ptr());
// SAFETY: `BTreeVec` uses `NodeRef`s in accordance with standard
// borrowing rules, so there are no existing references.
let (leaf, index) = unsafe { self.leaf_for_mut(index) };
let root = insert(leaf, index, item, self.size);
self.root = Some(root.as_ptr());
self.size += 1;
}
/// Inserts `item` at the end of the vector.
pub fn push(&mut self, item: T) {
self.insert(self.size, item);
}
/// Removes and returns the item at `index`.
///
/// # Panics
///
/// Panics if `index` is not less than [`self.len()`](Self::len).
pub fn remove(&mut self, index: usize) -> T {
assert!(index < self.size);
// SAFETY: `BTreeVec` uses `NodeRef`s in accordance with
// standard borrowing rules, so there are no existing references.
let (leaf, index) = unsafe { self.leaf_for_mut(index) };
let (root, item) = remove(leaf, index);
self.root = Some(root.as_ptr());
self.size -= 1;
item
}
/// Removes and returns the last item in the vector, or [`None`] if the
/// vector is empty.
pub fn pop(&mut self) -> Option<T> {
self.size.checked_sub(1).map(|s| self.remove(s))
}
/// Gets an iterator that returns references to each item in the vector.
pub fn iter(&self) -> Iter<'_, T, B> {
// SAFETY: `BTreeVec` uses `NodeRef`s in accordance with standard
// borrowing rules, so there are no existing mutable references.
Iter {
leaf: self.root.map(|_| unsafe { self.leaf_for(0) }.0),
index: 0,
phantom: PhantomData,
}
}
/// Gets an iterator that returns mutable references to each item in the
/// vector.
pub fn iter_mut(&mut self) -> IterMut<'_, T, B> {
// SAFETY: `BTreeVec` uses `NodeRef`s in accordance with standard
// borrowing rules, so there are no existing references.
IterMut {
leaf: self.root.map(|_| unsafe { self.leaf_for_mut(0) }.0),
index: 0,
phantom: PhantomData,
}
}
}
impl<T, const B: usize> Default for BTreeVec<T, B> {
fn default() -> Self {
Self::create()
}sourcepub fn get(&self, index: usize) -> Option<&T>
pub fn get(&self, index: usize) -> Option<&T>
Gets the item at index, or None if no such item exists.
Examples found in repository?
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
pub fn first(&self) -> Option<&T> {
self.get(0)
}
/// Gets a mutable reference to the first item in the vector, or [`None`]
/// if the vector is empty.
pub fn first_mut(&mut self) -> Option<&mut T> {
self.get_mut(0)
}
/// Gets the last item in the vector, or [`None`] if the vector is empty.
pub fn last(&self) -> Option<&T> {
self.size.checked_sub(1).and_then(|s| self.get(s))
}
/// Gets a mutable reference to the last item in the vector, or [`None`] if
/// the vector is empty.
pub fn last_mut(&mut self) -> Option<&mut T> {
self.size.checked_sub(1).and_then(move |s| self.get_mut(s))
}
/// Inserts `item` at `index`.
///
/// # Panics
///
/// Panics if `index` is greater than [`self.len()`](Self::len).
pub fn insert(&mut self, index: usize, item: T) {
assert!(index <= self.size);
self.root
.get_or_insert_with(|| LeafRef::alloc().into_prefix().as_ptr());
// SAFETY: `BTreeVec` uses `NodeRef`s in accordance with standard
// borrowing rules, so there are no existing references.
let (leaf, index) = unsafe { self.leaf_for_mut(index) };
let root = insert(leaf, index, item, self.size);
self.root = Some(root.as_ptr());
self.size += 1;
}
/// Inserts `item` at the end of the vector.
pub fn push(&mut self, item: T) {
self.insert(self.size, item);
}
/// Removes and returns the item at `index`.
///
/// # Panics
///
/// Panics if `index` is not less than [`self.len()`](Self::len).
pub fn remove(&mut self, index: usize) -> T {
assert!(index < self.size);
// SAFETY: `BTreeVec` uses `NodeRef`s in accordance with
// standard borrowing rules, so there are no existing references.
let (leaf, index) = unsafe { self.leaf_for_mut(index) };
let (root, item) = remove(leaf, index);
self.root = Some(root.as_ptr());
self.size -= 1;
item
}
/// Removes and returns the last item in the vector, or [`None`] if the
/// vector is empty.
pub fn pop(&mut self) -> Option<T> {
self.size.checked_sub(1).map(|s| self.remove(s))
}
/// Gets an iterator that returns references to each item in the vector.
pub fn iter(&self) -> Iter<'_, T, B> {
// SAFETY: `BTreeVec` uses `NodeRef`s in accordance with standard
// borrowing rules, so there are no existing mutable references.
Iter {
leaf: self.root.map(|_| unsafe { self.leaf_for(0) }.0),
index: 0,
phantom: PhantomData,
}
}
/// Gets an iterator that returns mutable references to each item in the
/// vector.
pub fn iter_mut(&mut self) -> IterMut<'_, T, B> {
// SAFETY: `BTreeVec` uses `NodeRef`s in accordance with standard
// borrowing rules, so there are no existing references.
IterMut {
leaf: self.root.map(|_| unsafe { self.leaf_for_mut(0) }.0),
index: 0,
phantom: PhantomData,
}
}
}
impl<T, const B: usize> Default for BTreeVec<T, B> {
fn default() -> Self {
Self::create()
}
}
impl<T, const B: usize> Index<usize> for BTreeVec<T, B> {
type Output = T;
fn index(&self, index: usize) -> &T {
self.get(index).unwrap()
}sourcepub fn get_mut(&mut self, index: usize) -> Option<&mut T>
pub fn get_mut(&mut self, index: usize) -> Option<&mut T>
Gets a mutable reference to the item at index, or None if no such
item exists.
Examples found in repository?
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
pub fn first_mut(&mut self) -> Option<&mut T> {
self.get_mut(0)
}
/// Gets the last item in the vector, or [`None`] if the vector is empty.
pub fn last(&self) -> Option<&T> {
self.size.checked_sub(1).and_then(|s| self.get(s))
}
/// Gets a mutable reference to the last item in the vector, or [`None`] if
/// the vector is empty.
pub fn last_mut(&mut self) -> Option<&mut T> {
self.size.checked_sub(1).and_then(move |s| self.get_mut(s))
}
/// Inserts `item` at `index`.
///
/// # Panics
///
/// Panics if `index` is greater than [`self.len()`](Self::len).
pub fn insert(&mut self, index: usize, item: T) {
assert!(index <= self.size);
self.root
.get_or_insert_with(|| LeafRef::alloc().into_prefix().as_ptr());
// SAFETY: `BTreeVec` uses `NodeRef`s in accordance with standard
// borrowing rules, so there are no existing references.
let (leaf, index) = unsafe { self.leaf_for_mut(index) };
let root = insert(leaf, index, item, self.size);
self.root = Some(root.as_ptr());
self.size += 1;
}
/// Inserts `item` at the end of the vector.
pub fn push(&mut self, item: T) {
self.insert(self.size, item);
}
/// Removes and returns the item at `index`.
///
/// # Panics
///
/// Panics if `index` is not less than [`self.len()`](Self::len).
pub fn remove(&mut self, index: usize) -> T {
assert!(index < self.size);
// SAFETY: `BTreeVec` uses `NodeRef`s in accordance with
// standard borrowing rules, so there are no existing references.
let (leaf, index) = unsafe { self.leaf_for_mut(index) };
let (root, item) = remove(leaf, index);
self.root = Some(root.as_ptr());
self.size -= 1;
item
}
/// Removes and returns the last item in the vector, or [`None`] if the
/// vector is empty.
pub fn pop(&mut self) -> Option<T> {
self.size.checked_sub(1).map(|s| self.remove(s))
}
/// Gets an iterator that returns references to each item in the vector.
pub fn iter(&self) -> Iter<'_, T, B> {
// SAFETY: `BTreeVec` uses `NodeRef`s in accordance with standard
// borrowing rules, so there are no existing mutable references.
Iter {
leaf: self.root.map(|_| unsafe { self.leaf_for(0) }.0),
index: 0,
phantom: PhantomData,
}
}
/// Gets an iterator that returns mutable references to each item in the
/// vector.
pub fn iter_mut(&mut self) -> IterMut<'_, T, B> {
// SAFETY: `BTreeVec` uses `NodeRef`s in accordance with standard
// borrowing rules, so there are no existing references.
IterMut {
leaf: self.root.map(|_| unsafe { self.leaf_for_mut(0) }.0),
index: 0,
phantom: PhantomData,
}
}
}
impl<T, const B: usize> Default for BTreeVec<T, B> {
fn default() -> Self {
Self::create()
}
}
impl<T, const B: usize> Index<usize> for BTreeVec<T, B> {
type Output = T;
fn index(&self, index: usize) -> &T {
self.get(index).unwrap()
}
}
impl<T, const B: usize> IndexMut<usize> for BTreeVec<T, B> {
fn index_mut(&mut self, index: usize) -> &mut T {
self.get_mut(index).unwrap()
}sourcepub fn first(&self) -> Option<&T>
pub fn first(&self) -> Option<&T>
Gets the first item in the vector, or None if the vector is empty.
sourcepub fn first_mut(&mut self) -> Option<&mut T>
pub fn first_mut(&mut self) -> Option<&mut T>
Gets a mutable reference to the first item in the vector, or None
if the vector is empty.
sourcepub fn last(&self) -> Option<&T>
pub fn last(&self) -> Option<&T>
Gets the last item in the vector, or None if the vector is empty.
sourcepub fn last_mut(&mut self) -> Option<&mut T>
pub fn last_mut(&mut self) -> Option<&mut T>
Gets a mutable reference to the last item in the vector, or None if
the vector is empty.
sourcepub fn pop(&mut self) -> Option<T>
pub fn pop(&mut self) -> Option<T>
Removes and returns the last item in the vector, or None if the
vector is empty.
sourcepub fn iter(&self) -> Iter<'_, T, B> ⓘ
pub fn iter(&self) -> Iter<'_, T, B> ⓘ
Gets an iterator that returns references to each item in the vector.
Examples found in repository?
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 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
macro_rules! impl_drop_for_btree_vec {
($($unsafe:ident)? $(#[$attr:meta])*) => {
$($unsafe)? impl<$(#[$attr])* T, const B: usize> ::core::ops::Drop
for $crate::BTreeVec<T, B>
{
fn drop(&mut self) {
if let Some(root) = self.root {
// SAFETY: `BTreeVec` uses `NodeRef`s in accordance with
// standard borrowing rules, so there are no existing
// references.
unsafe { NodeRef::new_mutable(root) }.destroy();
}
}
}
};
}
#[cfg(not(feature = "dropck_eyepatch"))]
impl_drop_for_btree_vec!();
// SAFETY: This `Drop` impl does not directly or indirectly access any data in
// any `T`, except for calling its destructor (see [1]), and `Self` contains a
// `PhantomData<Box<T>>` so dropck knows that `T` may be dropped (see [2]).
//
// [1]: https://doc.rust-lang.org/nomicon/dropck.html
// [2]: https://forge.rust-lang.org/libs/maintaining-std.html
// #is-there-a-manual-drop-implementation
#[cfg(feature = "dropck_eyepatch")]
impl_drop_for_btree_vec!(unsafe #[may_dangle]);
/// An iterator over the items in a [`BTreeVec`].
pub struct Iter<'a, T, const B: usize> {
leaf: Option<LeafRef<T, B>>,
index: usize,
phantom: PhantomData<&'a T>,
}
impl<'a, T, const B: usize> Iterator for Iter<'a, T, B> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let mut leaf = self.leaf?;
if self.index == leaf.length() {
self.leaf = self.leaf.take().unwrap().into_next().ok();
leaf = self.leaf?;
self.index = 0;
}
let index = self.index;
self.index += 1;
Some(leaf.into_child(index))
}
}
impl<T, const B: usize> FusedIterator for Iter<'_, T, B> {}
impl<T, const B: usize> Clone for Iter<'_, T, B> {
fn clone(&self) -> Self {
Self {
leaf: self.leaf,
index: self.index,
phantom: self.phantom,
}
}
}
// SAFETY: This type yields immutable references to items in the vector, so it
// can be `Send` as long as `T` is `Sync` (which means `&T` is `Send`).
unsafe impl<T: Sync, const B: usize> Send for Iter<'_, T, B> {}
// SAFETY: This type has no `&self` methods that access shared data or fields
// with non-`Sync` interior mutability, but `T` must be `Sync` to match the
// `Send` impl, since this type implements `Clone`, effectively allowing it to
// be sent.
unsafe impl<T: Sync, const B: usize> Sync for Iter<'_, T, B> {}
impl<'a, T, const B: usize> IntoIterator for &'a BTreeVec<T, B> {
type Item = &'a T;
type IntoIter = Iter<'a, T, B>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}