mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-05-23 00:09:26 +00:00
common: add corner case checks to Range
This commit is contained in:
parent
388e0649ac
commit
28c6c7b7b0
1 changed files with 11 additions and 1 deletions
|
|
@ -27,7 +27,11 @@ type Range[T uint32 | uint64] struct {
|
||||||
|
|
||||||
// NewRange creates a new range based of first element and number of elements.
|
// NewRange creates a new range based of first element and number of elements.
|
||||||
func NewRange[T uint32 | uint64](first, count T) Range[T] {
|
func NewRange[T uint32 | uint64](first, count T) Range[T] {
|
||||||
return Range[T]{first, first + count}
|
afterLast := first + count
|
||||||
|
if afterLast < first {
|
||||||
|
panic("range overflow")
|
||||||
|
}
|
||||||
|
return Range[T]{first, afterLast}
|
||||||
}
|
}
|
||||||
|
|
||||||
// First returns the first element of the range.
|
// First returns the first element of the range.
|
||||||
|
|
@ -97,6 +101,12 @@ func (r Range[T]) Intersection(q Range[T]) Range[T] {
|
||||||
|
|
||||||
// Union returns the union of two ranges. Panics for gapped ranges.
|
// Union returns the union of two ranges. Panics for gapped ranges.
|
||||||
func (r Range[T]) Union(q Range[T]) Range[T] {
|
func (r Range[T]) Union(q Range[T]) Range[T] {
|
||||||
|
if r.IsEmpty() {
|
||||||
|
return q
|
||||||
|
}
|
||||||
|
if q.IsEmpty() {
|
||||||
|
return r
|
||||||
|
}
|
||||||
if max(r.first, q.first) > min(r.afterLast, q.afterLast) {
|
if max(r.first, q.first) > min(r.afterLast, q.afterLast) {
|
||||||
panic("cannot create union; gap between ranges")
|
panic("cannot create union; gap between ranges")
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue