# HG changeset patch
# User Matthew Wild <mwild1@gmail.com>
# Date 1678818298 0
# Node ID 9bb044705ea1709cccb3cdc565f86af2a1044460
# Parent  bbae3acc669432890000a5a40c759a3c557f860a
util.ip: Add ip.truncate() to return a new IP with only the prefix of another

diff -r bbae3acc6694 -r 9bb044705ea1 util/ip.lua
--- a/util/ip.lua	Tue Mar 14 18:23:33 2023 +0000
+++ b/util/ip.lua	Tue Mar 14 18:24:58 2023 +0000
@@ -245,10 +245,22 @@
 	return getmetatable(obj) == ip_mt;
 end
 
+local function truncate(ip, n_bits)
+	if n_bits % 8 ~= 0 then
+		return error("ip.truncate() only supports multiples of 8 bits");
+	end
+	local n_octets = n_bits / 8;
+	if not is_ip(ip) then
+		ip = new_ip(ip);
+	end
+	return new_ip(net.ntop(ip.packed:sub(1, n_octets)..("\0"):rep(#ip.packed-n_octets)))
+end
+
 return {
 	new_ip = new_ip,
 	commonPrefixLength = commonPrefixLength,
 	parse_cidr = parse_cidr,
 	match = match,
 	is_ip = is_ip;
+	truncate = truncate;
 };