Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Deque

PagedDeque<T, PAGE = 1024> is a double-ended queue stored in fixed-size pages. An element keeps its address for as long as it stays in the deque, through pushes and pops at either end, reserve and shrink_to_fit. Spare pages are kept at the back and reused at either end.

Python: PagedDeque follows collections.deque (CPython 3.12 semantics), including maxlen, rotate and the comparison operators.

A two-page deque with existing elements A, B, C and D. A front push puts L before A, and a back push puts R after D.
Each push uses a free slot at its end of the deque. A push across a page boundary uses another page.

Example

from paged_collections import PagedDeque

values = PagedDeque([1, 2, 3])
values.appendleft(0)
values.append(4)
print("values =", list(values))
print("index 2 =", values[2])
print("front =", values.popleft())
print("back =", values.pop())
print("remaining =", list(values))
values.rotate(1)
print("rotated =", list(values))
use paged_collections::paged_deque::PagedDeque;

fn main() {
    let mut values: PagedDeque<i32> = PagedDeque::new();
    values.extend([1, 2, 3]);
    values.push_front(0);
    values.push_back(4);
    println!("values = {:?}", values.iter().collect::<Vec<_>>());
    println!("index 2 = {}", values[2]);
    println!("front = {}", values.pop_front().unwrap());
    println!("back = {}", values.pop_back().unwrap());
    println!("remaining = {:?}", values.iter().collect::<Vec<_>>());
}

Python output:

values = [0, 1, 2, 3, 4]
index 2 = 2
front = 0
back = 4
remaining = [1, 2, 3]
rotated = [3, 1, 2]

The Rust example prints the same lines without the rotation.

Complexity

OperationCost
pops, access, indexing, swappingO(1)
pushesamortized O(1), occasional page allocation and directory growth
insert, removeO(min(index, len − index)) moves
truncate, clearO(removed) drops; pages are kept
binary_search, partition_pointO(log len)
reserve, shrink_to_fitO(allocated or freed pages)

Front operations change indices without moving the remaining elements. Insertion, removal, swapping and retention can move elements.

Elements are not contiguous. pages() returns the initialized part of each used page, and the first and last slices can be partial.

Rust and Python

RustPython
push_back, push_frontappend, appendleft
pop_back, pop_frontpop, popleft
extendextend, extendleft
front, back, indexingd[0], d[-1], d[i]
insert, removeinsert(i, v), del d[i]; remove(value) searches by value
rotate(n), reverse(), count, index, maxlen
reserve, shrink_to_fitsame names

API: PagedDeque.