1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
11 "golang.org/x/text/collate"
12 "golang.org/x/text/language"
15 // Input holds an input string in both UTF-8 and UTF-16 format.
17 index int // used for restoring to original random order
20 key []byte // used for sorting
23 func (i Input) String() string {
27 func makeInput(s8 []byte, s16 []uint16) Input {
28 return Input{UTF8: s8, UTF16: s16}
31 func makeInputString(s string) Input {
34 UTF16: utf16.Encode([]rune(s)),
38 // Collator is an interface for architecture-specific implementations of collation.
39 type Collator interface {
40 // Key generates a sort key for the given input. Implemenations
41 // may return nil if a collator does not support sort keys.
44 // Compare returns -1 if a < b, 1 if a > b and 0 if a == b.
45 Compare(a, b Input) int
48 // CollatorFactory creates a Collator for a given language tag.
49 type CollatorFactory struct {
51 makeFn func(tag string) (Collator, error)
55 var collators = []CollatorFactory{}
57 // AddFactory registers f as a factory for an implementation of Collator.
58 func AddFactory(f CollatorFactory) {
59 collators = append(collators, f)
62 func getCollator(name, locale string) Collator {
63 for _, f := range collators {
65 col, err := f.makeFn(locale)
72 log.Fatalf("collator of type %q not found", name)
76 // goCollator is an implemention of Collator using go's own collator.
77 type goCollator struct {
83 AddFactory(CollatorFactory{"go", newGoCollator, "Go's native collator implementation."})
86 func newGoCollator(loc string) (Collator, error) {
87 c := &goCollator{c: collate.New(language.Make(loc))}
91 func (c *goCollator) Key(b Input) []byte {
92 return c.c.Key(&c.buf, b.UTF8)
95 func (c *goCollator) Compare(a, b Input) int {
96 return c.c.Compare(a.UTF8, b.UTF8)