From a8777fa1caccb3ffea5799d7a53c8f374941e78a Mon Sep 17 00:00:00 2001 From: b97tsk Date: Thu, 25 Jan 2024 14:44:34 +0800 Subject: [PATCH] Add method IsValid to type Interval --- intervalset.go | 8 ++++++++ intervalset_test.go | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/intervalset.go b/intervalset.go index 5b29f46..93b76a6 100644 --- a/intervalset.go +++ b/intervalset.go @@ -44,6 +44,14 @@ func (r Interval[E]) Equal(r2 Interval[E]) bool { return r.Low.Compare(r2.Low) == 0 && r.High.Compare(r2.High) == 0 } +// IsValid reports whether r is a valid Interval. +// A valid Interval r either satisfies r.Low.Compare(r.High) < 0 or equals to +// the zero value. +func (r Interval[E]) IsValid() bool { + c := r.Low.Compare(r.High) + return c < 0 || c == 0 && r.Equal(Interval[E]{}) +} + // Set returns the set of elements that are in r. // If r is the zero value, Set returns an empty set. // If r is an invalid Interval, Set panics. diff --git a/intervalset_test.go b/intervalset_test.go index 96075d3..f3b1976 100644 --- a/intervalset_test.go +++ b/intervalset_test.go @@ -7,6 +7,25 @@ import ( "github.com/b97tsk/intervals/elems" ) +func TestIsValid(t *testing.T) { + type E = elems.Int + + assertions := []bool{ + Interval[E]{}.IsValid(), + One[E](0).IsValid(), + Range[E](1, 5).IsValid(), + !Range[E](5, 1).IsValid(), + !Range[E](5, 5).IsValid(), + } + + for i, ok := range assertions { + if !ok { + t.Fail() + t.Logf("Case %v: FAILED", i) + } + } +} + func TestCreation(t *testing.T) { type E = elems.Int