Java Code Examples for java.nio.ByteBuffer#isDirect()

The following examples show how to use java.nio.ByteBuffer#isDirect() . 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: UnsafeBuffer.java    From agrona with Apache License 2.0 6 votes vote down vote up
public void wrap(final ByteBuffer buffer, final int offset, final int length)
{
    if (SHOULD_BOUNDS_CHECK)
    {
        boundsCheckWrap(offset, length, buffer.capacity());
    }

    if (buffer != byteBuffer)
    {
        byteBuffer = buffer;
    }

    if (buffer.isDirect())
    {
        byteArray = null;
        addressOffset = address(buffer) + offset;
    }
    else
    {
        byteArray = array(buffer);
        addressOffset = ARRAY_BASE_OFFSET + arrayOffset(buffer) + offset;
    }

    capacity = length;
}
 
Example 2
Source File: BrotliDeCompressor.java    From jbrotli with Apache License 2.0 6 votes vote down vote up
/**
 * One may use {@link ByteBuffer#position(int)} and {@link ByteBuffer#limit(int)} to adjust
 * how the buffers are used for reading and writing.
 *
 * @param in  compressed input
 * @param out output buffer
 * @return output buffer length
 * @throws BrotliException in case of something in native code went wrong
 */
public final int deCompress(ByteBuffer in, ByteBuffer out) throws BrotliException {
  int inPosition = in.position();
  int inLimit = in.limit();
  int inRemain = inLimit - inPosition;
  if (inRemain <= 0)
    throw new IllegalArgumentException("The source (in) position must me smaller then the source ByteBuffer's limit.");

  int outPosition = out.position();
  int outLimit = out.limit();
  int outRemain = outLimit - outPosition;
  if (outRemain <= 0)
    throw new IllegalArgumentException("The destination (out) position must me smaller then the source ByteBuffer's limit.");

  int outLength;
  if (in.isDirect() && out.isDirect()) {
    outLength = assertBrotliOk(deCompressByteBuffer(in, inPosition, inRemain, out, outPosition, outRemain));
  } else if (in.hasArray() && out.hasArray()) {
    outLength = assertBrotliOk(deCompressBytes(in.array(), inPosition + in.arrayOffset(), inRemain, out.array(), outPosition + out.arrayOffset(), outRemain));
  } else {
    throw new UnsupportedOperationException("Not supported ByteBuffer implementation. Both (input and output) buffer has to be of the same type. Use either direct BB or wrapped byte arrays. You may raise an issue on GitHub too ;-)");
  }
  in.position(inLimit);
  out.limit(outPosition + outLength);
  return outLength;
}
 
Example 3
Source File: PoolingGelfMessage.java    From xian with Apache License 2.0 6 votes vote down vote up
private void gzip(ByteBuffer source, ReusableGzipOutputStream gz) throws IOException {
    int size = source.position();

    if (source.isDirect()) {

        int read = 0;
        source.position(0);

        byte[] bytes = poolHolder.getByteArray();
        while (size > read) {

            if ((size - read) > bytes.length) {
                read += bytes.length;
                source.get(bytes);
                gz.write(bytes);
            } else {
                int remain = size - read;
                read += remain;
                source.get(bytes, 0, remain);
                gz.write(bytes, 0, remain);
            }
        }
    } else {
        gz.write(source.array(), source.arrayOffset(), source.position());
    }
}
 
Example 4
Source File: Deflater.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Sets preset dictionary for compression. A preset dictionary is used
 * when the history buffer can be predetermined. When the data is later
 * uncompressed with Inflater.inflate(), Inflater.getAdler() can be called
 * in order to get the Adler-32 value of the dictionary required for
 * decompression.
 * <p>
 * The bytes in given byte buffer will be fully consumed by this method.  On
 * return, its position will equal its limit.
 *
 * @param dictionary the dictionary data bytes
 * @see Inflater#inflate
 * @see Inflater#getAdler
 */
public void setDictionary(ByteBuffer dictionary) {
    synchronized (zsRef) {
        int position = dictionary.position();
        int remaining = Math.max(dictionary.limit() - position, 0);
        ensureOpen();
        if (dictionary.isDirect()) {
            long address = ((DirectBuffer) dictionary).address();
            try {
                setDictionaryBuffer(zsRef.address(), address + position, remaining);
            } finally {
                Reference.reachabilityFence(dictionary);
            }
        } else {
            byte[] array = ZipUtils.getBufferArray(dictionary);
            int offset = ZipUtils.getBufferOffset(dictionary);
            setDictionary(zsRef.address(), array, offset + position, remaining);
        }
        dictionary.position(position + remaining);
    }
}
 
Example 5
Source File: FlacDecoderJni.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
/** Decodes and consumes the next sample from the FLAC stream into the given byte buffer. */
@SuppressWarnings("ByteBufferBackingArray")
public void decodeSample(ByteBuffer output)
    throws IOException, InterruptedException, FlacFrameDecodeException {
  output.clear();
  int frameSize =
      output.isDirect()
          ? flacDecodeToBuffer(nativeDecoderContext, output)
          : flacDecodeToArray(nativeDecoderContext, output.array());
  if (frameSize < 0) {
    if (!isDecoderAtEndOfInput()) {
      throw new FlacFrameDecodeException("Cannot decode FLAC frame", frameSize);
    }
    // The decoder has read to EOI. Return a 0-size frame to indicate the EOI.
    output.limit(0);
  } else {
    output.limit(frameSize);
  }
}
 
Example 6
Source File: SteamUser.java    From steamworks4j with MIT License 6 votes vote down vote up
public int initiateGameConnection(ByteBuffer authBlob, SteamID steamIDGameServer,
								  int serverIP, short serverPort, boolean secure) throws SteamException {

	if (!authBlob.isDirect()) {
		throw new SteamException("Direct buffer required!");
	}

	int bytesWritten = initiateGameConnection(pointer, authBlob, authBlob.position(), authBlob.remaining(),
			steamIDGameServer.handle, serverIP, serverPort, secure);

	if (bytesWritten > 0) {
		authBlob.limit(bytesWritten);
	}

	return bytesWritten;
}
 
Example 7
Source File: ByteBufferReader.java    From AsyncSocket with MIT License 6 votes vote down vote up
public byte[] getAllByteArray() {
    // fast path to return the contents of the first and only byte buffer,
    // if that's what we're looking for. avoids allocation.
    if (mBuffers.size() == 1) {
        ByteBuffer peek = mBuffers.peek();
        if (peek.capacity() == remaining() && peek.isDirect()) {
            remaining = 0;
            return mBuffers.remove().array();
        }
    }

    byte[] ret = new byte[remaining()];
    get(ret);

    return ret;
}
 
Example 8
Source File: MMapFileBackedBitArray.java    From bloomfilter with Apache License 2.0 6 votes vote down vote up
/**
 * Method that helps unmap a memory-mapped file before being
 * garbage-collected.
 * 
 * @param cb
 */
protected void closeDirectBuffer(ByteBuffer cb) {
    if (!cb.isDirect()) {
    	return;
    }

    // we could use this type cast and call functions without reflection code,
    // but static import from sun.* package is risky for non-SUN virtual machine.
    //try { ((sun.nio.ch.DirectBuffer)cb).cleaner().clean(); } catch (Exception ex) { }
    try {
        Method cleaner = cb.getClass().getMethod("cleaner");
        cleaner.setAccessible(true);
        Method clean = Class.forName("sun.misc.Cleaner").getMethod("clean");
        clean.setAccessible(true);
        clean.invoke(cleaner.invoke(cb));
    } catch(Exception ex) { 
    	
    }
    
    cb = null;
}
 
Example 9
Source File: BufferUtils.java    From aion-germany with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new ByteBuffer with the same contents as the given ByteBuffer. The new ByteBuffer is seperate from the old one and changes are not reflected across. If you want to reflect changes,
 * consider using Buffer.duplicate().
 *
 * @param buf
 *            the ByteBuffer to copy
 * @return the copy
 */
public static ByteBuffer clone(ByteBuffer buf) {
	if (buf == null) {
		return null;
	}
	buf.rewind();

	ByteBuffer copy;
	if (buf.isDirect()) {
		copy = createByteBuffer(buf.limit());
	}
	else {
		copy = ByteBuffer.allocate(buf.limit());
	}
	copy.put(buf);

	return copy;
}
 
Example 10
Source File: ByteBufferWrapper.java    From epoll with MIT License 5 votes vote down vote up
public ByteBufferWrapper(ByteBuffer buffer) {
    if (!buffer.isDirect())
        throw new IllegalArgumentException("byte buffer must be direct");

    this.buffer = buffer;
    address = EpollCore.address(buffer);
}
 
Example 11
Source File: SocketOrChannelConnectionImpl.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public ByteBuffer read(ByteBuffer byteBuffer, int offset,
                       int length, long max_wait_time)
    throws IOException
{
    int size = offset + length;
    if (shouldUseDirectByteBuffers()) {

        if (! byteBuffer.isDirect()) {
            throw wrapper.unexpectedNonDirectByteBufferWithChannelSocket();
        }
        if (size > byteBuffer.capacity()) {
            if (orb.transportDebugFlag) {
                // print address of ByteBuffer being released
                int bbAddress = System.identityHashCode(byteBuffer);
                StringBuffer bbsb = new StringBuffer(80);
                bbsb.append(".read: releasing ByteBuffer id (")
                    .append(bbAddress).append(") to ByteBufferPool.");
                String bbmsg = bbsb.toString();
                dprint(bbmsg);
            }
            orb.getByteBufferPool().releaseByteBuffer(byteBuffer);
            byteBuffer = orb.getByteBufferPool().getByteBuffer(size);
        }
        byteBuffer.position(offset);
        byteBuffer.limit(size);
        readFully(byteBuffer, length, max_wait_time);
        byteBuffer.position(0);
        byteBuffer.limit(size);
        return byteBuffer;
    }
    if (byteBuffer.isDirect()) {
        throw wrapper.unexpectedDirectByteBufferWithNonChannelSocket();
    }
    byte[] buf = new byte[size];
    readFully(getSocket().getInputStream(), buf,
              offset, length, max_wait_time);
    return ByteBuffer.wrap(buf);
}
 
Example 12
Source File: SocketOrChannelConnectionImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public ByteBuffer read(ByteBuffer byteBuffer, int offset,
                       int length, long max_wait_time)
    throws IOException
{
    int size = offset + length;
    if (shouldUseDirectByteBuffers()) {

        if (! byteBuffer.isDirect()) {
            throw wrapper.unexpectedNonDirectByteBufferWithChannelSocket();
        }
        if (size > byteBuffer.capacity()) {
            if (orb.transportDebugFlag) {
                // print address of ByteBuffer being released
                int bbAddress = System.identityHashCode(byteBuffer);
                StringBuffer bbsb = new StringBuffer(80);
                bbsb.append(".read: releasing ByteBuffer id (")
                    .append(bbAddress).append(") to ByteBufferPool.");
                String bbmsg = bbsb.toString();
                dprint(bbmsg);
            }
            orb.getByteBufferPool().releaseByteBuffer(byteBuffer);
            byteBuffer = orb.getByteBufferPool().getByteBuffer(size);
        }
        byteBuffer.position(offset);
        byteBuffer.limit(size);
        readFully(byteBuffer, length, max_wait_time);
        byteBuffer.position(0);
        byteBuffer.limit(size);
        return byteBuffer;
    }
    if (byteBuffer.isDirect()) {
        throw wrapper.unexpectedDirectByteBufferWithNonChannelSocket();
    }
    byte[] buf = new byte[size];
    readFully(getSocket().getInputStream(), buf,
              offset, length, max_wait_time);
    return ByteBuffer.wrap(buf);
}
 
Example 13
Source File: ArrowOutputStream.java    From ArrowExample with Apache License 2.0 5 votes vote down vote up
@Override
public int write(ByteBuffer src) throws IOException {
    if(src.isDirect()){
        return writeDirectBuffer(src);
    } else {
        return writeHeapBuffer(src);
    }
}
 
Example 14
Source File: SocketOrChannelConnectionImpl.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public ByteBuffer read(ByteBuffer byteBuffer, int offset,
                       int length, long max_wait_time)
    throws IOException
{
    int size = offset + length;
    if (shouldUseDirectByteBuffers()) {

        if (! byteBuffer.isDirect()) {
            throw wrapper.unexpectedNonDirectByteBufferWithChannelSocket();
        }
        if (size > byteBuffer.capacity()) {
            if (orb.transportDebugFlag) {
                // print address of ByteBuffer being released
                int bbAddress = System.identityHashCode(byteBuffer);
                StringBuffer bbsb = new StringBuffer(80);
                bbsb.append(".read: releasing ByteBuffer id (")
                    .append(bbAddress).append(") to ByteBufferPool.");
                String bbmsg = bbsb.toString();
                dprint(bbmsg);
            }
            orb.getByteBufferPool().releaseByteBuffer(byteBuffer);
            byteBuffer = orb.getByteBufferPool().getByteBuffer(size);
        }
        byteBuffer.position(offset);
        byteBuffer.limit(size);
        readFully(byteBuffer, length, max_wait_time);
        byteBuffer.position(0);
        byteBuffer.limit(size);
        return byteBuffer;
    }
    if (byteBuffer.isDirect()) {
        throw wrapper.unexpectedDirectByteBufferWithNonChannelSocket();
    }
    byte[] buf = new byte[size];
    readFully(getSocket().getInputStream(), buf,
              offset, length, max_wait_time);
    return ByteBuffer.wrap(buf);
}
 
Example 15
Source File: UnsafeAccess.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Reads bytes at the given offset as an int value.
 * @param buf
 * @param offset
 * @return int value at offset
 */
static int getAsInt(ByteBuffer buf, int offset) {
  if (buf.isDirect()) {
    return theUnsafe.getInt(((DirectBuffer) buf).address() + offset);
  }
  return theUnsafe.getInt(buf.array(), BYTE_ARRAY_BASE_OFFSET + buf.arrayOffset() + offset);
}
 
Example 16
Source File: MemoryUtil.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public static void setBytes(long address, ByteBuffer buffer)
{
    int start = buffer.position();
    int count = buffer.limit() - start;
    if (count == 0)
        return;

    if (buffer.isDirect())
        setBytes(unsafe.getLong(buffer, DIRECT_BYTE_BUFFER_ADDRESS_OFFSET) + start, address, count);
    else
        setBytes(address, buffer.array(), buffer.arrayOffset() + start, count);
}
 
Example 17
Source File: Dictionary.java    From ShizuruNotes with Apache License 2.0 4 votes vote down vote up
public static void setData(ByteBuffer data) {
  if (!data.isDirect() || !data.isReadOnly()) {
    throw new BrotliRuntimeException("data must be a direct read-only byte buffer");
  }
  Dictionary.data = data;
}
 
Example 18
Source File: SteamUtils.java    From steamworks4j with MIT License 4 votes vote down vote up
public boolean getImageRGBA(int image, ByteBuffer dest) throws SteamException {
	if (!dest.isDirect()) {
		throw new SteamException("Direct buffer required!");
	}
	return getImageRGBA(pointer, image, dest, dest.position(), dest.remaining());
}
 
Example 19
Source File: ByteBufferPoolImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public void releaseByteBuffer(ByteBuffer thebb)
{
    if (thebb.isDirect())
    {
        synchronized (itsPool)
        {
            // use with debug to determine if byteBuffer is already
            // in the pool.
            boolean refInPool = false;
            int bbAddr = 0;

            if (debug)
            {
                // Check to make sure we don't have 'thebb' reference
                // already in the pool before adding it.

                for (int i = 0; i < itsPool.size() && refInPool == false; i++)
                {
                     ByteBuffer tmpbb = (ByteBuffer)itsPool.get(i);
                     if (thebb == tmpbb)
                     {
                         refInPool = true;
                         bbAddr = System.identityHashCode(thebb);
                     }
                }

            }

            // NOTE: The else part of this if will only get called
            //       if debug = true and refInPool = true, see logic above.
            if (refInPool == false || debug == false)
            {
                // add ByteBuffer back to the pool
                itsPool.add(thebb);
            }
            else // otherwise, log a stack trace with duplicate message
            {
                String threadName = Thread.currentThread().getName();
                Throwable t =
                        new Throwable(threadName +
                                     ": Duplicate ByteBuffer reference (" +
                                     bbAddr + ")");
                t.printStackTrace(System.out);
            }
        }

        // decrement the count of ByteBuffers released
        // IMPORTANT: Since this counter is used only for information
        //            purposes, it does not use synchronized access.
        itsObjectCounter--;
    }
    else
    {
        // ByteBuffer not pooled nor needed
        thebb = null;
    }
}
 
Example 20
Source File: MappedFile.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 4 votes vote down vote up
public static void clean(final ByteBuffer buffer) {
    if (buffer == null || !buffer.isDirect() || buffer.capacity() == 0)
        return;
    invoke(invoke(viewed(buffer), "cleaner"), "clean");
}