Update stdlib and concat to 6.1.0 both
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / to_bytes.rb
1 #
2 # to_bytes.rb
3 #
4 module Puppet::Parser::Functions
5   newfunction(:to_bytes, :type => :rvalue, :doc => <<-DOC
6     @summary
7         Converts the argument into bytes, for example 4 kB becomes 4096.
8
9     @return
10       converted value into bytes
11
12     Takes a single string value as an argument.
13     These conversions reflect a layperson's understanding of
14     1 MB = 1024 KB, when in fact 1 MB = 1000 KB, and 1 MiB = 1024 KiB.
15     DOC
16              ) do |arguments|
17
18     raise(Puppet::ParseError, "to_bytes(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1
19
20     arg = arguments[0]
21
22     return arg if arg.is_a? Numeric
23
24     value, prefix = *%r{([0-9.e+-]*)\s*([^bB]?)}.match(arg)[1, 2]
25
26     value = value.to_f
27     case prefix
28     when '' then return value.to_i
29     when 'k' then return (value * (1 << 10)).to_i
30     when 'M' then return (value * (1 << 20)).to_i
31     when 'G' then return (value * (1 << 30)).to_i
32     when 'T' then return (value * (1 << 40)).to_i
33     when 'P' then return (value * (1 << 50)).to_i
34     when 'E' then return (value * (1 << 60)).to_i
35     else raise Puppet::ParseError, "to_bytes(): Unknown prefix #{prefix}"
36     end
37   end
38 end