github.com/uber/kraken@v0.1.4/lib/torrent/scheduler/dispatch/piecerequest/rarest_first_policy.go (about) 1 // Copyright (c) 2016-2019 Uber Technologies, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 package piecerequest 15 16 import ( 17 "github.com/uber/kraken/utils/heap" 18 "github.com/uber/kraken/utils/syncutil" 19 20 "github.com/willf/bitset" 21 ) 22 23 // RarestFirstPolicy selects pieces that the fewest of our peers have to request first. 24 const RarestFirstPolicy = "rarest_first" 25 26 type rarestFirstPolicy struct{} 27 28 func newRarestFirstPolicy() *rarestFirstPolicy { 29 return &rarestFirstPolicy{} 30 } 31 32 func (p *rarestFirstPolicy) selectPieces( 33 limit int, 34 valid func(int) bool, 35 candidates *bitset.BitSet, 36 numPeersByPiece syncutil.Counters) ([]int, error) { 37 38 candidateQueue := heap.NewPriorityQueue() 39 for i, e := candidates.NextSet(0); e; i, e = candidates.NextSet(i + 1) { 40 candidateQueue.Push(&heap.Item{ 41 Value: int(i), 42 Priority: numPeersByPiece.Get(int(i)), 43 }) 44 } 45 46 pieces := make([]int, 0, limit) 47 for len(pieces) < limit && candidateQueue.Len() > 0 { 48 item, err := candidateQueue.Pop() 49 if err != nil { 50 return nil, err 51 } 52 53 candidate := item.Value.(int) 54 if valid(candidate) { 55 pieces = append(pieces, candidate) 56 } 57 } 58 59 return pieces, nil 60 }