summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorJeff McCune <jeff@puppetlabs.com>2012-08-14 08:47:41 -0700
committerJeff McCune <jeff@puppetlabs.com>2012-08-14 08:47:41 -0700
commitf30885118843f2eef15c048fe2cb504d7eaf8f77 (patch)
tree9c65541213d5c30e91d3b7e413efc49bf586363c /lib
parentdeafe88e02499a7bdababf0b5dc264fcc3edecf1 (diff)
parent247b69cbc01741257c3d3b72ad75bb62325eaf49 (diff)
downloadpuppet-stdlib-f30885118843f2eef15c048fe2cb504d7eaf8f77.tar.gz
puppet-stdlib-f30885118843f2eef15c048fe2cb504d7eaf8f77.tar.bz2
Merge branch 'feature/2.4.x/to_bytes_function' into 2.4.x
* feature/2.4.x/to_bytes_function: (#15872) Add to_bytes function
Diffstat (limited to 'lib')
-rw-r--r--lib/puppet/parser/functions/to_bytes.rb28
1 files changed, 28 insertions, 0 deletions
diff --git a/lib/puppet/parser/functions/to_bytes.rb b/lib/puppet/parser/functions/to_bytes.rb
new file mode 100644
index 0000000..8ff73d1
--- /dev/null
+++ b/lib/puppet/parser/functions/to_bytes.rb
@@ -0,0 +1,28 @@
+module Puppet::Parser::Functions
+ newfunction(:to_bytes, :type => :rvalue, :doc => <<-EOS
+ Converts the argument into bytes, for example 4 kB becomes 4096.
+ Takes a single string value as an argument.
+ EOS
+ ) 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 = */([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 'E' then return (value*(1<<50)).to_i
+ else raise Puppet::ParseError, "to_bytes(): Unknown prefix #{prefix}"
+ end
+ end
+end