Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/main/php/util/Bytes.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,19 @@ public function getIterator(): Traversable {
}
}

/**
* Slicing
*
* @param string|array $slice
* @return self
*/
public function __invoke($slice) {
list($start, $stop)= is_array($slice) ? $slice : explode(':', $slice, 2);
$offset= (int)$start;
$end= (int)$stop ?: $this->size;
return new self(substr($this->buffer, $offset, ($end < 0 ? $this->size + $end : $end) - $offset));
}

/**
* = list[] overloading
*
Expand Down
25 changes: 25 additions & 0 deletions src/test/php/util/unittest/BytesTest.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,25 @@

class BytesTest {

/** @return iterable */
private function slices() {
yield ['0:4', 'This']; // start:stop
yield ['5:7', 'is']; // start:stop - with non-zero start
yield ['5:-5', 'is a']; // start:stop - with negative offset
yield ['-4:-2', 'test']; // start:stop - with negative offsets

yield [':4', 'This']; // :stop
yield [':-5', 'This is a']; // :stop - with negative offset
yield ['5:', 'is a test']; // start:
yield ['-4:', 'test']; // start: - at negative offset
yield [':', 'This is a test']; // : - copy

yield [[0, 4], 'This']; // start:stop
yield [[5, 7], 'is']; // start:stop - with non-zero start
yield [[5, -5], 'is a']; // start:stop - with negative offset
yield [[-4, -2], 'test']; // start:stop - with negative offsets
}

/** @return iterable */
private function comparing() {
yield [new Bytes('Test'), 0];
Expand Down Expand Up @@ -338,6 +357,12 @@ public function iteration() {
Assert::equals($i, sizeof($c)- 1);
}

#[Test, Values(from: 'slices')]
public function slice($slice, $expected) {
$b= new Bytes('This is a test');
Assert::equals(new Bytes($expected), $b($slice));
}

#[Test, Values(from: 'comparing')]
public function compare($value, $expected) {
Assert::equals($expected, (new Bytes('Test'))->compareTo($value));
Expand Down