@@ -44,38 +44,35 @@ func newBuffer(nc net.Conn) buffer {
44
44
}
45
45
46
46
// 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`
47
49
func (b * buffer ) swap () {
48
50
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
60
51
}
61
52
62
53
// fill reads into the buffer until at least _need_ bytes are in it
63
54
func (b * buffer ) fill (need int ) error {
64
55
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 ]
65
61
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 )
69
67
}
70
68
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 :])
77
73
}
78
74
75
+ b .buf = dest
79
76
b .idx = 0
80
77
81
78
for {
0 commit comments