New built-in function to_double(s: string).

Closes #859.
This commit is contained in:
Robin Sommer 2012-07-24 15:04:14 -07:00
parent 43752b3d9f
commit c36a449c76
6 changed files with 51 additions and 1 deletions

View file

@ -1,4 +1,8 @@
2.0-851 | 2012-07-24 15:04:14 -0700
* New built-in function to_double(s: string). (Scott Campbell)
2.0-849 | 2012-07-24 11:06:16 -0700 2.0-849 | 2012-07-24 11:06:16 -0700
* Adding missing include needed on some systems. (Robin Sommer) * Adding missing include needed on some systems. (Robin Sommer)

View file

@ -1 +1 @@
2.0-849 2.0-851

View file

@ -2604,6 +2604,29 @@ function to_subnet%(sn: string%): subnet
return ret; return ret;
%} %}
## Converts a :bro:type:`string` to a :bro:type:`double`.
##
## str: The :bro:type:`string` to convert.
##
## Returns: The :bro:type:`string` *str* as double, or 0 if *str* has
## an invalid format.
##
function to_double%(str: string%): double
%{
const char* s = str->CheckString();
char* end_s;
double d = strtod(s, &end_s);
if ( s[0] == '\0' || end_s[0] != '\0' )
{
builtin_error("bad conversion to count", @ARG@[0]);
d = 0;
}
return new Val(d, TYPE_DOUBLE);
%}
## Converts a :bro:type:`count` to an :bro:type:`addr`. ## Converts a :bro:type:`count` to an :bro:type:`addr`.
## ##
## ip: The :bro:type:`count` to convert. ## ip: The :bro:type:`count` to convert.

View file

@ -0,0 +1,2 @@
error in /da/home/robin/bro/master/testing/btest/.tmp/bifs.to_double_from_string/to_double_from_string.bro, line 7 and /da/home/robin/bro/master/testing/btest/.tmp/bifs.to_double_from_string/to_double_from_string.bro, line 15: bad conversion to count (to_double(d) and NotADouble)
error in /da/home/robin/bro/master/testing/btest/.tmp/bifs.to_double_from_string/to_double_from_string.bro, line 7 and /da/home/robin/bro/master/testing/btest/.tmp/bifs.to_double_from_string/to_double_from_string.bro, line 16: bad conversion to count (to_double(d) and )

View file

@ -0,0 +1,5 @@
to_double(3.14) = 3.14 (SUCCESS)
to_double(-3.14) = -3.14 (SUCCESS)
to_double(0) = 0.0 (SUCCESS)
to_double(NotADouble) = 0.0 (SUCCESS)
to_double() = 0.0 (SUCCESS)

View file

@ -0,0 +1,16 @@
# @TEST-EXEC: bro -b %INPUT >output 2>error
# @TEST-EXEC: btest-diff output
# @TEST-EXEC: btest-diff error
function test_to_double(d: string, expect: double)
{
local result = to_double(d);
print fmt("to_double(%s) = %s (%s)", d, result,
result == expect ? "SUCCESS" : "FAILURE");
}
test_to_double("3.14", 3.14);
test_to_double("-3.14", -3.14);
test_to_double("0", 0);
test_to_double("NotADouble", 0);
test_to_double("", 0);