Skip to content

Instantly share code, notes, and snippets.

Last active Oct 19, 2021
What would you like to do?
Binary encoding of OUCH messages in Elixir

Reuse logic in Elixir

Here are commons ways to reuse logic in Elixir:

1a. Move Function to other module (guards, pattern-matching) 1b. Protocol - Polymorphism

  1. Behaviour Dynamic-func - with def method_name(implemetation, args)
# See:
# See:
# See:
alias Decimal, as: D
symbol = "BTC_IDR"
shares = 5000
price = "1.3"
# Encode
p = |> D.round(4) |> D.mult(10000) |> D.to_integer()
message = <<shares::big-integer-4*8, String.pad_trailing(symbol, 8)::binary-8, p::big-integer-32>>
# Decode
<<shares2::big-integer-size(4)-unit(8), symbol2::binary-8, p2::big-integer-32>> = message
{:ok, p2} = D.cast(p2)
price2 = p2 |> D.div(10000) |> D.to_string()
{shares2, symbol2, price2}
# Pattern-match
<<coinSymbol::binary-size(s), "_IDR" >> = symbol2
defprotocol Ouch42Binary do
@doc "Serialize "
def marshal?(struct)
def unmarshal?(binary)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment