Path: blob/master/test/jdk/java/nio/charset/coders/Surrogates.java
41153 views
/*1* Copyright (c) 2010, 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.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/* @test24* @summary Check that array-crossing surrogate pairs are handled properly25*/2627import java.io.*;28import java.nio.*;29import java.nio.charset.*;303132public class Surrogates {3334static PrintStream log = System.err;3536static char[] input;37static byte[] output;3839static final int LEN = 128;4041static void initData() throws IOException {42StringBuffer sb = new StringBuffer();43for (int i = 0; i < LEN; i++) {44int c = Character.MIN_SUPPLEMENTARY_CODE_POINT + 1;45sb.append(Character.toChars(c));46}47input = sb.toString().toCharArray();48ByteArrayOutputStream bos = new ByteArrayOutputStream();49OutputStreamWriter osw50= new OutputStreamWriter(bos, Charset.forName("UTF-8"));51osw.write(input);52osw.close();53output = bos.toByteArray();54}5556static void testLeftovers(boolean doMalformed)57throws Exception58{59log.print("Leftover surrogates, doMalformed = " + doMalformed);60ByteArrayOutputStream bos = new ByteArrayOutputStream();61OutputStreamWriter osw62= new OutputStreamWriter(bos, Charset.forName("UTF-8"));63for (int i = 0; i < input.length; i += 7)64osw.write(input, i, Math.min(input.length - i, 7));65if (doMalformed)66osw.write(input, 0, 1);67osw.close();68byte[] result = bos.toByteArray();6970// Ignore a trailing '?' if we wrote a malformed final surrogate71int rl = result.length + (doMalformed ? -1 : 0);7273if (rl != output.length)74throw new Exception("Incorrect result length "75+ rl + ", expected " + output.length);76for (int i = 0; i < output.length; i++)77if (result[i] != output[i])78throw new Exception("Unexpected result value at index " + i);79log.println(": Passed");80}8182public static void main(String[] args) throws Exception {83initData();84testLeftovers(false);85testLeftovers(true);86}8788}899091