| 72 | } |
| 73 | |
| 74 | func (e *encoder) WriteString(s string) (int, error) { |
| 75 | // This implementation is an optimization to avoid the heap allocation that |
| 76 | // would occur when converting the string to a []byte to call crc32.Update. |
| 77 | // |
| 78 | // Strings are rarely long in the kafka protocol, so the use of a 32 byte |
| 79 | // buffer is a good comprise between keeping the encoder value small and |
| 80 | // limiting the number of calls to Write. |
| 81 | // |
| 82 | // We introduced this optimization because memory profiles on the benchmarks |
| 83 | // showed that most heap allocations were caused by this code path. |
| 84 | n := 0 |
| 85 | |
| 86 | for len(s) != 0 { |
| 87 | c := copy(e.buffer[:], s) |
| 88 | w, err := e.Write(e.buffer[:c]) |
| 89 | n += w |
| 90 | if err != nil { |
| 91 | return n, err |
| 92 | } |
| 93 | s = s[c:] |
| 94 | } |
| 95 | |
| 96 | return n, nil |
| 97 | } |
| 98 | |
| 99 | func (e *encoder) setCRC(table *crc32.Table) { |
| 100 | e.table, e.crc32 = table, 0 |