mirror of https://github.com/tidwall/evio.git
reuse buffer option, closes #14
This commit is contained in:
parent
703dc170d8
commit
2856314c8f
5
evio.go
5
evio.go
|
@ -30,6 +30,11 @@ const (
|
|||
type Options struct {
|
||||
// TCPKeepAlive (SO_KEEPALIVE) socket option.
|
||||
TCPKeepAlive time.Duration
|
||||
// ReusePacketBuffer will force the connection to share and reuse the
|
||||
// input packet buffer with all connections that also use this option.
|
||||
// Default value is false, which means that all input data passed to the
|
||||
// Data event will be a uniquely copied []byte slice.
|
||||
ReusePacketBuffer bool
|
||||
}
|
||||
|
||||
// Info represents a information about the connection
|
||||
|
|
13
evio_loop.go
13
evio_loop.go
|
@ -524,8 +524,13 @@ func serve(events Events, lns []*listener) error {
|
|||
}
|
||||
if c.action == None {
|
||||
if events.Data != nil {
|
||||
if c.opts.ReusePacketBuffer {
|
||||
in = packet[:n]
|
||||
} else {
|
||||
in = append([]byte{}, packet[:n]...)
|
||||
}
|
||||
unlock()
|
||||
out, c.action = events.Data(c.id, append([]byte{}, packet[:n]...))
|
||||
out, c.action = events.Data(c.id, in)
|
||||
lock()
|
||||
if len(out) > 0 {
|
||||
if events.Prewrite != nil {
|
||||
|
@ -580,7 +585,11 @@ func serve(events Events, lns []*listener) error {
|
|||
c.err = err
|
||||
goto close
|
||||
}
|
||||
in = append([]byte{}, packet[:n]...)
|
||||
if c.opts.ReusePacketBuffer {
|
||||
in = packet[:n]
|
||||
} else {
|
||||
in = append([]byte{}, packet[:n]...)
|
||||
}
|
||||
}
|
||||
if events.Data != nil {
|
||||
unlock()
|
||||
|
|
37
evio_test.go
37
evio_test.go
|
@ -727,3 +727,40 @@ func testTranslate(network, addr string, kind string, stdlib bool) {
|
|||
// kind = "tcp6"
|
||||
// must(Serve(events, "tcp6://:9991"))
|
||||
// }
|
||||
|
||||
func TestReuseBuffer(t *testing.T) {
|
||||
reuses := []bool{true, false}
|
||||
for _, reuse := range reuses {
|
||||
var events Events
|
||||
events.Opened = func(id int, info Info) (out []byte, opts Options, action Action) {
|
||||
opts.ReusePacketBuffer = reuse
|
||||
return
|
||||
}
|
||||
var prev []byte
|
||||
events.Data = func(id int, in []byte) (out []byte, action Action) {
|
||||
if prev == nil {
|
||||
prev = in
|
||||
} else {
|
||||
reused := string(in) == string(prev)
|
||||
if reused != reuse {
|
||||
t.Fatalf("expected %v, got %v", reuse, reused)
|
||||
}
|
||||
action = Shutdown
|
||||
}
|
||||
return
|
||||
}
|
||||
events.Serving = func(_ Server) (action Action) {
|
||||
go func() {
|
||||
c, err := net.Dial("tcp", ":9991")
|
||||
must(err)
|
||||
defer c.Close()
|
||||
c.Write([]byte("packet1"))
|
||||
time.Sleep(time.Second / 5)
|
||||
c.Write([]byte("packet2"))
|
||||
}()
|
||||
return
|
||||
}
|
||||
must(Serve(events, "tcp://:9991"))
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue