phpday 2027 - Call for Papers

The Deque class

(PECL ds >= 1.0.0)

Introduction

A Deque (pronounced “deck”) is a sequence of values in a contiguous buffer that grows and shrinks automatically. The name is a common abbreviation of “double-ended queue” and is used internally by Ds\Queue.

Two pointers are used to keep track of a head and a tail. The pointers can “wrap around” the end of the buffer, which avoids the need to move other values around to make room. This makes shift and unshift very fast —  something a Ds\Vector can’t compete with.

Accessing a value by index requires a translation between the index and its corresponding position in the buffer: ((head + position) % capacity).

Strengths

  • Supports array syntax (square brackets).
  • Uses less overall memory than an array for the same number of values.
  • Automatically frees allocated memory when its size drops low enough.
  • get(), set(), push(), pop(), shift(), and unshift() are all O(1).

Weaknesses

  • Capacity must be a power of 2.
  • insert() and remove() are O(n).

Class synopsis

class Ds\Deque implements Ds\Sequence, ArrayAccess {
/* Constants */
const int MIN_CAPACITY = 8;
/* Methods */
public function allocate(int $capacity): void
public function apply(callable $callback): void
public function capacity(): int
public function clear(): void
public function contains(mixed ...$values): bool
public function copy(): Ds\Deque
public function filter(callable $callback = ?): Ds\Deque
public function find(mixed $value): mixed
public function first(): mixed
public function get(int $index): mixed
public function insert(int $index, mixed ...$values): void
public function isEmpty(): bool
public function join(string $glue = ?): string
public function last(): mixed
public function map(callable $callback): Ds\Deque
public function merge(mixed $values): Ds\Deque
public function pop(): mixed
public function push(mixed ...$values): void
public function reduce(callable $callback, mixed $initial = ?): mixed
public function remove(int $index): mixed
public function reverse(): void
public function reversed(): Ds\Deque
public function rotate(int $rotations): void
public function set(int $index, mixed $value): void
public function shift(): mixed
public function slice(int $index, int $length = ?): Ds\Deque
public function sort(callable $comparator = ?): void
public function sorted(callable $comparator = ?): Ds\Deque
public function sum(): int|float
public function toArray(): array
public function unshift(mixed $values = ?): void
}

Predefined Constants

Ds\Deque::MIN_CAPACITY

Changelog

Version Description
PECL ds 1.3.0 The class now implements ArrayAccess.

Table of Contents

User Contributed Notes

There are no user contributed notes for this page.
Adding new notes is disabled. Please see the links in the Found A Problem? section.
To Top