-
Notifications
You must be signed in to change notification settings - Fork 4
/
ma-stdio.go
103 lines (84 loc) · 2.06 KB
/
ma-stdio.go
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package mapipe
import (
"errors"
"io"
"net"
"os"
"time"
ma "github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr/net"
)
var (
StdioMultiaddr = ma.StringCast("/unix/stdio")
ProcStdioListener = StdioListener{}
ProcStdioConn = IOConn{
R: os.Stdin,
W: os.Stdout,
LAddr: StdioMultiaddr,
RAddr: StdioMultiaddr,
}
)
func Listen(a ma.Multiaddr) (manet.Listener, error) {
if StdioMultiaddr.Equal(a) {
return &ProcStdioListener, nil
}
return manet.Listen(a)
}
func Dial(a ma.Multiaddr) (manet.Conn, error) {
if StdioMultiaddr.Equal(a) {
return &ProcStdioConn, nil
}
return manet.Dial(a)
}
type StdioListener struct {
accepted bool // can only accept once
conn IOConn
}
func (sl *StdioListener) NetListener() net.Listener {
return nil
}
func (sl *StdioListener) Accept() (manet.Conn, error) {
if sl.accepted {
return nil, errors.New("no more connections")
}
sl.conn = ProcStdioConn
sl.accepted = true
return &sl.conn, nil
}
func (sl *StdioListener) Close() error {
return nil
}
func (sl *StdioListener) Multiaddr() ma.Multiaddr {
return StdioMultiaddr
}
func (sl *StdioListener) Addr() net.Addr {
return nil
}
type IOConn struct {
R io.Reader
W io.Writer
LAddr ma.Multiaddr
RAddr ma.Multiaddr
}
func (c *IOConn) Read(b []byte) (n int, err error) {
return c.R.Read(b)
}
func (c *IOConn) Write(b []byte) (n int, err error) {
return c.W.Write(b)
}
func (c *IOConn) Close() (err error) {
if rc, ok := c.R.(io.Closer); ok {
err = rc.Close()
}
if wc, ok := c.W.(io.Closer); ok {
err = wc.Close()
}
return
}
func (c *IOConn) LocalAddr() net.Addr { return nil }
func (c *IOConn) RemoteAddr() net.Addr { return nil }
func (c *IOConn) SetDeadline(t time.Time) error { return nil }
func (c *IOConn) SetReadDeadline(t time.Time) error { return nil }
func (c *IOConn) SetWriteDeadline(t time.Time) error { return nil }
func (c *IOConn) LocalMultiaddr() ma.Multiaddr { return c.LAddr }
func (c *IOConn) RemoteMultiaddr() ma.Multiaddr { return c.RAddr }