if Code.ensure_loaded?(Ecto) do defmodule AntlUtils.Ecto.UUID do @prefix_separator "_" @doc """ Convert a uuid to a hashid. ## Examples iex> UUID.to_hashid("00000000-0000-0000-0000-000000000001") "1" iex> UUID.to_hashid("bc205f5c-a98d-473f-b186-b251cd60b23e") "5izLo84gcDU7IdJsOLe1D4" iex> UUID.to_hashid("bc205f5c-a98d-473f-b186-b251cd60b23e", "prefix") "prefix_5izLo84gcDU7IdJsOLe1D4" """ @spec to_hashid(<<_::288>>, nil | binary) :: binary def to_hashid(<<_::288>> = uuid, prefix \\ nil) do hashid = uuid |> String.replace("-", "") |> String.to_integer(16) |> AntlUtils.Elixir.Integer.to_string(62) if prefix, do: "#{prefix}#{@prefix_separator}#{hashid}", else: hashid end @doc """ Convert a hashid to a uuid. ## Examples iex> UUID.to_uuid("5izLo84gcDU7IdJsOLe1D4") "bc205f5c-a98d-473f-b186-b251cd60b23e" iex> UUID.to_uuid("prefix_5izLo84gcDU7IdJsOLe1D4") "bc205f5c-a98d-473f-b186-b251cd60b23e" """ @spec to_uuid(binary) :: <<_::288>> def to_uuid(hashid) when is_binary(hashid) do hashid = hashid |> String.split(@prefix_separator) |> List.last() << part1::binary-size(8), part2::binary-size(4), part3::binary-size(4), part4::binary-size(4), part5::binary-size(12) >> = hashid |> AntlUtils.Elixir.String.to_integer(62) |> Integer.to_string(16) |> String.pad_leading(32, ["0"]) |> String.downcase() Ecto.UUID.cast!("#{part1}-#{part2}-#{part3}-#{part4}-#{part5}") end end end