Skip to content

Commit

Permalink
Add startsWith method
Browse files Browse the repository at this point in the history
  • Loading branch information
RobQuistNL committed Apr 26, 2023
1 parent 1dc670c commit 9f8f62c
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/ByteArray.php
Expand Up @@ -44,6 +44,36 @@ public static function fromArray(array $array): self
return $self;
}

public function startsWith(int|string|ByteArray $startsWith): bool
{
// If its an int we just check the first one
if (is_int($startsWith)) {
if ($this->count() == 0) {
return false;
}
return $this->array[0] == $startsWith;
}

// If its a string, we cast to ByteArray
if (is_string($startsWith)) {
return $this->startsWith(self::fromString($startsWith));
}

$startsWithLength = $startsWith->count();
if ($startsWithLength == 0) {
return true; // Well, technically, each array starts with an empty array.. Maybe throw a warning?
}

if ($startsWithLength > $this->count()) {
// If the given is longer than our own, we bail out
return false;
}

// If not we cut out the same length array
$cut = array_slice($this->array, 0, $startsWithLength);
return $cut == $startsWith->toArray(); // and return if its the same or not
}

public function append(ByteArray $array): self
{
foreach ($array->toArray() as $value) {
Expand Down
29 changes: 29 additions & 0 deletions tests/ByteArrayTest.php
Expand Up @@ -157,4 +157,33 @@ public function testIterator(): void
$this->assertSame(240, $array->current()); // First byte
}

/**
* @dataProvider provideStartsWith
*/
public function testStartsWith(ByteArray $given, $check, bool $expected): void
{
$this->assertSame($expected, $given->startsWith($check));
}

public static function provideStartsWith(): array
{
return [
[ByteArray::fromArray([]), ByteArray::fromArray([]), true],
[ByteArray::fromArray([]), '', true],
[ByteArray::fromArray([]), 0, false],
[ByteArray::fromArray([0]), 0, true],
[ByteArray::fromArray([0, 1, 2, 3]), 0, true],

[ByteArray::fromString('Testing?'), 'Testing?', true],
[ByteArray::fromString('Testing?'), 'Testing????', false],
[ByteArray::fromString('Testing?'), 'T', true],

[ByteArray::fromString('Testing?'), 0x54, true],
[ByteArray::fromString('Testing?'), 84, true],

[ByteArray::fromString('πŸš€πŸΈ'), ByteArray::fromString('πŸš€πŸΈ'), true],
[ByteArray::fromString('πŸš€πŸΈ'), ByteArray::fromString('πŸš€'), true],
[ByteArray::fromString('πŸš€πŸΈ'), 'πŸš€', true],
];
}
}

0 comments on commit 9f8f62c

Please sign in to comment.