aboutsummaryrefslogtreecommitdiffstats
path: root/gcc-4.8.1/libgo/go/exp/norm/example_iter_test.go
blob: edb9fcf55b87fc2804debb4d249302b1b4dd302b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package norm_test

import (
	"bytes"
	"exp/norm"
	"fmt"
	"unicode/utf8"
)

// EqualSimple uses a norm.Iter to compare two non-normalized
// strings for equivalence.
func EqualSimple(a, b string) bool {
	var ia, ib norm.Iter
	ia.InitString(norm.NFKD, a)
	ib.InitString(norm.NFKD, b)
	for !ia.Done() && !ib.Done() {
		if !bytes.Equal(ia.Next(), ib.Next()) {
			return false
		}
	}
	return ia.Done() && ib.Done()
}

// FindPrefix finds the longest common prefix of ASCII characters
// of a and b.
func FindPrefix(a, b string) int {
	i := 0
	for ; i < len(a) && i < len(b) && a[i] < utf8.RuneSelf && a[i] == b[i]; i++ {
	}
	return i
}

// EqualOpt is like EqualSimple, but optimizes the special
// case for ASCII characters.
func EqualOpt(a, b string) bool {
	n := FindPrefix(a, b)
	a, b = a[n:], b[n:]
	var ia, ib norm.Iter
	ia.InitString(norm.NFKD, a)
	ib.InitString(norm.NFKD, b)
	for !ia.Done() && !ib.Done() {
		if !bytes.Equal(ia.Next(), ib.Next()) {
			return false
		}
		if n := int64(FindPrefix(a[ia.Pos():], b[ib.Pos():])); n != 0 {
			ia.Seek(n, 1)
			ib.Seek(n, 1)
		}
	}
	return ia.Done() && ib.Done()
}

var compareTests = []struct{ a, b string }{
	{"aaa", "aaa"},
	{"aaa", "aab"},
	{"a\u0300a", "\u00E0a"},
	{"a\u0300\u0320b", "a\u0320\u0300b"},
	{"\u1E0A\u0323", "\x44\u0323\u0307"},
	// A character that decomposes into multiple segments
	// spans several iterations.
	{"\u3304", "\u30A4\u30CB\u30F3\u30AF\u3099"},
}

func ExampleIter() {
	for i, t := range compareTests {
		r0 := EqualSimple(t.a, t.b)
		r1 := EqualOpt(t.a, t.b)
		fmt.Printf("%d: %v %v\n", i, r0, r1)
	}
	// Output:
	// 0: true true
	// 1: false false
	// 2: true true
	// 3: true true
	// 4: true true
	// 5: true true
}