/**
   * Entry point to C language function: <code>
   *  GLint {@native gluBuild1DMipmapLevels}(GLenum target, GLint internalFormat, GLsizei width, GLenum format, GLenum type, GLint level, GLint base, GLint max, const void *  data)
   * </code> <br>
   * Part of <code>GLU_VERSION_1_X</code><br>
   *
   * @param data a direct or array-backed {@link java.nio.Buffer}
   */
  private int gluBuild1DMipmapLevelsC(
      int target,
      int internalFormat,
      int width,
      int format,
      int type,
      int level,
      int base,
      int max,
      Buffer data) {

    final boolean data_is_direct = Buffers.isDirect(data);
    final long __addr_ = getGLUProcAddressTable()._addressof_gluBuild1DMipmapLevels;
    if (__addr_ == 0) {
      throw new GLException(String.format("Method \"%s\" not available", "gluBuild1DMipmapLevels"));
    }
    return dispatch_gluBuild1DMipmapLevelsC1(
        target,
        internalFormat,
        width,
        format,
        type,
        level,
        base,
        max,
        data_is_direct ? data : Buffers.getArray(data),
        data_is_direct
            ? Buffers.getDirectBufferByteOffset(data)
            : Buffers.getIndirectBufferByteOffset(data),
        data_is_direct,
        __addr_);
  }
Ejemplo n.º 2
0
  public void loadBuffers() {
    SurfCell curSurf; // the current surface being worked with
    PolyCell curPoly; // the current polygon in the surface
    VertListCell curVertLC;

    curSurf = surfHead;
    int vertCount;
    while (curSurf != null) {
      int vertsPerPrim;
      vertCount = 0;
      curPoly = curSurf.polyHead;
      // vertCount += curPoly.numVerts;
      vertsPerPrim = curPoly.numVerts;
      while (curPoly != null) {
        vertCount += curPoly.numVerts;
        if (curPoly.numVerts != vertsPerPrim) {
          System.out.printf("Surface %s: Unequal number of vertices ", curSurf.name);
          System.out.printf(
              "\n    First prim had %d Cur Prim has %d\n", curPoly.numVerts, vertsPerPrim);
          return;
        }
        curPoly = curPoly.next;
      }
      curSurf.numVerts = vertCount;
      float vertices[] = new float[vertCount * 3];
      int vInd = 0;
      float normals[] = new float[vertCount * 3];
      int nInd = 0;
      curPoly = curSurf.polyHead;
      while (curPoly != null) {
        curVertLC = curPoly.vert;
        while (curVertLC != null) {
          // for(int i = 0; i < curPoly.numVerts; i++);{
          VertCell curVert = vertArray.get(curVertLC.vert);
          vertices[vInd++] = (float) curVert.worldPos.x;
          vertices[vInd++] = (float) curVert.worldPos.y;
          vertices[vInd++] = (float) curVert.worldPos.z;
          normals[nInd++] = (float) vertNormArray[curVertLC.vert].x;
          normals[nInd++] = (float) vertNormArray[curVertLC.vert].y;
          normals[nInd++] = (float) vertNormArray[curVertLC.vert].z;
          curVertLC = curVertLC.next;
        }
        curPoly = curPoly.next;
      }
      // now put vertices and normals into VertexArray or Buffer
      curSurf.vertexBuffer = Buffers.newDirectFloatBuffer(vertices.length);
      curSurf.vertexBuffer.put(vertices);
      curSurf.vertexBuffer.rewind();

      curSurf.normalBuffer = Buffers.newDirectFloatBuffer(normals.length);
      curSurf.normalBuffer.put(normals);
      curSurf.normalBuffer.rewind();

      curSurf = curSurf.next;
    }
  }
Ejemplo n.º 3
0
 @Override
 public void writeAsString(final int value)
     throws IndexOutOfBoundsException, WriteNotSupportedException {
   final int size = value < 0 ? Buffers.stringSize(-value) + 1 : Buffers.stringSize(value);
   if (!checkWritableBytesSafe(size)) {
     throw new IndexOutOfBoundsException();
   }
   Buffers.getBytes(value, this.lowerBoundary + this.writerIndex + size, this.buffer);
   this.writerIndex += size;
 }
 /** Optional, throws GLException if not available in profile */
 public final int gluScaleImage(
     int format,
     int widthin,
     int heightin,
     int typein,
     java.nio.Buffer datain,
     int widthout,
     int heightout,
     int typeout,
     java.nio.Buffer dataout) {
   validateMipmap();
   java.nio.ByteBuffer in = null;
   java.nio.ByteBuffer out = null;
   in = copyToByteBuffer(datain);
   if (dataout instanceof java.nio.ByteBuffer) {
     out = (java.nio.ByteBuffer) dataout;
   } else if (dataout instanceof java.nio.ShortBuffer) {
     out = Buffers.newDirectByteBuffer(dataout.remaining() * Buffers.SIZEOF_SHORT);
   } else if (dataout instanceof java.nio.IntBuffer) {
     out = Buffers.newDirectByteBuffer(dataout.remaining() * Buffers.SIZEOF_INT);
   } else if (dataout instanceof java.nio.FloatBuffer) {
     out = Buffers.newDirectByteBuffer(dataout.remaining() * Buffers.SIZEOF_FLOAT);
   } else {
     throw new IllegalArgumentException(
         "Unsupported destination buffer type (must be byte, short, int, or float)");
   }
   int errno =
       Mipmap.gluScaleImage(
           getCurrentGL2ES1(),
           format,
           widthin,
           heightin,
           typein,
           in,
           widthout,
           heightout,
           typeout,
           out);
   if (errno == 0) {
     out.rewind();
     if (out != dataout) {
       if (dataout instanceof java.nio.ShortBuffer) {
         ((java.nio.ShortBuffer) dataout).put(out.asShortBuffer());
       } else if (dataout instanceof java.nio.IntBuffer) {
         ((java.nio.IntBuffer) dataout).put(out.asIntBuffer());
       } else if (dataout instanceof java.nio.FloatBuffer) {
         ((java.nio.FloatBuffer) dataout).put(out.asFloatBuffer());
       } else {
         throw new RuntimeException("Should not reach here");
       }
     }
   }
   return (errno);
 }
Ejemplo n.º 5
0
 /**
  * Fill the current buffer with bytes from the specified array from the specified offset.
  *
  * @param s source array
  * @param o offset from the beginning of the array
  * @return number of written bytes
  */
 private int write(final byte[] s, final int o) {
   final Buffer bf = bm.current();
   final int len = Math.min(IO.BLOCKSIZE, s.length - o);
   System.arraycopy(s, o, bf.data, 0, len);
   bf.dirty = true;
   return len;
 }
Ejemplo n.º 6
0
public class Doubles {
  private static final Unsafe UNSAFE = Buffers.getUnsafe();
  private static final long BASE_OFFSET = UNSAFE.arrayBaseOffset(double[].class);
  private static final long INDEX_SCALE = UNSAFE.arrayIndexScale(double[].class);

  public static void sum(double[] sum, double[] addendA, double[] addendB) {
    checkArgs(sum.length == addendA.length && sum.length == addendB.length);

    for (int i = 0; i < 0 + sum.length; i++) {
      sum[i] = addendA[i] + addendB[i];
    }
  }

  public static void unsafeSum(double[] sum, double[] addendA, double[] addendB) {
    checkArgs(sum.length == addendA.length && sum.length == addendB.length);

    for (int i = 0; i < 0 + sum.length; i++) {
      long offset = i * INDEX_SCALE;
      UNSAFE.putDouble(
          sum,
          BASE_OFFSET + offset,
          UNSAFE.getDouble(addendA, BASE_OFFSET + offset)
              + UNSAFE.getDouble(addendB, BASE_OFFSET + offset));
    }
  }
}
Ejemplo n.º 7
0
  void deleteChars(char bufid, boolean reversable, boolean forward, int count) {
    String line = at().toString();
    String deleted = null;

    // Thread.dumpStack();

    // trace("count = " + count + " llen = " + line.length());

    if (line.length() == insertx() && reversable) forward = false;
    if (forward) {
      if (insertx() + count > line.length()) count = line.length() - insertx();
      deleted = line.substring(insertx(), insertx() + count);
      line = line.substring(0, insertx()) + line.substring(insertx() + count, line.length());
    } else {
      if (insertx() < count) count = insertx();
      if (0 == count) return;
      deleted = line.substring(insertx() - count, insertx());
      line = line.substring(0, insertx() - count) + line.substring(insertx(), line.length());
      cursorx(-count);
    }
    Buffers.deleted(bufid, deleted);
    changeElementStr(line);
    // trace("count = " + count + " llen = " + line.length());
    return;
  }
Ejemplo n.º 8
0
 @Override
 public void write1(final int pre, final int off, final int v) {
   final int o = off + cursor(pre);
   final Buffer bf = bm.current();
   final byte[] b = bf.data;
   b[o] = (byte) v;
   bf.dirty = true;
 }
Ejemplo n.º 9
0
 @Override
 public void close() {
   ByteBuffer tmp = this.nioInputBuffer;
   if (tmp != null) {
     this.nioInputBuffer = null;
     Buffers.releaseReceiveBuffer(tmp, getStats());
   }
 }
Ejemplo n.º 10
0
 private final ByteBuffer copyToByteBuffer(Buffer buf) {
   if (buf instanceof ByteBuffer) {
     if (buf.position() == 0) {
       return (ByteBuffer) buf;
     }
     return Buffers.copyByteBuffer((ByteBuffer) buf);
   } else if (buf instanceof ShortBuffer) {
     return Buffers.copyShortBufferAsByteBuffer((ShortBuffer) buf);
   } else if (buf instanceof IntBuffer) {
     return Buffers.copyIntBufferAsByteBuffer((IntBuffer) buf);
   } else if (buf instanceof FloatBuffer) {
     return Buffers.copyFloatBufferAsByteBuffer((FloatBuffer) buf);
   } else {
     throw new IllegalArgumentException(
         "Unsupported buffer type (must be one of byte, short, int, or float)");
   }
 }
Ejemplo n.º 11
0
  /**
   * Reads a block from disk.
   *
   * @param b block to fetch
   */
  private void readBlock(final int b) {
    if (!bm.cursor(b)) return;

    final Buffer bf = bm.current();
    try {
      if (bf.dirty) writeBlock(bf);
      bf.pos = b;
      if (b >= blocks) {
        blocks = b + 1;
      } else {
        file.seek(bf.pos * IO.BLOCKSIZE);
        file.readFully(bf.data);
      }
    } catch (final IOException ex) {
      Util.stack(ex);
    }
  }
Ejemplo n.º 12
0
 @Override
 public synchronized int read4(final int pre, final int off) {
   final int o = off + cursor(pre);
   final byte[] b = bm.current().data;
   return ((b[o] & 0xFF) << 24)
       + ((b[o + 1] & 0xFF) << 16)
       + ((b[o + 2] & 0xFF) << 8)
       + (b[o + 3] & 0xFF);
 }
Ejemplo n.º 13
0
 @Override
 protected void copy(final byte[] entries, final int pre, final int last) {
   for (int o = 0, i = pre; i < last; ++i, o += IO.NODESIZE) {
     final int off = cursor(i);
     final Buffer bf = bm.current();
     System.arraycopy(entries, o, bf.data, off, IO.NODESIZE);
     bf.dirty = true;
   }
 }
Ejemplo n.º 14
0
 @Override
 public void write4(final int pre, final int off, final int v) {
   final int o = off + cursor(pre);
   final Buffer bf = bm.current();
   final byte[] b = bf.data;
   b[o] = (byte) (v >>> 24);
   b[o + 1] = (byte) (v >>> 16);
   b[o + 2] = (byte) (v >>> 8);
   b[o + 3] = (byte) v;
   bf.dirty = true;
 }
Ejemplo n.º 15
0
  /** Sends an out-of-band datagram */
  public static void Netchan_OutOfBand(
      int net_socket, NetworkAddress adr, int length, byte data[]) {

    // write the packet header
    Buffer send = Buffer.allocate(Constants.MAX_MSGLEN);

    send.putInt(-1); // -1 sequence means out of band
    Buffers.Write(send, data, length);

    // send the datagram
    NET.SendPacket(net_socket, send.cursize, send.data, adr);
  }
Ejemplo n.º 16
0
  SSLEngineResult unwrap(ByteBuffer encryptedData) throws SSLException {
    ByteBuffer allEncryptedData = _buffers.prependCached(encryptedData);
    _buffers.prepareForUnwrap(allEncryptedData);
    SSLEngineResult result = doUnwrap();

    allEncryptedData.position(result.bytesConsumed());
    ByteBuffer unprocessedEncryptedData = BufferUtils.slice(allEncryptedData);

    emitPlainData(result);

    switch (result.getStatus()) {
      case BUFFER_UNDERFLOW:
        _buffers.cache(unprocessedEncryptedData);
        break;
      case BUFFER_OVERFLOW:
        _buffers.grow(BufferType.IN_PLAIN);
        if (unprocessedEncryptedData == null) {
          throw new RuntimeException(
              "Worker.unwrap had " + "buffer_overflow but all data was consumed!!");
        } else {
          unwrap(unprocessedEncryptedData);
        }
        break;
      case OK:
        if (unprocessedEncryptedData == null) {
          _buffers.clearCache();
        } else {
          _buffers.cache(unprocessedEncryptedData);
        }
        break;
      case CLOSED:
        break;
    }
    return result;
  }
Ejemplo n.º 17
0
  /** gets the buffer for receiving message length bytes */
  protected void ensureCapacity(int bufferSize) {
    // Ok, so we have a buffer that's big enough
    if (nioInputBuffer != null && nioInputBuffer.capacity() > bufferSize) {
      if (nioInputBuffer.capacity() - lastProcessedPosition < bufferSize) {
        nioInputBuffer.limit(lastReadPosition);
        nioInputBuffer.position(lastProcessedPosition);
        nioInputBuffer.compact();
        lastReadPosition = nioInputBuffer.position();
        lastProcessedPosition = 0;
      }
      return;
    }

    // otherwise, we have no buffer to a buffer that's too small

    if (nioInputBuffer == null) {
      int allocSize = conn.getReceiveBufferSize();
      if (allocSize == -1) {
        allocSize = conn.owner.getConduit().tcpBufferSize;
      }
      if (allocSize > bufferSize) {
        bufferSize = allocSize;
      }
    }
    ByteBuffer oldBuffer = nioInputBuffer;
    nioInputBuffer = Buffers.acquireReceiveBuffer(bufferSize, getStats());

    if (oldBuffer != null) {
      oldBuffer.limit(lastReadPosition);
      oldBuffer.position(lastProcessedPosition);
      nioInputBuffer.put(oldBuffer);
      lastReadPosition = nioInputBuffer.position(); // fix for 45064
      lastProcessedPosition = 0;
      Buffers.releaseReceiveBuffer(oldBuffer, getStats());
    }
  }
Ejemplo n.º 18
0
  SSLEngineResult wrap(ByteBuffer plainData) throws SSLException {
    _buffers.prepareForWrap(plainData);
    SSLEngineResult result = doWrap();

    emitWrappedData(result);

    switch (result.getStatus()) {
      case BUFFER_UNDERFLOW:
        throw new RuntimeException("BUFFER_UNDERFLOW while wrapping!");
      case BUFFER_OVERFLOW:
        _buffers.grow(BufferType.OUT_CIPHER);
        if (plainData.hasRemaining()) {
          plainData.position(result.bytesConsumed());
          ByteBuffer remainingData = BufferUtils.slice(plainData);
          wrap(remainingData);
        }
        break;
      case OK:
        break;
      case CLOSED:
        break;
    }
    return result;
  }
Ejemplo n.º 19
0
  @Override
  public synchronized void flush() throws IOException {
    for (final Buffer b : bm.all()) if (b.dirty) writeBlock(b);
    if (!dirty) return;

    try (final DataOutput out = new DataOutput(meta.dbfile(DATATBL + 'i'))) {
      out.writeNum(blocks);
      out.writeNum(used);

      // due to legacy issues, number of blocks is written several times
      out.writeNum(blocks);
      for (int a = 0; a < blocks; a++) out.writeNum(fpres[a]);
      out.writeNum(blocks);
      for (int a = 0; a < blocks; a++) out.writeNum(pages[a]);

      out.writeLongs(usedPages.toArray());
    }
    dirty = false;
  }
Ejemplo n.º 20
0
  /**
   * Entry point to C language function: <code>
   *  GLint {@native gluScaleImage}(GLenum format, GLsizei wIn, GLsizei hIn, GLenum typeIn, const void *  dataIn, GLsizei wOut, GLsizei hOut, GLenum typeOut, GLvoid *  dataOut)
   * </code> <br>
   * Part of <code>GLU_VERSION_1_X</code><br>
   *
   * @param dataIn a direct or array-backed {@link java.nio.Buffer}
   * @param dataOut a direct or array-backed {@link java.nio.Buffer}
   */
  private int gluScaleImageC(
      int format,
      int wIn,
      int hIn,
      int typeIn,
      Buffer dataIn,
      int wOut,
      int hOut,
      int typeOut,
      Buffer dataOut) {

    final boolean dataIn_is_direct = Buffers.isDirect(dataIn);
    final boolean dataOut_is_direct = Buffers.isDirect(dataOut);
    final long __addr_ = getGLUProcAddressTable()._addressof_gluScaleImage;
    if (__addr_ == 0) {
      throw new GLException(String.format("Method \"%s\" not available", "gluScaleImage"));
    }
    return dispatch_gluScaleImageC1(
        format,
        wIn,
        hIn,
        typeIn,
        dataIn_is_direct ? dataIn : Buffers.getArray(dataIn),
        dataIn_is_direct
            ? Buffers.getDirectBufferByteOffset(dataIn)
            : Buffers.getIndirectBufferByteOffset(dataIn),
        dataIn_is_direct,
        wOut,
        hOut,
        typeOut,
        dataOut_is_direct ? dataOut : Buffers.getArray(dataOut),
        dataOut_is_direct
            ? Buffers.getDirectBufferByteOffset(dataOut)
            : Buffers.getIndirectBufferByteOffset(dataOut),
        dataOut_is_direct,
        __addr_);
  }
Ejemplo n.º 21
0
 /**
  * In a number of occasions the rendering loop swaps two important FBOs. This method is used to
  * trigger the PostProcessor instance into refreshing the internal references to these FBOs.
  */
 public void refreshSceneOpaqueFBOs() {
   buffers.sceneOpaque = renderingProcess.getFBO("sceneOpaque");
   buffers.sceneOpaquePingPong = renderingProcess.getFBO("sceneOpaquePingPong");
 }
Ejemplo n.º 22
0
  // TODO: update javadoc when the rendering process becomes the FrameBuffersManager
  public void refreshDynamicFBOs() {
    // initial renderings
    buffers.sceneOpaque = renderingProcess.getFBO("sceneOpaque");
    buffers.sceneOpaquePingPong = renderingProcess.getFBO("sceneOpaquePingPong");

    buffers.sceneSkyBand0 = renderingProcess.getFBO("sceneSkyBand0");
    buffers.sceneSkyBand1 = renderingProcess.getFBO("sceneSkyBand1");

    buffers.sceneReflectiveRefractive = renderingProcess.getFBO("sceneReflectiveRefractive");
    // sceneReflected, in case one wonders, is not used by the post-processor.

    // pre-post composite
    buffers.outline = renderingProcess.getFBO("outline");
    buffers.ssao = renderingProcess.getFBO("ssao");
    buffers.ssaoBlurred = renderingProcess.getFBO("ssaoBlurred");

    // initial post-processing
    buffers.lightShafts = renderingProcess.getFBO("lightShafts");
    buffers.initialPost = renderingProcess.getFBO("initialPost");
    buffers.currentReadbackPBO = renderingProcess.getCurrentReadbackPBO();
    buffers.sceneToneMapped = renderingProcess.getFBO("sceneToneMapped");

    buffers.sceneHighPass = renderingProcess.getFBO("sceneHighPass");
    buffers.sceneBloom0 = renderingProcess.getFBO("sceneBloom0");
    buffers.sceneBloom1 = renderingProcess.getFBO("sceneBloom1");
    buffers.sceneBloom2 = renderingProcess.getFBO("sceneBloom2");

    buffers.sceneBlur0 = renderingProcess.getFBO("sceneBlur0");
    buffers.sceneBlur1 = renderingProcess.getFBO("sceneBlur1");

    // final post-processing
    buffers.ocUndistorted = renderingProcess.getFBO("ocUndistorted");
    buffers.sceneFinal = renderingProcess.getFBO("sceneFinal");

    fullScale = buffers.sceneOpaque.dimensions();
  }
Ejemplo n.º 23
0
  /**
   * tries to send an unreliable message to a connection, and handles the transmition /
   * retransmition of the reliable messages.
   *
   * <p>A 0 length will still generate a packet and deal with the reliable messages.
   */
  public static void Transmit(NetworkChannel chan, int length, byte data[]) {
    int send_reliable;
    int w1, w2;

    // check for message overflow
    if (chan.message.overflowed) {
      chan.fatal_error = true;
      Com.Printf(NET.AdrToString(chan.remote_address) + ":Outgoing message overflow\n");
      return;
    }

    send_reliable = chan.Netchan_NeedReliable() ? 1 : 0;

    if (chan.reliable_length == 0 && chan.message.cursize != 0) {
      System.arraycopy(chan.message_buf, 0, chan.reliable_buf, 0, chan.message.cursize);
      chan.reliable_length = chan.message.cursize;
      chan.message.cursize = 0;
      chan.reliable_sequence ^= 1;
    }

    // write the packet header
    Buffer send = Buffer.wrap(send_buf).order(ByteOrder.LITTLE_ENDIAN);

    w1 = (chan.outgoing_sequence & ~(1 << 31)) | (send_reliable << 31);
    w2 = (chan.incoming_sequence & ~(1 << 31)) | (chan.incoming_reliable_sequence << 31);

    chan.outgoing_sequence++;
    chan.last_sent = (int) Globals.curtime;

    send.putInt(w1);
    send.putInt(w2);

    // send the qport if we are a client
    if (chan.sock == Constants.NS_CLIENT) send.WriteShort((int) consoleQport.value);

    // copy the reliable message to the packet first
    if (send_reliable != 0) {
      Buffers.Write(send, chan.reliable_buf, chan.reliable_length);
      chan.last_reliable_sequence = chan.outgoing_sequence;
    }

    // add the unreliable part if space is available
    if (send.maxsize - send.cursize >= length) Buffers.Write(send, data, length);
    else Com.Printf("Netchan_Transmit: dumped unreliable\n");

    // send the datagram
    NET.SendPacket(chan.sock, send.cursize, send.data, chan.remote_address);

    if (showpackets.value != 0) {
      if (send_reliable != 0)
        Com.Printf(
            // "send %4i : s=%i reliable=%i ack=%i rack=%i\n"
            "send "
                + send.cursize
                + " : s="
                + (chan.outgoing_sequence - 1)
                + " reliable="
                + chan.reliable_sequence
                + " ack="
                + chan.incoming_sequence
                + " rack="
                + chan.incoming_reliable_sequence
                + "\n");
      else
        Com.Printf(
            // "send %4i : s=%i ack=%i rack=%i\n"
            "send "
                + send.cursize
                + " : s="
                + (chan.outgoing_sequence - 1)
                + " ack="
                + chan.incoming_sequence
                + " rack="
                + chan.incoming_reliable_sequence
                + "\n");
    }
  }
Ejemplo n.º 24
0
 /**
  * Convenience method for copying blocks.
  *
  * @param s source array
  * @param sp source position
  * @param d destination array
  * @param dp destination position
  * @param l source length
  */
 private void copy(final byte[] s, final int sp, final byte[] d, final int dp, final int l) {
   System.arraycopy(s, sp << IO.NODEPOWER, d, dp << IO.NODEPOWER, l << IO.NODEPOWER);
   bm.current().dirty = true;
 }
Ejemplo n.º 25
0
 @Override
 public synchronized int read1(final int pre, final int off) {
   final int o = off + cursor(pre);
   final byte[] b = bm.current().data;
   return b[o] & 0xFF;
 }
Ejemplo n.º 26
0
 private SSLEngineResult doUnwrap() throws SSLException {
   ByteBuffer cipherText = _buffers.get(BufferType.IN_CIPHER);
   ByteBuffer plainText = _buffers.get(BufferType.IN_PLAIN);
   return _engine.unwrap(cipherText, plainText);
 }
Ejemplo n.º 27
0
  @Override
  public void delete(final int pre, final int nr) {
    if (nr == 0) return;
    dirty();

    // get first block
    cursor(pre);

    // some useful variables to make code more readable
    int from = pre - fpre;
    final int last = pre + nr;

    // check if all entries are in current block: handle and return
    if (last - 1 < npre) {
      final Buffer bf = bm.current();
      copy(bf.data, from + nr, bf.data, from, npre - last);
      updatePre(nr);

      // if whole block was deleted, remove it from the index
      if (npre == fpre) {
        // mark the block as empty
        usedPages.clear(pages[page]);

        Array.move(fpres, page + 1, -1, used - page - 1);
        Array.move(pages, page + 1, -1, used - page - 1);

        --used;
        readPage(page);
      }
      return;
    }

    // handle blocks whose entries are to be deleted entirely

    // first count them
    int unused = 0;
    while (npre < last) {
      if (from == 0) {
        ++unused;
        // mark the blocks as empty; range clear cannot be used because the
        // blocks may not be consecutive
        usedPages.clear(pages[page]);
      }
      setPage(page + 1);
      from = 0;
    }

    // if the last block is empty, clear the corresponding bit
    readBlock(pages[page]);
    final Buffer bf = bm.current();
    if (npre == last) {
      usedPages.clear((int) bf.pos);
      ++unused;
      if (page < used - 1) readPage(page + 1);
      else ++page;
    } else {
      // delete entries at beginning of current (last) block
      copy(bf.data, last - fpre, bf.data, 0, npre - last);
    }

    // now remove them from the index
    if (unused > 0) {
      Array.move(fpres, page, -unused, used - page);
      Array.move(pages, page, -unused, used - page);
      used -= unused;
      page -= unused;
    }

    // update index entry for this block
    fpres[page] = pre;
    fpre = pre;
    updatePre(nr);
  }
Ejemplo n.º 28
0
  @Override
  public void insert(final int pre, final byte[] entries) {
    final int nnew = entries.length;
    if (nnew == 0) return;
    dirty();

    // number of records to be inserted
    final int nr = nnew >>> IO.NODEPOWER;

    int split = 0;
    if (used == 0) {
      // special case: insert new data into first block if database is empty
      readPage(0);
      usedPages.set(0);
      ++used;
    } else if (pre > 0) {
      // find the offset within the block where the new records will be inserted
      split = cursor(pre - 1) + IO.NODESIZE;
    } else {
      // all insert operations will add data after first node.
      // i.e., there is no "insert before first document" statement
      throw Util.notExpected("Insertion at beginning of populated table.");
    }

    // number of bytes occupied by old records in the current block
    final int nold = npre - fpre << IO.NODEPOWER;
    // number of bytes occupied by old records which will be moved at the end
    final int moved = nold - split;

    // special case: all entries fit in the current block
    Buffer bf = bm.current();
    if (nold + nnew <= IO.BLOCKSIZE) {
      Array.move(bf.data, split, nnew, moved);
      System.arraycopy(entries, 0, bf.data, split, nnew);
      bf.dirty = true;

      // increment first pre-values of blocks after the last modified block
      for (int i = page + 1; i < used; ++i) fpres[i] += nr;
      // update cached variables (fpre is not changed)
      npre += nr;
      meta.size += nr;
      return;
    }

    // append old entries at the end of the new entries
    final byte[] all = new byte[nnew + moved];
    System.arraycopy(entries, 0, all, 0, nnew);
    System.arraycopy(bf.data, split, all, nnew, moved);

    // fill in the current block with new entries
    // number of bytes which fit in the first block
    int nrem = IO.BLOCKSIZE - split;
    if (nrem > 0) {
      System.arraycopy(all, 0, bf.data, split, nrem);
      bf.dirty = true;
    }

    // number of new required blocks and remaining bytes
    final int req = all.length - nrem;
    int needed = req / IO.BLOCKSIZE;
    final int remain = req % IO.BLOCKSIZE;

    if (remain > 0) {
      // check if the last entries can fit in the block after the current one
      if (page + 1 < used) {
        final int o = occSpace(page + 1) << IO.NODEPOWER;
        if (remain <= IO.BLOCKSIZE - o) {
          // copy the last records
          readPage(page + 1);
          bf = bm.current();
          System.arraycopy(bf.data, 0, bf.data, remain, o);
          System.arraycopy(all, all.length - remain, bf.data, 0, remain);
          bf.dirty = true;
          // reduce the pre value, since it will be later incremented with nr
          fpres[page] -= remain >>> IO.NODEPOWER;
          // go back to the previous block
          readPage(page - 1);
        } else {
          // there is not enough space in the block - allocate a new one
          ++needed;
        }
      } else {
        // this is the last block - allocate a new one
        ++needed;
      }
    }

    // number of expected blocks: existing blocks + needed block - empty blocks
    final int exp = blocks + needed - (blocks - used);
    if (exp > fpres.length) {
      // resize directory arrays if existing ones are too small
      final int ns = Math.max(fpres.length << 1, exp);
      fpres = Arrays.copyOf(fpres, ns);
      pages = Arrays.copyOf(pages, ns);
    }

    // make place for the blocks where the new entries will be written
    Array.move(fpres, page + 1, needed, used - page - 1);
    Array.move(pages, page + 1, needed, used - page - 1);

    // write the all remaining entries
    while (needed-- > 0) {
      freeBlock();
      nrem += write(all, nrem);
      fpres[page] = fpres[page - 1] + IO.ENTRIES;
      pages[page] = (int) bm.current().pos;
    }

    // increment all fpre values after the last modified block
    for (int i = page + 1; i < used; ++i) fpres[i] += nr;

    meta.size += nr;

    // update cached variables
    fpre = fpres[page];
    npre = page + 1 < used && fpres[page + 1] < meta.size ? fpres[page + 1] : meta.size;
  }
Ejemplo n.º 29
0
 private SSLEngineResult doWrap() throws SSLException {
   ByteBuffer plainText = _buffers.get(BufferType.OUT_PLAIN);
   ByteBuffer cipherText = _buffers.get(BufferType.OUT_CIPHER);
   return _engine.wrap(plainText, cipherText);
 }
Ejemplo n.º 30
0
 public static NativeSizeBuffer allocateDirect(int size) {
   return new NativeSizeBuffer(Buffers.newDirectByteBuffer(elementSize() * size));
 }