Skip to content

Commit

Permalink
Merge pull request #967 from go-kivik/collateMutext
Browse files Browse the repository at this point in the history
Protect collator with a mutex
  • Loading branch information
flimzy committed May 10, 2024
2 parents a680e92 + 311b40f commit aa1978d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
11 changes: 9 additions & 2 deletions x/sqlite/collation.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,16 @@ import (
"slices"
"sort"
"strconv"
"sync"

"golang.org/x/text/collate"
"golang.org/x/text/language"
)

var collator = collate.New(language.Und)
var (
collatorMu = new(sync.Mutex)
collator = collate.New(language.Und)
)

func couchdbCmpString(a, b string) int {
return couchdbCmpJSON(json.RawMessage(a), json.RawMessage(b))
Expand Down Expand Up @@ -79,7 +83,10 @@ func couchdbCmpJSON(a, b json.RawMessage) int {
if bt != jsTypeString {
return -1
}
return collator.CompareString(string(a), string(b))
collatorMu.Lock()
cmp := collator.CompareString(string(a), string(b))
collatorMu.Unlock()
return cmp
case bt == jsTypeString:
return 1

Expand Down
6 changes: 6 additions & 0 deletions x/sqlite/collation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,9 @@ func Test_couchdbCmp(t *testing.T) {
})
}
}

// This test triggers the race detector if the collator isn't protected
func Test_collator_race(*testing.T) {
go couchdbCmpJSON(json.RawMessage(`"a"`), json.RawMessage(`"b"`))
go couchdbCmpJSON(json.RawMessage(`"a"`), json.RawMessage(`"b"`))
}

0 comments on commit aa1978d

Please sign in to comment.