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

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

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

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

// Stream returns the underlying peerstream.Stream
func (s *Stream) Stream() *ps.Stream {
18
	return s.stream
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
19
20
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
21
22
23
24
25
26
27
// 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 {
28
	return (*Conn)(s.stream.Conn())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
29
30
31
32
}

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

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

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

func (s *Stream) Protocol() string {
	return s.protocol
}

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

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

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