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