Skip to content

Commit

Permalink
feat(range): Range.invert()
Browse files Browse the repository at this point in the history
giann committed Apr 15, 2024
1 parent 59dbda3 commit e14654b
Showing 3 changed files with 21 additions and 2 deletions.
16 changes: 16 additions & 0 deletions src/builtin/range.zig
Original file line number Diff line number Diff line change
@@ -47,3 +47,19 @@ pub fn len(ctx: *obj.NativeCtx) c_int {

return 1;
}

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

ctx.vm.push(
Value.fromObj((ctx.vm.gc.allocateObject(
obj.ObjRange,
obj.ObjRange{
.high = range.low,
.low = range.high,
},
) catch @panic("Could not instanciate range")).toObj()),
);

return 1;
}
2 changes: 2 additions & 0 deletions src/obj.zig
Original file line number Diff line number Diff line change
@@ -2494,6 +2494,7 @@ pub const ObjRange = struct {
.{
.{ "toList", buzz_builtin.range.toList },
.{ "len", buzz_builtin.range.len },
.{ "invert", buzz_builtin.range.invert },
},
);

@@ -2502,6 +2503,7 @@ pub const ObjRange = struct {
.{
.{ "toList", "extern Function toList() > [int]" },
.{ "len", "extern Function len() > int" },
.{ "invert", "extern Function invert() > range" },
},
);

5 changes: 3 additions & 2 deletions tests/053-range.buzz
Original file line number Diff line number Diff line change
@@ -17,13 +17,14 @@ test "Range" {
}
std.assert(sum == 45, message: "Could iterate over range");

std.assert(rg.len() == 10);
std.assert(rg.len() == 10, message: "Could get range length");
}

test "Inverted range" {
int limit = 0;
range rg = 10..limit;

std.assert((0..10).invert() == rg, message: "Could invert range");
std.assert(rg.low == 10, message: "Could get low limit of range");
std.assert(rg.high == 0, message: "Could get high limit of range");

@@ -36,5 +37,5 @@ test "Inverted range" {
}
std.assert(sum == 55, message: "Could iterate over inverted range");

std.assert(rg.len() == 10);
std.assert(rg.len() == 10, message: "Could get range length");
}

0 comments on commit e14654b

Please sign in to comment.