-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Byter.php
75 lines (66 loc) · 1.84 KB
/
Byter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
declare(strict_types=1);
namespace PetrKnap\Binary;
use PetrKnap\Shorts\HasRequirements;
use RuntimeException;
class Byter
{
use HasRequirements;
private const ENCODING = '8bit';
public function __construct()
{
self::checkRequirements(
functions: [
'mb_strcut',
'mb_strlen',
],
);
}
/**
* @param int $size1 size of bite in bytes; if negative, bites from the end
*
* @return array<string> bites of specified sizes; and remains, if any
*
* @throws Exception\CouldNotBiteData
*/
public function bite(string $data, int $size1, int ...$sizeN): array
{
$remains = $data;
$bites = [];
foreach ([$size1, ...$sizeN] as $size) {
if (abs($size) > $this->size($remains)) {
throw new Exception\CouldNotBiteData(__METHOD__, $data, new RuntimeException(
'Remains are smaller than bite',
));
}
$bite = mb_strcut($remains, 0, $size, encoding: self::ENCODING);
$remains = mb_strcut($remains, $size, encoding: self::ENCODING);
if ($size < 0) {
$bites[] = $remains;
$remains = $bite;
} else {
$bites[] = $bite;
}
}
if ($remains !== '') {
$bites[] = $remains;
}
return $bites;
}
/**
* Backward version of {@see self::bite()}
*
* @link https://en.wikipedia.org/wiki/Backwards_(Red_Dwarf)
*/
public function unbite(string $bite1, string ...$biteN): string
{
return implode([$bite1, ...$biteN]);
}
/**
* @return int size in bytes
*/
public function size(string $data): int
{
return mb_strlen($data, encoding: self::ENCODING);
}
}