diff --git a/src/main/php/util/Bytes.class.php b/src/main/php/util/Bytes.class.php index e5f7d8b3b..7c4d984e0 100755 --- a/src/main/php/util/Bytes.class.php +++ b/src/main/php/util/Bytes.class.php @@ -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 * diff --git a/src/test/php/util/unittest/BytesTest.class.php b/src/test/php/util/unittest/BytesTest.class.php index 27b8c9e68..feb8663df 100755 --- a/src/test/php/util/unittest/BytesTest.class.php +++ b/src/test/php/util/unittest/BytesTest.class.php @@ -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]; @@ -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));