Java Code Examples for java.nio.CharBuffer#capacity()

The following examples show how to use java.nio.CharBuffer#capacity() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StreamEvent.java    From staedi with Apache License 2.0 6 votes vote down vote up
static CharBuffer put(CharBuffer buffer, CharArraySequence data) {
    final int length = data.length();

    if (buffer == null || buffer.capacity() < length) {
        buffer = CharBuffer.allocate(length);
    }

    buffer.clear();

    if (length > 0) {
        data.putToBuffer(buffer);
    }

    buffer.flip();

    return buffer;
}
 
Example 2
Source File: EditableSecureBuffer.java    From edslite with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return the char at the specified offset within the buffer.
 */
@Override
public char charAt(int where) {
    if(VERBOSE_LOG) Logger.debug(TAG + ": in charAt");
    CharBuffer cb = _sb.getCharBuffer();
    if(cb == null)
        return ' ';
    cb.clear();
    int len = cb.capacity() - mGapLength;
    if (where < 0) {
        throw new IndexOutOfBoundsException("charAt: " + where + " < 0");
    } else if (where >= len) {
        throw new IndexOutOfBoundsException("charAt: " + where + " >= length " + len);
    }

    if (where >= mGapStart)
        return cb.charAt(where + mGapLength);
    else
        return cb.charAt(where);
}
 
Example 3
Source File: Chars.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Randomize the char buffer's position and limit.
 */
static CharBuffer randomizeRange(CharBuffer cb) {
    int mid = cb.capacity() >>> 1;
    int start = RAND.nextInt(mid + 1); // from 0 to mid
    int end = mid + RAND.nextInt(cb.capacity() - mid + 1); // from mid to capacity
    cb.position(start);
    cb.limit(end);
    return cb;
}
 
Example 4
Source File: Chars.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Randomize the char buffer's position and limit.
 */
static CharBuffer randomizeRange(CharBuffer cb) {
    int mid = cb.capacity() >>> 1;
    int start = RAND.nextInt(mid + 1); // from 0 to mid
    int end = mid + RAND.nextInt(cb.capacity() - mid + 1); // from mid to capacity
    cb.position(start);
    cb.limit(end);
    return cb;
}
 
Example 5
Source File: Chars.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Randomize the char buffer's position and limit.
 */
static CharBuffer randomizeRange(CharBuffer cb) {
    int mid = cb.capacity() >>> 1;
    int start = RAND.nextInt(mid);
    int end = mid + RAND.nextInt(mid);
    cb.position(start);
    cb.limit(end);
    return cb;
}
 
Example 6
Source File: FileAuthHandler.java    From nats.java with Apache License 2.0 5 votes vote down vote up
/**
 * getJWT should return the user JWT associated with this connection.
 * This can return null for challenge only authentication, but for account/user
 * JWT-based authentication you need to return the JWT bytes here.
 * 
 * @return the user JWT
 */ 
public char[] getJWT() {
    try {
        char[] jwtChars = null;
        String fileToUse = this.jwtFile;

        if (this.credsFile != null) {
            fileToUse = this.credsFile;
        }

        // If no file is provided, assume this is challenge only authentication
        // and simply return null here.
        if (fileToUse == null) {
            return null;
        }

        byte[] data = Files.readAllBytes(Paths.get(fileToUse));
        ByteBuffer bb = ByteBuffer.wrap(data);
        CharBuffer chars = StandardCharsets.UTF_8.decode(bb);
        jwtChars = this.extract(chars, 1); // jwt is always first
        // Clear things up as best we can
        chars.clear();
        for (int i=0; i<chars.capacity();i++) {
            chars.put('\0');
        }
        bb.clear();
        for (int i=0;i<data.length;i++) {
            data[i] = 0;
        }

        return jwtChars;
    } catch (Exception exp) {
        throw new IllegalStateException("problem reading jwt", exp);
    }
}
 
Example 7
Source File: Chars.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Randomize the char buffer's position and limit.
 */
static CharBuffer randomizeRange(CharBuffer cb) {
    int mid = cb.capacity() >>> 1;
    int start = RAND.nextInt(mid);
    int end = mid + RAND.nextInt(mid);
    cb.position(start);
    cb.limit(end);
    return cb;
}
 
Example 8
Source File: Chars.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Randomize the char buffer's position and limit.
 */
static CharBuffer randomizeRange(CharBuffer cb) {
    int mid = cb.capacity() >>> 1;
    int start = RAND.nextInt(mid);
    int end = mid + RAND.nextInt(mid);
    cb.position(start);
    cb.limit(end);
    return cb;
}
 
Example 9
Source File: DefaultEncryptionProtocol.java    From armadillo with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public char[] deobfuscatePassword(@Nullable ByteArrayRuntimeObfuscator obfuscated) {
    if (obfuscated == null) return null;

    CharBuffer charBuffer = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(obfuscated.getBytes()));

    if (charBuffer.capacity() != charBuffer.limit()) {
        char[] compacted = new char[charBuffer.remaining()];
        charBuffer.get(compacted);
        return compacted;
    }
    return charBuffer.array();
}
 
Example 10
Source File: Chars.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Randomize the char buffer's position and limit.
 */
static CharBuffer randomizeRange(CharBuffer cb) {
    int mid = cb.capacity() >>> 1;
    int start = RAND.nextInt(mid);
    int end = mid + RAND.nextInt(mid);
    cb.position(start);
    cb.limit(end);
    return cb;
}
 
Example 11
Source File: CodeSetConversion.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public char[] getChars(byte[] bytes, int offset, int numBytes) {

            // Possible optimization of reading directly from the CDR
            // byte buffer.  The sun.io converter supposedly can handle
            // incremental conversions in which a char is broken across
            // two convert calls.
            //
            // Basic tests didn't show more than a 1 ms increase
            // worst case.  It's less than a factor of 2 increase.
            // Also makes the interface more difficult.


            try {

                ByteBuffer byteBuf = ByteBuffer.wrap(bytes, offset, numBytes);
                CharBuffer charBuf = btc.decode(byteBuf);

                // CharBuffer returned by the decoder will set its limit
                // to byte immediately after the last written byte.
                resultingNumChars = charBuf.limit();

                // IMPORTANT - It's possible the underlying char[] in the
                //             CharBuffer returned by btc.decode(byteBuf)
                //             is longer in length than the number of characters
                //             decoded. Hence, the check below to ensure the
                //             char[] returned contains all the chars that have
                //             been decoded and no more.
                if (charBuf.limit() == charBuf.capacity()) {
                    buffer = charBuf.array();
                } else {
                    buffer = new char[charBuf.limit()];
                    charBuf.get(buffer, 0, charBuf.limit()).position(0);
                }

                return buffer;

            } catch (IllegalStateException ile) {
                // There were a decoding operation already in progress
                throw wrapper.btcConverterFailure( ile ) ;
            } catch (MalformedInputException mie) {
                // There were illegal Unicode char pairs
                throw wrapper.badUnicodePair( mie ) ;
            } catch (UnmappableCharacterException uce) {
                // A character doesn't map to the desired code set.
                // CORBA formal 00-11-03.
                throw omgWrapper.charNotInCodeset( uce ) ;
            } catch (CharacterCodingException cce) {
                // If this happens, then a character decoding error occured.
                throw wrapper.btcConverterFailure( cce ) ;
            }
        }
 
Example 12
Source File: NetcatSource.java    From mt-flume with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
  logger.debug("Starting connection handler");
  Event event = null;

  try {
    Reader reader = Channels.newReader(socketChannel, "utf-8");
    Writer writer = Channels.newWriter(socketChannel, "utf-8");
    CharBuffer buffer = CharBuffer.allocate(maxLineLength);
    buffer.flip(); // flip() so fill() sees buffer as initially empty

    while (true) {
      // this method blocks until new data is available in the socket
      int charsRead = fill(buffer, reader);
      logger.debug("Chars read = {}", charsRead);

      // attempt to process all the events in the buffer
      int eventsProcessed = processEvents(buffer, writer);
      logger.debug("Events processed = {}", eventsProcessed);

      if (charsRead == -1) {
        // if we received EOF before last event processing attempt, then we
        // have done everything we can
        break;
      } else if (charsRead == 0 && eventsProcessed == 0) {
        if (buffer.remaining() == buffer.capacity()) {
          // If we get here it means:
          // 1. Last time we called fill(), no new chars were buffered
          // 2. After that, we failed to process any events => no newlines
          // 3. The unread data in the buffer == the size of the buffer
          // Therefore, we are stuck because the client sent a line longer
          // than the size of the buffer. Response: Drop the connection.
          logger.warn("Client sent event exceeding the maximum length");
          counterGroup.incrementAndGet("events.failed");
          writer.write("FAILED: Event exceeds the maximum length (" +
              buffer.capacity() + " chars, including newline)\n");
          writer.flush();
          break;
        }
      }
    }

    socketChannel.close();

    counterGroup.incrementAndGet("sessions.completed");
  } catch (IOException e) {
    counterGroup.incrementAndGet("sessions.broken");
  }

  logger.debug("Connection handler exiting");
}
 
Example 13
Source File: CodeSetConversion.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public char[] getChars(byte[] bytes, int offset, int numBytes) {

            // Possible optimization of reading directly from the CDR
            // byte buffer.  The sun.io converter supposedly can handle
            // incremental conversions in which a char is broken across
            // two convert calls.
            //
            // Basic tests didn't show more than a 1 ms increase
            // worst case.  It's less than a factor of 2 increase.
            // Also makes the interface more difficult.


            try {

                ByteBuffer byteBuf = ByteBuffer.wrap(bytes, offset, numBytes);
                CharBuffer charBuf = btc.decode(byteBuf);

                // CharBuffer returned by the decoder will set its limit
                // to byte immediately after the last written byte.
                resultingNumChars = charBuf.limit();

                // IMPORTANT - It's possible the underlying char[] in the
                //             CharBuffer returned by btc.decode(byteBuf)
                //             is longer in length than the number of characters
                //             decoded. Hence, the check below to ensure the
                //             char[] returned contains all the chars that have
                //             been decoded and no more.
                if (charBuf.limit() == charBuf.capacity()) {
                    buffer = charBuf.array();
                } else {
                    buffer = new char[charBuf.limit()];
                    charBuf.get(buffer, 0, charBuf.limit()).position(0);
                }

                return buffer;

            } catch (IllegalStateException ile) {
                // There were a decoding operation already in progress
                throw wrapper.btcConverterFailure( ile ) ;
            } catch (MalformedInputException mie) {
                // There were illegal Unicode char pairs
                throw wrapper.badUnicodePair( mie ) ;
            } catch (UnmappableCharacterException uce) {
                // A character doesn't map to the desired code set.
                // CORBA formal 00-11-03.
                throw omgWrapper.charNotInCodeset( uce ) ;
            } catch (CharacterCodingException cce) {
                // If this happens, then a character decoding error occured.
                throw wrapper.btcConverterFailure( cce ) ;
            }
        }
 
Example 14
Source File: CodeSetConversion.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public char[] getChars(byte[] bytes, int offset, int numBytes) {

            // Possible optimization of reading directly from the CDR
            // byte buffer.  The sun.io converter supposedly can handle
            // incremental conversions in which a char is broken across
            // two convert calls.
            //
            // Basic tests didn't show more than a 1 ms increase
            // worst case.  It's less than a factor of 2 increase.
            // Also makes the interface more difficult.


            try {

                ByteBuffer byteBuf = ByteBuffer.wrap(bytes, offset, numBytes);
                CharBuffer charBuf = btc.decode(byteBuf);

                // CharBuffer returned by the decoder will set its limit
                // to byte immediately after the last written byte.
                resultingNumChars = charBuf.limit();

                // IMPORTANT - It's possible the underlying char[] in the
                //             CharBuffer returned by btc.decode(byteBuf)
                //             is longer in length than the number of characters
                //             decoded. Hence, the check below to ensure the
                //             char[] returned contains all the chars that have
                //             been decoded and no more.
                if (charBuf.limit() == charBuf.capacity()) {
                    buffer = charBuf.array();
                } else {
                    buffer = new char[charBuf.limit()];
                    charBuf.get(buffer, 0, charBuf.limit()).position(0);
                }

                return buffer;

            } catch (IllegalStateException ile) {
                // There were a decoding operation already in progress
                throw wrapper.btcConverterFailure( ile ) ;
            } catch (MalformedInputException mie) {
                // There were illegal Unicode char pairs
                throw wrapper.badUnicodePair( mie ) ;
            } catch (UnmappableCharacterException uce) {
                // A character doesn't map to the desired code set.
                // CORBA formal 00-11-03.
                throw omgWrapper.charNotInCodeset( uce ) ;
            } catch (CharacterCodingException cce) {
                // If this happens, then a character decoding error occured.
                throw wrapper.btcConverterFailure( cce ) ;
            }
        }
 
Example 15
Source File: BaseFileManager.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("cast")
public CharBuffer decode(ByteBuffer inbuf, boolean ignoreEncodingErrors) {
    String encName = getEncodingName();
    CharsetDecoder decoder;
    try {
        decoder = getDecoder(encName, ignoreEncodingErrors);
    } catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
        log.error("unsupported.encoding", encName);
        return (CharBuffer)CharBuffer.allocate(1).flip();
    }

    // slightly overestimate the buffer size to avoid reallocation.
    float factor =
        decoder.averageCharsPerByte() * 0.8f +
        decoder.maxCharsPerByte() * 0.2f;
    CharBuffer dest = CharBuffer.
        allocate(10 + (int)(inbuf.remaining()*factor));

    while (true) {
        CoderResult result = decoder.decode(inbuf, dest, true);
        dest.flip();

        if (result.isUnderflow()) { // done reading
            // make sure there is at least one extra character
            if (dest.limit() == dest.capacity()) {
                dest = CharBuffer.allocate(dest.capacity()+1).put(dest);
                dest.flip();
            }
            return dest;
        } else if (result.isOverflow()) { // buffer too small; expand
            int newCapacity =
                10 + dest.capacity() +
                (int)(inbuf.remaining()*decoder.maxCharsPerByte());
            dest = CharBuffer.allocate(newCapacity).put(dest);
        } else if (result.isMalformed() || result.isUnmappable()) {
            // bad character in input
            StringBuilder unmappable = new StringBuilder();
            int len = result.length();

            for (int i = 0; i < len; i++) {
                unmappable.append(String.format("%02X", inbuf.get()));
            }

            String charsetName = charset == null ? encName : charset.name();

            log.error(dest.limit(),
                      Errors.IllegalCharForEncoding(unmappable.toString(), charsetName));

            // undo the flip() to prepare the output buffer
            // for more translation
            dest.position(dest.limit());
            dest.limit(dest.capacity());
            dest.put((char)0xfffd); // backward compatible
        } else {
            throw new AssertionError(result);
        }
    }
    // unreached
}
 
Example 16
Source File: BaseFileManager.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public CharBuffer decode(ByteBuffer inbuf, boolean ignoreEncodingErrors) {
    String encName = getEncodingName();
    CharsetDecoder decoder;
    try {
        decoder = getDecoder(encName, ignoreEncodingErrors);
    } catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
        log.error(Errors.UnsupportedEncoding(encName));
        return (CharBuffer) CharBuffer.allocate(1).flip();
    }

    // slightly overestimate the buffer size to avoid reallocation.
    float factor =
        decoder.averageCharsPerByte() * 0.8f +
        decoder.maxCharsPerByte() * 0.2f;
    CharBuffer dest = CharBuffer.
        allocate(10 + (int)(inbuf.remaining()*factor));

    while (true) {
        CoderResult result = decoder.decode(inbuf, dest, true);
        dest.flip();

        if (result.isUnderflow()) { // done reading
            // make sure there is at least one extra character
            if (dest.limit() == dest.capacity()) {
                dest = CharBuffer.allocate(dest.capacity()+1).put(dest);
                dest.flip();
            }
            return dest;
        } else if (result.isOverflow()) { // buffer too small; expand
            int newCapacity =
                10 + dest.capacity() +
                (int)(inbuf.remaining()*decoder.maxCharsPerByte());
            dest = CharBuffer.allocate(newCapacity).put(dest);
        } else if (result.isMalformed() || result.isUnmappable()) {
            // bad character in input
            StringBuilder unmappable = new StringBuilder();
            int len = result.length();

            for (int i = 0; i < len; i++) {
                unmappable.append(String.format("%02X", inbuf.get()));
            }

            String charsetName = charset == null ? encName : charset.name();

            log.error(dest.limit(),
                      Errors.IllegalCharForEncoding(unmappable.toString(), charsetName));

            // undo the flip() to prepare the output buffer
            // for more translation
            dest.position(dest.limit());
            dest.limit(dest.capacity());
            dest.put((char)0xfffd); // backward compatible
        } else {
            throw new AssertionError(result);
        }
    }
    // unreached
}
 
Example 17
Source File: CodeSetConversion.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public char[] getChars(byte[] bytes, int offset, int numBytes) {

            // Possible optimization of reading directly from the CDR
            // byte buffer.  The sun.io converter supposedly can handle
            // incremental conversions in which a char is broken across
            // two convert calls.
            //
            // Basic tests didn't show more than a 1 ms increase
            // worst case.  It's less than a factor of 2 increase.
            // Also makes the interface more difficult.


            try {

                ByteBuffer byteBuf = ByteBuffer.wrap(bytes, offset, numBytes);
                CharBuffer charBuf = btc.decode(byteBuf);

                // CharBuffer returned by the decoder will set its limit
                // to byte immediately after the last written byte.
                resultingNumChars = charBuf.limit();

                // IMPORTANT - It's possible the underlying char[] in the
                //             CharBuffer returned by btc.decode(byteBuf)
                //             is longer in length than the number of characters
                //             decoded. Hence, the check below to ensure the
                //             char[] returned contains all the chars that have
                //             been decoded and no more.
                if (charBuf.limit() == charBuf.capacity()) {
                    buffer = charBuf.array();
                } else {
                    buffer = new char[charBuf.limit()];
                    charBuf.get(buffer, 0, charBuf.limit()).position(0);
                }

                return buffer;

            } catch (IllegalStateException ile) {
                // There were a decoding operation already in progress
                throw wrapper.btcConverterFailure( ile ) ;
            } catch (MalformedInputException mie) {
                // There were illegal Unicode char pairs
                throw wrapper.badUnicodePair( mie ) ;
            } catch (UnmappableCharacterException uce) {
                // A character doesn't map to the desired code set.
                // CORBA formal 00-11-03.
                throw omgWrapper.charNotInCodeset( uce ) ;
            } catch (CharacterCodingException cce) {
                // If this happens, then a character decoding error occured.
                throw wrapper.btcConverterFailure( cce ) ;
            }
        }
 
Example 18
Source File: CodeSetConversion.java    From JDKSourceCode1.8 with MIT License 4 votes vote down vote up
public char[] getChars(byte[] bytes, int offset, int numBytes) {

            // Possible optimization of reading directly from the CDR
            // byte buffer.  The sun.io converter supposedly can handle
            // incremental conversions in which a char is broken across
            // two convert calls.
            //
            // Basic tests didn't show more than a 1 ms increase
            // worst case.  It's less than a factor of 2 increase.
            // Also makes the interface more difficult.


            try {

                ByteBuffer byteBuf = ByteBuffer.wrap(bytes, offset, numBytes);
                CharBuffer charBuf = btc.decode(byteBuf);

                // CharBuffer returned by the decoder will set its limit
                // to byte immediately after the last written byte.
                resultingNumChars = charBuf.limit();

                // IMPORTANT - It's possible the underlying char[] in the
                //             CharBuffer returned by btc.decode(byteBuf)
                //             is longer in length than the number of characters
                //             decoded. Hence, the check below to ensure the
                //             char[] returned contains all the chars that have
                //             been decoded and no more.
                if (charBuf.limit() == charBuf.capacity()) {
                    buffer = charBuf.array();
                } else {
                    buffer = new char[charBuf.limit()];
                    charBuf.get(buffer, 0, charBuf.limit()).position(0);
                }

                return buffer;

            } catch (IllegalStateException ile) {
                // There were a decoding operation already in progress
                throw wrapper.btcConverterFailure( ile ) ;
            } catch (MalformedInputException mie) {
                // There were illegal Unicode char pairs
                throw wrapper.badUnicodePair( mie ) ;
            } catch (UnmappableCharacterException uce) {
                // A character doesn't map to the desired code set.
                // CORBA formal 00-11-03.
                throw omgWrapper.charNotInCodeset( uce ) ;
            } catch (CharacterCodingException cce) {
                // If this happens, then a character decoding error occured.
                throw wrapper.btcConverterFailure( cce ) ;
            }
        }
 
Example 19
Source File: CodeSetConversion.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public char[] getChars(byte[] bytes, int offset, int numBytes) {

            // Possible optimization of reading directly from the CDR
            // byte buffer.  The sun.io converter supposedly can handle
            // incremental conversions in which a char is broken across
            // two convert calls.
            //
            // Basic tests didn't show more than a 1 ms increase
            // worst case.  It's less than a factor of 2 increase.
            // Also makes the interface more difficult.


            try {

                ByteBuffer byteBuf = ByteBuffer.wrap(bytes, offset, numBytes);
                CharBuffer charBuf = btc.decode(byteBuf);

                // CharBuffer returned by the decoder will set its limit
                // to byte immediately after the last written byte.
                resultingNumChars = charBuf.limit();

                // IMPORTANT - It's possible the underlying char[] in the
                //             CharBuffer returned by btc.decode(byteBuf)
                //             is longer in length than the number of characters
                //             decoded. Hence, the check below to ensure the
                //             char[] returned contains all the chars that have
                //             been decoded and no more.
                if (charBuf.limit() == charBuf.capacity()) {
                    buffer = charBuf.array();
                } else {
                    buffer = new char[charBuf.limit()];
                    charBuf.get(buffer, 0, charBuf.limit()).position(0);
                }

                return buffer;

            } catch (IllegalStateException ile) {
                // There were a decoding operation already in progress
                throw wrapper.btcConverterFailure( ile ) ;
            } catch (MalformedInputException mie) {
                // There were illegal Unicode char pairs
                throw wrapper.badUnicodePair( mie ) ;
            } catch (UnmappableCharacterException uce) {
                // A character doesn't map to the desired code set.
                // CORBA formal 00-11-03.
                throw omgWrapper.charNotInCodeset( uce ) ;
            } catch (CharacterCodingException cce) {
                // If this happens, then a character decoding error occured.
                throw wrapper.btcConverterFailure( cce ) ;
            }
        }
 
Example 20
Source File: BufferUtils.java    From morfologik-stemming with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * 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. 
 */
public static CharBuffer clearAndEnsureCapacity(CharBuffer buffer, int elements) {
  if (buffer == null || buffer.capacity() < elements) {
    buffer = CharBuffer.allocate(elements);
  } else {
    buffer.clear();
  }
  return buffer;
}