Update range to have exclusive and inclusive range.

This commit is contained in:
Christoffer Lerno
2023-06-26 10:18:09 +02:00
parent 0ec64c3be8
commit 83f8bbb91b
2 changed files with 36 additions and 3 deletions

View File

@@ -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;
}

View File

@@ -2,9 +2,11 @@ module range_test @test;
import std::collections::range;
def IntRange = Range<int>;
fn void! test_range()
def IntExRange = ExclusiveRange<int>;
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);
}