Debian Codegraph @

morfologik-stemming/src/main/java/morfologik/stemming/BufferUtils.java

raw
1 package morfologik.stemming;
2
3 import java.nio.ByteBuffer;
4 import java.nio.CharBuffer;
5 import java.nio.charset.CharacterCodingException;
6 import java.nio.charset.Charset;
7 import java.nio.charset.CharsetDecoder;
8 import java.nio.charset.CharsetEncoder;
9 import java.nio.charset.CoderResult;
10 import java.nio.charset.CodingErrorAction;
11 import java.util.Arrays;
12
13 public final class BufferUtils {
14 /**
15 * No instances.
16 */
17 private BufferUtils() {
18 // empty
19 }
20
21 /**
22 * Ensure the buffer's capacity is large enough to hold a given number
23 * of elements. If the input buffer is not large enough, a new buffer is allocated
24 * and returned.
25 *
26 * @param elements The required number of elements to be appended to the buffer.
27 *
28 * @param buffer
29 * The buffer to check or <code>null</code> if a new buffer should be
30 * allocated.
31 *
32 * @return Returns the same buffer or a new buffer with the given capacity.
33 */
34 public static ByteBuffer clearAndEnsureCapacity(ByteBuffer buffer, int elements) {
35 if (buffer == null || buffer.capacity() < elements) {
36 buffer = ByteBuffer.allocate(elements);
37 } else {
38 buffer.clear();
39 }
40 return buffer;
41 }
42
43 /**
44 * Ensure the buffer's capacity is large enough to hold a given number
45 * of elements. If the input buffer is not large enough, a new buffer is allocated
46 * and returned.
47 *
48 * @param elements The required number of elements to be appended to the buffer.
49 *
50 * @param buffer
51 * The buffer to check or <code>null</code> if a new buffer should be
52 * allocated.
53 *
54 * @return Returns the same buffer or a new buffer with the given capacity.
55 */
56 public static CharBuffer clearAndEnsureCapacity(CharBuffer buffer, int elements) {
57 if (buffer == null || buffer.capacity() < elements) {
58 buffer = CharBuffer.allocate(elements);
59 } else {
60 buffer.clear();
61 }
62 return buffer;
63 }
64
65 /**
66 * @param buffer The buffer to convert to a string.
67 * @param charset The charset to use when converting bytes to characters.
68 * @return A string representation of buffer's content.
69 */
70 public static String toString(ByteBuffer buffer, Charset charset) {
71 buffer = buffer.slice();
72 byte [] buf = new byte [buffer.remaining()];
73 buffer.get(buf);
74 return new String(buf, charset);
75 }
76
77 public static String toString(CharBuffer buffer) {
78 buffer = buffer.slice();
79 char [] buf = new char [buffer.remaining()];
80 buffer.get(buf);
81 return new String(buf);
82 }
83
84 /**
85 * @param buffer The buffer to read from.
86 * @return Returns the remaining bytes from the buffer copied to an array.
87 */
88 public static byte[] toArray(ByteBuffer buffer) {
89 byte [] dst = new byte [buffer.remaining()];
90 buffer.mark();
91 buffer.get(dst);
92 buffer.reset();
93 return dst;
94 }
95
96 /**
97 * Compute the length of the shared prefix between two byte sequences.
98 */
99 static int sharedPrefixLength(ByteBuffer a, int aStart, ByteBuffer b, int bStart) {
100 int i = 0;
101 final int max = Math.min(a.remaining() - aStart, b.remaining() - bStart);
102 aStart += a.position();
103 bStart += b.position();
104 while (i < max && a.get(aStart++) == b.get(bStart++)) {
105 i++;
106 }
107 return i;
108 }
109
110 /**
111 * Compute the length of the shared prefix between two byte sequences.
112 */
113 static int sharedPrefixLength(ByteBuffer a, ByteBuffer b) {
114 return sharedPrefixLength(a, 0, b, 0);
115 }
116
117 /**
118 * Convert byte buffer's content into characters. The input buffer's bytes are not
119 * consumed (mark is set and reset).
120 */
121 public static CharBuffer bytesToChars(CharsetDecoder decoder, ByteBuffer bytes, CharBuffer chars) {
122 assert decoder.malformedInputAction() == CodingErrorAction.REPORT;
123
124 chars = clearAndEnsureCapacity(chars, (int) (bytes.remaining() * decoder.maxCharsPerByte()));
125
126 bytes.mark();
127 decoder.reset();
128 CoderResult cr = decoder.decode(bytes, chars, true);
129 if (cr.isError()) {
130 bytes.reset();
131 try {
132 cr.throwException();
133 } catch (CharacterCodingException e) {
134 throw new RuntimeException("Input cannot be mapped to bytes using encoding "
135 + decoder.charset().name() + ": " + Arrays.toString(toArray(bytes)), e);
136 }
137 }
138
139 assert cr.isUnderflow(); // This should be guaranteed by ensuring max. capacity.
140 cr = decoder.flush(chars);
141 assert cr.isUnderflow();
142
143 chars.flip();
144 bytes.reset();
145
146 return chars;
147 }
148
149 /**
150 * Convert chars into bytes.
151 */
152 public static ByteBuffer charsToBytes(CharsetEncoder encoder, CharBuffer chars, ByteBuffer bytes)
153 throws UnmappableInputException {
154 assert encoder.malformedInputAction() == CodingErrorAction.REPORT;
155
156 bytes = clearAndEnsureCapacity(bytes, (int) (chars.remaining() * encoder.maxBytesPerChar()));
157
158 chars.mark();
159 encoder.reset();
160
161 CoderResult cr = encoder.encode(chars, bytes, true);
162 if (cr.isError()) {
163 chars.reset();
164 try {
165 cr.throwException();
166 } catch (CharacterCodingException e) {
167 throw new UnmappableInputException("Input cannot be mapped to characters using encoding "
168 + encoder.charset().name() + ": " + Arrays.toString(toArray(bytes)), e);
169 }
170 }
171
172 assert cr.isUnderflow(); // This should be guaranteed by ensuring max. capacity.
173 cr = encoder.flush(bytes);
174 assert cr.isUnderflow();
175
176 bytes.flip();
177 chars.reset();
178
179 return bytes;
180 }
181 }