1
1
mirror of https://github.com/walles/moar.git synced 2024-11-22 11:45:50 +03:00

Fix a race seen in CI

With go test -race. Wonder why I don't see it locally? Maybe -race works
better on Linux?
This commit is contained in:
Johan Walles 2024-11-06 19:50:33 +01:00
parent 8a8d9c3592
commit 6ef529a968

View File

@ -2,6 +2,7 @@ package m
import ( import (
"regexp" "regexp"
"sync"
"github.com/walles/moar/m/linenumbers" "github.com/walles/moar/m/linenumbers"
"github.com/walles/moar/m/textstyles" "github.com/walles/moar/m/textstyles"
@ -12,6 +13,7 @@ import (
type Line struct { type Line struct {
raw string raw string
plain *string plain *string
lock sync.Mutex
} }
// NewLine creates a new Line from a (potentially ANSI / man page formatted) string // NewLine creates a new Line from a (potentially ANSI / man page formatted) string
@ -19,6 +21,7 @@ func NewLine(raw string) Line {
return Line{ return Line{
raw: raw, raw: raw,
plain: nil, plain: nil,
lock: sync.Mutex{},
} }
} }
@ -56,8 +59,14 @@ func (line *Line) HighlightedTokens(linePrefix string, search *regexp.Regexp, li
// Plain returns a plain text representation of the initial string // Plain returns a plain text representation of the initial string
func (line *Line) Plain(lineNumber *linenumbers.LineNumber) string { func (line *Line) Plain(lineNumber *linenumbers.LineNumber) string {
line.lock.Lock()
defer line.lock.Unlock()
if line.plain == nil { if line.plain == nil {
line.lock.Unlock()
// The computation doesn't need the lock
plain := textstyles.WithoutFormatting(line.raw, lineNumber) plain := textstyles.WithoutFormatting(line.raw, lineNumber)
line.lock.Lock()
line.plain = &plain line.plain = &plain
} }
return *line.plain return *line.plain