Add has function to Range and ExclusiveRange.

This commit is contained in:
Dmitry Atamanov
2023-07-19 14:35:29 +05:00
committed by Christoffer Lerno
parent b453186de5
commit 7fbedae604
2 changed files with 28 additions and 12 deletions

View File

@@ -16,6 +16,11 @@ fn usz Range.len(&self) @operator(len)
return (usz)(self.end - self.start + (Type)1); return (usz)(self.end - self.start + (Type)1);
} }
fn bool Range.has(&self, Type value) @inline
{
return value >= self.start && value <= self.end;
}
/** /**
* @require index < self.len() : "Can't index into an empty range" * @require index < self.len() : "Can't index into an empty range"
**/ **/
@@ -46,6 +51,11 @@ fn usz ExclusiveRange.len(&self) @operator(len)
return (usz)(self.end - self.start); return (usz)(self.end - self.start);
} }
fn bool ExclusiveRange.has(&self, Type value) @inline
{
return value >= self.start && value < self.end;
}
fn void! ExclusiveRange.to_format(&self, Formatter* formatter) @dynamic fn void! ExclusiveRange.to_format(&self, Formatter* formatter) @dynamic
{ {
formatter.printf("[%s..<%s]", self.start, self.end)!; formatter.printf("[%s..<%s]", self.start, self.end)!;

View File

@@ -4,18 +4,6 @@ import std::collections::range;
def IntRange = Range(<int>); def IntRange = Range(<int>);
def IntExRange = ExclusiveRange(<int>); def IntExRange = ExclusiveRange(<int>);
fn void! test_exrange()
{
IntExRange range = { -4, 2 };
int sum = 0;
foreach (int z : range)
{
assert(z >= -4 && z < 2);
sum += z * z;
}
assert(sum == 31);
}
fn void! test_range() fn void! test_range()
{ {
IntRange range = { -4, 2 }; IntRange range = { -4, 2 };
@@ -26,5 +14,23 @@ fn void! test_range()
sum += z * z; sum += z * z;
} }
assert(sum == 35); assert(sum == 35);
assert(range.has(-4));
assert(range.has(2));
assert(!range.has(3));
}
fn void! test_exrange()
{
IntExRange range = { -4, 2 };
int sum = 0;
foreach (int z : range)
{
assert(z >= -4 && z < 2);
sum += z * z;
}
assert(sum == 31);
assert(range.has(-4));
assert(range.has(1));
assert(!range.has(2));
} }