// Copyright (c) Keith D Gregory, all rights reserved
package com.kdgregory.example.bytebuffer;

import java.nio.ByteBuffer;


/**
 *  Demonstrates the use of <code>slice()</code> to create a <code>ByteBuffer</code>
 *  that represents an arbitrary offset into an existing buffer. This is very useful
 *  for processing structured binary data, such as that found in a graphics file.
 */
public class SliceExample
{
    public static void main(String[] argv)
    throws Exception
    {
        byte[] data = new byte[256];
        for (int ii = 0 ; ii < data.length ; ii++)
            data[ii] = (byte)ii;

        ByteBuffer buf1 = ByteBuffer.wrap(data);

        buf1.position(128);
        ByteBuffer buf2 = buf1.slice();

        System.out.println(String.format(
                "buf2[0], before update = %08x",
                buf2.getInt(0)));

        // note that we're changing the original buffer
        buf1.putInt(128, 0x12345678);

        System.out.println(String.format(
                "buf2[0], after update  = %08x",
                buf2.getInt(0)));
    }
}
