Source File
linkedbuffer.go
Belonging Package
github.com/alitto/pond/v2/internal/linkedbuffer
package linkedbufferimport ()// LinkedBuffer implements an unbounded generic buffer that can be written to and read from concurrently.// It is implemented using a linked list of buffers.type LinkedBuffer[ any] struct {// Reader points to the buffer that is currently being readreadBuffer *buffer[]// Writer points to the buffer that is currently being writtenwriteBuffer *buffer[]maxCapacity intwriteCount atomic.Uint64readCount atomic.Uint64}func [ any](, int) *LinkedBuffer[] {:= newBuffer[]():= &LinkedBuffer[]{readBuffer: ,writeBuffer: ,maxCapacity: ,}return}// Write writes values to the bufferfunc ( *LinkedBuffer[]) ( ) {// Write elements:= .writeBuffer.Write()if == ErrEOF {// Increase next buffer capacityvar int:= .writeBuffer.Cap()if < 1024 {= * 2} else {= + /2}if > .maxCapacity {= .maxCapacity}if .writeBuffer.next == nil {.writeBuffer.next = newBuffer[]().writeBuffer = .writeBuffer.next}// Retry writing.()return}// Increment written count.writeCount.Add(1)}// Read reads values from the buffer and returns the number of elements readfunc ( *LinkedBuffer[]) () ( , error) {// Read element, = .readBuffer.Read()if == ErrEOF {if .readBuffer.next == nil {// No more elements to readreturn}// Move to next read bufferif .readBuffer != .readBuffer.next {.readBuffer = .readBuffer.next}// Retry readingreturn .()}// Increment read count.readCount.Add(1)return}// WriteCount returns the number of elements written to the buffer since it was createdfunc ( *LinkedBuffer[]) () uint64 {return .writeCount.Load()}// ReadCount returns the number of elements read from the buffer since it was createdfunc ( *LinkedBuffer[]) () uint64 {return .readCount.Load()}// Len returns the number of elements in the buffer that haven't yet been readfunc ( *LinkedBuffer[]) () uint64 {:= .writeCount.Load():= .readCount.Load()if < {// The writeCount counter wrapped aroundreturn math.MaxUint64 - +}return -}
![]() |
The pages are generated with Golds v0.8.4. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |