java.nio.ByteBuffer#capacity ( )源码实例Demo

下面列出了java.nio.ByteBuffer#capacity ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: buffer_bci   文件: NetworkProtocol.java
/**
 * Decodes a series of extended header chunks from the bytebuffer.
 *
 * @param buffer
 * @return
 * @throws ClientException
 */
private static Chunk[] decodeChunks(final ByteBuffer buffer)
		throws ClientException {
	final ArrayList<Chunk> chunks = new ArrayList<Chunk>();
	int nChunks = 0;

	// Read events while bytes remain in the buffer.
	try {
		while (buffer.position() < buffer.capacity()) {
			chunks.add(decodeChunk(buffer));
			nChunks++;
		}
	} catch (final BufferUnderflowException e) {
		throw new ClientException("Malformed header message");
	}

	return chunks.toArray(new Chunk[nChunks]);
}
 
源代码2 项目: webrtc_android   文件: YuvHelper.java
/** Helper method for copying I420 to tightly packed NV12 destination buffer. */
public static void I420ToNV12(ByteBuffer srcY, int srcStrideY, ByteBuffer srcU, int srcStrideU,
    ByteBuffer srcV, int srcStrideV, ByteBuffer dst, int width, int height) {
  final int chromaWidth = (width + 1) / 2;
  final int chromaHeight = (height + 1) / 2;

  final int minSize = width * height + chromaWidth * chromaHeight * 2;
  if (dst.capacity() < minSize) {
    throw new IllegalArgumentException("Expected destination buffer capacity to be at least "
        + minSize + " was " + dst.capacity());
  }

  final int startY = 0;
  final int startUV = height * width;

  dst.position(startY);
  final ByteBuffer dstY = dst.slice();
  dst.position(startUV);
  final ByteBuffer dstUV = dst.slice();

  nativeI420ToNV12(srcY, srcStrideY, srcU, srcStrideU, srcV, srcStrideV, dstY, width, dstUV,
      chromaWidth * 2, width, height);
}
 
源代码3 项目: mnemonic   文件: JavaVMemServiceImplNGTest.java
/**
 * test to verify the allocate() is working when initzero = true
 */
@Test(enabled = true, dependsOnMethods = "testToInitByCreateNewFile1")
public void testToAllocateWithInit() throws IOException, ClassNotFoundException {
  //Ensure it doesn't impact the test file
  String dest = "./jvmstestallocatewithinit.dat";
  Files.copy(Paths.get(testFile), Paths.get(dest));

  JavaVMemServiceImpl vms = new JavaVMemServiceImpl();
  long cap = 10 * 1024 * 1024;
  long memPool = vms.init(cap, dest, true);
  BufferBlockInfo blockInfo = vms.getMemPools().get((int)memPool).getByteBufferBlocksList().get(0);
  long handler = vms.allocate(memPool, 513, true);
  assertTrue(handler > 0L);
  ByteBuffer bb = vms.retrieveByteBuffer(memPool, handler);
  Assert.assertEquals(bb.capacity(), 513);
  for (int i = 0; i < bb.capacity(); i++) {
    Assert.assertEquals(bb.get(i), (byte)0);
  }
  vms.destroyByteBuffer(memPool, bb, null);
  vms.close(memPool);
  Files.delete(Paths.get(dest));
}
 
源代码4 项目: journalkeeper   文件: PreloadBufferPool.java
@Override
public void releaseDirect(ByteBuffer byteBuffer, BufferHolder bufferHolder) {
    directBufferHolders.remove(bufferHolder);
    int size = byteBuffer.capacity();
    PreLoadCache preLoadCache = bufferCache.get(size);
    if (null != preLoadCache) {
        if (needEviction() && preLoadCache.cache.size() >= preLoadCache.maxCount) {
            destroyOne(byteBuffer);
        } else {
            byteBuffer.clear();
            preLoadCache.cache.add(byteBuffer);
        }
        preLoadCache.onFlyCounter.getAndDecrement();
    } else {
        destroyOne(byteBuffer);
    }
}
 
源代码5 项目: buffer_bci   文件: NetworkProtocol.java
/**
 * Decodes a series of events from the ByteBuffer. Handles event values and
 * types as bytes.
 *
 * @param buffer
 * @return
 * @throws ClientException
 */
public static Event[] decodeEvents(final ByteBuffer buffer)
		throws ClientException {
	final ArrayList<Event> events = new ArrayList<Event>();
	int nEvents = 0;

	// Read events while bytes remain in the buffer.
	try {
		while (buffer.position() < buffer.capacity()) {
			events.add(decodeEvent(buffer));
			nEvents++;
		}
	} catch (final BufferUnderflowException e) {
		throw new ClientException("Malformed event message");
	}

	return events.toArray(new Event[nEvents]);
}
 
源代码6 项目: slick2d-maven   文件: AiffData.java
/**	
 * Creates a AiffData container from the specified ByetBuffer.
 * If the buffer is backed by an array, it will be used directly, 
 * else the contents of the buffer will be copied using get(byte[]).
 *
 * @param buffer ByteBuffer containing sound file
 * @return AiffData containing data, or null if a failure occured
 */
public static AiffData create(ByteBuffer buffer) {
	try {
		byte[] bytes = null;
		
		if(buffer.hasArray()) {
			bytes = buffer.array();
		} else {
			bytes = new byte[buffer.capacity()];
			buffer.get(bytes);
		}
		return create(bytes);
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
}
 
源代码7 项目: hbase   文件: TestByteBufferKeyValue.java
@Test
public void testGetKeyMethods() throws Exception {
  KeyValue kvCell = new KeyValue(row1, fam1, qual1, 0L, Type.Put, row1, tags);
  ByteBuffer buf = ByteBuffer.allocateDirect(kvCell.getKeyLength());
  ByteBufferUtils.copyFromArrayToBuffer(buf, kvCell.getBuffer(), kvCell.getKeyOffset(),
    kvCell.getKeyLength());
  ByteBufferExtendedCell offheapKeyOnlyKV = new ByteBufferKeyOnlyKeyValue(buf, 0, buf.capacity());
  assertEquals(
    ROW1,
    ByteBufferUtils.toStringBinary(offheapKeyOnlyKV.getRowByteBuffer(),
      offheapKeyOnlyKV.getRowPosition(), offheapKeyOnlyKV.getRowLength()));
  assertEquals(
    FAM1,
    ByteBufferUtils.toStringBinary(offheapKeyOnlyKV.getFamilyByteBuffer(),
      offheapKeyOnlyKV.getFamilyPosition(), offheapKeyOnlyKV.getFamilyLength()));
  assertEquals(
    QUAL1,
    ByteBufferUtils.toStringBinary(offheapKeyOnlyKV.getQualifierByteBuffer(),
      offheapKeyOnlyKV.getQualifierPosition(),
      offheapKeyOnlyKV.getQualifierLength()));
  assertEquals(0L, offheapKeyOnlyKV.getTimestamp());
  assertEquals(Type.Put.getCode(), offheapKeyOnlyKV.getTypeByte());
}
 
源代码8 项目: bboxdb   文件: QueryKeyRequest.java
@Override
public long writeToOutputStream(final OutputStream outputStream) throws PackageEncodeException {

	try {
		final byte[] tableBytes = table.getFullnameBytes();
		final byte[] keyBytes = key.getBytes();
		
		final ByteBuffer bb = ByteBuffer.allocate(8);
		bb.order(Const.APPLICATION_BYTE_ORDER);
		
		bb.put(getQueryType());
		
		if(pagingEnabled) {
			bb.put((byte) 1);
		} else {
			bb.put((byte) 0);
		}
		
		bb.putShort(tuplesPerPage);
		bb.putShort((short) tableBytes.length);
		bb.putShort((short) keyBytes.length);
		
		final long bodyLength = bb.capacity() + tableBytes.length + keyBytes.length;
		final long headerLength = appendRequestPackageHeader(bodyLength, outputStream);

		// Write body
		outputStream.write(bb.array());
		outputStream.write(tableBytes);
		outputStream.write(keyBytes);
		
		return headerLength + bodyLength;
	} catch (IOException e) {
		throw new PackageEncodeException("Got exception while converting package into bytes", e);
	}	
}
 
源代码9 项目: activemq-artemis   文件: ByteUtilTest.java
private static byte[] duplicateRemaining(ByteBuffer buffer, int offset, int bytes) {
   final int end = offset + bytes;
   final int expectedRemaining = buffer.capacity() - end;
   //it is handling the case of <0 just to allow from to > capacity
   if (expectedRemaining <= 0) {
      return null;
   }
   final byte[] remaining = new byte[expectedRemaining];
   final ByteBuffer duplicate = buffer.duplicate();
   duplicate.clear().position(end);
   duplicate.get(remaining, 0, expectedRemaining);
   return remaining;
}
 
源代码10 项目: bcm-android   文件: NativeSecp256k1.java
/**
 * libsecp256k1 PubKey Tweak-Add - Tweak pubkey by adding to it
 *
 * @param tweak  some bytes to tweak with
 * @param pubkey 32-byte seckey
 */
public static byte[] pubKeyTweakAdd(byte[] pubkey, byte[] tweak) throws AssertFailException {
    Preconditions.checkArgument(pubkey.length == 33 || pubkey.length == 65);

    ByteBuffer byteBuff = nativeECDSABuffer.get();
    if (byteBuff == null || byteBuff.capacity() < pubkey.length + tweak.length) {
        byteBuff = ByteBuffer.allocateDirect(pubkey.length + tweak.length);
        byteBuff.order(ByteOrder.nativeOrder());
        nativeECDSABuffer.set(byteBuff);
    }
    byteBuff.rewind();
    byteBuff.put(pubkey);
    byteBuff.put(tweak);

    byte[][] retByteArray;
    r.lock();
    try {
        retByteArray = secp256k1_pubkey_tweak_add(byteBuff, Secp256k1Context.getContext(), pubkey.length);
    } finally {
        r.unlock();
    }

    byte[] pubArr = retByteArray[0];

    int pubLen = (byte) new BigInteger(new byte[]{retByteArray[1][0]}).intValue() & 0xFF;
    int retVal = new BigInteger(new byte[]{retByteArray[1][1]}).intValue();

    assertEquals(pubArr.length, pubLen, "Got bad pubkey length.");

    assertEquals(retVal, 1, "Failed return value check.");

    return pubArr;
}
 
源代码11 项目: Slyther   文件: Draft.java
public static HandshakeBuilder translateHandshakeHttp( ByteBuffer buf, Role role ) throws InvalidHandshakeException , IncompleteHandshakeException {
	HandshakeBuilder handshake;

	String line = readStringLine( buf );
	if( line == null )
		throw new IncompleteHandshakeException( buf.capacity() + 128 );

	String[] firstLineTokens = line.split( " ", 3 );// eg. HTTP/1.1 101 Switching the Protocols
	if( firstLineTokens.length != 3 ) {
		throw new InvalidHandshakeException();
	}

	if( role == Role.CLIENT ) {
		// translating/parsing the response from the SERVER
		handshake = new HandshakeImpl1Server();
		ServerHandshakeBuilder serverhandshake = (ServerHandshakeBuilder) handshake;
		serverhandshake.setHttpStatus( Short.parseShort( firstLineTokens[ 1 ] ) );
		serverhandshake.setHttpStatusMessage( firstLineTokens[ 2 ] );
	} else {
		// translating/parsing the request from the CLIENT
		ClientHandshakeBuilder clienthandshake = new HandshakeImpl1Client();
		clienthandshake.setResourceDescriptor( firstLineTokens[ 1 ] );
		handshake = clienthandshake;
	}

	line = readStringLine( buf );
	while ( line != null && line.length() > 0 ) {
		String[] pair = line.split( ":", 2 );
		if( pair.length != 2 )
			throw new InvalidHandshakeException( "not an http header" );
		handshake.put( pair[ 0 ], pair[ 1 ].replaceFirst( "^ +", "" ) );
		line = readStringLine( buf );
	}
	if( line == null )
		throw new IncompleteHandshakeException();
	return handshake;
}
 
源代码12 项目: slick2d-maven   文件: Graphics.java
/**
 * Get an ara of pixels as RGBA values into a buffer
 * 
 * @param x The x position in the context to grab from
 * @param y The y position in the context to grab from
 * @param width The width of the area to grab from 
 * @param height The hiehgt of the area to grab from
 * @param target The target buffer to grab into
 */
public void getArea(int x, int y, int width, int height, ByteBuffer target)
{
	if (target.capacity() < width * height * 4) 
	{
		throw new IllegalArgumentException("Byte buffer provided to get area is not big enough");
	}
	
	predraw();	
	GL.glReadPixels(x, screenHeight - y - height, width, height, SGL.GL_RGBA,
			SGL.GL_UNSIGNED_BYTE, target);
	postdraw();
}
 
源代码13 项目: sdl_java_suite   文件: BaseAudioDecoder.java
protected MediaCodec.BufferInfo onInputBufferAvailable(@NonNull MediaExtractor extractor, @NonNull ByteBuffer inputBuffer) {
    long sampleTime = extractor.getSampleTime();
    int counter = 0;
    int maxresult = 0;
    int result;
    boolean advanced = false;

    do {
        result = extractor.readSampleData(inputBuffer, counter);
        if (result >= 0) {
            advanced = extractor.advance();
            maxresult = Math.max(maxresult, result);
            counter += result;
        }
    } while (result >= 0 && advanced && inputBuffer.capacity() - inputBuffer.limit() > maxresult);
    // the remaining capacity should be more than enough for another sample data block

    // queue the input buffer. At end of file counter will be 0 and flags marks end of stream
    // offset MUST be 0. The output buffer code cannot handle offsets
    // result < 0 means the end of the file input is reached
    int flags = advanced ? 0 : MediaCodec.BUFFER_FLAG_END_OF_STREAM;

    MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
    bufferInfo.set(0, counter, sampleTime, flags);

    return bufferInfo;
}
 
源代码14 项目: openjdk-8   文件: TrueTypeFont.java
private void setStyle(ByteBuffer os_2Table) {
        /* fsSelection is unsigned short at buffer offset 62 */
        if (os_2Table == null || os_2Table.capacity() < 64) {
            super.setStyle();
            return;
        }
        int fsSelection = os_2Table.getChar(62) & 0xffff;
        int italic  = fsSelection & fsSelectionItalicBit;
        int bold    = fsSelection & fsSelectionBoldBit;
        int regular = fsSelection & fsSelectionRegularBit;
//      System.out.println("platname="+platName+" font="+fullName+
//                         " family="+familyName+
//                         " R="+regular+" I="+italic+" B="+bold);
        if (regular!=0 && ((italic|bold)!=0)) {
            /* This is inconsistent. Try using the font name algorithm */
            super.setStyle();
            return;
        } else if ((regular|italic|bold) == 0) {
            /* No style specified. Try using the font name algorithm */
            super.setStyle();
            return;
        }
        switch (bold|italic) {
        case fsSelectionItalicBit:
            style = Font.ITALIC;
            break;
        case fsSelectionBoldBit:
            if (FontUtilities.isSolaris && platName.endsWith("HG-GothicB.ttf")) {
                /* Workaround for Solaris's use of a JA font that's marked as
                 * being designed bold, but is used as a PLAIN font.
                 */
                style = Font.PLAIN;
            } else {
                style = Font.BOLD;
            }
            break;
        case fsSelectionBoldBit|fsSelectionItalicBit:
            style = Font.BOLD|Font.ITALIC;
        }
    }
 
源代码15 项目: stratosphere   文件: DataInputDecoder.java
@Override
public ByteBuffer readBytes(ByteBuffer old) throws IOException {
	int length = readInt();
	ByteBuffer result;
	if (old != null && length <= old.capacity() && old.hasArray()) {
		result = old;
		result.clear();
	} else {
		result = ByteBuffer.allocate(length);
	}
	in.readFully(result.array(), result.arrayOffset() + result.position(), length);
	result.limit(length);
	return result;
}
 
源代码16 项目: OpenFit   文件: Fitness.java
@SuppressWarnings("unused")
public static void parseData() {
    Log.d(LOG_TAG, "Parsing data");
    ByteBuffer buffer = ByteBuffer.wrap(fitnessStream.toByteArray());
    buffer = buffer.order(ByteOrder.LITTLE_ENDIAN);

    if(buffer.capacity() < 14) {
        return;
    }

    byte msgType = buffer.get();
    int msgSize = buffer.getInt();
    int byte4 = buffer.getInt();
    int byte1 = buffer.getInt();
    byte byteFF = buffer.get();
    Log.d(LOG_TAG, "type: " + msgType);
    Log.d(LOG_TAG, "msgSize: " + msgSize);

    while(buffer.hasRemaining()) {
        byte fitnessType = buffer.get();
        Log.d(LOG_TAG, "Fitness type: " + fitnessType);
        if(fitnessType ==  OpenFitData.DATA_TYPE_USER_PROFILE) {
            Log.d(LOG_TAG, "User Profile");
            parseUserProfile(buffer);
        }
        else if(fitnessType ==  OpenFitData.DATA_TYPE_PEDOMETER_PROFILE) {
            Log.d(LOG_TAG, "Pedometer Profile");
            parsePedometerProfile(buffer);
        }
        else if(fitnessType ==  OpenFitData.DATA_TYPE_PEDO_RESULTRECORD) {
            Log.d(LOG_TAG, "Pedometer Result Record");
            parsePedoResultRecord(buffer);
        }
        else if(fitnessType ==  OpenFitData.DATA_TYPE_HEARTRATE_RESULTRECORD) {
            Log.d(LOG_TAG, "Heartrate Result Record");
            parseHeartrateResultRecord(buffer);
        }
        else if(fitnessType ==  OpenFitData.DATA_TYPE_PEDO_INFO) {
            Log.d(LOG_TAG, "Pedometer Info");
            parsePedoInfo(buffer);
        }
        else if(fitnessType == OpenFitData.DATA_TYPE_SLEEP_INFO) {
            Log.d(LOG_TAG, "Sleep Info");
            parseSleepInfo(buffer);
        }
        else if(fitnessType == OpenFitData.DATA_TYPE_SLEEP_RESULTRECORD) {
            Log.d(LOG_TAG, "Sleep Result Record");
            parseSleepResultRecord(buffer);
        }
        else if(fitnessType == OpenFitData.DATA_TYPE_COACHING_VARS) {
            Log.d(LOG_TAG, "Coaching Vars");
            parseCoachingVars(buffer);
        }
        else if(fitnessType == OpenFitData.DATA_TYPE_COACHING_EXERCISERESULT) {
            Log.d(LOG_TAG, "Coaching Excercise Result");
            parseCoachingExerciseResult(buffer);
        }
        else if(fitnessType == OpenFitData.DATA_TYPE_COACHING_RESULTRECORD) {
            Log.d(LOG_TAG, "Coaching Result Record");
            parseCoachingResultRecord(buffer);

        }
        else {
            Log.d(LOG_TAG, "Unsupported: " + fitnessType);
            //logBuffer(buffer);
            depleteBuffer(buffer);
        }
    }

    Log.d(LOG_TAG, "remaining buffer: " + buffer.remaining());
}
 
源代码17 项目: ignite   文件: CacheObjectAdapter.java
/**
 * @param cacheObjType Cache object type.
 * @param buf Buffer to write value to.
 * @param off Offset in source binary data.
 * @param len Length of the data to write.
 * @param valBytes Binary data.
 * @param start Start offset in binary data.
 * @return {@code True} if data were successfully written.
 * @throws IgniteCheckedException If failed.
 */
public static boolean putValue(byte cacheObjType,
    final ByteBuffer buf,
    int off,
    int len,
    byte[] valBytes,
    final int start)
    throws IgniteCheckedException
{
    int dataLen = valBytes.length;

    if (buf.remaining() < len)
        return false;

    final int headSize = 5; // 4 bytes len + 1 byte type

    if (off == 0 && len >= headSize) {
        buf.putInt(dataLen);
        buf.put(cacheObjType);

        len -= headSize;
    }
    else if (off >= headSize)
        off -= headSize;
    else {
        // Partial header write.
        final ByteBuffer head = ByteBuffer.allocate(headSize);

        head.order(buf.order());

        head.putInt(dataLen);
        head.put(cacheObjType);

        head.position(off);

        if (len < head.capacity())
            head.limit(off + Math.min(len, head.capacity() - off));

        buf.put(head);

        if (head.limit() < headSize)
            return true;

        len -= headSize - off;
        off = 0;
    }

    buf.put(valBytes, start + off, len);

    return true;
}
 
源代码18 项目: rocketmq   文件: MapedFile.java
public static void clean(final ByteBuffer buffer) {
    if (buffer == null || !buffer.isDirect() || buffer.capacity() == 0)
        return;
    invoke(invoke(viewed(buffer), "cleaner"), "clean");
}
 
源代码19 项目: JglTF   文件: BufferStructureBuilder.java
/**
 * Apply the given byte stride to the given buffer and return the result
 * as a new buffer. The directness or byte order of the result are not
 * specified.<br>
 * <br>
 * This is supposed to be applied to accessor byte buffers. For example:
 * For an an accessor with 2D float elements, the old byte stride will 
 * be 2 * 4, and the old byte buffer may contain 24 bytes. Calling this
 * method with a new byte stride of 3 * 4 will cause padding bytes to
 * be inserted in the returned buffer: 
 * <pre><code>
 * oldByteBuffer: |X0|Y0|X1|Y1|X2|Y2|
 * newByteBuffer: |X0|Y0|..|X1|Y1|..|X2|Y2|..|
 * </code></pre>
 *  
 * @param oldByteBuffer The old byte buffer 
 * @param oldByteStride The old byte stride
 * @param newByteStride The new byte stride
 * @return The new byte buffer
 */
private static ByteBuffer applyByteStride(
    ByteBuffer oldByteBuffer, int oldByteStride, int newByteStride)
{
    int count = oldByteBuffer.capacity() / oldByteStride;
    ByteBuffer newByteBuffer = ByteBuffer.allocate(count * newByteStride);
    for (int i = 0; i < count; i++)
    {
        int srcPos = i * oldByteStride;
        int dstPos = i * newByteStride;
        Buffers.bufferCopy(oldByteBuffer, srcPos, 
            newByteBuffer, dstPos, oldByteStride);
    }
    return newByteBuffer;
}
 
源代码20 项目: openjdk-jdk8u-backup   文件: ByteBufferArrayData.java
/**
 * Constructor
 *
 * @param buf ByteBuffer to create array data with.
 */
ByteBufferArrayData(final ByteBuffer buf) {
    super(buf.capacity());
    this.buf = buf;
}