1 11 package org.eclipse.jdi.internal.jdwp; 12 13 14 import java.io.DataInputStream ; 15 import java.io.DataOutputStream ; 16 import java.io.IOException ; 17 import java.io.UTFDataFormatException ; 18 19 24 public class JdwpString { 25 30 public static String read(DataInputStream in) throws IOException { 31 int utfSize = in.readInt(); 32 byte utfBytes[] = new byte[utfSize]; 33 in.readFully(utfBytes); 34 35 StringBuffer strBuffer = new StringBuffer (utfSize / 3 * 2); 36 for (int i = 0; i < utfSize;) { 37 int a = utfBytes[i] & 0xFF; 38 if ((a >> 4) < 12) { 39 strBuffer.append((char) a); 40 i++; 41 } else { 42 int b = utfBytes[i + 1] & 0xFF; 43 if ((a >> 4) < 14) { 44 if ((b & 0xBF) == 0) { 45 throw new UTFDataFormatException (JDWPMessages.JdwpString_Second_byte_input_does_not_match_UTF_Specification_1); 46 } 47 strBuffer.append((char) (((a & 0x1F) << 6) | (b & 0x3F))); 48 i += 2; 49 } else { 50 int c = utfBytes[i + 2] & 0xFF; 51 if ((a & 0xEF) > 0) { 52 if (((b & 0xBF) == 0) || ((c & 0xBF) == 0)) { 53 throw new UTFDataFormatException (JDWPMessages.JdwpString_Second_or_third_byte_input_does_not_mach_UTF_Specification_2); 54 } 55 strBuffer.append((char) (((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F))); 56 i += 3; 57 } else { 58 throw new UTFDataFormatException (JDWPMessages.JdwpString_Input_does_not_match_UTF_Specification_3); 59 } 60 } 61 } 62 } 63 return strBuffer.toString(); 64 } 65 66 67 72 public static void write(String str, DataOutputStream out) throws IOException { 73 if (str == null) 74 throw new NullPointerException (JDWPMessages.JdwpString_str_is_null_4); 75 int utfCount = 0; 76 for (int i = 0; i < str.length(); i++) { 77 int charValue = str.charAt(i); 78 if (charValue > 0 && charValue <= 127) 79 utfCount += 1; 80 else 81 if (charValue <= 2047) 82 utfCount += 2; 83 else 84 utfCount += 3; 85 } 86 byte utfBytes[] = new byte[utfCount]; 87 int utfIndex = 0; 88 for (int i = 0; i < str.length(); i++) { 89 int charValue = str.charAt(i); 90 if (charValue > 0 && charValue <= 127) 91 utfBytes[utfIndex++] = (byte) charValue; 92 else 93 if (charValue <= 2047) { 94 utfBytes[utfIndex++] = (byte) (0xc0 | (0x1f & (charValue >> 6))); 95 utfBytes[utfIndex++] = (byte) (0x80 | (0x3f & charValue)); 96 } else { 97 utfBytes[utfIndex++] = (byte) (0xe0 | (0x0f & (charValue >> 12))); 98 utfBytes[utfIndex++] = (byte) (0x80 | (0x3f & (charValue >> 6))); 99 utfBytes[utfIndex++] = (byte) (0x80 | (0x3f & charValue)); 100 } 101 } 102 out.writeInt(utfCount); 103 if (utfCount > 0) 104 out.write(utfBytes); 105 } 106 } 107 | Popular Tags |