CircularBuffer.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. /*
  3. * By adding type hints and enabling strict type checking, code can become
  4. * easier to read, self-documenting and reduce the number of potential bugs.
  5. * By default, type declarations are non-strict, which means they will attempt
  6. * to change the original type to match the type specified by the
  7. * type-declaration.
  8. *
  9. * In other words, if you pass a string to a function requiring a float,
  10. * it will attempt to convert the string value to a float.
  11. *
  12. * To enable strict mode, a single declare directive must be placed at the top
  13. * of the file.
  14. * This means that the strictness of typing is configured on a per-file basis.
  15. * This directive not only affects the type declarations of parameters, but also
  16. * a function's return type.
  17. *
  18. * For more info review the Concept on strict type checking in the PHP track
  19. * <link>.
  20. *
  21. * To disable strict typing, comment out the directive below.
  22. */
  23. declare(strict_types=1);
  24. class CircularBuffer {
  25. /**
  26. * @var int Array capacity.
  27. */
  28. private int $cap = 0;
  29. /**
  30. * @var \SplFixedArray Storage, faster than plain array and fixed size.
  31. */
  32. private SplFixedArray $data;
  33. /**
  34. * @var int Start of data with $this->>data.
  35. */
  36. private int $base = 0;
  37. /**
  38. * @var int Number of data items in $this->>data.
  39. */
  40. private int $length = 0;
  41. public function __construct(int $length) {
  42. $this->cap = $length;
  43. $this->data = new SplFixedArray($length);
  44. }
  45. public function clear(): void {
  46. $this->data = new SplFixedArray($this->cap);
  47. $this->base = 0;
  48. $this->length = 0;
  49. }
  50. /**
  51. * @throws \BufferEmptyError
  52. */
  53. public function read() {
  54. if ($this->length === 0) {
  55. throw new BufferEmptyError();
  56. }
  57. $res = $this->data[$this->base];
  58. $this->base = ($this->base + 1) % $this->cap;
  59. $this->length--;
  60. return $res;
  61. }
  62. /**
  63. * @throws \BufferFullError
  64. */
  65. public function write($item): void {
  66. if ($this->length == $this->cap) {
  67. throw new BufferFullError();
  68. }
  69. $this->data[($this->base+$this->length)%$this->cap] = $item;
  70. $this->length++;
  71. }
  72. public function forceWrite($item): void {
  73. $this->data[($this->base+$this->length)%$this->cap] = $item;
  74. if ($this->length === $this->cap) {
  75. $this->base = ($this->base+1)%$this->cap;
  76. }
  77. $this->length = min($this->cap, $this->length+1);
  78. }
  79. }
  80. class BufferFullError extends Exception {
  81. }
  82. class BufferEmptyError extends Exception {
  83. }