Path: blob/master/src/java.base/share/classes/jdk/internal/reflect/UTF8.java
41159 views
/*1* Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package jdk.internal.reflect;2627/** It is necessary to use a "bootstrap" UTF-8 encoder for encoding28constant pool entries because the character set converters rely on29Class.newInstance(). */3031class UTF8 {32// This encoder is not quite correct. It does not handle surrogate pairs.33static byte[] encode(String str) {34int len = str.length();35byte[] res = new byte[utf8Length(str)];36int utf8Idx = 0;37try {38for (int i = 0; i < len; i++) {39int c = str.charAt(i) & 0xFFFF;40if (c >= 0x0001 && c <= 0x007F) {41res[utf8Idx++] = (byte) c;42} else if (c == 0x0000 ||43(c >= 0x0080 && c <= 0x07FF)) {44res[utf8Idx++] = (byte) (0xC0 + (c >> 6));45res[utf8Idx++] = (byte) (0x80 + (c & 0x3F));46} else {47res[utf8Idx++] = (byte) (0xE0 + (c >> 12));48res[utf8Idx++] = (byte) (0x80 + ((c >> 6) & 0x3F));49res[utf8Idx++] = (byte) (0x80 + (c & 0x3F));50}51}52} catch (ArrayIndexOutOfBoundsException e) {53throw new InternalError54("Bug in sun.reflect bootstrap UTF-8 encoder", e);55}56return res;57}5859private static int utf8Length(String str) {60int len = str.length();61int utf8Len = 0;62for (int i = 0; i < len; i++) {63int c = str.charAt(i) & 0xFFFF;64if (c >= 0x0001 && c <= 0x007F) {65utf8Len += 1;66} else if (c == 0x0000 ||67(c >= 0x0080 && c <= 0x07FF)) {68utf8Len += 2;69} else {70utf8Len += 3;71}72}73return utf8Len;74}75}767778