Skip to content

Commit

Permalink
add Reset function to MemoryWriter (#99)
Browse files Browse the repository at this point in the history
Since the MemoryWriter was updated to address race conditions, access to the
slice is now private, so it cannot be replaced with an empty slice when you
want to reset it. This is done in the spectator-go-runtime-metrics library,
and may be done in other places.

This change adds a Reset function to the MemoryWriter, which can be used to
reset the storage to an empty slice.
  • Loading branch information
copperlight authored Jun 4, 2024
1 parent a361950 commit 9a2b37c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
6 changes: 6 additions & 0 deletions spectator/writer/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ func (m *MemoryWriter) Lines() []string {
return slices.Clone(m.lines)
}

func (m *MemoryWriter) Reset() {
m.mu.Lock()
defer m.mu.Unlock()
m.lines = []string{}
}

func (m *MemoryWriter) Close() error {
return nil
}
Expand Down
28 changes: 28 additions & 0 deletions spectator/writer/writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,31 @@ func TestMemoryWriter_Write(t *testing.T) {
t.Errorf("expected 10000 lines written to writer but found %d", linesWritten)
}
}

func TestMemoryWriter_Reset(t *testing.T) {
w, err := NewWriter("memory", logger.NewDefaultLogger())
if err != nil {
t.Errorf("failed to create writer: %s", err)
}
mw := w.(*MemoryWriter)

linesLength := len(mw.Lines())
if linesLength != 0 {
t.Errorf("expected 0 lines written to writer but found %d", linesLength)
}

mw.Write("")
mw.Write("")

linesLength = len(mw.Lines())
if linesLength != 2 {
t.Errorf("expected 2 lines written to writer but found %d", linesLength)
}

mw.Reset()

linesLength = len(mw.Lines())
if linesLength != 0 {
t.Errorf("expected 0 lines written to writer but found %d", linesLength)
}
}

0 comments on commit 9a2b37c

Please sign in to comment.