decred.org/dcrdex@v1.0.3/client/orderbook/rateindex.go (about) 1 // This code is available on the terms of the project LICENSE.md file, 2 // also available online at https://blueoakcouncil.org/license/1.0.0. 3 4 package orderbook 5 6 import ( 7 "fmt" 8 "sort" 9 ) 10 11 var ( 12 // defaultCapacity represents the default rate index capacity. 13 defaultCapacity = 10 14 ) 15 16 // rateIndex represents a sorted group of rate. 17 type rateIndex struct { 18 Rates []uint64 19 } 20 21 // newRateIndex creates a new rate index. 22 func newRateIndex() *rateIndex { 23 return &rateIndex{ 24 Rates: make([]uint64, 0, defaultCapacity), 25 } 26 } 27 28 // Add adds a new entry to the rate index with the order preserved. 29 func (ri *rateIndex) Add(entry uint64) { 30 i := sort.Search(len(ri.Rates), 31 func(i int) bool { return ri.Rates[i] >= entry }) 32 33 // Only add a new entry to the rate index if it does not 34 // already exist. 35 if i < len(ri.Rates) { 36 if ri.Rates[i] == entry { 37 return 38 } 39 } 40 41 ri.Rates = append(ri.Rates, 0) 42 copy(ri.Rates[i+1:], ri.Rates[i:]) 43 ri.Rates[i] = entry 44 } 45 46 // Remove removes an entry from the rate index with the order preserved. 47 func (ri *rateIndex) Remove(entry uint64) error { 48 i := sort.Search(len(ri.Rates), 49 func(i int) bool { return ri.Rates[i] >= entry }) 50 51 if i == len(ri.Rates) { 52 return fmt.Errorf("no entry found for value %d", entry) 53 } 54 55 if i < len(ri.Rates)-1 { 56 copy(ri.Rates[i:], ri.Rates[i+1:]) 57 } 58 ri.Rates[len(ri.Rates)-1] = uint64(0) 59 ri.Rates = ri.Rates[:len(ri.Rates)-1] 60 61 return nil 62 }