sockets.go 1.38 KB
Newer Older
Steven Allen's avatar
Steven Allen committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
package sockets

import (
	"sync"

	manet "github.com/multiformats/go-multiaddr-net"
)

var (
	mu          sync.Mutex
	initFn      = func() {}
	initialized = false
	listeners   = make(map[string][]manet.Listener)
	packetConns = make(map[string][]manet.PacketConn)
)

func initialize() {
	if !initialized {
		initFn()
		initialized = true
	}
}

// TakeSockets takes the listeners associated with the given name.
func TakeListeners(name string) ([]manet.Listener, error) {
	mu.Lock()
	defer mu.Unlock()
	initialize()

	s := listeners[name]
	delete(listeners, name)

	return s, nil
}

// ListListeners lists the names of the available listeners.
func ListListeners() ([]string, error) {
	mu.Lock()
	defer mu.Unlock()
	initialize()

	names := make([]string, 0, len(listeners))
	for name := range listeners {
		names = append(names, name)
	}
	return names, nil
}

// TakePacketConns takes the packet connections associated with the given name.
func TakePacketConns(name string) ([]manet.PacketConn, error) {
	mu.Lock()
	defer mu.Unlock()
	initialize()

	s := packetConns[name]
	delete(packetConns, name)

	return s, nil
}

// ListListeners lists the names of the available packet connections.
func ListPacketConns() ([]string, error) {
	mu.Lock()
	defer mu.Unlock()
	initialize()

	names := make([]string, 0, len(packetConns))
	for name := range packetConns {
		names = append(names, name)
	}
	return names, nil
}