diff options
author | Taketo Takashima <[email protected]> | 2024-08-07 19:18:31 +0900 |
---|---|---|
committer | git <[email protected]> | 2025-04-26 11:56:42 +0000 |
commit | 687bd837244309fa293d6e08d0e13a662fce3a83 (patch) | |
tree | 0939e42e9f23f4061f8167e9fdb42df326a3c434 | |
parent | c0417bd094abcc68be913ce49a430df7cefbcd44 (diff) |
[ruby/ipaddr] Added IPAddr#+/-
https://github.com/ruby/ipaddr/commit/78b4f53bf5
-rw-r--r-- | lib/ipaddr.rb | 10 | ||||
-rw-r--r-- | test/test_ipaddr.rb | 40 |
2 files changed, 50 insertions, 0 deletions
diff --git a/lib/ipaddr.rb b/lib/ipaddr.rb index a45055496c..525466bbd9 100644 --- a/lib/ipaddr.rb +++ b/lib/ipaddr.rb @@ -151,6 +151,16 @@ class IPAddr return self.clone.set(addr_mask(~@addr)) end + # Returns a new ipaddr greater than the original address by offset + def +(offset) + self.clone.set(@addr + offset, @family) + end + + # Returns a new ipaddr less than the original address by offset + def -(offset) + self.clone.set(@addr - offset, @family) + end + # Returns true if two ipaddrs are equal. def ==(other) other = coerce_other(other) diff --git a/test/test_ipaddr.rb b/test/test_ipaddr.rb index f2b7ed713f..7ecd37e9a4 100644 --- a/test/test_ipaddr.rb +++ b/test/test_ipaddr.rb @@ -399,6 +399,46 @@ class TC_Operator < Test::Unit::TestCase assert_equal("::", @in6_addr_any.to_s) end + def test_plus + a = IPAddr.new("192.168.1.10") + assert_equal("192.168.1.20", (a + 10).to_s) + + a = IPAddr.new("0.0.0.0") + assert_equal("0.0.0.10", (a + 10).to_s) + + a = IPAddr.new("255.255.255.255") + assert_raise(IPAddr::InvalidAddressError) { a + 10 } + + a = IPAddr.new("3ffe:505:2::a") + assert_equal("3ffe:505:2::14", (a + 10).to_s) + + a = IPAddr.new("::") + assert_equal("::a", (a + 10).to_s) + + a = IPAddr.new("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff") + assert_raise(IPAddr::InvalidAddressError) { a + 10 } + end + + def test_minus + a = IPAddr.new("192.168.1.10") + assert_equal("192.168.1.0", (a - 10).to_s) + + a = IPAddr.new("0.0.0.0") + assert_raise(IPAddr::InvalidAddressError) { a - 10 } + + a = IPAddr.new("255.255.255.255") + assert_equal("255.255.255.245", (a - 10).to_s) + + a = IPAddr.new("3ffe:505:2::a") + assert_equal("3ffe:505:2::", (a - 10).to_s) + + a = IPAddr.new("::") + assert_raise(IPAddr::InvalidAddressError) { a - 10 } + + a = IPAddr.new("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff") + assert_equal("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff5", (a - 10).to_s) + end + def test_equal assert_equal(true, @a == IPAddr.new("3FFE:505:2::")) assert_equal(true, @a == IPAddr.new("3ffe:0505:0002::")) |