]> git.donarmstrong.com Git - dsa-puppet.git/blob - 3rdparty/modules/stdlib/lib/puppet/parser/functions/is_numeric.rb
upgrade to stdlib 4.6.1
[dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / is_numeric.rb
1 #
2 # is_numeric.rb
3 #
4
5 module Puppet::Parser::Functions
6   newfunction(:is_numeric, :type => :rvalue, :doc => <<-EOS
7 Returns true if the given argument is a Numeric (Integer or Float),
8 or a String containing either a valid integer in decimal base 10 form, or
9 a valid floating point string representation.
10
11 The function recognizes only decimal (base 10) integers and float but not
12 integers in hex (base 16) or octal (base 8) form.
13
14 The string representation may start with a '-' (minus). If a decimal '.' is used,
15 it must be followed by at least one digit.
16
17 Valid examples:
18
19   77435
20   10e-12
21   -8475
22   0.2343
23   -23.561e3
24     EOS
25   ) do |arguments|
26
27     if (arguments.size != 1) then
28       raise(Puppet::ParseError, "is_numeric(): Wrong number of arguments "+
29         "given #{arguments.size} for 1")
30     end
31
32     value = arguments[0]
33
34     # Regex is taken from the lexer of puppet
35     # puppet/pops/parser/lexer.rb but modified to match also
36     # negative values and disallow invalid octal numbers or
37     # numbers prefixed with multiple 0's (except in hex numbers)
38     #
39     # TODO these parameters should be constants but I'm not sure
40     # if there is no risk to declare them inside of the module
41     # Puppet::Parser::Functions
42
43     # TODO decide if this should be used
44     # HEX numbers like
45     # 0xaa230F
46     # 0X1234009C
47     # 0x0012
48     # -12FcD
49     #numeric_hex = %r{^-?0[xX][0-9A-Fa-f]+$}
50
51     # TODO decide if this should be used
52     # OCTAL numbers like
53     # 01234567
54     # -045372
55     #numeric_oct = %r{^-?0[1-7][0-7]*$}
56
57     # Integer/Float numbers like
58     # -0.1234568981273
59     # 47291
60     # 42.12345e-12
61     numeric = %r{^-?(?:(?:[1-9]\d*)|0)(?:\.\d+)?(?:[eE]-?\d+)?$}
62
63     if value.is_a? Numeric or (value.is_a? String and (
64       value.match(numeric) #or
65     #  value.match(numeric_hex) or
66     #  value.match(numeric_oct)
67     ))
68       return true
69     else
70       return false
71     end
72   end
73 end
74
75 # vim: set ts=2 sw=2 et :