1/* 2 * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24/* @test 25 * @summary Check that array-crossing surrogate pairs are handled properly 26 */ 27 28import java.io.*; 29import java.nio.*; 30import java.nio.charset.*; 31 32 33public class Surrogates { 34 35 static PrintStream log = System.err; 36 37 static char[] input; 38 static byte[] output; 39 40 static final int LEN = 128; 41 42 static void initData() throws IOException { 43 StringBuffer sb = new StringBuffer(); 44 for (int i = 0; i < LEN; i++) { 45 int c = Character.MIN_SUPPLEMENTARY_CODE_POINT + 1; 46 sb.append(Character.toChars(c)); 47 } 48 input = sb.toString().toCharArray(); 49 ByteArrayOutputStream bos = new ByteArrayOutputStream(); 50 OutputStreamWriter osw 51 = new OutputStreamWriter(bos, Charset.forName("UTF-8")); 52 osw.write(input); 53 osw.close(); 54 output = bos.toByteArray(); 55 } 56 57 static void testLeftovers(boolean doMalformed) 58 throws Exception 59 { 60 log.print("Leftover surrogates, doMalformed = " + doMalformed); 61 ByteArrayOutputStream bos = new ByteArrayOutputStream(); 62 OutputStreamWriter osw 63 = new OutputStreamWriter(bos, Charset.forName("UTF-8")); 64 for (int i = 0; i < input.length; i += 7) 65 osw.write(input, i, Math.min(input.length - i, 7)); 66 if (doMalformed) 67 osw.write(input, 0, 1); 68 osw.close(); 69 byte[] result = bos.toByteArray(); 70 71 // Ignore a trailing '?' if we wrote a malformed final surrogate 72 int rl = result.length + (doMalformed ? -1 : 0); 73 74 if (rl != output.length) 75 throw new Exception("Incorrect result length " 76 + rl + ", expected " + output.length); 77 for (int i = 0; i < output.length; i++) 78 if (result[i] != output[i]) 79 throw new Exception("Unexpected result value at index " + i); 80 log.println(": Passed"); 81 } 82 83 public static void main(String[] args) throws Exception { 84 initData(); 85 testLeftovers(false); 86 testLeftovers(true); 87 } 88 89} 90