github.com/annchain/OG@v0.0.9/og/syncer/cache.go (about) 1 package syncer 2 3 import ( 4 "fmt" 5 "github.com/annchain/OG/arefactor/og/types" 6 "strings" 7 "sync" 8 ) 9 10 type SequencerCache struct { 11 mu sync.RWMutex 12 proposal map[types.Hash][]string 13 hashes types.Hashes 14 size int 15 } 16 17 func NewSequencerCache(size int) *SequencerCache { 18 return &SequencerCache{ 19 proposal: make(map[types.Hash][]string), 20 size: size, 21 } 22 } 23 24 func (p *SequencerCache) Add(seqHash types.Hash, peerId string) { 25 p.mu.Lock() 26 defer p.mu.Unlock() 27 var peers []string 28 var ok bool 29 peers, ok = p.proposal[seqHash] 30 if !ok { 31 if len(p.proposal) > p.size { 32 num := len(p.proposal) - p.size 33 oldHash := p.hashes[:num] 34 p.hashes = p.hashes[num:] 35 for _, key := range oldHash { 36 delete(p.proposal, key) 37 } 38 } 39 } 40 peers = append(peers, peerId) 41 p.proposal[seqHash] = peers 42 p.hashes = append(p.hashes, seqHash) 43 } 44 45 func (p *SequencerCache) GetPeer(seqHash types.Hash) string { 46 p.mu.RLock() 47 defer p.mu.RUnlock() 48 peers := p.proposal[seqHash] 49 if len(peers) > 0 { 50 return peers[0] 51 } 52 return "" 53 } 54 55 func (s SequencerCache) String() string { 56 s.mu.RLock() 57 defer s.mu.RUnlock() 58 var str string 59 str += fmt.Sprintf("size %d", s.size) 60 str += " hashes:" 61 for _, h := range s.hashes { 62 str += " " + h.String() 63 } 64 str += " map:" 65 for k, v := range s.proposal { 66 str += " key " + k.String() + " val " + strings.Join(v, ",") 67 } 68 return str 69 }