lib/ipaddress/prefix.rb in ipaddress-0.6.0 vs lib/ipaddress/prefix.rb in ipaddress-0.7.0

- old
+ new

@@ -81,34 +81,49 @@ end # class Prefix class Prefix32 < Prefix + IN4MASK = 0xffffffff + # # Creates a new prefix object for 32 bits IPv4 addresses # # prefix = IPAddress::Prefix32.new 24 # #=> 24 # def initialize(num) unless (1..32).include? num - raise ArgumentError, "Prefix must be in range 1..128, got: #{num}" + raise ArgumentError, "Prefix must be in range 1..32, got: #{num}" end super(num) end # + # Returns the length of the host portion + # of a netmask. + # + # prefix = Prefix32.new 24 + # + # prefix.host_prefix + # #=> 8 + # + def host_prefix + 32 - @prefix + end + + # # Transforms the prefix into a string of bits # representing the netmask # # prefix = IPAddress::Prefix32.new 24 # # prefix.bits # #=> "11111111111111111111111100000000" # def bits - "1" * @prefix + "0" * (32 - @prefix) + to_u32.to_s(2) end # # Gives the prefix in IPv4 dotted decimal format, # i.e. the canonical netmask we're all used to @@ -143,11 +158,11 @@ # # prefix.to_u32 # #=> 4294967040 # def to_u32 - [bits].pack("B*").unpack("N").first + (IN4MASK >> host_prefix) << host_prefix end # # Shortcut for the octecs in the dotted decimal # representation @@ -183,11 +198,11 @@ # #=> 24 # def self.parse_netmask(netmask) octets = netmask.split(".").map{|i| i.to_i} num = octets.pack("C"*octets.size).unpack("B*").first.count "1" - return IPAddress::Prefix.new(num) + return self.new(num) end end # class Prefix32 < Prefix class Prefix128 < Prefix @@ -227,10 +242,10 @@ # # prefix.to_u128 # #=> 340282366920938463444927863358058659840 # def to_u128 - eval "0b#{bits}.to_i" + bits.to_i(2) end end # class Prefix123 < Prefix end # module IPAddress