generated from okp4/template-oss
-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(logic): add bounded buffer utility
- Loading branch information
Showing
1 changed file
with
75 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
package util | ||
|
||
import ( | ||
"fmt" | ||
"io" | ||
) | ||
|
||
var ( | ||
_ = io.Writer(&BoundedBuffer{}) | ||
) | ||
|
||
var ( | ||
ErrInvalidSize = func(size int) error { | ||
return fmt.Errorf("invalid buffer size %d", size) | ||
} | ||
) | ||
|
||
// BoundedBuffer is a fixed size buffer that overwrites older data when the buffer is full. | ||
type BoundedBuffer struct { | ||
buf []byte | ||
offset int | ||
size int | ||
overflown bool | ||
} | ||
|
||
// NewBoundedBuffer creates a new BoundedBuffer with the given fixed size. | ||
// If size is 0, the buffer will be disabled. | ||
func NewBoundedBuffer(size int) (*BoundedBuffer, error) { | ||
if size < 0 { | ||
return nil, ErrInvalidSize(size) | ||
} | ||
|
||
return &BoundedBuffer{ | ||
buf: make([]byte, size), | ||
size: size, | ||
}, nil | ||
} | ||
|
||
// NewBoundedBufferMust is like NewBoundedBuffer but panics if an error occurs. | ||
func NewBoundedBufferMust(size int) *BoundedBuffer { | ||
b, err := NewBoundedBuffer(size) | ||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
return b | ||
} | ||
|
||
// Write implements io.Writer. | ||
func (b *BoundedBuffer) Write(p []byte) (n int, err error) { | ||
size := len(p) | ||
|
||
if b.size == 0 { | ||
return size, nil | ||
} | ||
|
||
for i := 0; i < size; i++ { | ||
b.buf[b.offset] = p[i] | ||
b.offset = (b.offset + 1) % b.size | ||
b.overflown = b.overflown || b.offset == 0 | ||
} | ||
|
||
return size, nil | ||
} | ||
|
||
// String returns the contents of the buffer as a string. | ||
func (b *BoundedBuffer) String() string { | ||
if b.overflown { | ||
r := string(b.buf[b.offset:]) + string(b.buf[:b.offset]) | ||
|
||
return r | ||
} | ||
|
||
return string(b.buf[:b.offset]) | ||
} |