cordyceps/list/cursor.rs
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 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
use super::{Link, Links, List};
use crate::{util::FmtOption, Linked};
use core::{
fmt, mem,
ops::{Deref, DerefMut},
pin::Pin,
ptr::NonNull,
};
/// A cursor over a [`List`] with editing operations.
///
/// A `CursorMut` is like a mutable [`Iterator`] (and it [implements the
/// `Iterator` trait](#impl-Iterator)), except that it can freely seek
/// back and forth, and can safely mutate the list during iteration. This is
/// because the lifetime of its yielded references is tied to its own lifetime,
/// instead of that of the underlying underlying list. This means cursors cannot
/// yield multiple elements at once.
///
/// Cursors always rest between two elements in the list, and index in a
/// logically circular way — once a cursor has advanced past the end of
/// the list, advancing it again will "wrap around" to the first element, and
/// seeking past the first element will wrap the cursor around to the end.
///
/// To accommodate this, there is a null non-element that yields `None` between
/// the head and tail of the list. This indicates that the cursor has reached
/// an end of the list.
///
/// This type implements the same interface as the
/// [`alloc::collections::linked_list::CursorMut`] type, and should behave
/// similarly.
pub struct CursorMut<'list, T: Linked<Links<T>> + ?Sized> {
core: CursorCore<T, &'list mut List<T>>,
}
/// A cursor over a [`List`].
///
/// A `Cursor` is like a by-reference [`Iterator`] (and it [implements the
/// `Iterator` trait](#impl-Iterator)), except that it can freely seek
/// back and forth, and can safely mutate the list during iteration. This is
/// because the lifetime of its yielded references is tied to its own lifetime,
/// instead of that of the underlying underlying list. This means cursors cannot
/// yield multiple elements at once.
///
/// Cursors always rest between two elements in the list, and index in a
/// logically circular way — once a cursor has advanced past the end of
/// the list, advancing it again will "wrap around" to the first element, and
/// seeking past the first element will wrap the cursor around to the end.
///
/// To accommodate this, there is a null non-element that yields `None` between
/// the head and tail of the list. This indicates that the cursor has reached
/// an end of the list.
///
/// This type implements the same interface as the
/// [`alloc::collections::linked_list::Cursor`] type, and should behave
/// similarly.
///
/// For a mutable cursor, see the [`CursorMut`] type.
pub struct Cursor<'list, T: Linked<Links<T>> + ?Sized> {
core: CursorCore<T, &'list List<T>>,
}
/// A type implementing shared functionality between mutable and immutable
/// cursors.
///
/// This allows us to only have a single implementation of methods like
/// `move_next` and `move_prev`, `peek_next,` and `peek_prev`, etc, for both
/// `Cursor` and `CursorMut`.
struct CursorCore<T: ?Sized, L> {
list: L,
curr: Link<T>,
index: usize,
}
// === impl CursorMut ====
impl<'list, T: Linked<Links<T>> + ?Sized> Iterator for CursorMut<'list, T> {
type Item = Pin<&'list mut T>;
fn next(&mut self) -> Option<Self::Item> {
let node = self.core.curr?;
self.move_next();
unsafe { Some(self.core.pin_node_mut(node)) }
}
/// A [`CursorMut`] can never return an accurate `size_hint` --- its lower
/// bound is always 0 and its upper bound is always `None`.
///
/// This is because the cursor may be moved around within the list through
/// methods outside of its `Iterator` implementation, and elements may be
/// added or removed using the cursor. This would make any `size_hint`s a
/// [`CursorMut`] returns inaccurate.
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(0, None)
}
}
impl<'list, T: Linked<Links<T>> + ?Sized> CursorMut<'list, T> {
pub(super) fn new(list: &'list mut List<T>, curr: Link<T>, index: usize) -> Self {
Self {
core: CursorCore { list, index, curr },
}
}
/// Returns the index of this cursor's position in the [`List`].
///
/// This returns `None` if the cursor is currently pointing to the
/// null element.
pub fn index(&self) -> Option<usize> {
self.core.index()
}
/// Moves the cursor position to the next element in the [`List`].
///
/// If the cursor is pointing at the null element, this moves it to the first
/// element in the [`List`]. If it is pointing to the last element in the
/// list, then this will move it to the null element.
pub fn move_next(&mut self) {
self.core.move_next()
}
/// Moves the cursor to the previous element in the [`List`].
///
/// If the cursor is pointing at the null element, this moves it to the last
/// element in the [`List`]. If it is pointing to the first element in the
/// list, then this will move it to the null element.
// XXX(eliza): i would have named this "move_back", personally, but
// `std::collections::LinkedList`'s cursor interface calls this
// "move_prev"...
pub fn move_prev(&mut self) {
self.core.move_prev()
}
/// Removes the current element from the [`List`] and returns the [`Handle`]
/// owning that element.
///
/// If the cursor is currently pointing to an element, that element is
/// removed and returned, and the cursor is moved to point to the next
/// element in the [`List`].
///
/// If the cursor is currently pointing to the null element, then no element
/// is removed and `None` is returned.
///
/// [`Handle`]: crate::Linked::Handle
pub fn remove_current(&mut self) -> Option<T::Handle> {
let node = self.core.curr?;
unsafe {
// before modifying `node`'s links, set the current element to the
// one after `node`.
self.core.curr = T::links(node).as_ref().next();
// safety: `List::remove` is unsafe to call, because the caller must
// guarantee that the removed node is part of *that* list. in this
// case, because the cursor can only access nodes from the list it
// points to, we know this is safe.
self.core.list.remove(node)
}
}
/// Find and remove the first element matching the provided `predicate`.
///
/// This traverses the list from the cursor's current position and calls
/// `predicate` with each element in the list. If `predicate` returns
/// `true` for a given element, that element is removed from the list and
/// returned, and the traversal ends. If the traversal reaches the end of
/// the list without finding a match, then no element is returned.
///
/// Note that if the cursor is not at the beginning of the list, then any
/// matching elements *before* the cursor's position will not be removed.
///
/// This method may be called multiple times to remove more than one
/// matching element.
pub fn remove_first(&mut self, mut predicate: impl FnMut(&T) -> bool) -> Option<T::Handle> {
while !predicate(unsafe { self.core.curr?.as_ref() }) {
// if the current element does not match, advance to the next node
// in the list.
self.move_next();
}
// if we have broken out of the loop without returning a `None`, remove
// the current element.
self.remove_current()
}
/// Borrows the element that the cursor is currently pointing at.
///
/// This returns `None` if the cursor is currently pointing to the
/// null element.
pub fn current(&self) -> Option<Pin<&T>> {
self.core.current()
}
/// Mutably borrows the element that the cursor is currently pointing at.
///
/// This returns `None` if the cursor is currently pointing to the
/// null element.
pub fn current_mut(&mut self) -> Option<Pin<&mut T>> {
self.core
.curr
.map(|node| unsafe { self.core.pin_node_mut(node) })
}
/// Borrows the next element after the cursor's current position in the
/// list.
///
/// If the cursor is pointing to the null element, this returns the first
/// element in the [`List`]. If the cursor is pointing to the last element
/// in the [`List`], this returns `None`.
pub fn peek_next(&self) -> Option<Pin<&T>> {
self.core.peek_next()
}
/// Borrows the previous element before the cursor's current position in the
/// list.
///
/// If the cursor is pointing to the null element, this returns the last
/// element in the [`List`]. If the cursor is pointing to the first element
/// in the [`List`], this returns `None`.
// XXX(eliza): i would have named this "move_back", personally, but
// `std::collections::LinkedList`'s cursor interface calls this
// "move_prev"...
pub fn peek_prev(&self) -> Option<Pin<&T>> {
self.core.peek_prev()
}
/// Mutably borrows the next element after the cursor's current position in
/// the list.
///
/// If the cursor is pointing to the null element, this returns the first
/// element in the [`List`]. If the cursor is pointing to the last element
/// in the [`List`], this returns `None`.
pub fn peek_next_mut(&mut self) -> Option<Pin<&mut T>> {
self.core
.next_link()
.map(|next| unsafe { self.core.pin_node_mut(next) })
}
/// Mutably borrows the previous element before the cursor's current
/// position in the list.
///
/// If the cursor is pointing to the null element, this returns the last
/// element in the [`List`]. If the cursor is pointing to the first element
/// in the [`List`], this returns `None`.
// XXX(eliza): i would have named this "move_back", personally, but
// `std::collections::LinkedList`'s cursor interface calls this
// "move_prev"...
pub fn peek_prev_mut(&mut self) -> Option<Pin<&mut T>> {
self.core
.prev_link()
.map(|prev| unsafe { self.core.pin_node_mut(prev) })
}
/// Inserts a new element into the [`List`] after the current one.
///
/// If the cursor is pointing at the null element then the new element is
/// inserted at the front of the [`List`].
pub fn insert_after(&mut self, element: T::Handle) {
let node = T::into_ptr(element);
assert_ne!(
self.core.curr,
Some(node),
"cannot insert a node after itself"
);
let next = self.core.next_link();
unsafe {
self.core
.list
.insert_nodes_between(self.core.curr, next, node, node, 1);
}
if self.core.curr.is_none() {
// The null index has shifted.
self.core.index = self.core.list.len;
}
}
/// Inserts a new element into the [`List`] before the current one.
///
/// If the cursor is pointing at the null element then the new element is
/// inserted at the front of the [`List`].
pub fn insert_before(&mut self, element: T::Handle) {
let node = T::into_ptr(element);
assert_ne!(
self.core.curr,
Some(node),
"cannot insert a node before itself"
);
let prev = self.core.prev_link();
unsafe {
self.core
.list
.insert_nodes_between(prev, self.core.curr, node, node, 1);
}
self.core.index += 1;
}
/// Returns the length of the [`List`] this cursor points to.
pub fn len(&self) -> usize {
self.core.list.len()
}
/// Returns `true` if the [`List`] this cursor points to is empty
pub fn is_empty(&self) -> bool {
self.core.list.is_empty()
}
/// Splits the list into two after the current element. This will return a
/// new list consisting of everything after the cursor, with the original
/// list retaining everything before.
///
/// If the cursor is pointing at the null element, then the entire contents
/// of the `List` are moved.
pub fn split_after(&mut self) -> List<T> {
let split_at = if self.core.index == self.core.list.len {
self.core.index = 0;
0
} else {
self.core.index + 1
};
unsafe {
// safety: we know we are splitting at a node that belongs to our list.
self.core.list.split_after_node(self.core.curr, split_at)
}
}
/// Splits the list into two before the current element. This will return a
/// new list consisting of everything before the cursor, with the original
/// list retaining everything after the cursor.
///
/// If the cursor is pointing at the null element, then the entire contents
/// of the `List` are moved.
pub fn split_before(&mut self) -> List<T> {
let split_at = self.core.index;
self.core.index = 0;
// TODO(eliza): this could be rewritten to use `let ... else` when
// that's supported on `cordyceps`' MSRV.
let split_node = match self.core.curr {
Some(node) => node,
// the split portion is the entire list. just return it.
None => return mem::replace(self.core.list, List::new()),
};
// the tail of the new list is the split node's `prev` node (which is
// replaced with `None`), as the split node is the new head of this list.
let tail = unsafe { T::links(split_node).as_mut().set_prev(None) };
let head = if let Some(tail) = tail {
// since `tail` is now the head of its own list, it has no `next`
// link any more.
let _next = unsafe { T::links(tail).as_mut().set_next(None) };
debug_assert_eq!(_next, Some(split_node));
// this list's head is now the split node.
self.core.list.head.replace(split_node)
} else {
None
};
let split = List {
head,
tail,
len: split_at,
};
// update this list's length (note that this occurs after constructing
// the new list, because we use this list's length to determine the new
// list's length).
self.core.list.len -= split_at;
split
}
/// Inserts all elements from `spliced` after the cursor's current position.
///
/// If the cursor is pointing at the null element, then the contents of
/// `spliced` are inserted at the beginning of the `List` the cursor points to.
pub fn splice_after(&mut self, mut spliced: List<T>) {
// TODO(eliza): this could be rewritten to use `let ... else` when
// that's supported on `cordyceps`' MSRV.
let (splice_head, splice_tail, splice_len) = match spliced.take_all() {
Some(splice) => splice,
// the spliced list is empty, do nothing.
None => return,
};
let next = self.core.next_link();
unsafe {
// safety: we know `curr` and `next` came from the same list that we
// are calling `insert_nodes_between` from, because they came from
// this cursor, which points at `self.list`.
self.core.list.insert_nodes_between(
self.core.curr,
next,
splice_head,
splice_tail,
splice_len,
);
}
if self.core.curr.is_none() {
self.core.index = self.core.list.len();
}
}
/// Inserts all elements from `spliced` before the cursor's current position.
///
/// If the cursor is pointing at the null element, then the contents of
/// `spliced` are inserted at the end of the `List` the cursor points to.
pub fn splice_before(&mut self, mut spliced: List<T>) {
// TODO(eliza): this could be rewritten to use `let ... else` when
// that's supported on `cordyceps`' MSRV.
let (splice_head, splice_tail, splice_len) = match spliced.take_all() {
Some(splice) => splice,
// the spliced list is empty, do nothing.
None => return,
};
let prev = self.core.prev_link();
unsafe {
// safety: we know `curr` and `prev` came from the same list that we
// are calling `insert_nodes_between` from, because they came from
// this cursor, which points at `self.list`.
self.core.list.insert_nodes_between(
prev,
self.core.curr,
splice_head,
splice_tail,
splice_len,
);
}
self.core.index += splice_len;
}
/// Returns a read-only cursor pointing to the current element.
///
/// The lifetime of the returned [`Cursor`] is bound to that of the
/// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
/// `CursorMut` is frozen for the lifetime of the [`Cursor`].
#[must_use]
pub fn as_cursor(&self) -> Cursor<'_, T> {
Cursor {
core: CursorCore {
list: self.core.list,
curr: self.core.curr,
index: self.core.index,
},
}
}
}
impl<T: Linked<Links<T>> + ?Sized> fmt::Debug for CursorMut<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self {
core: CursorCore { list, curr, index },
} = self;
f.debug_struct("CursorMut")
.field("curr", &FmtOption::new(curr))
.field("list", list)
.field("index", index)
.finish()
}
}
// === impl Cursor ====
impl<'list, T: Linked<Links<T>> + ?Sized> Iterator for Cursor<'list, T> {
type Item = Pin<&'list T>;
fn next(&mut self) -> Option<Self::Item> {
let node = self.core.curr?;
self.move_next();
unsafe { Some(self.core.pin_node(node)) }
}
/// A [`Cursor`] can never return an accurate `size_hint` --- its lower
/// bound is always 0 and its upper bound is always `None`.
///
/// This is because the cursor may be moved around within the list through
/// methods outside of its `Iterator` implementation. This would make any
/// `size_hint`s a `Cursor`] returns inaccurate.
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(0, None)
}
}
impl<'list, T: Linked<Links<T>> + ?Sized> Cursor<'list, T> {
pub(super) fn new(list: &'list List<T>, curr: Link<T>, index: usize) -> Self {
Self {
core: CursorCore { list, index, curr },
}
}
/// Returns the index of this cursor's position in the [`List`].
///
/// This returns `None` if the cursor is currently pointing to the
/// null element.
pub fn index(&self) -> Option<usize> {
self.core.index()
}
/// Moves the cursor position to the next element in the [`List`].
///
/// If the cursor is pointing at the null element, this moves it to the first
/// element in the [`List`]. If it is pointing to the last element in the
/// list, then this will move it to the null element.
pub fn move_next(&mut self) {
self.core.move_next();
}
/// Moves the cursor to the previous element in the [`List`].
///
/// If the cursor is pointing at the null element, this moves it to the last
/// element in the [`List`]. If it is pointing to the first element in the
/// list, then this will move it to the null element.
// XXX(eliza): i would have named this "move_back", personally, but
// `std::collections::LinkedList`'s cursor interface calls this
// "move_prev"...
pub fn move_prev(&mut self) {
self.core.move_prev();
}
/// Borrows the element that the cursor is currently pointing at.
///
/// This returns `None` if the cursor is currently pointing to the
/// null element.
pub fn current(&self) -> Option<Pin<&T>> {
self.core.current()
}
/// Borrows the next element after the cursor's current position in the
/// list.
///
/// If the cursor is pointing to the null element, this returns the first
/// element in the [`List`]. If the cursor is pointing to the last element
/// in the [`List`], this returns `None`.
pub fn peek_next(&self) -> Option<Pin<&T>> {
self.core.peek_next()
}
/// Borrows the previous element before the cursor's current position in the
/// list.
///
/// If the cursor is pointing to the null element, this returns the last
/// element in the [`List`]. If the cursor is pointing to the first element
/// in the [`List`], this returns `None`.
// XXX(eliza): i would have named this "move_back", personally, but
// `std::collections::LinkedList`'s cursor interface calls this
// "move_prev"...
pub fn peek_prev(&self) -> Option<Pin<&T>> {
self.core.peek_prev()
}
/// Returns the length of the [`List`] this cursor points to.
pub fn len(&self) -> usize {
self.core.list.len()
}
/// Returns `true` if the [`List`] this cursor points to is empty
pub fn is_empty(&self) -> bool {
self.core.list.is_empty()
}
}
impl<T: Linked<Links<T>> + ?Sized> fmt::Debug for Cursor<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self {
core: CursorCore { list, curr, index },
} = self;
f.debug_struct("Cursor")
.field("curr", &FmtOption::new(curr))
.field("list", list)
.field("index", index)
.finish()
}
}
// === impl CursorCore ===
impl<'list, T, L> CursorCore<T, L>
where
T: Linked<Links<T>> + ?Sized,
L: Deref<Target = List<T>> + 'list,
{
fn index(&self) -> Option<usize> {
self.curr?;
Some(self.index)
}
fn move_next(&mut self) {
match self.curr.take() {
// Advance the cursor to the current node's next element.
Some(curr) => unsafe {
self.curr = T::links(curr).as_ref().next();
self.index += 1;
},
// We have no current element --- move to the start of the list.
None => {
self.curr = self.list.head;
self.index = 0;
}
}
}
fn move_prev(&mut self) {
match self.curr.take() {
// Advance the cursor to the current node's prev element.
Some(curr) => unsafe {
self.curr = T::links(curr).as_ref().prev();
// this is saturating because the current node might be the 0th
// and we might have set `self.curr` to `None`.
self.index = self.index.saturating_sub(1);
},
// We have no current element --- move to the end of the list.
None => {
self.curr = self.list.tail;
self.index = self.index.checked_sub(1).unwrap_or(self.list.len());
}
}
}
fn current(&self) -> Option<Pin<&T>> {
// NOTE(eliza): in this case, we don't *need* to pin the reference,
// because it's immutable and you can't move out of a shared
// reference in safe code. but...it makes the API more consistent
// with `front_mut` etc.
self.curr.map(|node| unsafe { self.pin_node(node) })
}
fn peek_next(&self) -> Option<Pin<&T>> {
self.next_link().map(|next| unsafe { self.pin_node(next) })
}
fn peek_prev(&self) -> Option<Pin<&T>> {
self.prev_link().map(|prev| unsafe { self.pin_node(prev) })
}
#[inline(always)]
fn next_link(&self) -> Link<T> {
match self.curr {
Some(curr) => unsafe { T::links(curr).as_ref().next() },
None => self.list.head,
}
}
#[inline(always)]
fn prev_link(&self) -> Link<T> {
match self.curr {
Some(curr) => unsafe { T::links(curr).as_ref().prev() },
None => self.list.tail,
}
}
/// # Safety
///
/// - `node` must point to an element currently in this list.
unsafe fn pin_node(&self, node: NonNull<T>) -> Pin<&'list T> {
// safety: elements in the list must be pinned while they are in the
// list, so it is safe to construct a `pin` here provided that the
// `Linked` trait's invariants are upheld.
//
// the lifetime of the returned reference inside the `Pin` is the
// lifetime of the `CursorMut`'s borrow on the list, so the node ref
// cannot outlive its referent, provided that `node` actually came from
// this list (and it would be a violation of this function's safety
// invariants if it did not).
Pin::new_unchecked(node.as_ref())
}
}
impl<'list, T, L> CursorCore<T, L>
where
T: Linked<Links<T>> + ?Sized,
L: Deref<Target = List<T>> + DerefMut + 'list,
{
/// # Safety
///
/// - `node` must point to an element currently in this list.
unsafe fn pin_node_mut(&self, mut node: NonNull<T>) -> Pin<&'list mut T> {
// safety: elements in the list must be pinned while they are in the
// list, so it is safe to construct a `pin` here provided that the
// `Linked` trait's invariants are upheld.
//
// the lifetime of the returned reference inside the `Pin` is the
// lifetime of the `CursorMut`'s borrow on the list, so the node ref
// cannot outlive its referent, provided that `node` actually came from
// this list (and it would be a violation of this function's safety
// invariants if it did not).
Pin::new_unchecked(node.as_mut())
}
}