001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements. See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership. The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019 package org.apache.hadoop.io;
020
021 import java.io.IOException;
022 import java.io.DataInput;
023 import java.io.DataOutput;
024 import java.nio.ByteBuffer;
025 import java.nio.CharBuffer;
026 import java.nio.charset.CharacterCodingException;
027 import java.nio.charset.Charset;
028 import java.nio.charset.CharsetDecoder;
029 import java.nio.charset.CharsetEncoder;
030 import java.nio.charset.CodingErrorAction;
031 import java.nio.charset.MalformedInputException;
032 import java.text.CharacterIterator;
033 import java.text.StringCharacterIterator;
034 import java.util.Arrays;
035
036 import org.apache.avro.reflect.Stringable;
037
038 import org.apache.hadoop.classification.InterfaceAudience;
039 import org.apache.hadoop.classification.InterfaceStability;
040
041 /** This class stores text using standard UTF8 encoding. It provides methods
042 * to serialize, deserialize, and compare texts at byte level. The type of
043 * length is integer and is serialized using zero-compressed format. <p>In
044 * addition, it provides methods for string traversal without converting the
045 * byte array to a string. <p>Also includes utilities for
046 * serializing/deserialing a string, coding/decoding a string, checking if a
047 * byte array contains valid UTF8 code, calculating the length of an encoded
048 * string.
049 */
050 @Stringable
051 @InterfaceAudience.Public
052 @InterfaceStability.Stable
053 public class Text extends BinaryComparable
054 implements WritableComparable<BinaryComparable> {
055
056 static final int SHORT_STRING_MAX = 1024 * 1024;
057
058 private static ThreadLocal<CharsetEncoder> ENCODER_FACTORY =
059 new ThreadLocal<CharsetEncoder>() {
060 protected CharsetEncoder initialValue() {
061 return Charset.forName("UTF-8").newEncoder().
062 onMalformedInput(CodingErrorAction.REPORT).
063 onUnmappableCharacter(CodingErrorAction.REPORT);
064 }
065 };
066
067 private static ThreadLocal<CharsetDecoder> DECODER_FACTORY =
068 new ThreadLocal<CharsetDecoder>() {
069 protected CharsetDecoder initialValue() {
070 return Charset.forName("UTF-8").newDecoder().
071 onMalformedInput(CodingErrorAction.REPORT).
072 onUnmappableCharacter(CodingErrorAction.REPORT);
073 }
074 };
075
076 private static final byte [] EMPTY_BYTES = new byte[0];
077
078 private byte[] bytes;
079 private int length;
080
081 public Text() {
082 bytes = EMPTY_BYTES;
083 }
084
085 /** Construct from a string.
086 */
087 public Text(String string) {
088 set(string);
089 }
090
091 /** Construct from another text. */
092 public Text(Text utf8) {
093 set(utf8);
094 }
095
096 /** Construct from a byte array.
097 */
098 public Text(byte[] utf8) {
099 set(utf8);
100 }
101
102 /**
103 * Get a copy of the bytes that is exactly the length of the data.
104 * See {@link #getBytes()} for faster access to the underlying array.
105 */
106 public byte[] copyBytes() {
107 byte[] result = new byte[length];
108 System.arraycopy(bytes, 0, result, 0, length);
109 return result;
110 }
111
112 /**
113 * Returns the raw bytes; however, only data up to {@link #getLength()} is
114 * valid. Please use {@link #copyBytes()} if you
115 * need the returned array to be precisely the length of the data.
116 */
117 public byte[] getBytes() {
118 return bytes;
119 }
120
121 /** Returns the number of bytes in the byte array */
122 public int getLength() {
123 return length;
124 }
125
126 /**
127 * Returns the Unicode Scalar Value (32-bit integer value)
128 * for the character at <code>position</code>. Note that this
129 * method avoids using the converter or doing String instatiation
130 * @return the Unicode scalar value at position or -1
131 * if the position is invalid or points to a
132 * trailing byte
133 */
134 public int charAt(int position) {
135 if (position > this.length) return -1; // too long
136 if (position < 0) return -1; // duh.
137
138 ByteBuffer bb = (ByteBuffer)ByteBuffer.wrap(bytes).position(position);
139 return bytesToCodePoint(bb.slice());
140 }
141
142 public int find(String what) {
143 return find(what, 0);
144 }
145
146 /**
147 * Finds any occurence of <code>what</code> in the backing
148 * buffer, starting as position <code>start</code>. The starting
149 * position is measured in bytes and the return value is in
150 * terms of byte position in the buffer. The backing buffer is
151 * not converted to a string for this operation.
152 * @return byte position of the first occurence of the search
153 * string in the UTF-8 buffer or -1 if not found
154 */
155 public int find(String what, int start) {
156 try {
157 ByteBuffer src = ByteBuffer.wrap(this.bytes,0,this.length);
158 ByteBuffer tgt = encode(what);
159 byte b = tgt.get();
160 src.position(start);
161
162 while (src.hasRemaining()) {
163 if (b == src.get()) { // matching first byte
164 src.mark(); // save position in loop
165 tgt.mark(); // save position in target
166 boolean found = true;
167 int pos = src.position()-1;
168 while (tgt.hasRemaining()) {
169 if (!src.hasRemaining()) { // src expired first
170 tgt.reset();
171 src.reset();
172 found = false;
173 break;
174 }
175 if (!(tgt.get() == src.get())) {
176 tgt.reset();
177 src.reset();
178 found = false;
179 break; // no match
180 }
181 }
182 if (found) return pos;
183 }
184 }
185 return -1; // not found
186 } catch (CharacterCodingException e) {
187 // can't get here
188 e.printStackTrace();
189 return -1;
190 }
191 }
192 /** Set to contain the contents of a string.
193 */
194 public void set(String string) {
195 try {
196 ByteBuffer bb = encode(string, true);
197 bytes = bb.array();
198 length = bb.limit();
199 }catch(CharacterCodingException e) {
200 throw new RuntimeException("Should not have happened ", e);
201 }
202 }
203
204 /** Set to a utf8 byte array
205 */
206 public void set(byte[] utf8) {
207 set(utf8, 0, utf8.length);
208 }
209
210 /** copy a text. */
211 public void set(Text other) {
212 set(other.getBytes(), 0, other.getLength());
213 }
214
215 /**
216 * Set the Text to range of bytes
217 * @param utf8 the data to copy from
218 * @param start the first position of the new string
219 * @param len the number of bytes of the new string
220 */
221 public void set(byte[] utf8, int start, int len) {
222 setCapacity(len, false);
223 System.arraycopy(utf8, start, bytes, 0, len);
224 this.length = len;
225 }
226
227 /**
228 * Append a range of bytes to the end of the given text
229 * @param utf8 the data to copy from
230 * @param start the first position to append from utf8
231 * @param len the number of bytes to append
232 */
233 public void append(byte[] utf8, int start, int len) {
234 setCapacity(length + len, true);
235 System.arraycopy(utf8, start, bytes, length, len);
236 length += len;
237 }
238
239 /**
240 * Clear the string to empty.
241 */
242 public void clear() {
243 length = 0;
244 }
245
246 /*
247 * Sets the capacity of this Text object to <em>at least</em>
248 * <code>len</code> bytes. If the current buffer is longer,
249 * then the capacity and existing content of the buffer are
250 * unchanged. If <code>len</code> is larger
251 * than the current capacity, the Text object's capacity is
252 * increased to match.
253 * @param len the number of bytes we need
254 * @param keepData should the old data be kept
255 */
256 private void setCapacity(int len, boolean keepData) {
257 if (bytes == null || bytes.length < len) {
258 if (bytes != null && keepData) {
259 bytes = Arrays.copyOf(bytes, Math.max(len,length << 1));
260 } else {
261 bytes = new byte[len];
262 }
263 }
264 }
265
266 /**
267 * Convert text back to string
268 * @see java.lang.Object#toString()
269 */
270 @Override
271 public String toString() {
272 try {
273 return decode(bytes, 0, length);
274 } catch (CharacterCodingException e) {
275 throw new RuntimeException("Should not have happened " , e);
276 }
277 }
278
279 /** deserialize
280 */
281 public void readFields(DataInput in) throws IOException {
282 int newLength = WritableUtils.readVInt(in);
283 setCapacity(newLength, false);
284 in.readFully(bytes, 0, newLength);
285 length = newLength;
286 }
287
288 /** Skips over one Text in the input. */
289 public static void skip(DataInput in) throws IOException {
290 int length = WritableUtils.readVInt(in);
291 WritableUtils.skipFully(in, length);
292 }
293
294 /** serialize
295 * write this object to out
296 * length uses zero-compressed encoding
297 * @see Writable#write(DataOutput)
298 */
299 public void write(DataOutput out) throws IOException {
300 WritableUtils.writeVInt(out, length);
301 out.write(bytes, 0, length);
302 }
303
304 /** Returns true iff <code>o</code> is a Text with the same contents. */
305 public boolean equals(Object o) {
306 if (o instanceof Text)
307 return super.equals(o);
308 return false;
309 }
310
311 @Override
312 public int hashCode() {
313 return super.hashCode();
314 }
315
316 /** A WritableComparator optimized for Text keys. */
317 public static class Comparator extends WritableComparator {
318 public Comparator() {
319 super(Text.class);
320 }
321
322 public int compare(byte[] b1, int s1, int l1,
323 byte[] b2, int s2, int l2) {
324 int n1 = WritableUtils.decodeVIntSize(b1[s1]);
325 int n2 = WritableUtils.decodeVIntSize(b2[s2]);
326 return compareBytes(b1, s1+n1, l1-n1, b2, s2+n2, l2-n2);
327 }
328 }
329
330 static {
331 // register this comparator
332 WritableComparator.define(Text.class, new Comparator());
333 }
334
335 /// STATIC UTILITIES FROM HERE DOWN
336 /**
337 * Converts the provided byte array to a String using the
338 * UTF-8 encoding. If the input is malformed,
339 * replace by a default value.
340 */
341 public static String decode(byte[] utf8) throws CharacterCodingException {
342 return decode(ByteBuffer.wrap(utf8), true);
343 }
344
345 public static String decode(byte[] utf8, int start, int length)
346 throws CharacterCodingException {
347 return decode(ByteBuffer.wrap(utf8, start, length), true);
348 }
349
350 /**
351 * Converts the provided byte array to a String using the
352 * UTF-8 encoding. If <code>replace</code> is true, then
353 * malformed input is replaced with the
354 * substitution character, which is U+FFFD. Otherwise the
355 * method throws a MalformedInputException.
356 */
357 public static String decode(byte[] utf8, int start, int length, boolean replace)
358 throws CharacterCodingException {
359 return decode(ByteBuffer.wrap(utf8, start, length), replace);
360 }
361
362 private static String decode(ByteBuffer utf8, boolean replace)
363 throws CharacterCodingException {
364 CharsetDecoder decoder = DECODER_FACTORY.get();
365 if (replace) {
366 decoder.onMalformedInput(
367 java.nio.charset.CodingErrorAction.REPLACE);
368 decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
369 }
370 String str = decoder.decode(utf8).toString();
371 // set decoder back to its default value: REPORT
372 if (replace) {
373 decoder.onMalformedInput(CodingErrorAction.REPORT);
374 decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
375 }
376 return str;
377 }
378
379 /**
380 * Converts the provided String to bytes using the
381 * UTF-8 encoding. If the input is malformed,
382 * invalid chars are replaced by a default value.
383 * @return ByteBuffer: bytes stores at ByteBuffer.array()
384 * and length is ByteBuffer.limit()
385 */
386
387 public static ByteBuffer encode(String string)
388 throws CharacterCodingException {
389 return encode(string, true);
390 }
391
392 /**
393 * Converts the provided String to bytes using the
394 * UTF-8 encoding. If <code>replace</code> is true, then
395 * malformed input is replaced with the
396 * substitution character, which is U+FFFD. Otherwise the
397 * method throws a MalformedInputException.
398 * @return ByteBuffer: bytes stores at ByteBuffer.array()
399 * and length is ByteBuffer.limit()
400 */
401 public static ByteBuffer encode(String string, boolean replace)
402 throws CharacterCodingException {
403 CharsetEncoder encoder = ENCODER_FACTORY.get();
404 if (replace) {
405 encoder.onMalformedInput(CodingErrorAction.REPLACE);
406 encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
407 }
408 ByteBuffer bytes =
409 encoder.encode(CharBuffer.wrap(string.toCharArray()));
410 if (replace) {
411 encoder.onMalformedInput(CodingErrorAction.REPORT);
412 encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
413 }
414 return bytes;
415 }
416
417 static final public int ONE_MEGABYTE = 1024 * 1024;
418
419 /** Read a UTF8 encoded string from in
420 */
421 public static String readString(DataInput in) throws IOException {
422 int length = WritableUtils.readVInt(in);
423 byte [] bytes = new byte[length];
424 in.readFully(bytes, 0, length);
425 return decode(bytes);
426 }
427
428 /** Read a UTF8 encoded string with a maximum size
429 */
430 public static String readString(DataInput in, int maxLength)
431 throws IOException {
432 int length = WritableUtils.readVIntInRange(in, 0, maxLength - 1);
433 byte [] bytes = new byte[length];
434 in.readFully(bytes, 0, length);
435 return decode(bytes);
436 }
437
438 /** Write a UTF8 encoded string to out
439 */
440 public static int writeString(DataOutput out, String s) throws IOException {
441 ByteBuffer bytes = encode(s);
442 int length = bytes.limit();
443 WritableUtils.writeVInt(out, length);
444 out.write(bytes.array(), 0, length);
445 return length;
446 }
447
448 /** Write a UTF8 encoded string with a maximum size to out
449 */
450 public static int writeString(DataOutput out, String s, int maxLength)
451 throws IOException {
452 ByteBuffer bytes = encode(s);
453 int length = bytes.limit();
454 if (length >= maxLength) {
455 throw new IOException("string was too long to write! Expected " +
456 "less than " + maxLength + " bytes, but got " +
457 length + " bytes.");
458 }
459 WritableUtils.writeVInt(out, length);
460 out.write(bytes.array(), 0, length);
461 return length;
462 }
463
464 ////// states for validateUTF8
465
466 private static final int LEAD_BYTE = 0;
467
468 private static final int TRAIL_BYTE_1 = 1;
469
470 private static final int TRAIL_BYTE = 2;
471
472 /**
473 * Check if a byte array contains valid utf-8
474 * @param utf8 byte array
475 * @throws MalformedInputException if the byte array contains invalid utf-8
476 */
477 public static void validateUTF8(byte[] utf8) throws MalformedInputException {
478 validateUTF8(utf8, 0, utf8.length);
479 }
480
481 /**
482 * Check to see if a byte array is valid utf-8
483 * @param utf8 the array of bytes
484 * @param start the offset of the first byte in the array
485 * @param len the length of the byte sequence
486 * @throws MalformedInputException if the byte array contains invalid bytes
487 */
488 public static void validateUTF8(byte[] utf8, int start, int len)
489 throws MalformedInputException {
490 int count = start;
491 int leadByte = 0;
492 int length = 0;
493 int state = LEAD_BYTE;
494 while (count < start+len) {
495 int aByte = ((int) utf8[count] & 0xFF);
496
497 switch (state) {
498 case LEAD_BYTE:
499 leadByte = aByte;
500 length = bytesFromUTF8[aByte];
501
502 switch (length) {
503 case 0: // check for ASCII
504 if (leadByte > 0x7F)
505 throw new MalformedInputException(count);
506 break;
507 case 1:
508 if (leadByte < 0xC2 || leadByte > 0xDF)
509 throw new MalformedInputException(count);
510 state = TRAIL_BYTE_1;
511 break;
512 case 2:
513 if (leadByte < 0xE0 || leadByte > 0xEF)
514 throw new MalformedInputException(count);
515 state = TRAIL_BYTE_1;
516 break;
517 case 3:
518 if (leadByte < 0xF0 || leadByte > 0xF4)
519 throw new MalformedInputException(count);
520 state = TRAIL_BYTE_1;
521 break;
522 default:
523 // too long! Longest valid UTF-8 is 4 bytes (lead + three)
524 // or if < 0 we got a trail byte in the lead byte position
525 throw new MalformedInputException(count);
526 } // switch (length)
527 break;
528
529 case TRAIL_BYTE_1:
530 if (leadByte == 0xF0 && aByte < 0x90)
531 throw new MalformedInputException(count);
532 if (leadByte == 0xF4 && aByte > 0x8F)
533 throw new MalformedInputException(count);
534 if (leadByte == 0xE0 && aByte < 0xA0)
535 throw new MalformedInputException(count);
536 if (leadByte == 0xED && aByte > 0x9F)
537 throw new MalformedInputException(count);
538 // falls through to regular trail-byte test!!
539 case TRAIL_BYTE:
540 if (aByte < 0x80 || aByte > 0xBF)
541 throw new MalformedInputException(count);
542 if (--length == 0) {
543 state = LEAD_BYTE;
544 } else {
545 state = TRAIL_BYTE;
546 }
547 break;
548 } // switch (state)
549 count++;
550 }
551 }
552
553 /**
554 * Magic numbers for UTF-8. These are the number of bytes
555 * that <em>follow</em> a given lead byte. Trailing bytes
556 * have the value -1. The values 4 and 5 are presented in
557 * this table, even though valid UTF-8 cannot include the
558 * five and six byte sequences.
559 */
560 static final int[] bytesFromUTF8 =
561 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
562 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
563 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
564 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
565 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
566 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
567 0, 0, 0, 0, 0, 0, 0,
568 // trail bytes
569 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
570 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
571 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
572 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1,
573 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
574 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3,
575 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5 };
576
577 /**
578 * Returns the next code point at the current position in
579 * the buffer. The buffer's position will be incremented.
580 * Any mark set on this buffer will be changed by this method!
581 */
582 public static int bytesToCodePoint(ByteBuffer bytes) {
583 bytes.mark();
584 byte b = bytes.get();
585 bytes.reset();
586 int extraBytesToRead = bytesFromUTF8[(b & 0xFF)];
587 if (extraBytesToRead < 0) return -1; // trailing byte!
588 int ch = 0;
589
590 switch (extraBytesToRead) {
591 case 5: ch += (bytes.get() & 0xFF); ch <<= 6; /* remember, illegal UTF-8 */
592 case 4: ch += (bytes.get() & 0xFF); ch <<= 6; /* remember, illegal UTF-8 */
593 case 3: ch += (bytes.get() & 0xFF); ch <<= 6;
594 case 2: ch += (bytes.get() & 0xFF); ch <<= 6;
595 case 1: ch += (bytes.get() & 0xFF); ch <<= 6;
596 case 0: ch += (bytes.get() & 0xFF);
597 }
598 ch -= offsetsFromUTF8[extraBytesToRead];
599
600 return ch;
601 }
602
603
604 static final int offsetsFromUTF8[] =
605 { 0x00000000, 0x00003080,
606 0x000E2080, 0x03C82080, 0xFA082080, 0x82082080 };
607
608 /**
609 * For the given string, returns the number of UTF-8 bytes
610 * required to encode the string.
611 * @param string text to encode
612 * @return number of UTF-8 bytes required to encode
613 */
614 public static int utf8Length(String string) {
615 CharacterIterator iter = new StringCharacterIterator(string);
616 char ch = iter.first();
617 int size = 0;
618 while (ch != CharacterIterator.DONE) {
619 if ((ch >= 0xD800) && (ch < 0xDC00)) {
620 // surrogate pair?
621 char trail = iter.next();
622 if ((trail > 0xDBFF) && (trail < 0xE000)) {
623 // valid pair
624 size += 4;
625 } else {
626 // invalid pair
627 size += 3;
628 iter.previous(); // rewind one
629 }
630 } else if (ch < 0x80) {
631 size++;
632 } else if (ch < 0x800) {
633 size += 2;
634 } else {
635 // ch < 0x10000, that is, the largest char value
636 size += 3;
637 }
638 ch = iter.next();
639 }
640 return size;
641 }
642 }