code: public static CharBuffer clearAndEnsureCapacity(CharBuffer buffer, int elements) {
      if (buffer == null || buffer.capacity() < elements) {
        buffer = CharBuffer.allocate(elements);
      } else {
        buffer.clear();
      }
      return buffer;
    }
docs: Ensure the buffer's capacity is large enough to hold a given number
  of elements. If the input buffer is not large enough, a new buffer is allocated
  and returned.
  
  @param elements The required number of elements to be appended to the buffer.
  
  @param buffer
  The buffer to check or <code>null</code> if a new buffer should be
  allocated.
  
  @return Returns the same buffer or a new buffer with the given capacity.