Skip to content

Commit

Permalink
feat(range): Range.len()
Browse files Browse the repository at this point in the history
  • Loading branch information
giann committed Apr 15, 2024
1 parent 985f3d3 commit 59dbda3
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/builtin/range.zig
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub fn toList(ctx: *obj.NativeCtx) c_int {
},
) catch @panic("Could not instanciate list"),
),
) catch @panic("Could not instanceiate range");
) catch @panic("Could not instanciate range");

ctx.vm.push(Value.fromObj(list.toObj()));

Expand All @@ -32,3 +32,18 @@ pub fn toList(ctx: *obj.NativeCtx) c_int {

return 1;
}

pub fn len(ctx: *obj.NativeCtx) c_int {
const range = ctx.vm.peek(0).obj().access(obj.ObjRange, .Range, ctx.vm.gc).?;

ctx.vm.push(
Value.fromInteger(
if (range.low < range.high)
range.high - range.low
else
range.low - range.high,
),
);

return 1;
}
2 changes: 2 additions & 0 deletions src/obj.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2493,13 +2493,15 @@ pub const ObjRange = struct {
NativeFn,
.{
.{ "toList", buzz_builtin.range.toList },
.{ "len", buzz_builtin.range.len },
},
);

const members_typedef = std.ComptimeStringMap(
[]const u8,
.{
.{ "toList", "extern Function toList() > [int]" },
.{ "len", "extern Function len() > int" },
},
);

Expand Down
4 changes: 4 additions & 0 deletions tests/053-range.buzz
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ test "Range" {
sum = sum + n;
}
std.assert(sum == 45, message: "Could iterate over range");

std.assert(rg.len() == 10);
}

test "Inverted range" {
Expand All @@ -33,4 +35,6 @@ test "Inverted range" {
sum = sum + n;
}
std.assert(sum == 55, message: "Could iterate over inverted range");

std.assert(rg.len() == 10);
}

0 comments on commit 59dbda3

Please sign in to comment.