github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/p2p/peer/addr/addrsrcs.go (about) 1 // Package addr provides utility functions to handle peer addresses. 2 package addr 3 4 import ( 5 ma "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr" 6 ) 7 8 // AddrSource is a source of addresses. It allows clients to retrieve 9 // a set of addresses at a last possible moment in time. It is used 10 // to query a set of addresses that may change over time, as a result 11 // of the network changing interfaces or mappings. 12 type Source interface { 13 Addrs() []ma.Multiaddr 14 } 15 16 // CombineSources returns a new AddrSource which is the 17 // concatenation of all input AddrSources: 18 // 19 // combined := CombinedSources(a, b) 20 // combined.Addrs() // append(a.Addrs(), b.Addrs()...) 21 // 22 func CombineSources(srcs ...Source) Source { 23 return combinedAS(srcs) 24 } 25 26 type combinedAS []Source 27 28 func (cas combinedAS) Addrs() []ma.Multiaddr { 29 var addrs []ma.Multiaddr 30 for _, s := range cas { 31 addrs = append(addrs, s.Addrs()...) 32 } 33 return addrs 34 } 35 36 // UniqueSource returns a new AddrSource which omits duplicate 37 // addresses from the inputs: 38 // 39 // unique := UniqueSource(a, b) 40 // unique.Addrs() // append(a.Addrs(), b.Addrs()...) 41 // // but only adds each addr once. 42 // 43 func UniqueSource(srcs ...Source) Source { 44 return uniqueAS(srcs) 45 } 46 47 type uniqueAS []Source 48 49 func (uas uniqueAS) Addrs() []ma.Multiaddr { 50 seen := make(map[string]struct{}) 51 var addrs []ma.Multiaddr 52 for _, s := range uas { 53 for _, a := range s.Addrs() { 54 s := a.String() 55 if _, found := seen[s]; !found { 56 addrs = append(addrs, a) 57 seen[s] = struct{}{} 58 } 59 } 60 } 61 return addrs 62 } 63 64 // Slice is a simple slice of addresses that implements 65 // the AddrSource interface. 66 type Slice []ma.Multiaddr 67 68 func (as Slice) Addrs() []ma.Multiaddr { 69 return as 70 }