Skip to content

Commit

Permalink
fix(str): str.sub returns "" when start is out of bounds
Browse files Browse the repository at this point in the history
  • Loading branch information
giann committed Jan 29, 2025
1 parent 7e557fd commit 43eed4b
Showing 1 changed file with 8 additions and 7 deletions.
15 changes: 8 additions & 7 deletions src/builtin/str.zig
Original file line number Diff line number Diff line change
Expand Up @@ -220,12 +220,9 @@ pub fn replace(ctx: *NativeCtx) c_int {

pub fn sub(ctx: *NativeCtx) c_int {
const self = ObjString.cast(ctx.vm.peek(2).obj()).?;
const start = @min(
@max(
0,
ctx.vm.peek(1).integer(),
),
self.string.len - 1,
const start = @max(
0,
ctx.vm.peek(1).integer(),
);
const upto = if (ctx.vm.peek(0).integerOrNull()) |u|
@max(0, u)
Expand All @@ -236,7 +233,11 @@ pub fn sub(ctx: *NativeCtx) c_int {
@intCast(start + upto.?)
else
self.string.len;
const substr = self.string[@intCast(start)..limit];

const substr = if (start < self.string.len)
self.string[@intCast(start)..limit]
else
"";

ctx.vm.push(
(ctx.vm.gc.copyString(substr) catch {
Expand Down

0 comments on commit 43eed4b

Please sign in to comment.