Skip to content

Commit

Permalink
Add bytesTerminateMulti() and readBytesTermMulti()
Browse files Browse the repository at this point in the history
  • Loading branch information
generalmimon committed Jul 31, 2024
1 parent c0b39b0 commit 78f00d9
Showing 1 changed file with 53 additions and 2 deletions.
55 changes: 53 additions & 2 deletions lib/Kaitai/Struct/Stream.php
Original file line number Diff line number Diff line change
Expand Up @@ -304,8 +304,8 @@ private static function getMaskOnes(int $n): int {

public function readBytes(int $numberOfBytes): string {
// It is legitimate to ask for 0 bytes in Kaitai Struct API,
// but PHP's fread() considers this an error, so check &
// handle this case before fread()
// but PHP's fread() considers this an error, so check and
// handle this case before calling fread()
if ($numberOfBytes == 0) {
return '';
}
Expand Down Expand Up @@ -348,6 +348,42 @@ public function readBytesTerm($term, bool $includeTerm, bool $consumeTerm, bool
return $r;
}

public function readBytesTermMulti(string $term, bool $includeTerm, bool $consumeTerm, bool $eosError): string {
$unitSize = strlen($term);

// PHP's fread() considers asking for 0 bytes an error, so check and
// handle this case before calling fread()
if ($unitSize === 0) {
return '';
}

$r = '';
while (true) {
$c = fread($this->stream, $unitSize);
if ($c === false) {
$c = '';
}
if (strlen($c) < $unitSize) {
if ($eosError) {
throw new NoTerminatorFoundError($term);
}
$r .= $c;
break;
}
if ($c === $term) {
if ($includeTerm) {
$r .= $c;
}
if (!$consumeTerm) {
$this->seek($this->pos() - $unitSize);
}
break;
}
$r .= $c;
}
return $r;
}

/**
* @deprecated Unused since Kaitai Struct Compiler v0.9+ - compatibility with older versions
*/
Expand Down Expand Up @@ -382,6 +418,21 @@ public static function bytesTerminate(string $bytes, $term, bool $includeTerm):
}
}

public static function bytesTerminateMulti(string $bytes, string $term, bool $includeTerm): string {
$unitSize = strlen($term);
$searchIndex = strpos($bytes, $term);
while (true) {
if ($searchIndex === false) {
return $bytes;
}
$mod = $searchIndex % $unitSize;
if ($mod === 0) {
return substr($bytes, 0, $searchIndex + ($includeTerm ? $unitSize : 0));
}
$searchIndex = strpos($bytes, $term, $searchIndex + ($unitSize - $mod));
}
}

public static function bytesToStr(string $bytes, string $encoding): string {
return iconv($encoding, 'utf-8', $bytes);
}
Expand Down

0 comments on commit 78f00d9

Please sign in to comment.