1/* 2 * Copyright (C) 2016 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 17 18package libcore.java.nio; 19 20import junit.framework.TestCase; 21 22import java.nio.CharBuffer; 23import java.util.Arrays; 24 25public class CharBufferTest extends TestCase { 26 27 public void testChars() { 28 char highSurrogate = '\uD83D', lowSurrogate = '\uDE02'; 29 String s = "Hello\n\tworld" + highSurrogate + lowSurrogate; 30 CharBuffer cb = CharBuffer.allocate(32).append(s); 31 cb.rewind(); 32 int[] expected = new int[s.length()]; 33 for (int i = 0; i < s.length(); ++i) { 34 expected[i] = (int) s.charAt(i); 35 } 36 assertTrue(Arrays.equals(expected, cb.chars().limit(s.length()).toArray())); 37 } 38 39 public void testCodePoints() { 40 String s = "Hello\n\tworld"; 41 CharBuffer cb = CharBuffer.allocate(32).append(s); 42 cb.rewind(); 43 int[] expected = new int[s.length()]; 44 for (int i = 0; i < s.length(); ++i) { 45 expected[i] = (int) s.charAt(i);} 46 assertTrue(Arrays.equals(expected, cb.codePoints().limit(s.length()).toArray())); 47 48 // Surrogate code point 49 char high = '\uD83D', low = '\uDE02'; 50 String surrogateCP = new String(new char[]{high, low, low, '0'}); 51 cb = CharBuffer.allocate(32).append(surrogateCP); 52 cb.rewind(); 53 assertEquals(Character.toCodePoint(high, low), cb.codePoints().toArray()[0]); 54 assertEquals((int) low, cb.codePoints().toArray()[1]); // Unmatched surrogate. 55 assertEquals((int) '0', cb.codePoints().toArray()[2]); 56 } 57} 58