File: to_bytes.rb

package info (click to toggle)
puppet-module-puppetlabs-stdlib 9.4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,448 kB
  • sloc: ruby: 3,522; sh: 46; makefile: 2
file content (39 lines) | stat: -rw-r--r-- 1,193 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# frozen_string_literal: true

#
# to_bytes.rb
#
module Puppet::Parser::Functions
  newfunction(:to_bytes, type: :rvalue, doc: <<-DOC
    @summary
        Converts the argument into bytes, for example 4 kB becomes 4096.

    @return
      converted value into bytes

    Takes a single string value as an argument.
    These conversions reflect a layperson's understanding of
    1 MB = 1024 KB, when in fact 1 MB = 1000 KB, and 1 MiB = 1024 KiB.
  DOC
  ) do |arguments|
    raise(Puppet::ParseError, "to_bytes(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1

    arg = arguments[0]

    return arg if arg.is_a? Numeric

    value, prefix = *%r{([0-9.e+-]*)\s*([^bB]?)}.match(arg)[1, 2]

    value = value.to_f
    case prefix
    when '' then return value.to_i
    when 'k' then return (value * (1 << 10)).to_i
    when 'M' then return (value * (1 << 20)).to_i
    when 'G' then return (value * (1 << 30)).to_i
    when 'T' then return (value * (1 << 40)).to_i
    when 'P' then return (value * (1 << 50)).to_i
    when 'E' then return (value * (1 << 60)).to_i
    else raise Puppet::ParseError, "to_bytes(): Unknown prefix #{prefix}"
    end
  end
end