Checks if there is enough space in the buffer to write N additional bytes. Will grow the buffer
if necessary. It takes current position in the buffer into account.

@param numBytesToAdd the number of bytes you want to add to the buffer
13868
public void ensureHasSpace(int numBytesToAdd) {
    if (numBytesToAdd < 0) {
      throw new IllegalArgumentException("Number of bytes can't be negative");
    }
    int capacityLeft = getCapacityLeft();
    if (capacityLeft < numBytesToAdd) {
      grow(numBytesToAdd - capacityLeft, true);
    }
  }
1028780
public void addByte(int b)
    throws IOException
  {
    int nextHead = (_byteHead + 1) % _byteBuffer.length;

    while (nextHead == _byteTail) {
      int ch = readChar();

      if (ch < 0) {
        break;
      }

      outputChar(ch);
    }

    _byteBuffer[_byteHead] = (byte) b;
    _byteHead = nextHead;
  }
1051687
void ensurePadding() {
        final int N = mLayerState.mNum;
        if (mPaddingL != null && mPaddingL.length >= N) {
            return;
        }

        mPaddingL = new int[N];
        mPaddingT = new int[N];
        mPaddingR = new int[N];
        mPaddingB = new int[N];
    }
180344
protected static int growSize(int current, int requiredSize) {
    // Double until 64, then increase by 50% each time.
    int newCapacity = ((current < 64) ? ((current + 1) << 1) : ((current >> 1) * 3));
    // overflow?
    if (newCapacity < 0) {
      throw new OutOfMemoryError();
    }
    if (requiredSize > newCapacity) {
      newCapacity = requiredSize;
    }
    return requiredSize;
  }
196507
public void add(int offset, byte []buffer, int bufOffset, int length)
  {
    insertCode(offset, length);
    
    _code.set(offset, buffer, bufOffset, length);
  }
1075360
@Override
	public void add(BufferOrEvent boe) throws IOException {
		try {
			ByteBuffer contents;
			if (boe.isBuffer()) {
				Buffer buf = boe.getBuffer();
				contents = buf.getNioBufferReadable();
			}
			else {
				contents = EventSerializer.toSerializedEvent(boe.getEvent());
			}

			headBuffer.clear();
			headBuffer.putInt(boe.getChannelIndex());
			headBuffer.putInt(contents.remaining());
			headBuffer.put((byte) (boe.isBuffer() ? 0 : 1));
			headBuffer.flip();

			bytesWritten += (headBuffer.remaining() + contents.remaining());

			FileUtils.writeCompletely(currentChannel, headBuffer);
			FileUtils.writeCompletely(currentChannel, contents);
		}
		finally {
			if (boe.isBuffer()) {
				boe.getBuffer().recycleBuffer();
			}
		}
	}
719319
int insert(Object caller, int version, bbBlock curr, int pos, int len)
    {
        assert mutation_in_progress(caller, version);
        // DEBUG: int amountMoved = 0;
        // DEBUG: int before = this._buf_limit;
        // DEBUG: assert _validate();
        // if there's room in the current block - just
        // move the "trailing" bytes down and we're done
        int neededSpace = len - curr.unusedBlockCapacity();
        if (neededSpace <= 0) {
            // we have all the space we need in the current block
            // DEBUG: amountMoved =
            insertInCurrOnly(caller, version, curr, pos, len);
        }
        else {
            // we'll need at least some additional space beyond the curr
            // block, see if there's room in the
            // next one, otherwise we'll make more (blocks)
            bbBlock next = null;
            if (curr._idx < this._next_block_position - 1) {
                // if there is another block
                next = this._blocks.get(curr._idx + 1);
            }
            if (next != null &&
                (neededSpace <= next.unusedBlockCapacity())
            ) {
                // with the addition of the free space in the following block we have enough
                // DEBUG: amountMoved =
                insertInCurrAndNext(caller, version, curr, pos, len, next);
            }
            else {
                // we'll have to make one or more new blocks
                // first figure out much will be in the first
                // and last blocks (i.e. ignoring the whole
                // blocks
                int lenNeededInLastAddedBlock = neededSpace % _blockSizeUpperLimit;
                int tailLen = curr.bytesAvailableToRead(pos);
                if (lenNeededInLastAddedBlock < tailLen) lenNeededInLastAddedBlock = tailLen;
                if (lenNeededInLastAddedBlock < neededSpace
                 && neededSpace < this._blockSizeUpperLimit) {
                    // if we need less than the largest block then we should
                    // make *one* block with all of the needed space
                    lenNeededInLastAddedBlock = neededSpace;
                }
                bbBlock newblock = insertMakeNewTailBlock(caller, version, curr, lenNeededInLastAddedBlock);
                // now see if the curr block and this newblock have enough
                // available space to do the job, and if there's some trailing
                // data from curr that will end up staying in curr
                if (len <= (curr.unusedBlockCapacity()
                           + newblock.unusedBlockCapacity())
                ) {
                    // insert this as a zero length block immediately  after _curr
                    // insertBlock also adjusts the trailing blocks idx values
                    insertBlock(newblock);
                    // now pretend we just have the "push into the next block" case
                    // DEBUG: amountMoved =
                    insertInCurrAndNext(caller, version, curr, pos, len, newblock);
                }
                else {
                    // and last we have the case of having to insert more than 1 block
                    // which means all of the trailing bytes in _curr move into the last
                    // block
                    // DEBUG: amountMoved =
                    insertAsManyBlocksAsNeeded(caller, version, curr, pos, len, newblock);
                }
            }
        }
        // DEBUG: if (this._buf_limit - before != len
        // DEBUG: || amountMoved != len) {
        // DEBUG: throw new BlockedBufferException("insert went wrong #1 !!!");
        // DEBUG: }
        assert _validate();
        return len;
    }
1080266
public static void copyFromBytes(
			MemorySegment[] segments, int offset,
			byte[] bytes, int bytesOffset, int numBytes) {
		if (segments.length == 1) {
			segments[0].put(offset, bytes, bytesOffset, numBytes);
		} else {
			copyMultiSegmentsFromBytes(segments, offset, bytes, bytesOffset, numBytes);
		}
	}
451536
protected final void prepareAdd()
    {
        if (currentPageBuilder.isFull()) {
            valueBlocksRetainedSizeInBytes += currentPageBuilder.getRetainedSizeInBytes();
            sumPositions.add(totalPositions);
            currentPageBuilder = currentPageBuilder.newPageBuilderLike();
            values.add(currentPageBuilder);

            verify(values.size() <= MAX_NUM_BLOCKS);
        }

        long currentGroupId = getGroupId();
        short insertedBlockIndex = (short) (values.size() - 1);
        int insertedPosition = currentPageBuilder.getPositionCount();

        if (totalPositions == capacity) {
            capacity *= 1.5;
            nextBlockIndex.ensureCapacity(capacity);
            nextPosition.ensureCapacity(capacity);
        }

        if (isEmpty()) {
            // new linked list, set up the header pointer
            headBlockIndex.set(currentGroupId, insertedBlockIndex);
            headPosition.set(currentGroupId, insertedPosition);
        }
        else {
            // existing linked list, link the new entry to the tail
            long absoluteTailAddress = toAbsolutePosition(tailBlockIndex.get(currentGroupId), tailPosition.get(currentGroupId));
            nextBlockIndex.set(absoluteTailAddress, insertedBlockIndex);
            nextPosition.set(absoluteTailAddress, insertedPosition);
        }
        tailBlockIndex.set(currentGroupId, insertedBlockIndex);
        tailPosition.set(currentGroupId, insertedPosition);
        groupEntryCount.increment(currentGroupId);
        currentPageBuilder.declarePosition();
        totalPositions++;
    }
359793
public void putBytes(ByteBuffer writeBuffer) {

        if (writeBuffer.remaining() < CONNECTION_ID_LENGTH) {
            throw new IllegalArgumentException("Could not add ConnectionHandle to byte buffer: not enough space.");
        }

        writeBuffer.putLong(this.connID);
        writeBuffer.putInt(this.seqNum);
        writeBuffer.put(this.connHandleCreatorId);
        writeBuffer.put(this.myFlags);
        writeBuffer.put(this.myType);
        writeBuffer.put((byte) 0xFF); // place holder - empty flag
    }
1157504
public void add(int theOpCode, int theOperand1, int theOperand2) {
        if (DEBUGCODE) {
            System.out.println("Add " + bytecodeStr(theOpCode)
                + ", " + Integer.toHexString(theOperand1)
                + ", " + Integer.toHexString(theOperand2));
        }
        int newStack = itsStackTop + stackChange(theOpCode);
        if (newStack < 0 || Short.MAX_VALUE < newStack)
            badStack(newStack);

        if (theOpCode == ByteCode.IINC) {
            if (theOperand1 < 0 ||  65536 <= theOperand1)
                throw new ClassFileFormatException("out of range variable");
            if (theOperand2 < 0 ||  65536 <= theOperand2)
                throw new ClassFileFormatException("out of range increment");

            if (theOperand1 > 255 || theOperand2 < -128 || theOperand2 > 127) {
                addToCodeBuffer(ByteCode.WIDE);
                addToCodeBuffer(ByteCode.IINC);
                addToCodeInt16(theOperand1);
                addToCodeInt16(theOperand2);
            } else {
                addToCodeBuffer(ByteCode.IINC);
                addToCodeBuffer(theOperand1);
                addToCodeBuffer(theOperand2);
            }
        } else if (theOpCode == ByteCode.MULTIANEWARRAY) {
            if (!(0 <= theOperand1 && theOperand1 < 65536))
                throw new IllegalArgumentException("out of range index");
            if (!(0 <= theOperand2 && theOperand2 < 256))
                throw new IllegalArgumentException("out of range dimensions");

            addToCodeBuffer(ByteCode.MULTIANEWARRAY);
            addToCodeInt16(theOperand1);
            addToCodeBuffer(theOperand2);
        } else {
            throw new IllegalArgumentException(
                "Unexpected opcode for 2 operands");
        }
        itsStackTop = (short) newStack;
        if (newStack > itsMaxStack)
            itsMaxStack = (short) newStack;
        if (DEBUGSTACK) {
            System.out.println("After " + bytecodeStr(theOpCode)
                + " stack = " + itsStackTop);
        }

    }
827552
public boolean add() {
        if (root == NIL) {
            root = nodeAllocator.newNode();
            copy(root);
            fixAggregates(root);
            return true;
        } else {
            int node = root; assert parent(root) == NIL;
            int parent;
            int cmp;
            do {
                cmp = compare(node);
                if (cmp < 0) {
                    parent = node;
                    node = left(node);
                } else if (cmp > 0) {
                    parent = node;
                    node = right(node);
                } else {
                    merge(node);
                    return false;
                }
            } while (node != NIL);

            node = nodeAllocator.newNode();
            if (node >= capacity()) {
                resize(oversize(node + 1));
            }
            copy(node);
            parent(node, parent);
            if (cmp < 0) {
                left(parent, node);
            } else {
                assert cmp > 0;
                right(parent, node);
            }

            rebalance(node);

            return true;
        }
    }
1302779
public int read(byte[] Data, int NumBytes)
	{
		int retcode = DDC_SUCCESS;
		try
		{
			file.read(Data, 0, NumBytes);
		}
		catch (IOException ioe)
		{
			retcode = DDC_FILE_ERROR;
		}
		return retcode;
	}
213484
private <T extends INode> T addNode(String src, T child,
        long childDiskspace, boolean inheritPermission)
  throws QuotaExceededException {
    byte[][] components = INode.getPathComponents(src);
    byte[] path = components[components.length - 1];
    child.setLocalName(path);
    cacheName(child);
    INode[] inodes = new INode[components.length];
    writeLock();
    try {
      rootDir.getExistingPathINodes(components, inodes);
      return addChild(inodes, inodes.length-1, child, childDiskspace,
                      inheritPermission);
    } finally {
      writeUnlock();
    }
  }
538473
private boolean checkMultiReadBuffer() throws IOException {
        //first check existing buffer
        if (null != this.buffer) {
            if (this.buffer.hasRemaining()) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "checkMultiReadBuffer, remaining ->" + this);
                }
                return true;
            }
            if (firstReadCompleteforMulti) { // multiRead enabled and subsequent read
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "checkMultiReadBuffer, buffer is completely read, ready this buffer for the subsequent read ->" + this);
                }
                postDataBuffer.get(postDataIndex).flip(); // make position 0 , to read it again from start
                postDataIndex++;
            } else {
                this.buffer.release();
            }
            this.buffer = null;
        }
        // no buffer read from store or first read of buffer
        if (firstReadCompleteforMulti) {
            // first read from what we have stored, if need more than go to channel
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "checkMultiReadBuffer ,index ->" + postDataIndex + " ,storage.size ->" + postDataBuffer.size());
            }
            if (postDataBuffer.size() <= postDataIndex) {
                //get remaining from channel now as read needs more than the stored
                readRemainingFromChannel();
            }
            if (postDataBuffer.size() > postDataIndex) {
                this.buffer = postDataBuffer.get(postDataIndex);
            }

            if (null != this.buffer) {
                // record the new amount of data read from the store
                this.bytesReadFromStore += this.buffer.remaining();
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "checkMultiReadBuffer ->" + this);
                }
                return true;
            }
        } else { // multiRead enabled and first read
            if (getBufferFromChannel()) {
                // store the channel buffer
                postDataBuffer.add(postDataIndex, this.buffer.duplicate());
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "checkMultiReadBuffer, buffer ->" + postDataBuffer.get(postDataIndex)
                                 + " ,buffersize ->" + postDataBuffer.size() + " ,index ->" + postDataIndex);
                }
                postDataIndex++;

                // record the new amount of data read from the channel
                this.bytesRead += this.buffer.remaining();
                return true;
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "checkMultiReadBuffer:  no more buffer ->" + this);
        }
        return false;
    }
562129
public void put(byte[] source)
    {
        // If the buffer is small.
        if (mBuffer.capacity() < (mLength + source.length))
        {
            expandBuffer(mLength + source.length + ADDITIONAL_BUFFER_SIZE);
        }

        mBuffer.put(source);
        mLength += source.length;
    }
1022938
public void put(int data)
    {
        // If the buffer is small.
        if (mBuffer.capacity() < (mLength + 1))
        {
            expandBuffer(mLength + ADDITIONAL_BUFFER_SIZE);
        }

        mBuffer.put((byte)data);
        ++mLength;
    }