1/* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package libcore.util; 18 19/** 20 * Various special-case charset conversions (for performance). 21 * 22 * @hide internal use only 23 */ 24public final class CharsetUtils { 25 /** 26 * Returns a new byte array containing the bytes corresponding to the characters in the given 27 * string, encoded in US-ASCII. Unrepresentable characters are replaced by (byte) '?'. 28 */ 29 public static native byte[] toAsciiBytes(String s, int offset, int length); 30 31 /** 32 * Returns a new byte array containing the bytes corresponding to the characters in the given 33 * string, encoded in ISO-8859-1. Unrepresentable characters are replaced by (byte) '?'. 34 */ 35 public static native byte[] toIsoLatin1Bytes(String s, int offset, int length); 36 37 /** 38 * Returns a new byte array containing the bytes corresponding to the characters in the given 39 * string, encoded in UTF-8. All characters are representable in UTF-8. 40 */ 41 public static native byte[] toUtf8Bytes(String s, int offset, int length); 42 43 /** 44 * Returns a new byte array containing the bytes corresponding to the characters in the given 45 * string, encoded in UTF-16BE. All characters are representable in UTF-16BE. 46 */ 47 public static byte[] toBigEndianUtf16Bytes(String s, int offset, int length) { 48 byte[] result = new byte[length * 2]; 49 int end = offset + length; 50 int resultIndex = 0; 51 for (int i = offset; i < end; ++i) { 52 char ch = s.charAt(i); 53 result[resultIndex++] = (byte) (ch >> 8); 54 result[resultIndex++] = (byte) ch; 55 } 56 return result; 57 } 58 59 /** 60 * Decodes the given US-ASCII bytes into the given char[]. Equivalent to but faster than: 61 * 62 * for (int i = 0; i < count; ++i) { 63 * char ch = (char) (data[start++] & 0xff); 64 * value[i] = (ch <= 0x7f) ? ch : REPLACEMENT_CHAR; 65 * } 66 */ 67 public static native void asciiBytesToChars(byte[] bytes, int offset, int length, char[] chars); 68 69 /** 70 * Decodes the given ISO-8859-1 bytes into the given char[]. Equivalent to but faster than: 71 * 72 * for (int i = 0; i < count; ++i) { 73 * value[i] = (char) (data[start++] & 0xff); 74 * } 75 */ 76 public static native void isoLatin1BytesToChars(byte[] bytes, int offset, int length, char[] chars); 77 78 private CharsetUtils() { 79 } 80} 81