RingBuffer.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Intl\Data\Util;
  11. use Symfony\Component\Intl\Exception\OutOfBoundsException;
  12. /**
  13. * Implements a ring buffer.
  14. *
  15. * A ring buffer is an array-like structure with a fixed size. If the buffer
  16. * is full, the next written element overwrites the first bucket in the buffer,
  17. * then the second and so on.
  18. *
  19. * @author Bernhard Schussek <bschussek@gmail.com>
  20. *
  21. * @internal
  22. */
  23. class RingBuffer implements \ArrayAccess
  24. {
  25. private $values = array();
  26. private $indices = array();
  27. private $cursor = 0;
  28. private $size;
  29. public function __construct($size)
  30. {
  31. $this->size = $size;
  32. }
  33. /**
  34. * {@inheritdoc}
  35. */
  36. public function offsetExists($key)
  37. {
  38. return isset($this->indices[$key]);
  39. }
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function offsetGet($key)
  44. {
  45. if (!isset($this->indices[$key])) {
  46. throw new OutOfBoundsException(sprintf(
  47. 'The index "%s" does not exist.',
  48. $key
  49. ));
  50. }
  51. return $this->values[$this->indices[$key]];
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function offsetSet($key, $value)
  57. {
  58. if (false !== ($keyToRemove = array_search($this->cursor, $this->indices))) {
  59. unset($this->indices[$keyToRemove]);
  60. }
  61. $this->values[$this->cursor] = $value;
  62. $this->indices[$key] = $this->cursor;
  63. $this->cursor = ($this->cursor + 1) % $this->size;
  64. }
  65. /**
  66. * {@inheritdoc}
  67. */
  68. public function offsetUnset($key)
  69. {
  70. if (isset($this->indices[$key])) {
  71. $this->values[$this->indices[$key]] = null;
  72. unset($this->indices[$key]);
  73. }
  74. }
  75. }