github.com/uber/kraken@v0.1.4/core/peer_info.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 core
    15  
    16  import "sort"
    17  
    18  // PeerInfo defines peer metadata scoped to a torrent.
    19  type PeerInfo struct {
    20  	PeerID   PeerID `json:"peer_id"`
    21  	IP       string `json:"ip"`
    22  	Port     int    `json:"port"`
    23  	Origin   bool   `json:"origin"`
    24  	Complete bool   `json:"complete"`
    25  }
    26  
    27  // NewPeerInfo creates a new PeerInfo.
    28  func NewPeerInfo(
    29  	peerID PeerID,
    30  	ip string,
    31  	port int,
    32  	origin bool,
    33  	complete bool) *PeerInfo {
    34  
    35  	return &PeerInfo{
    36  		PeerID:   peerID,
    37  		IP:       ip,
    38  		Port:     port,
    39  		Origin:   origin,
    40  		Complete: complete,
    41  	}
    42  }
    43  
    44  // PeerInfoFromContext derives PeerInfo from a PeerContext.
    45  func PeerInfoFromContext(pctx PeerContext, complete bool) *PeerInfo {
    46  	return NewPeerInfo(pctx.PeerID, pctx.IP, pctx.Port, pctx.Origin, complete)
    47  }
    48  
    49  // PeerInfos groups PeerInfo structs for sorting.
    50  type PeerInfos []*PeerInfo
    51  
    52  // Len for sorting.
    53  func (s PeerInfos) Len() int { return len(s) }
    54  
    55  // Swap for sorting
    56  func (s PeerInfos) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
    57  
    58  // PeersByPeerID sorts PeerInfos by peer id.
    59  type PeersByPeerID struct{ PeerInfos }
    60  
    61  // Less for sorting.
    62  func (s PeersByPeerID) Less(i, j int) bool {
    63  	return s.PeerInfos[i].PeerID.LessThan(s.PeerInfos[j].PeerID)
    64  }
    65  
    66  // SortedByPeerID returns a copy of peers which has been sorted by peer id.
    67  func SortedByPeerID(peers []*PeerInfo) []*PeerInfo {
    68  	c := make([]*PeerInfo, len(peers))
    69  	copy(c, peers)
    70  	sort.Sort(PeersByPeerID{PeerInfos(c)})
    71  	return c
    72  }