fix parse_frac bug for leading space leading to infinite recursion

This commit is contained in:
Adrian Mariano 2023-03-22 16:11:31 -04:00
parent 05eec08542
commit 654e3cd86a
2 changed files with 23 additions and 18 deletions

View file

@ -468,24 +468,23 @@ function parse_float(str) =
// parse_frac("-2 12/4",mixed=false); // Returns nan // parse_frac("-2 12/4",mixed=false); // Returns nan
// parse_frac("2 1/4",mixed=false); // Returns nan // parse_frac("2 1/4",mixed=false); // Returns nan
function parse_frac(str,mixed=true,improper=true,signed=true) = function parse_frac(str,mixed=true,improper=true,signed=true) =
str == undef ? undef : str == undef ? undef
len(str)==0 ? 0 : : len(str)==0 ? 0
signed && str[0]=="-" ? -parse_frac(substr(str,1),mixed=mixed,improper=improper,signed=false) : : str[0]==" " ? NAN
signed && str[0]=="+" ? parse_frac(substr(str,1),mixed=mixed,improper=improper,signed=false) : : signed && str[0]=="-" ? -parse_frac(substr(str,1),mixed=mixed,improper=improper,signed=false)
mixed ? ( : signed && str[0]=="+" ? parse_frac(substr(str,1),mixed=mixed,improper=improper,signed=false)
!in_list(str_find(str," "), [undef,0]) || is_undef(str_find(str,"/"))? ( : mixed && (str_find(str," ")!=undef || str_find(str,"/")==undef)? // Mixed allowed and there is a space or no slash
let(whole = str_split(str,[" "])) let(whole = str_split(str,[" "]))
_parse_int_recurse(whole[0],10,len(whole[0])-1) + parse_frac(whole[1], mixed=false, improper=improper, signed=false) _parse_int_recurse(whole[0],10,len(whole[0])-1) + parse_frac(whole[1], mixed=false, improper=improper, signed=false)
) : parse_frac(str,mixed=false, improper=improper) : let(split = str_split(str,"/"))
) : ( len(split)!=2 ? NAN
let(split = str_split(str,"/")) : let(
len(split)!=2 ? (0/0) : numerator = _parse_int_recurse(split[0],10,len(split[0])-1),
let( denominator = _parse_int_recurse(split[1],10,len(split[1])-1)
numerator = _parse_int_recurse(split[0],10,len(split[0])-1), )
denominator = _parse_int_recurse(split[1],10,len(split[1])-1) !improper && numerator>=denominator? NAN
) !improper && numerator>=denominator? (0/0) : : denominator<0 ? NAN
denominator<0 ? (0/0) : numerator/denominator : numerator/denominator;
);
// Function: parse_num() // Function: parse_num()

View file

@ -215,6 +215,12 @@ module test_parse_frac() {
assert(parse_frac("3/0") == INF); assert(parse_frac("3/0") == INF);
assert(parse_frac("-3/0") == -INF); assert(parse_frac("-3/0") == -INF);
assert(is_nan(parse_frac("0/0"))); assert(is_nan(parse_frac("0/0")));
assert(is_nan(parse_frac("-77/9", improper=false)));
assert(is_nan(parse_frac("-2 12/4",improper=false)));
assert(is_nan(parse_frac("-2 12/4",signed=false)));
assert(is_nan(parse_frac("-2 12/4",mixed=false)));
assert(is_nan(parse_frac("2 1/4",mixed=false)));
assert(is_nan(parse_frac("2", mixed=false)));
} }
test_parse_frac(); test_parse_frac();