Commit 5b8f9ed7

5b8f9ed7e01aMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 4 files · +2 added · ~2 modified

Description

Return nil from Array#at on an out-of-range index

[1,2,3,4,5,6].at(99) returned the raw SP_INT_NIL sentinel (a huge integer) instead of nil, because at was typed as the plain element type, so == nil, .nil?, and inspect never recognised the out-of-bounds value.

Type Array#at on an int_array/float_array as the nullable element type (int?/float?) so consumers test the scalar-nil sentinel. at always takes a single index (no slice) and is never used on a hot path -- it has zero self-host / optcarrot surface -- so this does not cascade the sentinel the way making [] nullable would. Also make sp_FloatArray_get return the float-nil on an out-of-range index, mirroring sp_IntArray_get, so the float? path observes nil rather than 0.0.

Fixes #1324

Co-Authored-By: Claude Opus 4.8 [email protected]

Details

Commit
5b8f9ed7e01a
Parent
97da57c9d882

lib/sp_runtime.hmodifiedView file

@@ -1054,7 +1054,7 @@
10541054 static inline mrb_float sp_FloatArray_delete_at(sp_FloatArray*a,mrb_int i){if(!a)return 0.0;if(a->frozen){sp_raise_frozen_array();return 0.0;}if(i<0)i+=a->len;if(i<0||i>=a->len)return 0.0;mrb_float v=a->data[i];for(mrb_int j=i;j+1<a->len;j++)a->data[j]=a->data[j+1];a->len--;return v;}
10551055 static inline mrb_int sp_FloatArray_length(sp_FloatArray*a){return a->len;}
10561056 static inline mrb_bool sp_FloatArray_empty(sp_FloatArray*a){return a->len==0;}
1057-static inline mrb_float sp_FloatArray_get(sp_FloatArray*a,mrb_int i){if(!a)return 0.0;if(i<0)i+=a->len;if(i<0||i>=a->len)return 0.0;return a->data[i];}
1057+static inline mrb_float sp_FloatArray_get(sp_FloatArray*a,mrb_int i){if(!a)return sp_float_nil();if(i<0)i+=a->len;if(i<0||i>=a->len)return sp_float_nil();return a->data[i];}
10581058 /* first/last as float? : nil (sentinel) when empty, else the element.
10591059 `[i]` stays non-nullable (0.0 for OOB) -- only first/last produce nil,
10601060 matching CRuby where Array#first/#last on an empty array return nil. */