github.1485827954.workers.dev/ethereum/go-ethereum@v1.14.3/beacon/light/range.go (about) 1 // Copyright 2023 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package light 18 19 // periodRange represents a (possibly zero-length) range of integers (sync periods). 20 type periodRange struct { 21 Start, End uint64 22 } 23 24 // isEmpty returns true if the length of the range is zero. 25 func (a periodRange) isEmpty() bool { 26 return a.End == a.Start 27 } 28 29 // contains returns true if the range includes the given period. 30 func (a periodRange) contains(period uint64) bool { 31 return period >= a.Start && period < a.End 32 } 33 34 // canExpand returns true if the range includes or can be expanded with the given 35 // period (either the range is empty or the given period is inside, right before or 36 // right after the range). 37 func (a periodRange) canExpand(period uint64) bool { 38 return a.isEmpty() || (period+1 >= a.Start && period <= a.End) 39 } 40 41 // expand expands the range with the given period. 42 // This method assumes that canExpand returned true: otherwise this is a no-op. 43 func (a *periodRange) expand(period uint64) { 44 if a.isEmpty() { 45 a.Start, a.End = period, period+1 46 return 47 } 48 if a.Start == period+1 { 49 a.Start-- 50 } 51 if a.End == period { 52 a.End++ 53 } 54 } 55 56 // split splits the range into two ranges. The 'fromPeriod' will be the first 57 // element in the second range (if present). 58 // The original range is unchanged by this operation 59 func (a *periodRange) split(fromPeriod uint64) (periodRange, periodRange) { 60 if fromPeriod <= a.Start { 61 // First range empty, everything in second range, 62 return periodRange{}, *a 63 } 64 if fromPeriod >= a.End { 65 // Second range empty, everything in first range, 66 return *a, periodRange{} 67 } 68 x := periodRange{a.Start, fromPeriod} 69 y := periodRange{fromPeriod, a.End} 70 return x, y 71 } 72 73 // each invokes the supplied function fn once per period in range 74 func (a *periodRange) each(fn func(uint64)) { 75 for p := a.Start; p < a.End; p++ { 76 fn(p) 77 } 78 }