Write implements io.Writer. It is safe for concurrent use. All bytes are accepted; the return value always equals len(p) with a nil error.
(p []byte)
| 78 | // All bytes are accepted; the return value always equals |
| 79 | // len(p) with a nil error. |
| 80 | func (b *HeadTailBuffer) Write(p []byte) (int, error) { |
| 81 | if len(p) == 0 { |
| 82 | return 0, nil |
| 83 | } |
| 84 | |
| 85 | b.mu.Lock() |
| 86 | defer b.mu.Unlock() |
| 87 | |
| 88 | n := len(p) |
| 89 | b.totalBytes += n |
| 90 | |
| 91 | // Fill head buffer if it is not yet full. |
| 92 | if !b.headFull { |
| 93 | remaining := b.maxHead - len(b.head) |
| 94 | if remaining > 0 { |
| 95 | take := remaining |
| 96 | if take > len(p) { |
| 97 | take = len(p) |
| 98 | } |
| 99 | b.head = append(b.head, p[:take]...) |
| 100 | p = p[take:] |
| 101 | if len(b.head) >= b.maxHead { |
| 102 | b.headFull = true |
| 103 | } |
| 104 | } |
| 105 | if len(p) == 0 { |
| 106 | return n, nil |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | // Write remaining bytes into the tail ring buffer. |
| 111 | b.writeTail(p) |
| 112 | return n, nil |
| 113 | } |
| 114 | |
| 115 | // writeTail appends data to the tail ring buffer. The caller |
| 116 | // must hold b.mu. |