Skip to content

Instantly share code, notes, and snippets.

@justanotherdot
Created April 10, 2018 04:50
Show Gist options
  • Select an option

  • Save justanotherdot/0d78a088b6f4994415c037baf8c71728 to your computer and use it in GitHub Desktop.

Select an option

Save justanotherdot/0d78a088b6f4994415c037baf8c71728 to your computer and use it in GitHub Desktop.
Minimal uuid4 implementation
defmodule UUID4 do
@moduledoc """
Rough sketch of a uuid4 implementation
"""
@doc false
def uuid4 do
<<u0::48, _::4, u1::12, _::2, u2::62>> = :crypto.strong_rand_bytes(16)
<<u0::48, 4::4, u1::12, 2::2, u2::62>>
end
@doc false
def to_string(<<u0::32, u1::16, u2::16, u3::16, u4::48>>) do
cs = :io_lib.format("~8.16.0b-~4.16.0b-~4.16.0b-~4.16.0b-~12.16.0b", [u0, u1, u2, u3, u4])
{:just, List.to_string(cs)}
end
def to_string(_) do
{:nothing, nil}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment