github.com/uber/kraken@v0.1.4/tracker/peerstore/testing.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 peerstore
    15  
    16  import (
    17  	"errors"
    18  	"sync"
    19  
    20  	"github.com/uber/kraken/core"
    21  )
    22  
    23  type testStore struct {
    24  	sync.Mutex
    25  	torrents map[core.InfoHash][]core.PeerInfo
    26  }
    27  
    28  // TestStore returns a thread-safe, in-memory peer store for testing purposes.
    29  func NewTestStore() Store {
    30  	return &testStore{
    31  		torrents: make(map[core.InfoHash][]core.PeerInfo),
    32  	}
    33  }
    34  
    35  func (s *testStore) UpdatePeer(h core.InfoHash, p *core.PeerInfo) error {
    36  	s.Lock()
    37  	defer s.Unlock()
    38  
    39  	peers, ok := s.torrents[h]
    40  	if !ok {
    41  		s.torrents[h] = []core.PeerInfo{*p}
    42  		return nil
    43  	}
    44  	for i := range peers {
    45  		if p.PeerID == peers[i].PeerID {
    46  			peers[i] = *p
    47  			return nil
    48  		}
    49  	}
    50  	s.torrents[h] = append(peers, *p)
    51  	return nil
    52  }
    53  
    54  func (s *testStore) GetPeers(h core.InfoHash, n int) ([]*core.PeerInfo, error) {
    55  	s.Lock()
    56  	defer s.Unlock()
    57  
    58  	peers, ok := s.torrents[h]
    59  	if !ok {
    60  		return nil, errors.New("no peers found for info hash")
    61  	}
    62  	copies := make([]*core.PeerInfo, len(peers))
    63  	for i, p := range peers {
    64  		copies[i] = new(core.PeerInfo)
    65  		*copies[i] = p
    66  	}
    67  	return copies, nil
    68  }