Created
July 11, 2021 02:01
-
-
Save cbaggers/0bce6c3d08c7a5d9441210af507afe1e to your computer and use it in GitHub Desktop.
epgsql user defined type codec
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
%% I do not know if this is the right way to do this, but I didn't find an example | |
%% of how to do it properly :) | |
-module(epgsql_codec_emote_slot_override_v0). | |
-behaviour(epgsql_codec). | |
-include_lib("vanguard/include/ale.hrl"). | |
-export([init/2, names/0, encode/3, decode/3, decode_text/3]). | |
-export_type([data/0]). | |
-type data() :: emote_slot_override_tuple(). | |
-type emote_slot_override_tuple() :: {string(), integer()}. | |
-define(COLUMN_COUNT, 2). | |
-define(UUID_BYTESIZE, 16). | |
-define(INT2_BYTESIZE, 2). | |
init(_Opts, PgSock) -> | |
Codec = epgsql_sock:get_codec(PgSock), | |
UuidOid = epgsql_binary:type_to_oid(uuid, Codec), | |
Int2Oid = epgsql_binary:type_to_oid(int2, Codec), | |
Pair = {UuidOid, Int2Oid}, | |
Pair. | |
names() -> [emote_slot_override_v0]. | |
encode({IdStr, SlotIndex}, emote_slot_override_v0, State) when is_list(IdStr) -> | |
encode({list_to_binary(IdStr), SlotIndex}, emote_slot_override_v0, State); | |
encode({IdStr, SlotIndex}, emote_slot_override_v0, State) when is_binary(IdStr) -> | |
{UuidOid, Int2Oid} = State, | |
Hex = binary:replace(IdStr, <<"-">>, <<>>, [global]), | |
Int = erlang:binary_to_integer(Hex, 16), | |
<<?COLUMN_COUNT:32/big-signed-integer, | |
UuidOid:32/big-signed-integer, | |
?UUID_BYTESIZE:32/big-signed-integer, | |
Int:128/big-unsigned-integer, | |
Int2Oid:32/big-signed-integer, | |
?INT2_BYTESIZE:32/big-signed-integer, | |
SlotIndex:16/big-signed-integer>>. | |
decode(<<?COLUMN_COUNT:32/big-signed-integer, | |
UuidTypeId:32/big-signed-integer, | |
?UUID_BYTESIZE:32/big-signed-integer, | |
U0:32, U1:16, U2:16, U3:16, U4:48, | |
Int2TypeId:32/big-signed-integer, | |
?INT2_BYTESIZE:32/big-signed-integer, | |
SlotIndex:16/big-signed-integer>>, | |
emote_slot_override_v0, | |
State) -> | |
{UuidTypeId, Int2TypeId} = State, %% Checking the type ids are correct | |
Format = "~8.16.0b-~4.16.0b-~4.16.0b-~4.16.0b-~12.16.0b", | |
Id = iolist_to_binary(io_lib:format(Format, [U0, U1, U2, U3, U4])), | |
{Id, SlotIndex}. | |
decode_text(V, _, _) -> V. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment