diff --git a/CHANGELOG.md b/CHANGELOG.md index 82181783..e01e8473 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## Added - Enum can now have `rg`, `ud`, `void`, `pat` has value type - Object can have `const` properties (https://github.com/buzz-language/buzz/issues/13). A object with only `const` properties is considered itself `const`. Although we don't do anything yet with that concept. https://github.com/buzz-language/buzz/issues/114 is the objective but it requires being able to build objects and instances at compile time which is not yet possible. +- `rg.subsetOf`, `rg.intersect` ## Modified diff --git a/src/builtin/range.zig b/src/builtin/range.zig index e9cb657d..a934bb6d 100644 --- a/src/builtin/range.zig +++ b/src/builtin/range.zig @@ -85,3 +85,29 @@ pub fn subsetOf(ctx: *obj.NativeCtx) c_int { return 1; } + +pub fn intersect(ctx: *obj.NativeCtx) c_int { + const rangeA = ctx.vm.peek(1).obj().access(obj.ObjRange, .Range, ctx.vm.gc).?; + const rangeB = 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 = @max( + @min(rangeB.low, rangeB.high), + @min(rangeA.low, rangeA.high), + ), + .low = @min( + @max(rangeB.low, rangeB.high), + @max(rangeA.low, rangeA.high), + ), + }, + ) catch { + ctx.vm.panic("Out of memory"); + unreachable; + }).toObj()), + ); + + return 1; +} diff --git a/src/obj.zig b/src/obj.zig index a40ae762..6ce4695b 100644 --- a/src/obj.zig +++ b/src/obj.zig @@ -2500,6 +2500,7 @@ pub const ObjRange = struct { .{ "len", buzz_builtin.range.len }, .{ "invert", buzz_builtin.range.invert }, .{ "subsetOf", buzz_builtin.range.subsetOf }, + .{ "intersect", buzz_builtin.range.intersect }, }, ); @@ -2509,6 +2510,7 @@ pub const ObjRange = struct { .{ "len", "extern Function len() > int" }, .{ "invert", "extern Function invert() > rg" }, .{ "subsetOf", "extern Function subsetOf(rg other) > bool" }, + .{ "intersect", "extern Function intersect(rg other) > rg" }, }, );