Imported Upstream version 4.8.1
[platform/upstream/gcc48.git] / libgo / go / exp / locale / collate / tools / colcmp / col.go
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.
4
5 package main
6
7 import (
8         "exp/locale/collate"
9         "log"
10         "unicode/utf16"
11 )
12
13 // Input holds an input string in both UTF-8 and UTF-16 format.
14 type Input struct {
15         index int // used for restoring to original random order
16         UTF8  []byte
17         UTF16 []uint16
18         key   []byte // used for sorting
19 }
20
21 func (i Input) String() string {
22         return string(i.UTF8)
23 }
24
25 func makeInput(s8 []byte, s16 []uint16) Input {
26         return Input{UTF8: s8, UTF16: s16}
27 }
28
29 func makeInputString(s string) Input {
30         return Input{
31                 UTF8:  []byte(s),
32                 UTF16: utf16.Encode([]rune(s)),
33         }
34 }
35
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.
40         Key(s Input) []byte
41
42         // Compare returns -1 if a < b, 1 if a > b and 0 if a == b.
43         Compare(a, b Input) int
44 }
45
46 // CollatorFactory creates a Collator for a given locale.
47 type CollatorFactory struct {
48         name        string
49         makeFn      func(locale string) (Collator, error)
50         description string
51 }
52
53 var collators = []CollatorFactory{}
54
55 // AddFactory registers f as a factory for an implementation of Collator.
56 func AddFactory(f CollatorFactory) {
57         collators = append(collators, f)
58 }
59
60 func getCollator(name, locale string) Collator {
61         for _, f := range collators {
62                 if f.name == name {
63                         col, err := f.makeFn(locale)
64                         if err != nil {
65                                 log.Fatal(err)
66                         }
67                         return col
68                 }
69         }
70         log.Fatalf("collator of type %q not found", name)
71         return nil
72 }
73
74 // goCollator is an implemention of Collator using go's own collator.
75 type goCollator struct {
76         c   *collate.Collator
77         buf collate.Buffer
78 }
79
80 func init() {
81         AddFactory(CollatorFactory{"go", newGoCollator, "Go's native collator implementation."})
82 }
83
84 func newGoCollator(locale string) (Collator, error) {
85         c := &goCollator{c: collate.New(locale)}
86         return c, nil
87 }
88
89 func (c *goCollator) Key(b Input) []byte {
90         return c.c.Key(&c.buf, b.UTF8)
91 }
92
93 func (c *goCollator) Compare(a, b Input) int {
94         return c.c.Compare(a.UTF8, b.UTF8)
95 }