reuse buffer option, closes #14

This commit is contained in:
Josh Baker 2017-12-21 12:25:33 -07:00
parent 703dc170d8
commit 2856314c8f
3 changed files with 53 additions and 2 deletions

View File

@ -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

View File

@ -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()

View File

@ -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"))
}
}