From f28d03c0a335deb9f7b334cd137b077e041635f3 Mon Sep 17 00:00:00 2001 From: Wouter van Oortmerssen Date: Tue, 15 Oct 2024 12:28:32 -0700 Subject: [PATCH] slice(): better checking and clearer error for going past the end --- dev/src/builtins.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/dev/src/builtins.cpp b/dev/src/builtins.cpp index 79873c83..8629174b 100644 --- a/dev/src/builtins.cpp +++ b/dev/src/builtins.cpp @@ -364,9 +364,11 @@ nfr("slice", "xs,start,size", "A]*II", "A]1", [](StackPtr &, VM &vm, Value &l, Value &s, Value &e) { auto size = e.ival(); auto start = s.ival(); - if (size < 0) size = l.vval()->len - start; - if (start < 0 || start + size > l.vval()->len) - vm.BuiltinError("slice: values out of range"); + if (size < 0) size = std::max((iint)0, l.vval()->len - start); + if (start < 0) + vm.BuiltinError(cat("slice: start cannot be negative: ", start)); + if (start + size > l.vval()->len) + vm.BuiltinError(cat("slice: range extends beyond the end: ", start + size, " > ", l.vval()->len)); auto nv = (LVector *)vm.NewVec(0, size, l.vval()->tti); nv->Append(vm, l.vval(), start, size); return Value(nv);