forked from tunabay/go-bitarray
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bitarray_compare.go
97 lines (87 loc) · 1.91 KB
/
bitarray_compare.go
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// Copyright (c) 2021 Hirotsuna Mizuno. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
package bitarray
import (
"bytes"
)
// Compare returns an integer comparing two bit arrays lexicographically. The
// result will be 0 if x == y, -1 if x < y, and +1 if y < x. A nil argument is
// equivalent to an empty bit array.
func Compare(x, y BitArrayer) int {
var bax, bay *BitArray
if x != nil {
bax = x.BitArray()
}
if y != nil {
bay = y.BitArray()
}
xLen, yLen, xlty := bax.Len(), bay.Len(), -1
if yLen < xLen {
bax, bay, xLen, yLen, xlty = bay, bax, yLen, xLen, +1
}
switch {
case yLen == 0:
return 0
case xLen == 0:
return xlty
case bax.b == nil:
if xLen == yLen && (bay.b == nil || allBytesZero(bay.b)) {
return 0
}
return xlty
case bay.b == nil:
if allBytesZero(bax.b) {
if xLen == yLen {
return 0
}
return xlty
}
return -xlty
}
ce := bax.nBits >> 3 // end index of common bytes
cc := bytes.Compare(bax.b[:ce], bay.b[:ce])
switch {
case 0 < cc:
return -xlty
case cc < 0:
return xlty
}
if bax.nBits&7 == 0 { // no more x bits
if xLen == yLen {
return 0
}
return xlty
}
// compare the fractional bits in the last byte
cs := 8 - bax.nBits&7
xl, yl := bax.b[ce]>>cs, bay.b[ce]>>cs
switch {
case yl < xl:
return -xlty
case xl < yl, xLen != yLen:
return xlty
}
return 0
}
// Equal returns whether the bit array is the same as specified one.
// nil and zero length bit array are considered to be equal.
func (ba *BitArray) Equal(x BitArrayer) bool {
var bax *BitArray
if x != nil {
bax = x.BitArray()
}
switch {
case ba.IsZero():
return bax.IsZero()
case bax.IsZero():
return false
case ba.nBits != bax.nBits:
return false
case ba.b == nil:
return bax.b == nil || allBytesZero(bax.b)
case bax.b == nil:
return allBytesZero(ba.b)
}
return bytes.Equal(ba.b, bax.b)
}