RingBuffer.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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\ResourceBundle\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. class RingBuffer implements \ArrayAccess
  22. {
  23. private $values = array();
  24. private $indices = array();
  25. private $cursor = 0;
  26. private $size;
  27. public function __construct($size)
  28. {
  29. $this->size = $size;
  30. }
  31. /**
  32. * {@inheritdoc}
  33. */
  34. public function offsetExists($key)
  35. {
  36. return isset($this->indices[$key]);
  37. }
  38. /**
  39. * {@inheritdoc}
  40. */
  41. public function offsetGet($key)
  42. {
  43. if (!isset($this->indices[$key])) {
  44. throw new OutOfBoundsException(sprintf(
  45. 'The index "%s" does not exist.',
  46. $key
  47. ));
  48. }
  49. return $this->values[$this->indices[$key]];
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public function offsetSet($key, $value)
  55. {
  56. if (false !== ($keyToRemove = array_search($this->cursor, $this->indices))) {
  57. unset($this->indices[$keyToRemove]);
  58. }
  59. $this->values[$this->cursor] = $value;
  60. $this->indices[$key] = $this->cursor;
  61. $this->cursor = ($this->cursor + 1) % $this->size;
  62. }
  63. /**
  64. * {@inheritdoc}
  65. */
  66. public function offsetUnset($key)
  67. {
  68. if (isset($this->indices[$key])) {
  69. $this->values[$this->indices[$key]] = null;
  70. unset($this->indices[$key]);
  71. }
  72. }
  73. }