Commit cf66e946
cf66e946a205Merged
Ryan Seys <[email protected]> · 5 months ago · 4 files · +2 added · ~2 modified
Description
core: validate clamp bounds against NaN and min>max
Integer#clamp and Float#clamp must raise ArgumentError when the minimum bound exceeds the maximum, and Float#clamp must also raise when any operand is NaN (comparisons with NaN are undefined). Previously both silently returned a wrong value. Match CRuby's exact error classes and messages.
Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]
Details
- Commit
- cf66e946a205
- Parent
- b1e4d47607fd
lib/sp_runtime.hmodifiedView file
@@ -1423,6 +1423,24 @@
14231423
out[o]=0;sp_str_set_len(out,(size_t)o);return out;14241424
}14251425
#define sp_float_inspect sp_float_to_s1426+
1427+
/* Bound-checked clamp. The arithmetic lives in the compiled-once leaf1428+
helpers (sp_core.c); the validation rides here because it needs the1429+
error-message machinery (sp_sprintf) and Ruby float inspect, neither of1430+
which the decoupled sp_core.c TU links against. CRuby's Comparable#clamp1431+
compares min<=>max first (so a NaN bound names max), then self against1432+
each bound (so a NaN receiver names min); a non-NaN min>max is the1433+
ordinary ArgumentError. */1434+
static inline mrb_int sp_int_clamp_ck(mrb_int v,mrb_int lo,mrb_int hi){1435+
if(lo>hi)sp_raise_cls("ArgumentError","min argument must be less than or equal to max argument");1436+
return sp_int_clamp(v,lo,hi);1437+
}1438+
static inline mrb_float sp_float_clamp_ck(mrb_float v,mrb_float lo,mrb_float hi){1439+
if(lo!=lo||hi!=hi)sp_raise_cls("ArgumentError",sp_sprintf("comparison of Float with %s failed",sp_float_to_s(hi)));1440+
if(lo>hi)sp_raise_cls("ArgumentError","min argument must be less than or equal to max argument");1441+
if(v!=v)sp_raise_cls("ArgumentError",sp_sprintf("comparison of Float with %s failed",sp_float_to_s(lo)));1442+
return sp_float_clamp(v,lo,hi);1443+
}14261444
/* String#inspect: wrap in double quotes and escape \, ", \n, \t, \r,14271445
plus any non-printable byte as \xNN. Output is always ASCII-safe. */14281446
static const char*sp_str_inspect(const char*s){if(!s){char*r=sp_str_alloc_raw(4);r[0]='n';r[1]='i';r[2]='l';r[3]=0;return r;}size_t sl=sp_str_byte_len(s);size_t cap=sl*4+3;char*r=sp_str_alloc_raw(cap);size_t o=0;r[o++]='"';for(size_t i=0;i<sl;i++){unsigned char c=(unsigned char)s[i];if(c=='\\'||c=='"'){r[o++]='\\';r[o++]=c;}else if(c=='\n'){r[o++]='\\';r[o++]='n';}else if(c=='\t'){r[o++]='\\';r[o++]='t';}else if(c=='\r'){r[o++]='\\';r[o++]='r';}else if(c<0x20||c==0x7f){snprintf(r+o,5,"\\x%02X",c);o+=4;}else{r[o++]=(char)c;}}r[o++]='"';r[o]=0;sp_str_set_len(r,o);return r;}src/codegen_call.cmodifiedView file
Loading diff…
test/clamp_bounds.rbaddedView file
Loading diff…
test/clamp_bounds.rb.expectedaddedView file
Loading diff…