github.com/divan/go-ethereum@v1.8.14-0.20180820134928-1de9ada4016d/swarm/network/simulation/bucket.go (about) 1 // Copyright 2018 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 simulation 18 19 import ( 20 "github.com/ethereum/go-ethereum/p2p/discover" 21 ) 22 23 // BucketKey is the type that should be used for keys in simulation buckets. 24 type BucketKey string 25 26 // NodeItem returns an item set in ServiceFunc function for a particualar node. 27 func (s *Simulation) NodeItem(id discover.NodeID, key interface{}) (value interface{}, ok bool) { 28 s.mu.Lock() 29 defer s.mu.Unlock() 30 31 if _, ok := s.buckets[id]; !ok { 32 return nil, false 33 } 34 return s.buckets[id].Load(key) 35 } 36 37 // SetNodeItem sets a new item associated with the node with provided NodeID. 38 // Buckets should be used to avoid managing separate simulation global state. 39 func (s *Simulation) SetNodeItem(id discover.NodeID, key interface{}, value interface{}) { 40 s.mu.Lock() 41 defer s.mu.Unlock() 42 43 s.buckets[id].Store(key, value) 44 } 45 46 // NodesItems returns a map of items from all nodes that are all set under the 47 // same BucketKey. 48 func (s *Simulation) NodesItems(key interface{}) (values map[discover.NodeID]interface{}) { 49 s.mu.RLock() 50 defer s.mu.RUnlock() 51 52 ids := s.NodeIDs() 53 values = make(map[discover.NodeID]interface{}, len(ids)) 54 for _, id := range ids { 55 if _, ok := s.buckets[id]; !ok { 56 continue 57 } 58 if v, ok := s.buckets[id].Load(key); ok { 59 values[id] = v 60 } 61 } 62 return values 63 } 64 65 // UpNodesItems returns a map of items with the same BucketKey from all nodes that are up. 66 func (s *Simulation) UpNodesItems(key interface{}) (values map[discover.NodeID]interface{}) { 67 s.mu.RLock() 68 defer s.mu.RUnlock() 69 70 ids := s.UpNodeIDs() 71 values = make(map[discover.NodeID]interface{}) 72 for _, id := range ids { 73 if _, ok := s.buckets[id]; !ok { 74 continue 75 } 76 if v, ok := s.buckets[id].Load(key); ok { 77 values[id] = v 78 } 79 } 80 return values 81 }