Ver código fonte

collate.Collator is not goroutine safe

Dmitry Panov 6 anos atrás
pai
commit
e12d52a0a7
2 arquivos alterados com 12 adições e 4 exclusões
  1. 9 4
      builtin_string.go
  2. 3 0
      runtime.go

+ 9 - 4
builtin_string.go

@@ -11,9 +11,14 @@ import (
 	"unicode/utf8"
 )
 
-var (
-	collator = collate.New(language.Und)
-)
+func (r *Runtime) collator() *collate.Collator {
+	collator := r._collator
+	if collator == nil {
+		collator = collate.New(language.Und)
+		r._collator = collator
+	}
+	return collator
+}
 
 func (r *Runtime) builtin_String(call FunctionCall) Value {
 	if len(call.Arguments) > 0 {
@@ -216,7 +221,7 @@ func (r *Runtime) stringproto_localeCompare(call FunctionCall) Value {
 	r.checkObjectCoercible(call.This)
 	this := norm.NFD.String(call.This.String())
 	that := norm.NFD.String(call.Argument(0).String())
-	return intToValue(int64(collator.CompareString(this, that)))
+	return intToValue(int64(r.collator().CompareString(this, that)))
 }
 
 func (r *Runtime) stringproto_match(call FunctionCall) Value {

+ 3 - 0
runtime.go

@@ -10,6 +10,8 @@ import (
 	"reflect"
 	"strconv"
 
+	"golang.org/x/text/collate"
+
 	js_ast "github.com/dop251/goja/ast"
 	"github.com/dop251/goja/parser"
 )
@@ -98,6 +100,7 @@ type Runtime struct {
 	globalObject    *Object
 	stringSingleton *stringObject
 	rand            RandSource
+	_collator       *collate.Collator
 
 	typeInfoCache   map[reflect.Type]*reflectTypeInfo
 	fieldNameMapper FieldNameMapper