Total Complexity | 5 |
Total Lines | 59 |
Duplicated Lines | 0 % |
Coverage | 100% |
Changes | 0 |
1 | <?php |
||
15 | final class Bits implements Value |
||
16 | { |
||
17 | private $value; |
||
18 | private $original; |
||
19 | |||
20 | 92 | public function __construct(bool $first, bool ...$bits) |
|
21 | { |
||
22 | 92 | array_unshift($bits, $first); |
|
23 | 92 | $value = 0; |
|
24 | 92 | $stream = new Stream('bool'); |
|
25 | |||
26 | 92 | foreach ($bits as $i => $bit) { |
|
27 | 92 | $stream = $stream->add($bit); |
|
28 | 92 | $bit = (int) $bit; |
|
29 | 92 | $value |= $bit << $i; |
|
30 | } |
||
31 | |||
32 | 92 | $this->value = chr($value); |
|
33 | 92 | $this->original = $stream; |
|
34 | 92 | } |
|
35 | |||
36 | 58 | public static function fromStream(Readable $stream): Value |
|
37 | { |
||
38 | 58 | return new self( |
|
39 | ...$stream |
||
40 | 58 | ->read(1) |
|
41 | 58 | ->toEncoding('ASCII') |
|
42 | 58 | ->chunk() |
|
43 | 58 | ->reduce( |
|
44 | 58 | new Seq, |
|
45 | 58 | static function(Seq $bits, Str $bit): Seq { |
|
46 | 58 | return (new Str(decbin(ord((string) $bit)))) |
|
47 | 58 | ->chunk() |
|
48 | 58 | ->reduce( |
|
49 | 58 | $bits, |
|
50 | 58 | static function(Seq $bits, Str $bit): Seq { |
|
51 | 58 | return $bits->add((int) (string) $bit); |
|
52 | 58 | } |
|
53 | ); |
||
54 | 58 | } |
|
55 | ) |
||
56 | 58 | ->map(static function(int $bit): bool { |
|
57 | 58 | return (bool) $bit; |
|
58 | 58 | }) |
|
59 | 58 | ->reverse() |
|
60 | ); |
||
61 | } |
||
62 | |||
63 | /** |
||
64 | * @return StreamInterface<bool> |
||
65 | */ |
||
66 | 44 | public function original(): StreamInterface |
|
67 | { |
||
68 | 44 | return $this->original; |
|
69 | } |
||
70 | |||
71 | 91 | public function __toString(): string |
|
74 | } |
||
75 | } |
||
76 |