package com.cloudera.util;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import org.junit.Assert;
import org.junit.Test;
@Test
ByteBuffer buf = ByteBuffer.allocate(100);
buf.putInt(0xdead);
buf.putInt(0xbeef);
Assert.assertEquals(100, buf.array().length);
Assert.assertEquals(100, buf.capacity());
Assert.assertEquals(92, buf.remaining());
Assert.assertEquals(8, buf.position());
Assert.assertEquals(0xdead, buf.getInt(0));
Assert.assertEquals(0xbeef, buf.getInt(4));
Assert.assertEquals(100, buf.array().length);
Assert.assertEquals(100, buf.capacity());
Assert.assertEquals(92, buf.remaining());
Assert.assertEquals(8, buf.position());
buf.flip();
Assert.assertEquals(0xdead, buf.getInt());
Assert.assertEquals(0xbeef, buf.getInt());
Assert.assertEquals(0xdead, buf.getInt(0));
Assert.assertEquals(0xbeef, buf.getInt(4));
Assert.assertEquals(100, buf.array().length);
Assert.assertEquals(100, buf.capacity());
Assert.assertEquals(0, buf.remaining());
Assert.assertEquals(8, buf.position());
buf.flip();
Assert.assertEquals(100, buf.array().length);
Assert.assertEquals(100, buf.capacity());
Assert.assertEquals(8, buf.remaining());
Assert.assertEquals(0, buf.position());
buf.clear();
Assert.assertEquals(100, buf.array().length);
Assert.assertEquals(100, buf.capacity());
Assert.assertEquals(100, buf.remaining());
Assert.assertEquals(0, buf.position());
Assert.assertEquals(0xdead, buf.getInt(0));
Assert.assertEquals(0xbeef, buf.getInt(4));
buf.putInt(0xf00d);
buf.putInt(0xcafe);
Assert.assertEquals(0xf00d, buf.getInt(0));
Assert.assertEquals(0xcafe, buf.getInt(4));
}
@Test
byte[] bs = new byte[100];
for (int i = 0; i < bs.length; i++) {
bs[i] = (byte) i;
}
InputStream is = new ByteArrayInputStream(bs);
ReadableByteChannel rch = Channels.newChannel(is);
ByteBuffer buf = ByteBuffer.allocate(100);
buf.limit(8);
System.out.println("artificially set limit to :" + buf.limit());
rch.read(buf);
Assert.assertEquals(0, buf.get(0));
Assert.assertEquals(1, buf.get(1));
Assert.assertEquals(7, buf.get(7));
buf.clear();
System.out.println("after clear limit is :" + buf.limit());
Assert.assertEquals(100, buf.limit());
buf.limit(8);
rch.read(buf);
Assert.assertEquals(8, buf.get(0));
Assert.assertEquals(9, buf.get(1));
Assert.assertEquals(15, buf.get(7));
System.out.println("limit was :" + buf.limit());
buf.limit(buf.limit() + 8);
System.out.println("limit now bumped up to :" + buf.limit());
rch.read(buf);
Assert.assertEquals(8, buf.get(0));
Assert.assertEquals(9, buf.get(1));
Assert.assertEquals(15, buf.get(7));
Assert.assertEquals(16, buf.get(8));
Assert.assertEquals(17, buf.get(9));
Assert.assertEquals(23, buf.get(15));
}
}