blob: 23db166478ec3add367f104bdfaa49877f051ffb (
plain) (
blame)
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.text;
import java.nio.ByteBuffer;
/**
* @author baldersheim
* @since 5.2
*/
public abstract class AbstractUtf8Array implements Comparable<AbstractUtf8Array> {
/**
* This will write the utf8 sequence to the given target.
*/
final public void writeTo(ByteBuffer target) {
target.put(getBytes(), getByteOffset(), getByteLength());
}
/**
* This will return the byte at the given position.
*/
public byte getByte(int index) { return getBytes()[getByteOffset() + index]; }
/**
*
* @return Length in bytes of the utf8 sequence.
*/
public abstract int getByteLength();
/**
* Wraps the utf8 sequence in a ByteBuffer
* @return The wrapping buffer.
*/
public ByteBuffer wrap() { return ByteBuffer.wrap(getBytes(), getByteOffset(), getByteLength()); }
/**
*
* @return The backing byte array.
*/
protected abstract byte [] getBytes();
public boolean isEmpty() { return getByteLength() == 0; }
/**
*
* @return The offset in the backing array where the utf8 sequence starts.
*/
protected abstract int getByteOffset();
@Override
public int hashCode() {
final int l = getByteLength();
final int c = getByteOffset();
final byte [] b = getBytes();
int h = 0;
for (int i=0; i < l; i++) {
int v = b[c+i];
h ^= v << ((i%4)*8);
}
return h;
}
@Override
public boolean equals(Object o) {
if (o instanceof AbstractUtf8Array) {
AbstractUtf8Array other = (AbstractUtf8Array)o;
return compareTo(other) == 0;
} else if (o instanceof String) {
return toString().equals(o);
}
return false;
}
/**
* Will convert the utf8 sequence to a Java string
* @return The converted Java String
*/
@Override
public String toString() {
return Utf8.toString(getBytes(), getByteOffset(), getByteLength());
}
@Override
public int compareTo(AbstractUtf8Array rhs) {
final int l = getByteLength();
final int rl = rhs.getByteLength();
if (l < rl) {
return -1;
} else if (l > rl) {
return 1;
} else {
final byte [] b = getBytes();
final byte [] rb = rhs.getBytes();
final int c = getByteOffset();
final int rc = rhs.getByteOffset();
for (int i=0; i < l; i++) {
if (b[c+i] < rb[rc+i]) {
return -1;
} else if (b[c+i] > rb[rc+i]) {
return 1;
}
}
return 0;
}
}
public Utf8Array ascii7BitLowerCase() {
byte [] upper = new byte[getByteLength()];
for (int i=0; i< upper.length; i++ ) {
byte b = getByte(i);
if ((b >= 0x41) && (b < (0x41+26))) {
b |= 0x20; // Lowercase
}
upper[i] = b;
}
return new Utf8Array(upper);
}
}
|