Deep copy duplicate() of Java's ByteBuffer

Viewed 36977

java.nio.ByteBuffer#duplicate() returns a new byte buffer that shares the old buffer's content. Changes to the old buffer's content will be visible in the new buffer, and vice versa. What if I want a deep copy of the byte buffer?

6 Answers

I believe this should supply a full deep copy, including the mark, "out-of-bounds" data, etc...just in case you need the most complete sandbox-safe carbon copy of a ByteBuffer.

The only thing it doesn't copy is the read-only trait, which you can easily get by just calling this method and tagging on a ".asReadOnlyBuffer()"

public static ByteBuffer cloneByteBuffer(ByteBuffer original)
{
    //Get position, limit, and mark
    int pos = original.position();
    int limit = original.limit();
    int mark = -1;
    try
    {
        original.reset();
        mark = original.position();
    }
    catch (InvalidMarkException e)
    {
        //This happens when the original's mark is -1, so leave mark at default value of -1
    }

    //Create clone with matching capacity and byte order
    ByteBuffer clone = (original.isDirect()) ? ByteBuffer.allocateDirect(original.capacity()) : ByteBuffer.allocate(original.capacity());
    clone.order(original.order());

    //Copy FULL buffer contents, including the "out-of-bounds" part
    original.limit(original.capacity());
    original.position(0);
    clone.put(original);

    //Set mark of both buffers to what it was originally
    if (mark != -1)
    {
        original.position(mark);
        original.mark();

        clone.position(mark);
        clone.mark();
    }

    //Set position and limit of both buffers to what they were originally
    original.position(pos);
    original.limit(limit);
    clone.position(pos);
    clone.limit(limit);

    return clone;
}
Related