@@ -44,38 +44,35 @@ func newBuffer(nc net.Conn) buffer {
4444}
4545
4646// swap replaces the active buffer with the background buffer
47+ // this is a delayed swap that simply increases the buffer counter;
48+ // the actual swap will be performed the next time we call `buffer.fill`
4749func (b * buffer ) swap () {
4850 b .dbufn += 1
49- dest := b .dbuf [b .dbufn & 1 ]
50- if b .length > 0 {
51- // existing buffer is too large for double-buffering;
52- // we must allocate a temporary buffer that will be discarded
53- if b .length > len (dest ) {
54- dest = make ([]byte , b .length )
55- }
56- copy (dest [0 :b .length ], b .buf [b .idx :])
57- }
58- b .buf = dest
59- b .idx = 0
6051}
6152
6253// fill reads into the buffer until at least _need_ bytes are in it
6354func (b * buffer ) fill (need int ) error {
6455 n := b .length
56+ // fill data into its double-buffering target: if we've called
57+ // swap on this buffer, we'll be copying to the background buffer,
58+ // and then filling it with network data; otherwise we'll just move
59+ // the contents of the current buffer to the front before filling it
60+ dest := b .dbuf [b .dbufn & 1 ]
6561
66- // move existing data to the beginning
67- if n > 0 && b .idx > 0 {
68- copy (b .buf [0 :n ], b .buf [b .idx :])
62+ // grow buffer if necessary to fit the whole packet.
63+ if need > len (dest ) {
64+ // Round up to the next multiple of the default size;
65+ // this buffer will be discarded the next time we swap buffers
66+ dest = make ([]byte , ((need / defaultBufSize )+ 1 )* defaultBufSize )
6967 }
7068
71- // grow buffer if necessary
72- if need > len (b .buf ) {
73- // Round up to the next multiple of the default size
74- newBuf := make ([]byte , ((need / defaultBufSize )+ 1 )* defaultBufSize )
75- copy (newBuf , b .buf )
76- b .buf = newBuf
69+ // if we're filling the fg buffer, move the existing data to the start of it.
70+ // if we're filling the bg buffer, copy over the data
71+ if n > 0 {
72+ copy (dest [0 :n ], b .buf [b .idx :])
7773 }
7874
75+ b .buf = dest
7976 b .idx = 0
8077
8178 for {
0 commit comments