Improve LogMonitor to handle empty writes and ensure buffer immutability

- Add a check to return immediately if the write buffer is empty
- Create a copy of new history data to ensure it is immutable
- Update the `GetHistory` method to use the `any` type for the buffer interface
- Add a test case to verify that the buffer remains unchanged
  even if the original message is modified after writing
This commit is contained in:
Benson Wong
2024-11-02 10:41:23 -07:00
parent f45469f7ff
commit 63d4a7d0eb
2 changed files with 40 additions and 2 deletions

View File

@@ -30,13 +30,19 @@ func NewLogMonitorWriter(stdout io.Writer) *LogMonitor {
}
func (w *LogMonitor) Write(p []byte) (n int, err error) {
if len(p) == 0 {
return 0, nil
}
n, err = w.stdout.Write(p)
if err != nil {
return n, err
}
w.bufferMu.Lock()
w.buffer.Value = p
bufferCopy := make([]byte, len(p))
copy(bufferCopy, p)
w.buffer.Value = bufferCopy
w.buffer = w.buffer.Next()
w.bufferMu.Unlock()
@@ -49,7 +55,7 @@ func (w *LogMonitor) GetHistory() []byte {
defer w.bufferMu.RUnlock()
var history []byte
w.buffer.Do(func(p interface{}) {
w.buffer.Do(func(p any) {
if p != nil {
if content, ok := p.([]byte); ok {
history = append(history, content...)