Created
April 17, 2019 18:26
-
-
Save mbklein/e87e11e3a31344b7bcc548a478918283 to your computer and use it in GitHub Desktop.
Extracting timestamp and randomness from ULID (using Ecto.ULID)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule ULID.Data do | |
defstruct time: nil, random: nil | |
def from_binary(<<time::integer-size(48), random::binary-size(10)>>) do | |
time | |
|> DateTime.from_unix(:millisecond) | |
|> parse(random) | |
end | |
def from_string(ulid) do | |
ulid | |
|> Ecto.ULID.dump() | |
|> parse | |
end | |
defp parse(%NaiveDateTime{} = time, random) do | |
{:ok, %__MODULE__{time: time, random: random}} | |
end | |
defp parse({:ok, %DateTime{} = time}, random) do | |
time | |
|> DateTime.to_naive() | |
|> parse(random) | |
end | |
defp parse({:ok, <<data::binary-size(16)>>}) do | |
from_binary(data) | |
end | |
defp parse(:error), do: {:error, :invalid_ulid} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment