summaryrefslogtreecommitdiff
path: root/src/Structure.php
blob: 307397ddca2972576377d051ca1f66d033aa13c5 (plain)
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
<?php

declare(strict_types=1);

namespace Zhineng\Snowflake;

final class Structure
{
    /**
     * The ID components.
     *
     * @var \Zhineng\Snowflake\Component[]
     */
    private array $fields = [];

    /**
     * The current bit offset.
     */
    private int $currentOffset = 0;

    /**
     * The number of sequence fields added.
     */
    private int $sequenceCount = 0;

    /**
     * Add a field to the structure.
     */
    public function add(Component $field): self
    {
        if ($field instanceof Sequence && ++$this->sequenceCount > 1) {
            throw new \LogicException('Only one sequence field is allowed in a structure.');
        }

        if ($this->currentOffset + $field->bits() > 63) {
            throw new \OverflowException('Total structure size cannot exceed 63 bits.');
        }

        $this->fields[] = $field->setOffset($this->currentOffset);
        $this->currentOffset += $field->bits();

        return $this;
    }

    /**
     * The ID components.
     *
     * @return \Zhineng\Snowflake\Component[]
     */
    public function components(): array
    {
        return $this->fields;
    }

    /**
     * The total size in bits.
     */
    public function size(): int
    {
        return $this->currentOffset;
    }
}