From 5412f3f1c1cade37041c2770ab328c146cf7c74a Mon Sep 17 00:00:00 2001 From: "David R. MacIver" Date: Tue, 10 Dec 2013 09:18:16 +0000 Subject: [PATCH] convert range bounds to integers in a way that avoids undefined behaviour --- jv_aux.c | 17 +++++++++++------ tests/all.test | 4 ++++ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/jv_aux.c b/jv_aux.c index e994053..ec2aaa1 100644 --- a/jv_aux.c +++ b/jv_aux.c @@ -26,13 +26,18 @@ static int parse_slice(jv j, jv slice, int* pstart, int* pend) { jv_free(end_jv); return 0; } else { - int start = (int)jv_number_value(start_jv); - int end = (int)jv_number_value(end_jv); - if (start < 0) start = len + start; - if (end < 0) end = len + end; + double dstart = jv_number_value(start_jv); + double dend = jv_number_value(end_jv); + if (dstart < 0) dstart += len; + if (dend < 0) dend += len; + if (dstart < 0) dstart = 0; + if (dstart > len) dstart = len; + + int start = (int)dstart; + int end = (dend > len) ? len : (int)dend; + // Ends are exclusive but e.g. 1 < 1.5 so :1.5 should be :2 not :1 + if(end < dend) end += 1; - if (start < 0) start = 0; - if (start > len) start = len; if (end > len) end = len; if (end < start) end = start; assert(0 <= start && start <= end && end <= len); diff --git a/tests/all.test b/tests/all.test index 15e075d..3615bee 100644 --- a/tests/all.test +++ b/tests/all.test @@ -722,3 +722,7 @@ keys [][.] 1000000000000000000 null + +map([1,2][0:.]) +[-1, 1, 2, 3, 1000000000000000000] +[[1], [1], [1,2], [1,2], [1,2]] -- 2.40.0