Skip to content

Instantly share code, notes, and snippets.

@devi
Created May 8, 2014 05:10
Show Gist options
  • Select an option

  • Save devi/abb01a3f71a9359965b1 to your computer and use it in GitHub Desktop.

Select an option

Save devi/abb01a3f71a9359965b1 to your computer and use it in GitHub Desktop.
<?php
class SimpleArray implements Iterator, ArrayAccess, Countable {
private $size = 1;
private $buffer = null;
private $index = 0;
private $position = 0;
public function __construct($size = 1, $initial_value = 0) {
$this->size = $size;
$this->buffer = new SplFixedArray($size);
for ($i = 0; $i < $size; ++$i) $this->buffer[$i] = $initial_value;
}
public function getSize() {
return $this->size;
}
public function setIndex($i) {
$this->index = $i;
}
public function seek($index) {
while($this->position < $index && $this->valid()) {
$this->next();
}
if (!$this->valid()) {
throw new OutOfBoundsException('Invalid seek position');
}
}
public function rewind() {
$this->index = 0;
$this->position = 0;
}
public function current() {
return $this->buffer[$this->index+$this->position];
}
public function key() {
return $this->position;
}
public function next() {
++$this->position;
}
public function valid() {
return isset($this->buffer[$this->position]);
}
public function count() {
return count($this->buffer) - $this->index;
}
public function offsetExists($offset) {
$offset += $this->index;
return isset($this->buffer[$offset]);
}
public function offsetGet($offset) {
$offset += $this->index;
if (!isset($this->buffer[$offset]))
throw new OutOfBoundsException('Index invalid or out of range.');
return isset($this->buffer[$offset]) ? $this->buffer[$offset] : null;
}
public function offsetSet($offset, $value) {
if (!isset($this->buffer[$offset]))
throw new OutOfBoundsException('Index invalid or out of range.');
$this->buffer[$offset] = $value;
}
public function offsetUnset($offset) {
throw new \BadMethodCallException("Unset not implemented.");
}
public static function fromArray($array) {
$l = count($array);
$r = new SimpleArray($l);
for ($i = 0; $i < $l; ++$i)
$r[$i] = $array[$i];
return $r;
}
public function toArray() {
$l = $this->getSize();
$r = array();
for ($i = 0; $i < $l; ++$i)
$r[$i] = $this->buffer[$i];
return $r;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment