Skip to content

Commit

Permalink
Add tointeger and isinteger
Browse files Browse the repository at this point in the history
  • Loading branch information
nicowilliams committed Feb 2, 2017
1 parent 15cfdcd commit cd3569d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/builtin.c
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,33 @@ static jv f_tonumber(jq_state *jq, jv input) {
return type_error(input, "cannot be parsed as a number");
}

static jv f_toint(jq_state *jq, jv input) {
input = f_tonumber(jq, input);
if (!jv_is_valid(input))
return input;
if (jv_is_int64(input) || jv_is_uint64(input))
return input;
double d = jv_number_value(input);
if (d < 0 && d >= INT64_MIN) {
int64_t i = d;
if (i < 0)
return jv_int64(i);
} else if (d < UINT64_MAX) {
uint64_t u = d;
if (d == (double)u)
return jv_uint64(u);
}
return jv_number(nearbyint(d));
}

static jv f_isint(jq_state *jq, jv input) {
if (jv_get_kind(input) != JV_KIND_NUMBER)
return type_error(input, "only numbers can be integers");
if (jv_is_int64(input) || jv_is_uint64(input) || jv_is_integer(input))
return jv_true();
return jv_false();
}

static jv f_length(jq_state *jq, jv input) {
if (jv_get_kind(input) == JV_KIND_ARRAY) {
return jv_number(jv_array_length(input));
Expand Down Expand Up @@ -1285,6 +1312,8 @@ static const struct cfunction function_list[] = {
{(cfunction_ptr)f_json_parse, "fromjson", 1},
{(cfunction_ptr)f_tonumber, "tonumber", 1},
{(cfunction_ptr)f_tostring, "tostring", 1},
{(cfunction_ptr)f_toint, "tointeger", 1},
{(cfunction_ptr)f_isint, "isinteger", 1},
{(cfunction_ptr)f_keys, "keys", 1},
{(cfunction_ptr)f_keys_unsorted, "keys_unsorted", 1},
{(cfunction_ptr)f_startswith, "startswith", 2},
Expand Down
1 change: 1 addition & 0 deletions src/jv.c
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ int jv_is_integer(jv j){
}
#endif
double x = jv_number_value(j);
/* XXX Check against actual double min/max integers */
if(x != x || x > INT_MAX || x < INT_MIN){
return 0;
}
Expand Down

0 comments on commit cd3569d

Please sign in to comment.