Skip to content

Commit

Permalink
optimize stream.Write
Browse files Browse the repository at this point in the history
  • Loading branch information
xtaci committed Sep 8, 2016
1 parent 88f1e7a commit f75ca5b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 11 deletions.
10 changes: 4 additions & 6 deletions session.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,12 +195,10 @@ func (s *Session) recvLoop() {
if _, ok := s.streams[f.sid]; !ok {
stream := newStream(f.sid, s.config.MaxFrameSize, s)
s.streams[f.sid] = stream
go func() {
select {
case s.chAccepts <- stream:
case <-s.die:
}
}()
select {
case s.chAccepts <- stream:
case <-s.die:
}
}
s.streamLock.Unlock()
case cmdRST:
Expand Down
18 changes: 13 additions & 5 deletions stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package smux

import (
"bytes"
"encoding/binary"
"sync"
"sync/atomic"

Expand Down Expand Up @@ -70,14 +71,21 @@ func (s *Stream) Write(b []byte) (n int, err error) {
}

frames := s.split(b, cmdPSH, s.id)
// combine the frames
var buffer bytes.Buffer
// preallocate buffer
buffer := make([]byte, len(frames)*headerSize+len(b))
bts := buffer

// combine frames into a large blob
for k := range frames {
bts, _ := frames[k].MarshalBinary()
buffer.Write(bts)
bts[0] = version
bts[1] = frames[k].cmd
binary.LittleEndian.PutUint16(bts[2:], uint16(len(frames[k].data)))
binary.LittleEndian.PutUint32(bts[4:], frames[k].sid)
copy(bts[headerSize:], frames[k].data)
bts = bts[len(frames[k].data)+headerSize:]
}

if _, err = s.sess.writeBinary(buffer.Bytes()); err != nil {
if _, err = s.sess.writeBinary(buffer); err != nil {
return 0, err
}
return len(b), nil
Expand Down

0 comments on commit f75ca5b

Please sign in to comment.