From 0fa93d691c10034bdb07d6e373d6546d242db567 Mon Sep 17 00:00:00 2001 From: Henrik Hautakoski Date: Fri, 26 Jun 2026 09:46:08 +0200 Subject: [PATCH] Add BinaryReader::readPaddedString --- src/BinaryReader.php | 9 ++++++++ tests/Unit/BinaryReaderTest.php | 38 +++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/src/BinaryReader.php b/src/BinaryReader.php index fe0399d..a89df23 100644 --- a/src/BinaryReader.php +++ b/src/BinaryReader.php @@ -129,4 +129,13 @@ class BinaryReader return $value >= 0x8000_0000 ? $value - 0x1_0000_0000 : $value; } + + /** + * Reads a string of fixed length, trimming any padding characters from the end. + */ + public function readPaddedString(int $length, string $pad_chars = "\x00") : string + { + $data = $this->read($length); + return rtrim($data, $pad_chars); + } } diff --git a/tests/Unit/BinaryReaderTest.php b/tests/Unit/BinaryReaderTest.php index c1d6424..fa256bb 100644 --- a/tests/Unit/BinaryReaderTest.php +++ b/tests/Unit/BinaryReaderTest.php @@ -82,3 +82,41 @@ it('reads 32 bit integers in little and big endian', function () { ->and($reader->readInt32LE())->toBe(-2147483648) ->and($reader->readInt32BE())->toBe(-1); }); + +it('reads a padded string with no padding present', function () { + $reader = BinaryReader::string('hello'); + + expect($reader->readPaddedString(5))->toBe('hello'); +}); + +it('strips null bytes from the end of a padded string', function () { + $reader = BinaryReader::string("hello\x00\x00\x00"); + + expect($reader->readPaddedString(8))->toBe('hello'); +}); + +it('returns empty string for an all-null padded string', function () { + $reader = BinaryReader::string("\x00\x00\x00"); + + expect($reader->readPaddedString(3))->toBe(''); +}); + +it('advances the cursor by the full field length after readPaddedString', function () { + $reader = BinaryReader::string("hi\x00\x00" . 'end'); + + $reader->readPaddedString(4); + + expect($reader->read(3))->toBe('end'); +}); + +it('throws when not enough bytes remain for readPaddedString', function () { + $reader = BinaryReader::string('ab'); + + expect(fn () => $reader->readPaddedString(5))->toThrow(RuntimeException::class, 'Not enough bytes'); +}); + +it('strips custom padding characters from the end of a padded string', function () { + $reader = BinaryReader::string("hello "); + + expect($reader->readPaddedString(8, ' '))->toBe('hello'); +});