github.com/tenywen/fabric@v1.0.0-beta.0.20170620030522-a5b1ed380643/gossip/util/msgs.go (about)

     1  /*
     2  Copyright IBM Corp. 2017 All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  		 http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package util
    18  
    19  import (
    20  	"sync"
    21  
    22  	"github.com/hyperledger/fabric/gossip/common"
    23  	proto "github.com/hyperledger/fabric/protos/gossip"
    24  )
    25  
    26  // MembershipStore struct which encapsulates
    27  // membership message store abstraction
    28  type MembershipStore struct {
    29  	m map[string]*proto.SignedGossipMessage
    30  	sync.RWMutex
    31  }
    32  
    33  // NewMembershipStore creates new membership store instance
    34  func NewMembershipStore() *MembershipStore {
    35  	return &MembershipStore{m: make(map[string]*proto.SignedGossipMessage)}
    36  }
    37  
    38  // MsgByID returns a message stored by a certain ID, or nil
    39  // if such an ID isn't found
    40  func (m *MembershipStore) MsgByID(pkiID common.PKIidType) *proto.SignedGossipMessage {
    41  	m.RLock()
    42  	defer m.RUnlock()
    43  	if msg, exists := m.m[string(pkiID)]; exists {
    44  		return msg
    45  	}
    46  	return nil
    47  }
    48  
    49  // Size of the membership store
    50  func (m *MembershipStore) Size() int {
    51  	m.RLock()
    52  	defer m.RUnlock()
    53  	return len(m.m)
    54  }
    55  
    56  // Put associates msg with the given pkiID
    57  func (m *MembershipStore) Put(pkiID common.PKIidType, msg *proto.SignedGossipMessage) {
    58  	m.Lock()
    59  	defer m.Unlock()
    60  	m.m[string(pkiID)] = msg
    61  }
    62  
    63  // Remove removes a message with a given pkiID
    64  func (m *MembershipStore) Remove(pkiID common.PKIidType) {
    65  	m.Lock()
    66  	defer m.Unlock()
    67  	delete(m.m, string(pkiID))
    68  }
    69  
    70  // ToSlice returns a slice backed by the elements
    71  // of the MembershipStore
    72  func (m *MembershipStore) ToSlice() []*proto.SignedGossipMessage {
    73  	m.RLock()
    74  	defer m.RUnlock()
    75  	members := make([]*proto.SignedGossipMessage, len(m.m))
    76  	i := 0
    77  	for _, member := range m.m {
    78  		members[i] = member
    79  		i++
    80  	}
    81  	return members
    82  }