Hey all,
I recently needed to get a port()
from a string representation of it for…reasons. I discovered a handy little function in OTP 20.0 called list_to_port but quickly found out that ONLY works in 20.0+.
I mashed together an elixir version of term_to_port() from recon which I thought might be useful to others (not sure if this is even a common problem, common enough to be added to OTP I suppose):
def term_to_port(<<"#Port<0.", id :: binary>> ) do
n = id |> String.trim_trailing(">") |> String.to_integer()
term_to_port(n)
end
def term_to_port(n) when is_integer(n) do
name = Node.self() |> Atom.to_charlist() |> :erlang.iolist_to_binary()
length = :erlang.iolist_size(name)
self = :erlang.term_to_binary(self())
vsn = :binary.last(self)
<<131, 102, 100,
length :: size(2)-unit(8),
name :: size(length)-binary,
n :: size(4)-unit(8),
vsn :: size(8)>>
|> :erlang.binary_to_term
end
It’s very rough around the edges but useful nonetheless.