Skip to content

Commit

Permalink
Implement iterator
Browse files Browse the repository at this point in the history
  • Loading branch information
RobQuistNL committed Apr 26, 2023
1 parent db4d63b commit 1dc670c
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/ByteArray.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,16 @@
/**
* A class to hold an array of bytes
*/
class ByteArray implements \Stringable, \Countable //@todo might implement ArrayAccess or Traversable
class ByteArray implements \Stringable, \Countable, \Iterator
{
private int $position = 0;

private array $array = [];

private function __construct()
{
// Private constructor
$this->position = 0;
}

/**
Expand Down Expand Up @@ -94,4 +97,25 @@ public function count(): int
{
return count($this->array);
}

// Iterator implementation
public function rewind(): void {
$this->position = 0;
}

public function current(): int {
return $this->array[$this->position];
}

public function key(): int {
return $this->position;
}

public function next(): void {
++$this->position;
}

public function valid(): bool {
return isset($this->array[$this->position]);
}
}
38 changes: 38 additions & 0 deletions tests/ByteArrayTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,4 +119,42 @@ public static function provideCount() : array
[ByteArray::fromString('🚀'), 4],
];
}

public function testIterator(): void
{
$expected = ['f0', '9f', '9a', '80'];

$i = 0;
foreach (ByteArray::fromString('🚀') as $byte) {
$this->assertSame($expected[$i++], dechex($byte));
}

$array = ByteArray::fromString('🚀🐸');
$this->assertSame(0, $array->key());
$this->assertTrue($array->valid());
$this->assertSame(240, $array->current()); // First byte
$array->next();
$this->assertTrue($array->valid());
$this->assertSame(159, $array->current()); // Second byte
for ($i = 0; $i < 6; $i++) { // Iterate the next 6 bytes
$array->next();
$this->assertTrue($array->valid());
}

$array->next(); // Now we should be out of range of the array
$this->assertFalse($array->valid());
$this->assertSame(8, $array->key());

// But we can keep iterating
$array->next();
$this->assertFalse($array->valid());
$this->assertSame(9, $array->key());

// And rewind
$array->rewind();
$this->assertSame(0, $array->key());
$this->assertTrue($array->valid());
$this->assertSame(240, $array->current()); // First byte
}

}

0 comments on commit 1dc670c

Please sign in to comment.