DevilKing's blog

冷灯看剑,剑上几分功名?炉香无需计苍生,纵一穿烟逝,万丈云埋,孤阳还照古陵

0%

RingBuffer

原repo

定义read pointer/write pointer部分

1
2
3
4
5
6
7
8
type RingBuffer struct {
buf []byte
size int
r int // next position to read
w int // next position to write
isFull bool
mu sync.Mutex
}

read部分:

  • Read reads up to len(p) bytes into p. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. Even if Read returns n < len(p), it may use all of p as scratch space during the call. If some data is available but not len(p) bytes, Read conventionally returns what is available instead of waiting for more.
  • When Read encounters an error or end-of-file condition after successfully reading n > 0 bytes, it returns the number of bytes read. It may return the (non-nil) error from the same call or return the error (and n == 0) from a subsequent call.
  • Callers should always process the n > 0 bytes returned before considering the error err. Doing so correctly handles I/O errors that happen after reading some bytes and also both of the allowed EOF behaviors

write部分:

  • Write writes len(p) bytes from p to the underlying buf.It returns the number of bytes written from p (0 <= n <= len(p)) and any error encountered that caused the write to stop early.Write returns a non-nil error if it returns n < len(p).
  • Write must not modify the slice data, even temporarily.