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

The following examples show how to use java.nio.IntBuffer#rewind() . 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
/**
 * Creates a new IntBuffer with the same contents as the given IntBuffer.
 * The new IntBuffer is separate from the old one and changes are not
 * reflected across. If you want to reflect changes, consider using
 * Buffer.duplicate().
 *
 * @param buf
 *            the IntBuffer to copy
 * @return the copy
 */
public static IntBuffer clone(IntBuffer buf) {
    if (buf == null) {
        return null;
    }
    buf.rewind();

    IntBuffer copy;
    if (isDirect(buf)) {
        copy = createIntBuffer(buf.limit());
    } else {
        copy = IntBuffer.allocate(buf.limit());
    }
    copy.put(buf);

    return copy;
}
 
Example 2
Source File: BufferUtils.java    From aion-germany with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new IntBuffer with the same contents as the given IntBuffer. The new IntBuffer 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 IntBuffer to copy
 * @return the copy
 */
public static IntBuffer clone(IntBuffer buf) {
	if (buf == null) {
		return null;
	}
	buf.rewind();

	IntBuffer copy;
	if (buf.isDirect()) {
		copy = createIntBuffer(buf.limit());
	}
	else {
		copy = IntBuffer.allocate(buf.limit());
	}
	copy.put(buf);

	return copy;
}
 
Example 3
Source File: OffHeapHashMap.java    From offheap-store with Apache License 2.0 6 votes vote down vote up
private static boolean updateEncodingInTable(IntBuffer table, int limit, int hash, long oldEncoding, long newEncoding, long mask) {
  table.position(indexFor(spread(hash), table));

  for (int i = 0; i < limit; i++) {
    if (!table.hasRemaining()) {
      table.rewind();
    }

    IntBuffer entry = (IntBuffer) table.slice().limit(ENTRY_SIZE);

    if (isTerminating(entry)) {
      return false;
    } else if (isPresent(entry) && (hash == entry.get(KEY_HASHCODE)) && ((oldEncoding & mask) == (readLong(entry, ENCODING) & mask))) {
      entry.put(createEntry(hash, (readLong(entry, ENCODING) & ~mask) | newEncoding & mask, entry.get(STATUS)));
      return true;
    } else {
      table.position(table.position() + ENTRY_SIZE);
    }
  }
  return false;
}
 
Example 4
Source File: OffHeapHashMap.java    From offheap-store with Apache License 2.0 5 votes vote down vote up
private void updatePendingTables(int hash, long oldEncoding, IntBuffer newEntry) {
  if (hasUsedIterators) {
    pendingTableFrees.reap();

    Iterator<PendingPage> it = pendingTableFrees.values();
    while (it.hasNext()) {
      PendingPage pending = it.next();

      IntBuffer pendingTable = pending.tablePage.asIntBuffer();
      pendingTable.position(indexFor(spread(hash), pendingTable));

      for (int i = 0; i < pending.reprobe; i++) {
        if (!pendingTable.hasRemaining()) {
          pendingTable.rewind();
        }

        IntBuffer entry = (IntBuffer) pendingTable.slice().limit(ENTRY_SIZE);

        if (isTerminating(entry)) {
          break;
        } else if (isPresent(entry) && (hash == entry.get(KEY_HASHCODE)) && (oldEncoding == readLong(entry, ENCODING))) {
          entry.put(newEntry.duplicate());
          break;
        } else {
          pendingTable.position(pendingTable.position() + ENTRY_SIZE);
        }
      }
    }
  }
}
 
Example 5
Source File: BinaryOutputCapsule.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected void write(IntBuffer value) throws IOException {
    if (value == null) {
        write(NULL_OBJECT);
        return;
    }
    value.rewind();
    int length = value.limit();
    write(length);

    for (int x = 0; x < length; x++) {
        writeForBuffer(value.get());
    }
    value.rewind();
}
 
Example 6
Source File: NativeCursors.java    From Monocle with GNU General Public License v2.0 5 votes vote down vote up
private static void colorKeyCursor32(byte[] source, IntBuffer destBuffer,
                                     int transparentPixel) {
    IntBuffer sourceBuffer = ByteBuffer.wrap(source).asIntBuffer();
    while (sourceBuffer.position() < sourceBuffer.limit()) {
        int i = sourceBuffer.get();
        if ((i & 0xff) == 0) {
            destBuffer.put(transparentPixel);
        } else {
            destBuffer.put(i);
        }
    }
    destBuffer.rewind();
}
 
Example 7
Source File: TestUtils.java    From succinct with Apache License 2.0 5 votes vote down vote up
public static FSDataInputStream getStream(IntBuffer buf) throws IOException {
  File tmpDir = Files.createTempDir();
  Path filePath = new Path(tmpDir.getAbsolutePath() + "/testOut");
  FileSystem fs = FileSystem.get(filePath.toUri(), new Configuration());
  FSDataOutputStream fOut = fs.create(filePath);
  buf.rewind();
  while (buf.hasRemaining()) {
    fOut.writeInt(buf.get());
  }
  fOut.close();
  buf.rewind();
  return fs.open(filePath);
}
 
Example 8
Source File: DOMOutputCapsule.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void write(IntBuffer value, String name, IntBuffer defVal) throws IOException {
    if (value == null) {
        return;
    }
    if (value.equals(defVal)) {
        return;
    }

    Element el = appendElement(name);
    el.setAttribute("size", String.valueOf(value.limit()));
    StringBuilder buf = new StringBuilder();
    int pos = value.position();
    value.rewind();
    int ctr = 0;
    while (value.hasRemaining()) {
        ctr++;
        buf.append(value.get());
        buf.append(" ");
    }
    if (ctr != value.limit()) {
        throw new IOException("'" + name
            + "' buffer contention resulted in write data consistency.  "
            + ctr + " values written when should have written "
            + value.limit());
    }
    
    if (buf.length() > 0) {
        //remove last space
        buf.setLength(buf.length() - 1);
    }
    value.position(pos);
    el.setAttribute(dataAttributeName, buf.toString());
    currentElement = (Element) el.getParentNode();
}
 
Example 9
Source File: NDManager.java    From djl with Apache License 2.0 5 votes vote down vote up
/**
 * Creates and initializes a 2D {@link NDArray}.
 *
 * @param data the float array that needs to be set
 * @return a new instance of {@link NDArray}
 */
default NDArray create(int[][] data) {
    IntBuffer buffer = IntBuffer.allocate(data.length * data[0].length);
    for (int[] d : data) {
        buffer.put(d);
    }
    buffer.rewind();
    return create(buffer, new Shape(data.length, data[0].length));
}
 
Example 10
Source File: OffHeapHashMap.java    From offheap-store with Apache License 2.0 5 votes vote down vote up
@Override
public Long getEncodingForHashAndBinary(int hash, ByteBuffer binaryKey) {
  if (size == 0) {
    return null;
  }

  IntBuffer view = (IntBuffer) hashtable.duplicate().position(indexFor(spread(hash)));

  int limit = reprobeLimit();

  for (int i = 0; i < limit; i++) {
    if (!view.hasRemaining()) {
      view.rewind();
    }

    IntBuffer entry = (IntBuffer) view.slice().limit(ENTRY_SIZE);

    if (isTerminating(entry)) {
      return null;
    } else if (isPresent(entry) && binaryKeyEquals(binaryKey, hash, readLong(entry, ENCODING), entry.get(KEY_HASHCODE))) {
      return readLong(entry, ENCODING);
    } else {
      view.position(view.position() + ENTRY_SIZE);
    }
  }
  return null;
}
 
Example 11
Source File: OffHeapHashMap.java    From offheap-store with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public V get(Object key) {
  int hash = key.hashCode();

  if (size == 0) {
    return null;
  }

  IntBuffer view = (IntBuffer) hashtable.duplicate().position(indexFor(spread(hash)));

  int limit = reprobeLimit();

  for (int i = 0; i < limit; i++) {
    if (!view.hasRemaining()) {
      view.rewind();
    }

    IntBuffer entry = (IntBuffer) view.slice().limit(ENTRY_SIZE);

    if (isTerminating(entry)) {
      return null;
    } else if (isPresent(entry) && keyEquals(key, hash, readLong(entry, ENCODING), entry.get(KEY_HASHCODE))) {
      hit(view.position(), entry);
      return (V) storageEngine.readValue(readLong(entry, ENCODING));
    } else {
      view.position(view.position() + ENTRY_SIZE);
    }
  }
  return null;
}
 
Example 12
Source File: OffHeapHashMap.java    From offheap-store with Apache License 2.0 5 votes vote down vote up
@Override
public boolean containsKey(Object key) {
  int hash = key.hashCode();

  if (size == 0) {
    return false;
  }

  IntBuffer view = (IntBuffer) hashtable.duplicate().position(indexFor(spread(hash)));

  int limit = reprobeLimit();

  for (int i = 0; i < limit; i++) {
    if (!view.hasRemaining()) {
      view.rewind();
    }

    IntBuffer entry = (IntBuffer) view.slice().limit(ENTRY_SIZE);

    if (isTerminating(entry)) {
      return false;
    } else if (isPresent(entry) && keyEquals(key, hash, readLong(entry, ENCODING), entry.get(KEY_HASHCODE))) {
      hit(view.position(), entry);
      return true;
    } else {
      view.position(view.position() + ENTRY_SIZE);
    }
  }
  return false;
}
 
Example 13
Source File: DOMOutputCapsule.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void write(IntBuffer value, String name, IntBuffer defVal) throws IOException {
    if (value == null) {
        return;
    }
    if (value.equals(defVal)) {
        return;
    }

    Element el = appendElement(name);
    el.setAttribute("size", String.valueOf(value.limit()));
    StringBuilder buf = new StringBuilder();
    int pos = value.position();
    value.rewind();
    int ctr = 0;
    while (value.hasRemaining()) {
        ctr++;
        buf.append(value.get());
        buf.append(" ");
    }
    if (ctr != value.limit())
        throw new IOException("'" + name
            + "' buffer contention resulted in write data consistency.  "
            + ctr + " values written when should have written "
            + value.limit());
    buf.setLength(buf.length() - 1);
    value.position(pos);
    el.setAttribute(dataAttributeName, buf.toString());
    currentElement = (Element) el.getParentNode();
}
 
Example 14
Source File: BufferUtils.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a new IntBuffer of an appropriate size to hold the specified number of ints only if the given buffer if not already the right size.
 *
 * @param buf
 *            the buffer to first check and rewind
 * @param size
 *            number of ints that need to be held by the newly created buffer
 * @return the requested new IntBuffer
 */
public static IntBuffer createIntBuffer(IntBuffer buf, int size) {
	if (buf != null && buf.limit() == size) {
		buf.rewind();
		return buf;
	}

	buf = createIntBuffer(size);
	return buf;
}
 
Example 15
Source File: BinaryOutputCapsule.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void write(IntBuffer value) throws IOException {
    if (value == null) {
        write(NULL_OBJECT);
        return;
    }
    value.rewind();
    int length = value.limit();
    write(length);

    for (int x = 0; x < length; x++) {
        writeForBuffer(value.get());
    }
    value.rewind();
}
 
Example 16
Source File: ThreadSafeIntBuffer.java    From succinct with Apache License 2.0 4 votes vote down vote up
public IntBufferLocal(IntBuffer src) {
  _src = (IntBuffer) src.rewind();
}
 
Example 17
Source File: Test.java    From tribaltrouble with GNU General Public License v2.0 4 votes vote down vote up
public final static void main(String[] args) {
		try {
			Display.setDisplayMode(new DisplayMode(DISPLAY_WIDTH, DISPLAY_HEIGHT));
			Display.create();
			initGL();

			// Load font
			InputStream font_is = Utils.makeURL("/fonts/tahoma.ttf").openStream();
			java.awt.Font src_font = java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, font_is);
			java.awt.Font font = src_font.deriveFont(14f);

			// Load text
			InputStreamReader text_is = new InputStreamReader(Utils.makeURL("/test_text.txt").openStream());
			StringBuffer str_buffer = new StringBuffer();
			int c = text_is.read();
			do {
				str_buffer.append((char)c);
				c = text_is.read();
			} while (c != -1);
			String str = str_buffer.toString();

			// Build texture
			int[] pixels = new int[WIDTH*HEIGHT];
//			ByteBuffer pixel_data = ByteBuffer.wrap(pixels);						// NEW
//			pixelDataFromString(WIDTH, HEIGHT, str, font, pixels);					// NEW
			IntBuffer pixel_data = BufferUtils.createIntBuffer(WIDTH*HEIGHT);	// OLD
			pixel_data.put(pixels);													// OLD
			pixel_data.rewind();

			int texture_handle = createTexture(WIDTH, HEIGHT, pixel_data);
			
		FontRenderContext frc = g2d.getFontRenderContext();
		AttributedString att_str = new AttributedString(str);
		att_str.addAttribute(TextAttribute.FONT, font);
		AttributedCharacterIterator iterator = att_str.getIterator();
		LineBreakMeasurer measurer = new LineBreakMeasurer(iterator, frc);
		
			while (!Display.isCloseRequested()) {
long start_time = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
pixelDataFromString(WIDTH, HEIGHT, str, font, pixels, measurer);
pixel_data.put(pixels); // OLD
pixel_data.rewind();

//texture_handle = createTexture(WIDTH, HEIGHT, pixel_data);
updateTexture(WIDTH, HEIGHT, pixel_data);
				GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
				GL11.glLoadIdentity();
				
				// Background
				/*
				GL11.glDisable(GL11.GL_TEXTURE_2D);
				GL11.glColor4f(.1f, .1f, .1f, 1f);
				GL11.glBegin(GL11.GL_QUADS);
				GL11.glVertex3f(0f, DISPLAY_HEIGHT-RENDER_SIZE, 1f);
				GL11.glVertex3f(RENDER_SIZE, DISPLAY_HEIGHT-RENDER_SIZE, 1f);
				GL11.glVertex3f(RENDER_SIZE, DISPLAY_HEIGHT, 1f);
				GL11.glVertex3f(0f, DISPLAY_HEIGHT, 1f);
				GL11.glEnd();
				*/

				// Text
				GL11.glEnable(GL11.GL_TEXTURE_2D);
				GL11.glColor4f(1f, 1f, 1f, 1f);
				GL11.glBegin(GL11.GL_QUADS);
				GL11.glTexCoord2f(0f, 1f);
				GL11.glVertex3f(0f, DISPLAY_HEIGHT-RENDER_SIZE, 1f);
				GL11.glTexCoord2f(1f, 1f);
				GL11.glVertex3f(RENDER_SIZE, DISPLAY_HEIGHT-RENDER_SIZE, 1f);
				GL11.glTexCoord2f(1f, 0f);
				GL11.glVertex3f(RENDER_SIZE, DISPLAY_HEIGHT, 1f);
				GL11.glTexCoord2f(0f, 0f);
				GL11.glVertex3f(0f, DISPLAY_HEIGHT, 1f);
				GL11.glEnd();
				Display.update();
}
long total_time = System.currentTimeMillis() - start_time;
System.out.println("total_time = " + total_time);

			}
			Display.destroy();
		} catch (Exception t) {
			t.printStackTrace();
		}
	}
 
Example 18
Source File: Gl_440_multi_draw_indirect_id_arb.java    From jogl-samples with MIT License 4 votes vote down vote up
private boolean initBuffer(GL4 gl4) {

        gl4.glGenBuffers(Buffer.MAX, bufferName);

        gl4.glBindBuffer(GL_SHADER_STORAGE_BUFFER, bufferName.get(Buffer.VERTEX));
        FloatBuffer vertexBuffer = GLBuffers.newDirectFloatBuffer(vertexData);
        gl4.glBufferData(GL_SHADER_STORAGE_BUFFER, vertexSize, vertexBuffer, GL_STATIC_DRAW);
        BufferUtils.destroyDirectBuffer(vertexBuffer);
        gl4.glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);

        gl4.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferName.get(Buffer.ELEMENT));
        ShortBuffer elementBuffer = GLBuffers.newDirectShortBuffer(elementData);
        gl4.glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementSize, elementBuffer, GL_STATIC_DRAW);
        BufferUtils.destroyDirectBuffer(elementBuffer);
        gl4.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

        int[] vertexIndirection = {0, 1, 2};
        gl4.glBindBuffer(GL_UNIFORM_BUFFER, bufferName.get(Buffer.VERTEX_INDIRECTION));
        IntBuffer vertexIndirectionBuffer = GLBuffers.newDirectIntBuffer(vertexIndirection);
        gl4.glBufferData(GL_UNIFORM_BUFFER, Integer.BYTES * 3, vertexIndirectionBuffer, GL_DYNAMIC_DRAW);
        BufferUtils.destroyDirectBuffer(vertexIndirectionBuffer);
        gl4.glBindBuffer(GL_UNIFORM_BUFFER, 0);

        int padding = Math.max(Mat4.SIZE, uniformArrayStride.get(0));
        gl4.glBindBuffer(GL_UNIFORM_BUFFER, bufferName.get(Buffer.TRANSFORM));
        gl4.glBufferData(GL_UNIFORM_BUFFER, padding * 3, null, GL_DYNAMIC_DRAW);
        gl4.glBindBuffer(GL_UNIFORM_BUFFER, 0);

        DrawElementsIndirectCommand[] commands = new DrawElementsIndirectCommand[6];
        commands[0] = new DrawElementsIndirectCommand(elementCount, 1, 0, 0, 0);
        commands[1] = new DrawElementsIndirectCommand(elementCount >> 1, 1, 6, 4, 1);
        commands[2] = new DrawElementsIndirectCommand(elementCount, 1, 9, 7, 2);
        commands[3] = new DrawElementsIndirectCommand(elementCount, 1, 0, 0, 0);
        commands[4] = new DrawElementsIndirectCommand(elementCount >> 1, 1, 6, 4, 1);
        commands[5] = new DrawElementsIndirectCommand(elementCount, 1, 9, 7, 2);

        drawCount[0] = 3;
        drawCount[1] = 2;
        drawCount[2] = 1;
        drawOffset[0] = 0;
        drawOffset[1] = 1;
        drawOffset[2] = 3;

        IntBuffer commandsBuffer = GLBuffers.newDirectIntBuffer(5 * commands.length);
        for (DrawElementsIndirectCommand command : commands) {
            commandsBuffer.put(command.toIa_());
        }
        commandsBuffer.rewind();
        gl4.glBindBuffer(GL_DRAW_INDIRECT_BUFFER, bufferName.get(Buffer.INDIRECT));
        gl4.glBufferData(GL_DRAW_INDIRECT_BUFFER, commandsBuffer.capacity() * Integer.BYTES, commandsBuffer, 
                GL_STATIC_DRAW);
        BufferUtils.destroyDirectBuffer(commandsBuffer);
        gl4.glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0);

        return true;
    }
 
Example 19
Source File: Bert.java    From easy-bert with MIT License 4 votes vote down vote up
private Inputs getInputs(final String[] sequences) {
    final String[][] tokens = tokenizer.tokenize(sequences);

    final IntBuffer inputIds = IntBuffer.allocate(sequences.length * model.maxSequenceLength);
    final IntBuffer inputMask = IntBuffer.allocate(sequences.length * model.maxSequenceLength);
    final IntBuffer segmentIds = IntBuffer.allocate(sequences.length * model.maxSequenceLength);

    /*
     * In BERT:
     * inputIds are the indexes in the vocabulary for each token in the sequence
     * inputMask is a binary mask that shows which inputIds have valid data in them
     * segmentIds are meant to distinguish paired sequences during training tasks. Here they're always 0 since we're only doing inference.
     */
    int instance = 1;
    for(final String[] token : tokens) {
        final int[] ids = tokenizer.convert(token);
        inputIds.put(startTokenId);
        inputMask.put(1);
        segmentIds.put(0);
        for(int i = 0; i < ids.length && i < model.maxSequenceLength - 2; i++) {
            inputIds.put(ids[i]);
            inputMask.put(1);
            segmentIds.put(0);
        }
        inputIds.put(separatorTokenId);
        inputMask.put(1);
        segmentIds.put(0);

        while(inputIds.position() < model.maxSequenceLength * instance) {
            inputIds.put(0);
            inputMask.put(0);
            segmentIds.put(0);
        }
        instance++;
    }

    inputIds.rewind();
    inputMask.rewind();
    segmentIds.rewind();

    return new Inputs(inputIds, inputMask, segmentIds, sequences.length);
}
 
Example 20
Source File: BufferUtils.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * Create a new IntBuffer of an appropriate size to hold the specified
 * number of ints only if the given buffer if not already the right size.
 *
 * @param buf
 *            the buffer to first check and rewind
 * @param size
 *            number of ints that need to be held by the newly created
 *            buffer
 * @return the requested new IntBuffer
 */
public static IntBuffer createIntBuffer(IntBuffer buf, int size) {
    if (buf != null && buf.limit() == size) {
        buf.rewind();
        return buf;
    }

    buf = createIntBuffer(size);
    return buf;
}