2
0
mirror of https://github.com/soheilhy/cmux.git synced 2024-09-20 02:55:46 +08:00

Require two Read calls to get EOF

This is maybe slightly less efficient, but it is easier to reason
about, and seems to be the style in which most of the standard library
is written. For instance, bytes.Buffer behaves this way.
This commit is contained in:
Tamir Duberstein 2016-02-25 22:02:00 -05:00
parent 36dc9894b6
commit 69ab4c207f
2 changed files with 16 additions and 16 deletions

14
cmux.go
View File

@ -197,19 +197,11 @@ func newMuxConn(c net.Conn) *MuxConn {
// a non-zero number of bytes at the end of the input stream may // a non-zero number of bytes at the end of the input stream may
// return either err == EOF or err == nil. The next Read should // return either err == EOF or err == nil. The next Read should
// return 0, EOF. // return 0, EOF.
//
// This function implements the latter behaviour, returning the
// (non-nil) error from the same call.
func (m *MuxConn) Read(p []byte) (int, error) { func (m *MuxConn) Read(p []byte) (int, error) {
n1, err := m.buf.Read(p) if n, err := m.buf.Read(p); err != io.EOF {
if err == nil && m.buf.Len() == 0 { return n, err
err = io.EOF
} }
if n1 == len(p) || err != io.EOF { return m.Conn.Read(p)
return n1, err
}
n2, err := m.Conn.Read(p[n1:])
return n1 + n2, err
} }
func (m *MuxConn) getSniffer() io.Reader { func (m *MuxConn) getSniffer() io.Reader {

View File

@ -278,12 +278,20 @@ func TestHTTP2(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
var b [len(http2.ClientPreface)]byte {
if _, err := muxedConn.Read(b[:]); err != io.EOF { var b [len(http2.ClientPreface)]byte
t.Fatal(err) if _, err := muxedConn.Read(b[:]); err != nil {
t.Fatal(err)
}
if string(b[:]) != http2.ClientPreface {
t.Errorf("got unexpected read %s, expected %s", b, http2.ClientPreface)
}
} }
if string(b[:]) != http2.ClientPreface { {
t.Errorf("got unexpected read %s, expected %s", b, http2.ClientPreface) var b [1]byte
if _, err := muxedConn.Read(b[:]); err != io.EOF {
t.Errorf("unexpected error %v, expected %v", err, io.EOF)
}
} }
} }