schemator-php
141 строка · 2.9 Кб
1<?php
2
3declare(strict_types=1);
4
5namespace Smoren\Schemator\Structs;
6
7use Smoren\Schemator\Interfaces\BitmapInterface;
8
9class Bitmap implements BitmapInterface
10{
11/**
12* @var int bitmap value
13*/
14protected int $value;
15
16/**
17* {@inheritDoc}
18*/
19public static function create($value): BitmapInterface
20{
21if (is_array($value)) {
22return static::createFromArray($value);
23}
24if ($value instanceof BitmapInterface) {
25return new static($value->getValue());
26}
27return new static($value);
28}
29
30/**
31* {@inheritDoc}
32*/
33public static function createFromArray(array $bits): BitmapInterface
34{
35$value = 0;
36foreach ($bits as $code) {
37$value += 2 ** $code;
38}
39return new static($value);
40}
41
42/**
43* {@inheritDoc}
44*/
45public static function toBitmap($bitmap): BitmapInterface
46{
47return ($bitmap instanceof BitmapInterface) ? $bitmap : static::create($bitmap);
48}
49
50/**
51* Bitmap constructor.
52*
53* @param int $value bitmap value
54*/
55final public function __construct(int $value)
56{
57$this->value = $value;
58}
59
60/**
61* {@inheritDoc}
62*/
63public function getValue(): int
64{
65return $this->value;
66}
67
68/**
69* {@inheritDoc}
70*/
71public function intersectsWith($bitmap): bool
72{
73$bitmap = static::toBitmap($bitmap);
74return ($this->getValue() & $bitmap->getValue()) !== 0;
75}
76
77/**
78* {@inheritDoc}
79*/
80public function includes($bitmap): bool
81{
82$bitmap = static::toBitmap($bitmap);
83return ($this->getValue() & $bitmap->getValue()) === $bitmap->getValue();
84}
85
86/**
87* {@inheritDoc}
88*/
89public function isEqualWith($bitmap): bool
90{
91$bitmap = static::toBitmap($bitmap);
92return $this->getValue() === $bitmap->getValue();
93}
94
95/**
96* {@inheritDoc}
97*/
98public function add($bitmap): BitmapInterface
99{
100$bitmap = static::toBitmap($bitmap);
101return new static($this->getValue() | $bitmap->getValue());
102}
103
104/**
105* {@inheritDoc}
106*/
107public function sub($bitmap): BitmapInterface
108{
109$bitmap = static::toBitmap($bitmap);
110return new static($this->getValue() & (~$bitmap->getValue()));
111}
112
113/**
114* {@inheritDoc}
115*/
116public function hasBit(int $bitPosition): bool
117{
118return $this->intersectsWith(Bitmap::createFromArray([$bitPosition]));
119}
120
121/**
122* {@inheritDoc}
123*/
124public function toArray(): array
125{
126$bitmap = $this->getValue();
127$result = [];
128$i = 0;
129
130while ($bitmap) {
131if ($bitmap % 2) {
132$result[] = $i;
133}
134
135$bitmap = (int)($bitmap / 2);
136++$i;
137}
138
139return $result;
140}
141}
142