From 83f8bbb91b8a47ac126394fa91286b242ef0fcdc Mon Sep 17 00:00:00 2001 From: Christoffer Lerno Date: Mon, 26 Jun 2023 10:18:09 +0200 Subject: [PATCH] Update range to have exclusive and inclusive range. --- lib/std/collections/range.c3 | 21 ++++++++++++++++++++- test/unit/stdlib/collections/range.c3 | 18 ++++++++++++++++-- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/lib/std/collections/range.c3 b/lib/std/collections/range.c3 index e1b1216a4..f9bdbc23e 100644 --- a/lib/std/collections/range.c3 +++ b/lib/std/collections/range.c3 @@ -13,7 +13,7 @@ struct Range fn usz Range.len(Range* range) @operator(len) { if (range.end < range.start) return 0; - return (usz)(range.end - range.start); + return (usz)(range.end - range.start + (Type)1); } /** @@ -24,3 +24,22 @@ fn Type Range.get(Range* range, usz index) @operator([]) return range.start + (Type)index; } +struct ExclusiveRange +{ + Type start; + Type end; +} + +fn usz ExclusiveRange.len(ExclusiveRange* range) @operator(len) +{ + if (range.end < range.start) return 0; + return (usz)(range.end - range.start); +} + +/** + * @require index < range.len() : "Can't index into an empty range" + **/ +fn Type ExclusiveRange.get(ExclusiveRange* range, usz index) @operator([]) +{ + return range.start + (Type)index; +} diff --git a/test/unit/stdlib/collections/range.c3 b/test/unit/stdlib/collections/range.c3 index 4d6487ca4..2054dc405 100644 --- a/test/unit/stdlib/collections/range.c3 +++ b/test/unit/stdlib/collections/range.c3 @@ -2,9 +2,11 @@ module range_test @test; import std::collections::range; def IntRange = Range; -fn void! test_range() +def IntExRange = ExclusiveRange; + +fn void! test_exrange() { - IntRange range = { -4, 2 }; + IntExRange range = { -4, 2 }; int sum = 0; foreach (int z : range) { @@ -12,4 +14,16 @@ fn void! test_range() sum += z * z; } assert(sum == 31); +} + +fn void! test_range() +{ + IntRange range = { -4, 2 }; + int sum = 0; + foreach (int z : range) + { + assert(z >= -4 && z < 3); + sum += z * z; + } + assert(sum == 35); } \ No newline at end of file