about summary refs log tree commit diff
path: root/app/lib/fast_ip_map.rb
diff options
context:
space:
mode:
authorStarfall <us@starfall.systems>2020-10-30 09:55:47 -0500
committerStarfall <us@starfall.systems>2020-10-30 09:55:47 -0500
commit259470ec37dfc5c3d34ed5456adcd3ab1a622a18 (patch)
tree0ed8e47864234419df1133ed7cbac481ea8e12dc /app/lib/fast_ip_map.rb
parentab2148ef84c2880465599bd8c80e15378cf0a517 (diff)
parent5a41704f8926d9594c66028ca30dc1fc0f98da3d (diff)
Merge branch 'glitch' into main
Diffstat (limited to 'app/lib/fast_ip_map.rb')
-rw-r--r--app/lib/fast_ip_map.rb32
1 files changed, 32 insertions, 0 deletions
diff --git a/app/lib/fast_ip_map.rb b/app/lib/fast_ip_map.rb
new file mode 100644
index 000000000..ba30b45f3
--- /dev/null
+++ b/app/lib/fast_ip_map.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+class FastIpMap
+  MAX_IPV4_PREFIX = 32
+  MAX_IPV6_PREFIX = 128
+
+  # @param [Enumerable<IPAddr>] addresses
+  def initialize(addresses)
+    @fast_lookup = {}
+    @ranges      = []
+
+    # Hash look-up is faster but only works for exact matches, so we split
+    # exact addresses from non-exact ones
+    addresses.each do |address|
+      if (address.ipv4? && address.prefix == MAX_IPV4_PREFIX) || (address.ipv6? && address.prefix == MAX_IPV6_PREFIX)
+        @fast_lookup[address.to_s] = true
+      else
+        @ranges << address
+      end
+    end
+
+    # We're more likely to hit wider-reaching ranges when checking for
+    # inclusion, so make sure they're sorted first
+    @ranges.sort_by!(&:prefix)
+  end
+
+  # @param [IPAddr] address
+  # @return [Boolean]
+  def include?(address)
+    @fast_lookup[address.to_s] || @ranges.any? { |cidr| cidr.include?(address) }
+  end
+end