Packages

Efficient Gleam representation for IP addresses

Current section

Files

Jump to
glip src glip_ffi.erl
Raw

src/glip_ffi.erl

-module(glip_ffi).
% Enable inlining, as all the functions are very small.
-compile(inline).
-export([to_string/1, parse_ip/1, parse_ip_preserving_string/1, address_family/1,
to_external_ip/1, enrich/1]).
parse_ip(String) ->
Charlist = unicode:characters_to_list(String),
case inet:parse_strict_address(Charlist) of
{ok, Ip} ->
{ok, Ip};
_ ->
{error, nil}
end.
parse_ip_preserving_string(String) ->
case parse_ip(String) of
{ok, Ip} ->
{ok, {ip_with_string, Ip, String}};
Error ->
Error
end.
to_external_ip(Address) ->
case ip of
{ip_with_string, Ip, _} ->
Ip;
_ ->
Address
end.
address_family(Address) ->
case to_external_ip(Address) of
{_, _, _, _} ->
ipv4;
{_, _, _, _, _, _, _, _} ->
ipv6
end.
to_string(Address) ->
case Address of
{ip_with_string, _, String} ->
String;
Ip ->
ip_to_string(Ip)
end.
enrich(Address) ->
case Address of
{ip_with_string, _, String} ->
String;
Ip ->
ip_to_string(Ip)
end.
ip_to_string(Ip) ->
String = inet:ntoa(Ip),
unicode:characters_to_binary(String).