Skip to content

Instantly share code, notes, and snippets.

@heri16
Last active Oct 19, 2021
Embed
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: http://www.nasdaqtrader.com/content/technicalsupport/specifications/tradingproducts/ouch4.2.pdf
# See: https://hexdocs.pm/elixir/Kernel.SpecialForms.html#%3C%3C%3E%3E/1-modifiers
# See: https://hexdocs.pm/elixir/Kernel.SpecialForms.html#%3C%3C%3E%3E/1-options
alias Decimal, as: D
symbol = "BTC_IDR"
shares = 5000
price = "1.3"
# Encode
p = D.new(price) |> 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)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment