}
@Test
public void testGetString() throws Exception {
IoBuffer buf = IoBuffer.allocate(16);
CharsetDecoder decoder;
Charset charset = Charset.forName("UTF-8");
buf.clear();
buf.putString("hello", charset.newEncoder());
buf.put((byte) 0);
buf.flip();
assertEquals("hello", buf.getString(charset.newDecoder()));
buf.clear();
buf.putString("hello", charset.newEncoder());
buf.flip();
assertEquals("hello", buf.getString(charset.newDecoder()));
decoder = Charset.forName("ISO-8859-1").newDecoder();
buf.clear();
buf.put((byte) 'A');
buf.put((byte) 'B');
buf.put((byte) 'C');
buf.put((byte) 0);
buf.position(0);
assertEquals("ABC", buf.getString(decoder));
assertEquals(4, buf.position());
buf.position(0);
buf.limit(1);
assertEquals("A", buf.getString(decoder));
assertEquals(1, buf.position());
buf.clear();
assertEquals("ABC", buf.getString(10, decoder));
assertEquals(10, buf.position());
buf.clear();
assertEquals("A", buf.getString(1, decoder));
assertEquals(1, buf.position());
// Test a trailing garbage
buf.clear();
buf.put((byte) 'A');
buf.put((byte) 'B');
buf.put((byte) 0);
buf.put((byte) 'C');
buf.position(0);
assertEquals("AB", buf.getString(4, decoder));
assertEquals(4, buf.position());
buf.clear();
buf.fillAndReset(buf.limit());
decoder = Charset.forName("UTF-16").newDecoder();
buf.put((byte) 0);
buf.put((byte) 'A');
buf.put((byte) 0);
buf.put((byte) 'B');
buf.put((byte) 0);
buf.put((byte) 'C');
buf.put((byte) 0);
buf.put((byte) 0);
buf.position(0);
assertEquals("ABC", buf.getString(decoder));
assertEquals(8, buf.position());
buf.position(0);
buf.limit(2);
assertEquals("A", buf.getString(decoder));
assertEquals(2, buf.position());
buf.position(0);
buf.limit(3);
assertEquals("A", buf.getString(decoder));
assertEquals(2, buf.position());
buf.clear();
assertEquals("ABC", buf.getString(10, decoder));
assertEquals(10, buf.position());
buf.clear();
assertEquals("A", buf.getString(2, decoder));
assertEquals(2, buf.position());
buf.clear();
try {
buf.getString(1, decoder);
fail();
}
catch (IllegalArgumentException e) {
// Expected an Exception, signifies test success
assertTrue(true);
}
// Test getting strings from an empty buffer.
buf.clear();
buf.limit(0);
assertEquals("", buf.getString(decoder));
assertEquals("", buf.getString(2, decoder));
// Test getting strings from non-empty buffer which is filled with 0x00
buf.clear();
buf.putInt(0);
buf.clear();
buf.limit(4);
assertEquals("", buf.getString(decoder));
assertEquals(2, buf.position());
assertEquals(4, buf.limit());
buf.position(0);
assertEquals("", buf.getString(2, decoder));
assertEquals(2, buf.position());
assertEquals(4, buf.limit());
}