Created
February 22, 2021 18:54
-
-
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.
This file contains 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 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