swarm_stream.go 1.46 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package swarm

import (
Jeromy's avatar
Jeromy committed
4
	inet "github.com/libp2p/go-libp2p-net"
Jeromy's avatar
Jeromy committed
5
	protocol "github.com/libp2p/go-libp2p-protocol"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6

Jeromy's avatar
Jeromy committed
7
	ps "github.com/jbenet/go-peerstream"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8 9
)

10
// Stream is a wrapper around a ps.Stream that exposes a way to get
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11
// our Conn and Swarm (instead of just the ps.Conn and ps.Swarm)
12 13
type Stream struct {
	stream   *ps.Stream
14
	protocol protocol.ID
15
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
16 17 18

// Stream returns the underlying peerstream.Stream
func (s *Stream) Stream() *ps.Stream {
19
	return s.stream
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20 21 22 23 24 25 26 27 28
}

// Conn returns the Conn associated with this Stream, as an inet.Conn
func (s *Stream) Conn() inet.Conn {
	return s.SwarmConn()
}

// SwarmConn returns the Conn associated with this Stream, as a *Conn
func (s *Stream) SwarmConn() *Conn {
29
	return (*Conn)(s.stream.Conn())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
30 31 32 33
}

// Read reads bytes from a stream.
func (s *Stream) Read(p []byte) (n int, err error) {
34
	return s.stream.Read(p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
35 36 37 38
}

// Write writes bytes to a stream, flushing for each call.
func (s *Stream) Write(p []byte) (n int, err error) {
39
	return s.stream.Write(p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
40 41 42 43 44
}

// Close closes the stream, indicating this side is finished
// with the stream.
func (s *Stream) Close() error {
45 46 47
	return s.stream.Close()
}

48
func (s *Stream) Protocol() protocol.ID {
49 50 51
	return s.protocol
}

52
func (s *Stream) SetProtocol(p protocol.ID) {
53
	s.protocol = p
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
54 55 56
}

func wrapStream(pss *ps.Stream) *Stream {
57 58 59
	return &Stream{
		stream: pss,
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
60 61 62 63 64 65 66 67 68
}

func wrapStreams(st []*ps.Stream) []*Stream {
	out := make([]*Stream, len(st))
	for i, s := range st {
		out[i] = wrapStream(s)
	}
	return out
}