Module: Ifconf::Parsers::MaskConverter

Defined in:
lib/ifconf/parsers/mask_converter.rb

Overview

Pure-function utilities for converting between dotted-decimal, hex, and CIDR prefix subnet masks.

Class Method Summary collapse

Class Method Details

.dotted_to_prefix(mask) ⇒ Object



11
12
13
14
15
# File 'lib/ifconf/parsers/mask_converter.rb', line 11

def dotted_to_prefix(mask)
  octets = mask.split(".").map(&:to_i)
  bits = octets.map { |o| o.to_s(2).rjust(8, "0") }.join
  bits.count("1")
end

.hex_to_dotted(hex) ⇒ Object



27
28
29
# File 'lib/ifconf/parsers/mask_converter.rb', line 27

def hex_to_dotted(hex)
  prefix_to_dotted(hex_to_prefix(hex))
end

.hex_to_prefix(hex) ⇒ Object



22
23
24
25
# File 'lib/ifconf/parsers/mask_converter.rb', line 22

def hex_to_prefix(hex)
  int_val = Integer(hex)
  int_val.to_s(2).count("1")
end

.prefix_to_dotted(prefix) ⇒ Object



17
18
19
20
# File 'lib/ifconf/parsers/mask_converter.rb', line 17

def prefix_to_dotted(prefix)
  bits = ("1" * prefix).ljust(32, "0")
  bits.scan(/.{8}/).map { |b| b.to_i(2) }.join(".")
end

.prefix_to_hex(prefix) ⇒ Object



31
32
33
34
# File 'lib/ifconf/parsers/mask_converter.rb', line 31

def prefix_to_hex(prefix)
  mask_int = prefix.zero? ? 0 : ((0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF)
  format("0x%08x", mask_int)
end

.to_prefix(mask) ⇒ Object



7
8
9
# File 'lib/ifconf/parsers/mask_converter.rb', line 7

def to_prefix(mask)
  mask.start_with?("0x") ? hex_to_prefix(mask) : dotted_to_prefix(mask)
end

.valid_mask?(mask) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
48
49
50
51
52
53
54
55
# File 'lib/ifconf/parsers/mask_converter.rb', line 45

def valid_mask?(mask)
  octets = mask.split(".")
  return false unless octets.length == 4

  int_vals = octets.map(&:to_i)
  return false if int_vals.any? { |o| o.negative? || o > 255 }

  bits = int_vals.map { |o| o.to_s(2).rjust(8, "0") }.join
  # Must be contiguous 1s followed by 0s
  bits.match?(/\A1*0*\z/)
end

.wildcard(prefix) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/ifconf/parsers/mask_converter.rb', line 36

def wildcard(prefix)
  mask_int = prefix.zero? ? 0 : ((0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF)
  wildcard_int = mask_int ^ 0xFFFFFFFF
  [(wildcard_int >> 24) & 0xFF,
   (wildcard_int >> 16) & 0xFF,
   (wildcard_int >> 8) & 0xFF,
   wildcard_int & 0xFF].join(".")
end