# DoubleEndedQueue.sol

> 次に、DoubleEndedQueue.solを見ていきます。

- URL: https://cardene.dev/books/erc404/888a1a
- 本: ERC404大全 (https://cardene.dev/books/erc404.md)
- 章: 4 / 14
- 前の章: https://cardene.dev/books/erc404/6562c7.md
- 次の章: https://cardene.dev/books/erc404/dc1d6b.md
- 公開日: 2024-04-19
- 更新日: 2024-04-19
- トピック: Blockchain
- タグ: solidity, ethereum, erc721, erc20

次に、`DoubleEndedQueue.sol`を見ていきます。

https://github.com/Pandora-Labs-Org/erc404/blob/main/contracts/lib/DoubleEndedQueue.sol

`DoubleEndedQueue.sol` コントラクトは、Solidityで二重終端キュー（deque）の機能を実装したものです。
このライブラリを使用すると、開発者はスマートコントラクト内で `uint256` データ型を使用して、効率的に先頭または末尾から要素を追加・削除する操作を行えます。
全ての基本操作（挿入、削除、アクセス）は定数時間（O(1)）で実行されるよう最適化されています。
このようなデータ構造は、LIFO（Last In First Out、後入れ先出し）やFIFO（First In First Out、先入れ先出し）などのキュー操作を効率的にサポートするために使用されます。

:::details コード
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/DoubleEndedQueue.sol)
// Modified by Pandora Labs to support native uint256 operations
pragma solidity ^0.8.20;

/**
 * @dev A sequence of items with the ability to efficiently push and pop items (i.e. insert and remove) on both ends of
 * the sequence (called front and back). Among other access patterns, it can be used to implement efficient LIFO and
 * FIFO queues. Storage use is optimized, and all operations are O(1) constant time. This includes {clear}, given that
 * the existing queue contents are left in storage.
 *
 * The struct is called `Uint256Deque`. This data structure can only be used in storage, and not in memory.
 *
 * ```solidity
 * DoubleEndedQueue.Uint256Deque queue;
 * ```
 */
library DoubleEndedQueue {
  /**
   * @dev An operation (e.g. {front}) couldn't be completed due to the queue being empty.
   */
  error QueueEmpty();

  /**
   * @dev A push operation couldn't be completed due to the queue being full.
   */
  error QueueFull();

  /**
   * @dev An operation (e.g. {at}) couldn't be completed due to an index being out of bounds.
   */
  error QueueOutOfBounds();

  /**
   * @dev Indices are 128 bits so begin and end are packed in a single storage slot for efficient access.
   *
   * Struct members have an underscore prefix indicating that they are "private" and should not be read or written to
   * directly. Use the functions provided below instead. Modifying the struct manually may violate assumptions and
   * lead to unexpected behavior.
   *
   * The first item is at data[begin] and the last item is at data[end - 1]. This range can wrap around.
   */
  struct Uint256Deque {
    uint128 _begin;
    uint128 _end;
    mapping(uint128 index => uint256) _data;
  }

  /**
   * @dev Inserts an item at the end of the queue.
   *
   * Reverts with {QueueFull} if the queue is full.
   */
  function pushBack(Uint256Deque storage deque, uint256 value) internal {
    unchecked {
      uint128 backIndex = deque._end;
      if (backIndex + 1 == deque._begin) revert QueueFull();
      deque._data[backIndex] = value;
      deque._end = backIndex + 1;
    }
  }

  /**
   * @dev Removes the item at the end of the queue and returns it.
   *
   * Reverts with {QueueEmpty} if the queue is empty.
   */
  function popBack(
    Uint256Deque storage deque
  ) internal returns (uint256 value) {
    unchecked {
      uint128 backIndex = deque._end;
      if (backIndex == deque._begin) revert QueueEmpty();
      --backIndex;
      value = deque._data[backIndex];
      delete deque._data[backIndex];
      deque._end = backIndex;
    }
  }

  /**
   * @dev Inserts an item at the beginning of the queue.
   *
   * Reverts with {QueueFull} if the queue is full.
   */
  function pushFront(Uint256Deque storage deque, uint256 value) internal {
    unchecked {
      uint128 frontIndex = deque._begin - 1;
      if (frontIndex == deque._end) revert QueueFull();
      deque._data[frontIndex] = value;
      deque._begin = frontIndex;
    }
  }

  /**
   * @dev Removes the item at the beginning of the queue and returns it.
   *
   * Reverts with `QueueEmpty` if the queue is empty.
   */
  function popFront(
    Uint256Deque storage deque
  ) internal returns (uint256 value) {
    unchecked {
      uint128 frontIndex = deque._begin;
      if (frontIndex == deque._end) revert QueueEmpty();
      value = deque._data[frontIndex];
      delete deque._data[frontIndex];
      deque._begin = frontIndex + 1;
    }
  }

  /**
   * @dev Returns the item at the beginning of the queue.
   *
   * Reverts with `QueueEmpty` if the queue is empty.
   */
  function front(
    Uint256Deque storage deque
  ) internal view returns (uint256 value) {
    if (empty(deque)) revert QueueEmpty();
    return deque._data[deque._begin];
  }

  /**
   * @dev Returns the item at the end of the queue.
   *
   * Reverts with `QueueEmpty` if the queue is empty.
   */
  function back(
    Uint256Deque storage deque
  ) internal view returns (uint256 value) {
    if (empty(deque)) revert QueueEmpty();
    unchecked {
      return deque._data[deque._end - 1];
    }
  }

  /**
   * @dev Return the item at a position in the queue given by `index`, with the first item at 0 and last item at
   * `length(deque) - 1`.
   *
   * Reverts with `QueueOutOfBounds` if the index is out of bounds.
   */
  function at(
    Uint256Deque storage deque,
    uint256 index
  ) internal view returns (uint256 value) {
    if (index >= length(deque)) revert QueueOutOfBounds();
    // By construction, length is a uint128, so the check above ensures that index can be safely downcast to uint128
    unchecked {
      return deque._data[deque._begin + uint128(index)];
    }
  }

  /**
   * @dev Resets the queue back to being empty.
   *
   * NOTE: The current items are left behind in storage. This does not affect the functioning of the queue, but misses
   * out on potential gas refunds.
   */
  function clear(Uint256Deque storage deque) internal {
    deque._begin = 0;
    deque._end = 0;
  }

  /**
   * @dev Returns the number of items in the queue.
   */
  function length(Uint256Deque storage deque) internal view returns (uint256) {
    unchecked {
      return uint256(deque._end - deque._begin);
    }
  }

  /**
   * @dev Returns true if the queue is empty.
   */
  function empty(Uint256Deque storage deque) internal view returns (bool) {
    return deque._end == deque._begin;
  }
}
:::

## Error & Struct

### Error
- **QueueEmpty**
    - キューが空のため、操作（例：`front`）を完了できませんでした。
- **QueueFull**
    - キューが満杯のため、プッシュ操作を完了できませんでした。
- **QueueOutOfBounds**
    - インデックスが範囲外のため、操作（例：`at`）を完了できませんでした。

### Struct
- **Uint256Deque**
    - `uint256` 型のデータを格納するための二重終端キュー（deque）。
    - **_begin (uint128)**
        - キュー内の先頭要素のインデックス。
    - **_end (uint128)**
        - キュー内の末尾要素の次のインデックス。
    - **_data (mapping(uint128 => uint256))**
        - インデックスに基づいて `uint256` 型の値を格納するマッピング。
        - `_begin` が先頭要素を、`_end - 1` が末尾要素を指します。
        - この範囲は循環することがあります。

この構造体は、データの先頭や末尾からの効率的な挿入や削除を可能にし、LIFO（後入れ先出し）や FIFO（先入れ先出し）などのキュー操作をサポートします。

## 関数

### pushBack

```solidity
function pushBack(Uint256Deque storage deque, uint256 value) internal {
    unchecked {
      uint128 backIndex = deque._end;
      if (backIndex + 1 == deque._begin) revert QueueFull();
      deque._data[backIndex] = value;
      deque._end = backIndex + 1;
    }
}
```

**概要**
キューの末尾にアイテムを追加する関数。

**詳細**
キューが満杯の場合、`QueueFull` エラーで処理が中断されます。

**引数**
- `deque`
    - 操作対象のデック。
- `value`
    - キューに追加する値。

---

### popBack

```solidity
function popBack(Uint256Deque storage deque) internal returns (uint256 value) {
    unchecked {
      uint128 backIndex = deque._end;
      if (backIndex == deque._begin) revert QueueEmpty();
      --backIndex;
      value = deque._data[backIndex];
      delete deque._data[backIndex];
      deque._end = backIndex;
    }
}
```

**概要**
キューの末尾からアイテムを取り出し返す関数。

**詳細**
キューが空の場合、`QueueEmpty` エラーで処理が中断されます。

**引数**
- `deque`
    - 操作対象のデック。

**戻り値**
- `value`
    - キューの末尾から取り出された値。

---

### pushFront

```solidity
function pushFront(Uint256Deque storage deque, uint256 value) internal {
    unchecked {
      uint128 frontIndex = deque._begin - 1;
      if (frontIndex == deque._end) revert QueueFull();
      deque._data[frontIndex] = value;
      deque._begin = frontIndex;
    }
}
```

**概要**
キューの先頭にアイテムを追加する関数。

**詳細**
キューが満杯の場合、`QueueFull` エラーで処理が中断されます。

**引数**
- `deque`
    - 操作対象のデック。
- `value`
    - キューに追加する値。

---

### popFront

```solidity
function popFront(Uint256Deque storage deque) internal returns (uint256 value) {
    unchecked {
      uint128 frontIndex = deque._begin;
      if (frontIndex == deque._end) revert QueueEmpty();
      value = deque._data[frontIndex];
      delete deque._data[frontIndex];
      deque._begin = frontIndex + 1;
    }
}
```

**概要**
キューの先頭からアイテムを取り出し返す関数。

**詳細**
キューが空の場合、`QueueEmpty` エラーで処理が中断されます。

**引数**
- `deque`
    - 操作対象のデック。

**戻り値**
- `value`
    - キューの先頭から取り出された値。

---

### front

```solidity
function front(Uint256Deque storage deque) internal view returns (uint256 value) {
    if (empty(deque)) revert QueueEmpty();
    return deque._data[deque._begin];
}
```

**概要**
キューの先頭にあるアイテムを返す関数。

**詳細**
キューが空の場合、`QueueEmpty` エラーで処理が中断されます。

**引数**
- `deque`
    - 参照するデック。

**戻り値**
- `value`
    - キューの先頭にある値。

---

### back

```solidity
function back(Uint256Deque storage deque) internal view returns (uint256 value) {
    if (empty(deque)) revert QueueEmpty();
    unchecked {
      return deque._data[deque._end - 1];
    }
}
```

**概要**
キューの末尾にあるアイテムを返す関数。

**詳細**
キューが空の場合、`QueueEmpty` エラーで処理が中断されます。

**引数**
- `deque`
    - 参照するデック。

**戻り値**
- `value`
    - キューの末尾にある値。

---

### at

```solidity
function at(Uint256Deque storage deque, uint256 index) internal view returns (uint256 value) {
    if (index >= length(deque)) revert QueueOutOfBounds();
    unchecked {
      return deque._data[deque._begin + uint128(index)];
    }
}
```

**概要**
指定された位置にあるキューのアイテムを返す関数。

**詳細**
指定されたインデックスが範囲外の場合、`QueueOutOfBounds` エラーで処理が中断されます。

**引数**
- `deque`
    - 参照するデック。
- `index`
    - 取得したいアイテムの位置。

**戻り値**
- `value`
    - 指定された位置にあるキューの値。

---

### clear

```solidity
function clear(Uint256Deque storage deque) internal {
    deque._begin = 0;
    deque._end = 0;
}
```

**概要**
キューを空にする関数。

**詳細**
この操作では、現存するアイテムはストレージに残され、ガスの払い戻しが行われません。

**引数**
- `deque`
    - 操作対象のデック。

---

### length

```solidity
function length(Uint256Deque storage deque) internal view returns (uint256) {
    unchecked {
      return uint256(deque._end - deque._begin);
    }
}
```

**概要**
キューに含まれるアイテムの数を返す関数。

**詳細**
キュー内のアイテムの総数を計算します。

**引数**
- `deque`
    - 参照するデック。

**戻り値**
- キュー内のアイテムの総数。

---

### empty

```solidity
function empty(Uint256Deque storage deque) internal view returns (bool) {
    return deque._end == deque._begin;
}
```

**概要**
キューが空かどうかを判断する関数。

**詳細**
キューが空の場合には `true` を返し、そうでない場合には `false` を返します。

**引数**
- `deque`
    - 評価するデック。

**戻り値**
- キューが空の場合は `true`、そうでない場合は `false`。
