summaryrefslogtreecommitdiff
path: root/src/Structure.php
diff options
context:
space:
mode:
authorZhineng Li <[email protected]>2026-01-05 16:26:11 +0800
committerZhineng Li <[email protected]>2026-01-05 16:26:11 +0800
commita49763dd739c3c68c4a8322896d594e926ac8e6b (patch)
treeab96cf55ccf828ec3c61d7cf5c440cc8fe837a9b /src/Structure.php
first commit
Diffstat (limited to 'src/Structure.php')
-rw-r--r--src/Structure.php62
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;
+ }
+}