View Source Sonyflakex.State (Sonyflakex v0.2.0)
Handles internal state data.
Summary
Functions
Creates state tuple used internally by Sonyflakex.
Increments current sequence number and checks for overflow.
Initializes ID generator state.
Converts internal state to integer ID.
Types
@type sonyflake_id() :: non_neg_integer()
ID generated by Sonyflake
@type t() :: {non_neg_integer(), non_neg_integer(), non_neg_integer(), non_neg_integer()}
Represents internal ID generator state used to compute the next ID.
Tuple composed by (in order):
- start_time: Timestamp used as relative starting point relative to elapsed time used in generated IDs.
- elapsed_time: Timestamp in 10 ms unit of how much time has passed since start_time.
- machine_id: Value used to uniquely identify each machine generating IDs.
- sequence: Number incremented for IDs generated in the same 10 ms time window.
Functions
@spec create_state( non_neg_integer(), non_neg_integer(), non_neg_integer(), non_neg_integer() ) :: t()
Creates state tuple used internally by Sonyflakex.
Examples
iex> Sonyflakex.State.create_state(1, 2, 3, 4)
{1, 2, 3, 4}
@spec increment_sequence(t()) :: {:error, :overflow} | {:ok, non_neg_integer()}
Increments current sequence number and checks for overflow.
Returns:
{:ok, new_sequence}
: if the sequence can be incremented its new value is returned as the second element of the response.{:error, :overflow}
: if incrementing the sequence would overflow the 8 bit field then it returns an error response.
Examples
iex> Sonyflakex.State.increment_sequence({1, 1, 1, 41})
{:ok, 42}
iex> Sonyflakex.State.increment_sequence({1, 1, 1, 255})
{:error, :overflow}
Initializes ID generator state.
This method should be used by clients to create the initial state for the ID generator with the following default configuration:
- Start time: '2014-09-01T00:00:00Z' is used when calculating elapsed time for timestamps in state.
- Machine ID: Lower 16 bits of one of the machine's private IP addresses. If you run multiple generators in the same machine this field will be set to the same value and duplicated IDs might be generated.
@spec to_id(t()) :: sonyflake_id()
Converts internal state to integer ID.
Examples
iex> Sonyflakex.State.to_id({1, 2, 3, 4})
33816579