summaryrefslogtreecommitdiff
path: root/lib/puppet/parser/functions
diff options
context:
space:
mode:
authorfhats <fhats@yelp.com>2015-08-27 10:40:20 +0100
committerDavid Schmitt <david.schmitt@puppetlabs.com>2015-08-27 10:42:13 +0100
commit2d4f5aa4d943e27ffeae524469f9c6eb18ce64d8 (patch)
treefca31ecf05fee935edd06ea1b2e8ed8aaa24fa84 /lib/puppet/parser/functions
parent1bed010dbbd4590b3299c81b0e962e76b8ffa845 (diff)
downloadpuppet-stdlib-2d4f5aa4d943e27ffeae524469f9c6eb18ce64d8.tar.gz
puppet-stdlib-2d4f5aa4d943e27ffeae524469f9c6eb18ce64d8.tar.bz2
Adds a convert_base function, which can convert numbers between bases
Squashed, improved docs, updated error handling and unit tests by David S.
Diffstat (limited to 'lib/puppet/parser/functions')
-rw-r--r--lib/puppet/parser/functions/convert_base.rb35
1 files changed, 35 insertions, 0 deletions
diff --git a/lib/puppet/parser/functions/convert_base.rb b/lib/puppet/parser/functions/convert_base.rb
new file mode 100644
index 0000000..0fcbafe
--- /dev/null
+++ b/lib/puppet/parser/functions/convert_base.rb
@@ -0,0 +1,35 @@
+module Puppet::Parser::Functions
+
+ newfunction(:convert_base, :type => :rvalue, :arity => 2, :doc => <<-'ENDHEREDOC') do |args|
+
+ Converts a given integer or base 10 string representing an integer to a specified base, as a string.
+
+ Usage:
+
+ $binary_repr = convert_base(5, 2) # $binary_repr is now set to "101"
+ $hex_repr = convert_base("254", "16") # $hex_repr is now set to "fe"
+
+ ENDHEREDOC
+
+ raise Puppet::ParseError, ("convert_base(): First argument must be either a string or an integer") unless (args[0].is_a?(Integer) or args[0].is_a?(String))
+ raise Puppet::ParseError, ("convert_base(): Second argument must be either a string or an integer") unless (args[1].is_a?(Integer) or args[1].is_a?(String))
+
+ if args[0].is_a?(String)
+ raise Puppet::ParseError, ("convert_base(): First argument must be an integer or a string corresponding to an integer in base 10") unless args[0] =~ /^[0-9]+$/
+ end
+
+ if args[1].is_a?(String)
+ raise Puppet::ParseError, ("convert_base(): First argument must be an integer or a string corresponding to an integer in base 10") unless args[1] =~ /^[0-9]+$/
+ end
+
+ number_to_convert = args[0]
+ new_base = args[1]
+
+ number_to_convert = number_to_convert.to_i()
+ new_base = new_base.to_i()
+
+ raise Puppet::ParseError, ("convert_base(): base must be at least 2 and must not be greater than 36") unless new_base >= 2 and new_base <= 36
+
+ return number_to_convert.to_s(new_base)
+ end
+end