Commit 63f9e71a
63f9e71a55caMerged
NHH <[email protected]> · 5 months ago · 4 files · +2 added · ~2 modified
Description
runtime,codegen: implement Integer#ceil/floor/round/truncate with ndigits
Integer#ceil, #floor, #round, and #truncate without an argument already returned self, but calling with a precision argument (e.g. 1234.ceil(-2)) fell through to the unresolved-call path and silently returned 0. CRuby rounds to the nearest 10^(-ndigits) for negative ndigits; positive ndigits are a no-op on integers.
Added sp_int_round, sp_int_ceil, sp_int_floor, sp_int_truncate runtime helpers using pow/ceil/floor/round, and a codegen arm for Integer receivers with an argument.
Details
- Commit
- 63f9e71a55ca
- Parent
- 25031c1dd270
lib/sp_runtime.hmodifiedView file
@@ -199,6 +199,15 @@
199199
static mrb_int sp_int_sqrt(mrb_int n){if(n<0)return 0;if(n<2)return n;mrb_int x=n,y=(x+1)/2;while(y<x){x=y;y=(x+n/x)/2;}return x;}200200
static inline char *sp_str_alloc_raw(size_t total_with_null); /* fwd decl */201201
static const char*sp_int_chr(mrb_int n){char*s=sp_str_alloc_raw(2);s[0]=(char)n;s[1]=0;return s;}202+
/* Integer#round(ndigits): round to nearest 10^(-ndigits).203+
Integer#ceil(ndigits): round up to 10^(-ndigits).204+
Integer#floor(ndigits): round down to 10^(-ndigits).205+
Integer#truncate(ndigits): truncate toward zero at 10^(-ndigits).206+
Positive ndigits are a no-op on integers. */207+
static mrb_int sp_int_round(mrb_int v,mrb_int nd){if(nd>=0)return v;mrb_int f=(mrb_int)pow(10,-nd);return(mrb_int)round((double)v/f)*f;}208+
static mrb_int sp_int_ceil(mrb_int v,mrb_int nd){if(nd>=0)return v;mrb_int f=(mrb_int)pow(10,-nd);return(mrb_int)ceil((double)v/f)*f;}209+
static mrb_int sp_int_floor(mrb_int v,mrb_int nd){if(nd>=0)return v;mrb_int f=(mrb_int)pow(10,-nd);return(mrb_int)floor((double)v/f)*f;}210+
static mrb_int sp_int_truncate(mrb_int v,mrb_int nd){if(nd>=0)return v;mrb_int f=(mrb_int)pow(10,-nd);return(v>=0?(mrb_int)floor((double)v/f):(mrb_int)ceil((double)v/f))*f;}202211
203212
/* Forward decls for helpers used across this header (and by the204213
string->number parsers that now live in libspinel_rt.a). */spinel_codegen.rbmodifiedView file
Loading diff…
test/int_ceil_floor_round_truncate_ndigits.rbaddedView file
Loading diff…
test/int_ceil_floor_round_truncate_ndigits.rb.expectedaddedView file
Loading diff…