diff options
Diffstat (limited to 'src/Structure.php')
| -rw-r--r-- | src/Structure.php | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/src/Structure.php b/src/Structure.php new file mode 100644 index 0000000..307397d --- /dev/null +++ b/src/Structure.php @@ -0,0 +1,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; + } +} |
