Skip to content

Instantly share code, notes, and snippets.

@alecho
Created February 22, 2021 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alecho/a168b724b778d9d70b024c2a51629dec to your computer and use it in GitHub Desktop.
Save alecho/a168b724b778d9d70b024c2a51629dec to your computer and use it in GitHub Desktop.
Store and retrieve a json object as a map with interlay and some binary values.
defmodule CoseKey do
use Ecto.Type
def type, do: :map
# Case the COSE Key x and y coordinates to base 64 encoded binaries.
def cast(%{-2 => x_coord, -3 => y_coord} = map) do
{:ok,
map
|> Map.put(-2, Base.encode64(x_coord))
|> Map.put(-3, Base.encode64(y_coord))}
end
# Maps without a -2 and -3 key fail
def cast(_), do: :error
# JSON would like the inegers to be string but we need both positive and
# negative integers. Also, Decode the coordinates back to regular binaries.
def load(map) when is_map(map) do
{:ok,
map
|> Enum.map(&key_to_int_and_maybe_decode_value/1)
|> Enum.into(%{})}
end
defp key_to_int_and_maybe_decode_value({k, v}) when k in ["-2", "-3"] do
{parse_int(k), Base.decode64!(v, padding: false)}
end
defp key_to_int_and_maybe_decode_value({k, v}), do: {parse_int(k), v}
defp parse_int(binary) do
{int, _} = Integer.parse(binary)
int
end
def dump(map) when is_map(map), do: {:ok, map}
def dump(_), do: :error
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment