Class: Vagrant::Util::Numeric

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant/util/numeric.rb

Constant Summary collapse

KILOBYTE =

Authors Note: This conversion has been borrowed from the ActiveSupport Numeric class Conversion helper constants

1024
MEGABYTE =
KILOBYTE * 1024
GIGABYTE =
MEGABYTE * 1024
TERABYTE =
GIGABYTE * 1024
PETABYTE =
TERABYTE * 1024
EXABYTE =
PETABYTE * 1024
BYTES_CONVERSION_MAP =
{KB: KILOBYTE, MB: MEGABYTE, GB: GIGABYTE, TB: TERABYTE,
PB: PETABYTE, EB: EXABYTE}
SHORTHAND_MATCH_REGEX =

Regex borrowed from the vagrant-disksize config class

/^(?<number>[0-9]+)\s?(?<unit>KB|MB|GB|TB)?$/
LOGGER =
Log4r::Logger.new("vagrant::util::numeric")

Class Method Summary collapse

Class Method Details

.bytes_to_megabytes(bytes) ⇒ Integer

Rounds actual value to two decimal places

Parameters:

  • bytes (Integer)

Returns:

  • (Integer)

    megabytes - bytes representation in megabytes



56
57
58
# File 'lib/vagrant/util/numeric.rb', line 56

def bytes_to_megabytes(bytes)
  (bytes / MEGABYTE.to_f).round(2)
end

.reset!Object

Reset the cached values for platform. This is not considered a public API and should only be used for testing.



63
64
65
# File 'lib/vagrant/util/numeric.rb', line 63

def reset!
  instance_variables.each(&method(:remove_instance_variable))
end

.string_to_bytes(str) ⇒ Integer?

A helper that converts a shortcut string to its bytes representation. The expected format of str is essentially: "XX" Where XX is shorthand for KB, MB, GB, TB, PB, or EB. For example, 50 megabytes:

str = "50MB"

Parameters:

  • - (String)

    str

Returns:

  • (Integer, nil)
    • bytes - returns nil if method fails to convert to bytes


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/vagrant/util/numeric.rb', line 33

def string_to_bytes(str)
  bytes = nil

  str = str.to_s.strip
  matches = SHORTHAND_MATCH_REGEX.match(str)
  if matches
    number = matches[:number].to_i
    unit = matches[:unit].to_sym

    if BYTES_CONVERSION_MAP.key?(unit)
      bytes = number * BYTES_CONVERSION_MAP[unit]
    else
      LOGGER.error("An invalid unit or format was given, string_to_bytes cannot convert #{str}")
    end
  end

  bytes
end