Java Code Examples for java.nio.IntBuffer#remaining()

The following examples show how to use java.nio.IntBuffer#remaining() . 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: BufferUtils.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static IntBuffer ensureLargeEnough(IntBuffer buffer, int required) {
    if (buffer != null) {
        buffer.limit(buffer.capacity());
    }
    if (buffer == null || (buffer.remaining() < required)) {
        int position = (buffer != null ? buffer.position() : 0);
        IntBuffer newVerts = createIntBuffer(position + required);
        if (buffer != null) {
            buffer.flip();
            newVerts.put(buffer);
            newVerts.position(position);
        }
        buffer = newVerts;
    }
    return buffer;
}
 
Example 2
Source File: GeoMap.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public IntBuffer writeIndexArray(IntBuffer store){
    int faceN = (getWidth()-1)*(getHeight()-1)*2;

    if (store!=null){
        if (store.remaining() < faceN*3)
            throw new BufferUnderflowException();
    }else{
        store = BufferUtils.createIntBuffer(faceN*3);
    }

    int i = 0;
    for (int z = 0; z < getHeight()-1; z++){
        for (int x = 0; x < getWidth()-1; x++){
            store.put(i).put(i+getWidth()).put(i+getWidth()+1);
            store.put(i+getWidth()+1).put(i+1).put(i);
            i++;

            // TODO: There's probably a better way to do this..
            if (x==getWidth()-2) i++;
        }
    }
    store.flip();

    return store;
}
 
Example 3
Source File: BufferUtils.java    From Ultraino with MIT License 6 votes vote down vote up
public static IntBuffer ensureLargeEnough(IntBuffer buffer, int required) {
    if (buffer != null) {
        buffer.limit(buffer.capacity());
    }
    if (buffer == null || (buffer.remaining() < required)) {
        int position = (buffer != null ? buffer.position() : 0);
        IntBuffer newVerts = createIntBuffer(position + required);
        if (buffer != null) {
            buffer.flip();
            newVerts.put(buffer);
            newVerts.position(position);
        }
        buffer = newVerts;
    }
    return buffer;
}
 
Example 4
Source File: ArrayUtils.java    From icafe with Eclipse Public License 1.0 6 votes vote down vote up
public static int[] toIntArray(byte[] data, int offset, int len, boolean bigEndian) {
	
	ByteBuffer byteBuffer = ByteBuffer.wrap(data, offset, len);
	
	if (bigEndian) {
		byteBuffer.order(ByteOrder.BIG_ENDIAN);
	} else {
		byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
	}
	
	IntBuffer intBuf = byteBuffer.asIntBuffer();
	int[] array = new int[intBuf.remaining()];
	intBuf.get(array);
	
	return array;
}
 
Example 5
Source File: ArrayUtils.java    From pixymeta-android with Eclipse Public License 1.0 6 votes vote down vote up
public static int[] toIntArray(byte[] data, int offset, int len, boolean bigEndian) {
	
	ByteBuffer byteBuffer = ByteBuffer.wrap(data, offset, len);
	
	if (bigEndian) {
		byteBuffer.order(ByteOrder.BIG_ENDIAN);
	} else {
		byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
	}
	
	IntBuffer intBuf = byteBuffer.asIntBuffer();
	int[] array = new int[intBuf.remaining()];
	intBuf.get(array);
	
	return array;
}
 
Example 6
Source File: GeoMap.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public IntBuffer writeIndexArray(IntBuffer store){
    int faceN = (getWidth()-1)*(getHeight()-1)*2;

    if (store!=null){
        if (store.remaining() < faceN*3)
            throw new BufferUnderflowException();
    }else{
        store = BufferUtils.createIntBuffer(faceN*3);
    }

    int i = 0;
    for (int z = 0; z < getHeight()-1; z++){
        for (int x = 0; x < getWidth()-1; x++){
            store.put(i).put(i+getWidth()).put(i+getWidth()+1);
            store.put(i+getWidth()+1).put(i+1).put(i);
            i++;

            // TODO: There's probably a better way to do this..
            if (x==getWidth()-2) i++;
        }
    }
    store.flip();

    return store;
}
 
Example 7
Source File: IosGL.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void fromArray(int n, int[] array, IntBuffer buffer) {
    if (buffer.remaining() < n) { 
        throw new BufferOverflowException();
    }
    int pos = buffer.position();
    buffer.put(array, 0, n);
    buffer.position(pos);
}
 
Example 8
Source File: NDArray.java    From djl with Apache License 2.0 5 votes vote down vote up
/**
 * Converts this {@code NDArray} to an int array.
 *
 * @return an int array
 * @throws IllegalStateException when {@link DataType} of this {@code NDArray} mismatches
 */
default int[] toIntArray() {
    if (getDataType() != DataType.INT32) {
        throw new IllegalStateException(
                "DataType mismatch, Required int" + " Actual " + getDataType());
    }
    IntBuffer ib = toByteBuffer().asIntBuffer();
    int[] ret = new int[ib.remaining()];
    ib.get(ret);
    return ret;
}
 
Example 9
Source File: IosGL.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private int toArray(IntBuffer buffer) {
    int remain = buffer.remaining();
    if (buffer.remaining() > 16) {
        throw new ArrayIndexOutOfBoundsException();
    }
    int pos = buffer.position();
    buffer.get(temp_array, 0, remain);
    buffer.position(pos);
    return remain;
}
 
Example 10
Source File: MegaSdk.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
public static int[] unpack ( byte[] bytes ) {
    // first, wrap the input array in a ByteBuffer:
    ByteBuffer byteBuf = ByteBuffer.wrap( bytes );

    // then turn it into an IntBuffer, using big-endian ("Network") byte order:
    byteBuf.order( ByteOrder.BIG_ENDIAN );
    IntBuffer intBuf = byteBuf.asIntBuffer();

    // finally, dump the contents of the IntBuffer into an array
    int[] integers = new int[ intBuf.remaining() ];
    intBuf.get( integers );
    return integers;
}
 
Example 11
Source File: StrutsTokenCracker.java    From J2EEScan with GNU General Public License v2.0 5 votes vote down vote up
private static int[] bytesToInt(byte[] bytes) {
    //I don't feel like to doing binary operations today..
    IntBuffer intBuf = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN).asIntBuffer();
    int[] array = new int[intBuf.remaining()];
    intBuf.get(array);
    return array;
}
 
Example 12
Source File: Encryption.java    From browserprint with MIT License 5 votes vote down vote up
/**
 * Decrypt an array of integers from a String.
 * 
 * @param encrypted
 * @param context
 * @return
 * @throws ServletException
 */
public static int[] decryptIntegers(String encrypted, String password) throws ServletException {
	String encryptedParts[] = encrypted.split("\\|");
	if (encryptedParts.length != 3) {
		throw new ServletException("Invalid encrypted string.");
	}

	/* Extract the encrypted data, initialisation vector, and salt from the cookie. */
	Decoder decoder = Base64.getDecoder();
	byte ciphertext[] = decoder.decode(encryptedParts[0]);
	byte iv[] = decoder.decode(encryptedParts[1]);
	byte salt[] = decoder.decode(encryptedParts[2]);
	byte plainbytes[];
	try {
		/* Derive the key, given password and salt. */
		SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
		KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
		SecretKey tmp = factory.generateSecret(spec);
		SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

		/* Decrypt the message, given derived key and initialization vector. */
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
		plainbytes = cipher.doFinal(ciphertext);
	} catch (Exception ex) {
		throw new ServletException(ex);
	}
	IntBuffer buff = ByteBuffer.wrap(plainbytes).asIntBuffer();
	int integers[] = new int[buff.remaining()];
	for (int i = 0; i < integers.length; ++i) {
		integers[i] = buff.get();
	}
	return integers;
}
 
Example 13
Source File: CryptoRandomSource.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Converts a {@code byte} array to an {@code int} array. The {@code byte} array is assumed to
 * contain {@code int}s encoded in little endian order.
 */
static int[] bytesToInts(final byte[] bytes) {
  final ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length).order(ByteOrder.LITTLE_ENDIAN);
  byteBuffer.put(bytes);
  byteBuffer.rewind();
  final IntBuffer intBuffer = byteBuffer.asIntBuffer();
  final int[] ints = new int[intBuffer.remaining()];
  intBuffer.get(ints);
  return ints;
}
 
Example 14
Source File: StaticMeshesLoader.java    From lwjglbook with Apache License 2.0 5 votes vote down vote up
protected static void processIndices(AIMesh aiMesh, List<Integer> indices) {
    int numFaces = aiMesh.mNumFaces();
    AIFace.Buffer aiFaces = aiMesh.mFaces();
    for (int i = 0; i < numFaces; i++) {
        AIFace aiFace = aiFaces.get(i);
        IntBuffer buffer = aiFace.mIndices();
        while (buffer.remaining() > 0) {
            indices.add(buffer.get());
        }
    }
}
 
Example 15
Source File: StaticMeshesLoader.java    From lwjglbook with Apache License 2.0 5 votes vote down vote up
private static void processIndices(AIMesh aiMesh, List<Integer> indices) {
    int numFaces = aiMesh.mNumFaces();
    AIFace.Buffer aiFaces = aiMesh.mFaces();
    for (int i = 0; i < numFaces; i++) {
        AIFace aiFace = aiFaces.get(i);
        IntBuffer buffer = aiFace.mIndices();
        while (buffer.remaining() > 0) {
            indices.add(buffer.get());
        }
    }
}
 
Example 16
Source File: Spot.java    From dexter with Apache License 2.0 5 votes vote down vote up
/**
 * Decodes a Spot from a byte representation, if the given text match the
 * spot text encoded in the byte array.
 * 
 * @see toByteArray
 * 
 * @param text
 *            - the spot text to decode
 * @param data
 *            - the binary rep for the spot
 * @return A spot if the given string <code> text </code> matches the text
 *         of the spot encoded in data, otherwise null
 */
public static Spot fromByteArray(String text, byte[] data) {
	int len = data[0];

	if (text.length() != len) {
		logger.warn("len {} !=  {} len", len, text);
		return null;
	}

	String s = null;
	try {
		s = new String(Arrays.copyOfRange(data, 1, 1 + len), "US-ASCII");
	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	if (!s.equals(text)) {
		logger.warn(" {} !=  {} ", s, text);
		return null;
	}

	IntBuffer intBuf = ByteBuffer.wrap(
			Arrays.copyOfRange(data, 1 + len, data.length)).asIntBuffer();
	int[] array = new int[intBuf.remaining()];
	intBuf.get(array);
	// List<Entity> entities = null;
	List<Entity> entities = new ArrayList<Entity>(array.length - 2);

	for (int i = 2; i < array.length; i += 2) {
		entities.add(new Entity(array[i], array[i + 1]));
	}
	Spot spot = new Spot(text, entities, array[0], array[1]);
	return spot;
}
 
Example 17
Source File: IntJustCopy.java    From metrics with Apache License 2.0 5 votes vote down vote up
private void copy(IntBuffer src, IntOutputStream dst) {
    int[] buf = new int[1024];
    int len;
    while ((len = src.remaining()) > 0) {
        if (len > buf.length) {
            len = buf.length;
        }
        src.get(buf, 0, len);
        dst.write(buf, 0, len);
    }
}
 
Example 18
Source File: PrimitiveIntArraySerializationProvider.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public int[] readField(final byte[] fieldData, final byte serializationVersion) {
  if ((fieldData == null) || (fieldData.length == 0)) {
    return null;
  }
  if (serializationVersion < FieldUtils.SERIALIZATION_VERSION) {
    final IntBuffer buff = ByteBuffer.wrap(fieldData).asIntBuffer();
    final int[] result = new int[buff.remaining()];
    buff.get(result);
    return result;
  } else {
    return readField(fieldData);
  }
}
 
Example 19
Source File: BridgeTestCommand.java    From commons-rng with Apache License 2.0 4 votes vote down vote up
/**
 * Starts the executable process and writes {@code int} values to a data file and the stdin
 * of the executable. Captures stdout of the executable to a file.
 */
private void runBridgeTest() {
    final List<String> command = ProcessUtils.buildSubProcessCommand(executable, executableArguments);

    try {
        final File dataFile = new File(fileOutputPrefix + ".data");
        final File outputFile = new File(fileOutputPrefix + ".out");
        final File errorFile = new File(fileOutputPrefix + ".err");

        // Store int values
        final IntBuffer buffer = IntBuffer.allocate(Integer.SIZE * 2);

        try (BufferedWriter textOutput = Files.newBufferedWriter(dataFile.toPath())) {
            // Write int data using a single bit in all possible positions
            int value = 1;
            for (int i = 0; i < Integer.SIZE; i++) {
                writeInt(textOutput, buffer, value);
                value <<= 1;
            }

            // Write random int data
            while (buffer.remaining() != 0) {
                writeInt(textOutput, buffer, ThreadLocalRandom.current().nextInt());
            }
        }

        // Pass the same values to the output application
        buffer.flip();
        UniformRandomProvider rng = new IntProvider() {
            @Override
            public int next() {
                return buffer.get();
            }
        };

        // Start the application.
        final ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectOutput(ProcessBuilder.Redirect.to(outputFile));
        builder.redirectError(ProcessBuilder.Redirect.to(errorFile));
        final Process testingProcess = builder.start();

        // Open the stdin of the process and write to a custom data sink.
        // Note: The 'bridge' command only supports 32-bit data in order to
        // demonstrate passing suitable data for TestU01 BigCrush.
        final boolean raw64 = false;
        try (RngDataOutput sink = RNGUtils.createDataOutput(rng, raw64,
                testingProcess.getOutputStream(), buffer.capacity() * 4, byteOrder)) {
            sink.write(rng);
        }

        final Integer exitValue = ProcessUtils.getExitValue(testingProcess);
        if (exitValue == null) {
            LogUtils.error("%s did not exit. Process was killed.", command.get(0));
        } else {
            if (exitValue.intValue() != 0) {
                LogUtils.error("%s exit code = %d", command.get(0), exitValue.intValue());
            }
        }

    } catch (IOException ex) {
        throw new ApplicationException("Failed to run process: " + ex.getMessage(), ex);
    }
}
 
Example 20
Source File: IOUtils.java    From thulac4j with Apache License 2.0 3 votes vote down vote up
/**
 * Gets the contents of an <code>InputStream</code> as a int array.
 * <p>
 * This method buffers the input internally, so there is no need to use a
 * <code>BufferedInputStream</code>.
 *
 * @param input the <code>InputStream</code> to read from
 * @return the requested int array
 * @throws NullPointerException if the input is null
 * @throws IOException          if an I/O error occurs
 */
public static int[] toIntArray(final InputStream input) throws IOException {
	byte[] bytes = toByteArray(input);
	IntBuffer intBuffer = ByteBuffer.wrap(bytes)
			.order(ByteOrder.LITTLE_ENDIAN)
			.asIntBuffer();
	int[] array = new int[intBuffer.remaining()];
	intBuffer.get(array);
	return array;
}