开发者

Deep copy duplicate() of Java's ByteBuffer

java.nio.ByteBuf开发者_StackOverflowfer#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?


I think the deep copy need not involve byte[]. Try the following:

public static ByteBuffer clone(ByteBuffer original) {
       ByteBuffer clone = ByteBuffer.allocate(original.capacity());
       original.rewind();//copy from the beginning
       clone.put(original);
       original.rewind();
       clone.flip();
       return clone;
}


As this question still comes up as one of the first hits to copying a ByteBuffer, I will offer my solution. This solution does not touch the original buffer, including any mark set, and will return a deep copy with the same capacity as the original.

public static ByteBuffer cloneByteBuffer(final ByteBuffer original) {
    // Create clone with same capacity as original.
    final ByteBuffer clone = (original.isDirect()) ?
        ByteBuffer.allocateDirect(original.capacity()) :
        ByteBuffer.allocate(original.capacity());

    // Create a read-only copy of the original.
    // This allows reading from the original without modifying it.
    final ByteBuffer readOnlyCopy = original.asReadOnlyBuffer();

    // Flip and read from the original.
    readOnlyCopy.flip();
    clone.put(readOnlyCopy);

    return clone;
}

If one cares for the position, limit, or order to be set the same as the original, then that's an easy addition to the above:

clone.position(original.position());
clone.limit(original.limit());
clone.order(original.order());
return clone;


Based off of mingfai's solution:

This will give you an almost true deep copy. The only thing lost will be the mark. If orig is a HeapBuffer and the offset is not zero or the capacity is less than the backing array than the outlying data is not copied.

public static ByteBuffer deepCopy( ByteBuffer orig )
{
    int pos = orig.position(), lim = orig.limit();
    try
    {
        orig.position(0).limit(orig.capacity()); // set range to entire buffer
        ByteBuffer toReturn = deepCopyVisible(orig); // deep copy range
        toReturn.position(pos).limit(lim); // set range to original
        return toReturn;
    }
    finally // do in finally in case something goes wrong we don't bork the orig
    {
        orig.position(pos).limit(lim); // restore original
    }
}

public static ByteBuffer deepCopyVisible( ByteBuffer orig )
{
    int pos = orig.position();
    try
    {
        ByteBuffer toReturn;
        // try to maintain implementation to keep performance
        if( orig.isDirect() )
            toReturn = ByteBuffer.allocateDirect(orig.remaining());
        else
            toReturn = ByteBuffer.allocate(orig.remaining());

        toReturn.put(orig);
        toReturn.order(orig.order());

        return (ByteBuffer) toReturn.position(0);
    }
    finally
    {
        orig.position(pos);
    }
}


One more simple solution

public ByteBuffer deepCopy(ByteBuffer source, ByteBuffer target) {

    int sourceP = source.position();
    int sourceL = source.limit();

    if (null == target) {
        target = ByteBuffer.allocate(source.remaining());
    }
    target.put(source);
    target.flip();

    source.position(sourceP);
    source.limit(sourceL);
    return target;
}


You'll need to iterate the entire buffer and copy by value into the new buffer.


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜