Packages

Efficient Gleam representation for IP addresses

Current section

Files

Jump to
glip src glip_ffi.mjs
Raw

src/glip_ffi.mjs

import net from "node:net";
import { Result$Ok, Result$Error } from "./gleam.mjs";
import { AddressFamily$Ipv4, AddressFamily$Ipv6 } from "./glip.mjs";
export function parse_ip(address) {
switch (net.isIP(address)) {
case 4:
return Result$Ok({ family: AddressFamily$Ipv4(), address });
case 6:
return Result$Ok({ family: AddressFamily$Ipv6(), address });
default:
return Result$Error(undefined);
}
}
export function to_string(ip) {
return typeof ip == "string" ? ip : ip.address;
}
export function address_family(ip) {
if (typeof ip == "string") {
switch (net.isIP(ip)) {
case 4:
return AddressFamily$Ipv4();
case 6:
return AddressFamily$Ipv6();
default:
throw new RangeError("Not a valid IP, this should not be reached!");
}
} else {
return ip.family;
}
}
export function enrich(ip) {
return ip instanceof String ? parse_ip(ip) : ip;
}
export function identity(val) {
return val;
}