Skip to content

Commit

Permalink
Change method Set to panic when called on an invalid Interval
Browse files Browse the repository at this point in the history
  • Loading branch information
b97tsk committed Jan 25, 2024
1 parent 36b26c4 commit dd6e767
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
15 changes: 10 additions & 5 deletions intervalset.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,16 @@ type Interval[E Elem[E]] struct {

// One returns an Interval that only contains a single element v.
//
// If v is the maximum value of E, One returns an invalid Interval.
// If there is no element next to v, One returns an invalid Interval.
// Note that calling Set method on an invalid Interval panics.
func One[E Enum[E]](v E) Interval[E] {
return Range(v, v.Next())
}

// Range returns an Interval of range [lo, hi).
//
// If lo.Compare(hi) >= 0, Range returns an invalid Interval.
// Note that calling Set method on an invalid Interval panics.
func Range[E Elem[E]](lo, hi E) Interval[E] {
return Interval[E]{lo, hi}
}
Expand All @@ -45,14 +47,17 @@ func (r Interval[E]) Equal(r2 Interval[E]) bool {
}

// Set returns the set of elements that are in r.
//
// If r is an invalid Interval, Set returns an empty set.
// If r is the zero value, Set returns an empty set.
// If r is an invalid Interval, Set panics.
func (r Interval[E]) Set() Set[E] {
if r.Low.Compare(r.High) >= 0 {
switch c := r.Low.Compare(r.High); {
case c < 0:
return Set[E]{r}
case c == 0 && r.Equal(Interval[E]{}):
return nil
}

return Set[E]{r}
panic("invalid Interval")
}

// A Set is a slice of separate intervals sorted in ascending order.
Expand Down
18 changes: 17 additions & 1 deletion intervalset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func TestCreation(t *testing.T) {
Set[E]{{1, 5}},
},
{
Range[E](5, 1).Set(),
Interval[E]{}.Set(),
nil,
},
{
Expand Down Expand Up @@ -53,6 +53,9 @@ func TestCreation(t *testing.T) {
t.Logf("Case %v: want %v, but got %v", i, c.Expected, c.Actual)
}
}

shouldPanic(t, func() { _ = Range[E](5, 1).Set() }, "Range[E](5, 1).Set() didn't panic.")
shouldPanic(t, func() { _ = Range[E](5, 5).Set() }, "Range[E](5, 5).Set() didn't panic.")
}

func TestAdd(t *testing.T) {
Expand Down Expand Up @@ -204,3 +207,16 @@ func TestExtent(t *testing.T) {
}
}
}

func shouldPanic(t *testing.T, f func(), name string) {
t.Helper()

defer func() {
if recover() == nil {
t.Log(name, "did not panic.")
t.Fail()
}
}()

f()
}

0 comments on commit dd6e767

Please sign in to comment.