mirror of
https://github.com/c3lang/c3c.git
synced 2026-02-27 12:01:16 +00:00
Update range to have exclusive and inclusive range.
This commit is contained in:
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
Reference in New Issue
Block a user