Here you can find the source of appendOrRealloc(ByteBuffer dest, ByteBuffer toAppend)
Parameter | Description |
---|---|
dest | The buffer into which to write or to reallocate if necessary. |
toAppend | The data to write into dest. |
static ByteBuffer appendOrRealloc(ByteBuffer dest, ByteBuffer toAppend)
//package com.java2s; /************************************************************************* * * * This file is part of the 20n/act project. * * 20n/act enables DNA prediction for synthetic biology/bioengineering. * * Copyright (C) 2017 20n Labs, Inc. * * * * Please direct all queries to act@20n.com. * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *************************************************************************/ import java.nio.ByteBuffer; public class Main { /**/* w w w . j ava 2 s .c om*/ * Appends the contents of toAppend to dest if there is capacity, or does the equivalent of C's "realloc" by * allocating a larger buffer and copying both dest and toAppend into that new buffer. * * Always call this function as: * <pre> * {@code * dest = appendOrRealloc(dest, toAppend) * } * </pre> * as we can't actually resize or reallocate dest once it's been allocated. * * @param dest The buffer into which to write or to reallocate if necessary. * @param toAppend The data to write into dest. * @return dest or a new, larger buffer containing both dest and toAppend. */ static ByteBuffer appendOrRealloc(ByteBuffer dest, ByteBuffer toAppend) { /* Before reading this function, review this excellent explanation of the behaviors of ByteBuffers: * http://mindprod.com/jgloss/bytebuffer.html */ // Assume toAppend is pre-flipped to avoid a double flip, which would be Very Bad. if (dest.capacity() - dest.position() < toAppend.limit()) { // Whoops, we have to reallocate! ByteBuffer newDest = ByteBuffer.allocate(dest.capacity() << 1); // TODO: make sure these are page-divisible sizes. dest.flip(); // Switch dest to reading mode. newDest.put(dest); // Write all of dest into the new buffer. dest = newDest; } dest.put(toAppend); return dest; } }