Slight memory usage reduction

This commit is contained in:
2026-07-01 10:12:07 +01:00
parent 34f14e8dc0
commit c185289c74
4 changed files with 41 additions and 30 deletions
+10 -8
View File
@@ -1,11 +1,11 @@
package mockserver
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"os"
"strings"
"sync"
"time"
@@ -77,26 +77,28 @@ func (r *Recorder) record(ctx context.Context) {
}
func (r *Recorder) view(ctx context.Context) {
var s strings.Builder
var buf bytes.Buffer
var nBytes int
buf.Grow(2048)
for {
select {
case <-ctx.Done():
return
case viewData := <-r.viewCh:
s.Reset()
fmt.Fprintf(os.Stdout, "\x1b[2J\x1b[H")
buf.Reset()
buf.WriteString("\x1b[2J\x1b[H")
stringifyRecordingProgress(&s, nBytes)
fmt.Fprintf(&s, "\n\n")
stringifyRecordingProgress(&buf, nBytes)
fmt.Fprintf(&buf, "\n\n")
r.viewDataMut.RLock()
nBytes = viewData.TotalBytes
stringifyOutgaugeData(&s, &r.SDK)
stringifyOutgaugeData(&buf, &r.SDK)
r.viewDataMut.RUnlock()
fmt.Fprint(os.Stdout, s.String())
_, _ = buf.WriteTo(os.Stdout)
}
}
}
+10 -10
View File
@@ -9,7 +9,6 @@ import (
"fmt"
"io"
"os"
"strings"
"sync"
"time"
"unsafe"
@@ -69,33 +68,34 @@ func (r *Replayer) renderToTerminal(ctx context.Context) {
// return fmt.Errorf("error stating file: %v", err)
}
// NOTE: temporary until I make a better view
var s strings.Builder
var buf bytes.Buffer
var bytesReader bytes.Reader
buf.Grow(2048)
for {
select {
case <-ctx.Done():
return
case data := <-r.dataViewCh:
// Reset to the start of the terminal
s.Reset()
fmt.Fprintf(os.Stdout, "\x1b[2J\x1b[H")
buf.Reset()
buf.WriteString("\x1b[2J\x1b[H")
bytesReader.Reset(data.SDK.Buffer)
err := binary.Read(&bytesReader, binary.LittleEndian, r.SDK.Data)
if err != nil {
fmt.Fprintf(&s, "FAILED TO PARSE DATA\nError: %+v", err)
fmt.Fprint(os.Stdout, s.String())
fmt.Fprintf(&buf, "FAILED TO PARSE DATA\nError: %+v", err)
_, _ = buf.WriteTo(os.Stdout)
continue
}
percent := int(float64(data.SizeRead) / float64(fileInfo.Size()) * 100)
fmt.Fprintf(&s, "Replayed: %d%%\n", percent)
fmt.Fprintf(&buf, "Replayed: %d%%\n", percent)
stringifyOutgaugeData(&s, data.SDK)
stringifyOutgaugeData(&buf, data.SDK)
fmt.Fprint(os.Stdout, s.String())
buf.WriteTo(os.Stdout)
}
}
}
+3 -3
View File
@@ -1,8 +1,8 @@
package mockserver
import (
"bytes"
"fmt"
"strings"
bngsdk "github.com/ESilva15/gobngsdk"
)
@@ -14,7 +14,7 @@ const (
GiB
)
func stringifyRecordingProgress(s *strings.Builder, nBytes int) {
func stringifyRecordingProgress(s *bytes.Buffer, nBytes int) {
if nBytes < KiB {
fmt.Fprintf(s, "%d B", nBytes)
} else if nBytes < MiB {
@@ -26,7 +26,7 @@ func stringifyRecordingProgress(s *strings.Builder, nBytes int) {
}
}
func stringifyOutgaugeData(s *strings.Builder, sdk *bngsdk.BeamNGSDK) {
func stringifyOutgaugeData(s *bytes.Buffer, sdk *bngsdk.BeamNGSDK) {
// NOTE: write a string serialization function on the SDK itself
fmt.Fprint(s, "Outgauge {\n")
fmt.Fprintf(s, " Time: %d ms\n", sdk.Data.Time)