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.
13 // Input holds an input string in both UTF-8 and UTF-16 format.
15 index int // used for restoring to original random order
18 key []byte // used for sorting
21 func (i Input) String() string {
25 func makeInput(s8 []byte, s16 []uint16) Input {
26 return Input{UTF8: s8, UTF16: s16}
29 func makeInputString(s string) Input {
32 UTF16: utf16.Encode([]rune(s)),
36 // Collator is an interface for architecture-specific implementations of collation.
37 type Collator interface {
38 // Key generates a sort key for the given input. Implemenations
39 // may return nil if a collator does not support sort keys.
42 // Compare returns -1 if a < b, 1 if a > b and 0 if a == b.
43 Compare(a, b Input) int
46 // CollatorFactory creates a Collator for a given locale.
47 type CollatorFactory struct {
49 makeFn func(locale string) (Collator, error)
53 var collators = []CollatorFactory{}
55 // AddFactory registers f as a factory for an implementation of Collator.
56 func AddFactory(f CollatorFactory) {
57 collators = append(collators, f)
60 func getCollator(name, locale string) Collator {
61 for _, f := range collators {
63 col, err := f.makeFn(locale)
70 log.Fatalf("collator of type %q not found", name)
74 // goCollator is an implemention of Collator using go's own collator.
75 type goCollator struct {
81 AddFactory(CollatorFactory{"go", newGoCollator, "Go's native collator implementation."})
84 func newGoCollator(locale string) (Collator, error) {
85 c := &goCollator{c: collate.New(locale)}
89 func (c *goCollator) Key(b Input) []byte {
90 return c.c.Key(&c.buf, b.UTF8)
93 func (c *goCollator) Compare(a, b Input) int {
94 return c.c.Compare(a.UTF8, b.UTF8)