2022-04-21 22:06:08 +08:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"golang.org/x/exp/constraints"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Range[T constraints.Ordered] struct {
|
|
|
|
start T
|
|
|
|
end T
|
|
|
|
}
|
|
|
|
|
2023-06-04 11:51:30 +08:00
|
|
|
func NewRange[T constraints.Ordered](start, end T) Range[T] {
|
2022-04-21 22:06:08 +08:00
|
|
|
if start > end {
|
2023-06-04 11:51:30 +08:00
|
|
|
return Range[T]{
|
2022-04-21 22:06:08 +08:00
|
|
|
start: end,
|
|
|
|
end: start,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-04 11:51:30 +08:00
|
|
|
return Range[T]{
|
2022-04-21 22:06:08 +08:00
|
|
|
start: start,
|
|
|
|
end: end,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-04 11:51:30 +08:00
|
|
|
func (r Range[T]) Contains(t T) bool {
|
2022-04-21 22:06:08 +08:00
|
|
|
return t >= r.start && t <= r.end
|
|
|
|
}
|
|
|
|
|
2023-06-04 11:51:30 +08:00
|
|
|
func (r Range[T]) LeftContains(t T) bool {
|
2022-04-21 22:06:08 +08:00
|
|
|
return t >= r.start && t < r.end
|
|
|
|
}
|
|
|
|
|
2023-06-04 11:51:30 +08:00
|
|
|
func (r Range[T]) RightContains(t T) bool {
|
2022-04-21 22:06:08 +08:00
|
|
|
return t > r.start && t <= r.end
|
|
|
|
}
|
|
|
|
|
2023-06-04 11:51:30 +08:00
|
|
|
func (r Range[T]) Start() T {
|
2022-04-21 22:06:08 +08:00
|
|
|
return r.start
|
|
|
|
}
|
|
|
|
|
2023-06-04 11:51:30 +08:00
|
|
|
func (r Range[T]) End() T {
|
2022-04-21 22:06:08 +08:00
|
|
|
return r.end
|
|
|
|
}
|