Update position in data segment (usually on defrag)

@throws IOException
17818
public void updateDataSegmentPosition(long iPosition, final int iDataSegmentId, final long iDataSegmentPosition)
      throws IOException {
    iPosition = iPosition * RECORD_SIZE;

    acquireExclusiveLock();
    try {

      final long[] pos = fileSegment.getRelativePosition(iPosition);

      final OFile f = fileSegment.files[(int) pos[0]];
      long p = pos[1];

      f.writeShort(p, (short) iDataSegmentId);
      f.writeLong(p += OBinaryProtocol.SIZE_SHORT, iDataSegmentPosition);

    } finally {
      releaseExclusiveLock();
    }
  }
1205058
@Override
    public GZIPChannel position(long newPosition) throws IOException
    {
        int skip = (int) (newPosition - position());
        if (skip < 0)
        {
            throw new UnsupportedOperationException("backwards position not supported");
        }
        if (skip > skipBuffer.capacity())
        {
            throw new UnsupportedOperationException(skip+" skip not supported maxSkipSize="+maxSkipSize);
        }
        if (skip > 0)
        {
            if (skipBuffer == null)
            {
                throw new UnsupportedOperationException("skip not supported maxSkipSize="+maxSkipSize);
            }
            skipBuffer.clear();
            skipBuffer.limit(skip);
            if (options.contains(READ))
            {
                read(skipBuffer);
            }
            else
            {
                write(skipBuffer);
            }
        }
        return this;
    }
124145
public void seek(int offset) throws IOException {
    if (!(offset >= bufferOffset && offset < bufferOffset + maxBufferSize)) {
      writeBuffer();
      newBuffer(offset);
      aFile.seek(offset);
    }
    position = offset;
  }
870165
private void skip() {
        try {
            int blockSize;
            do {
                blockSize = read();
                rawData.position(rawData.position() + blockSize);
            } while (blockSize > 0);
        } catch (IllegalArgumentException ex) {
        }
    }
832538
@Override
  public synchronized void flush() throws IOException {
    checkOpen();
    COSDataBlocks.DataBlock dataBlock = getActiveBlock();
    if (dataBlock != null) {
      dataBlock.flush();
    }
  }
963100
private void moveToNext(final int i) {
    final HistogramSeekableView it = iterators[i];
    if (it.hasNext()) {
      putDataPoint(i, it.next());
    } else {
      endReached(i);
    }
  }
1210969
public void setReadPosition(long pointer) {
		final int bufferNum = (int) (pointer >>> this.segmentSizeBits);
		final int offset = (int) (pointer & (this.memorySegmentSize - 1));
		
		this.currentBufferNum = bufferNum;
		seekInput(this.partitionBuffers[bufferNum], offset,
					bufferNum < this.partitionBuffers.length-1 ? this.memorySegmentSize : this.finalBufferLimit);
		
	}
1263974
public void update(char[] data, int start, int end) {
        int i;

        for (i = start; i < end; i++) {
            if (data[i] == '\n') {
                col = 1;
                line++;
            } else {
                col++;
            }
        }
        ofs += (end - start);
    }
502878
@Override
  public int available() throws IOException {
    if (dataSegmentIn == null) {
      if (!moveToNextDataSegment()) {
        return 0;
      }
    }
    do {
      int result = dataSegmentIn.available();
      if (result != 0) {
        return result;
      }
      if (!moveToNextDataSegment()) {
        return 0;
      }
    } while (true);
  }
229993
private int updateElementInReadBuffer(Data data, int indexInChunk) {
        workingBuffer.position(indexInChunk);
        int minElement = indexInChunk / gp.getElementSize();
        int numberOfEntries = workingBuffer.limit() / gp.getElementSize();
        byte[] actualKey = data.getKey();
        // binary search
        int maxElement = numberOfEntries - 1;
        int midElement;
        int compare;
        byte[] tmpKey = new byte[actualKey.length];
        while (minElement <= maxElement) {
            midElement = minElement + (maxElement - minElement) / 2;
            indexInChunk = midElement * gp.getElementSize();
            workingBuffer.position(indexInChunk);
            workingBuffer.get(tmpKey);
            compare = KeyUtils.compareKey(actualKey, tmpKey);
            if (compare == 0) {
                // first read the old element
                workingBuffer.position(indexInChunk);
                byte[] b = new byte[gp.getElementSize()];
                workingBuffer.get(b);
                @SuppressWarnings("unchecked")
                Data toUpdate = (Data)prototype.fromByteBuffer(ByteBuffer.wrap(b));
                // update the old element and write it
                toUpdate.update(data);
                workingBuffer.position(indexInChunk);
                workingBuffer.put(data.toByteBuffer());
                return indexInChunk;
            } else if (compare < 0) {
                maxElement = midElement - 1;
            } else {
                minElement = midElement + 1;
            }
        }
        return -1;
    }
362673
@Override
    public void updateArrayFile(DataWriter writer, long position) throws IOException {
        writer.writeInt(position, val);
    }
17386
public void defrag() {

        if (cacheReadonly) {
            return;
        }

        if (fileFreePosition == INITIAL_FREE_POS) {
            return;
        }

        database.logger.appLog.logContext(SimpleLog.LOG_NORMAL, "start");

        try {
            boolean wasNio = dataFile.wasNio();

            cache.saveAll();

            DataFileDefrag dfd = new DataFileDefrag(database, this, fileName);

            dfd.process();
            close(false);
            deleteFile(wasNio);
            renameDataFile(wasNio);
            backupFile();
            database.getProperties().setProperty(
                HsqlDatabaseProperties.hsqldb_cache_version,
                HsqlDatabaseProperties.THIS_CACHE_VERSION);
            database.getProperties().save();
            cache.clear();

            cache = new Cache(this);

            open(cacheReadonly);
            dfd.updateTableIndexRoots();
            dfd.updateTransactionRowIDs();
        } catch (Throwable e) {
            database.logger.appLog.logContext(e, null);

            if (e instanceof HsqlException) {
                throw (HsqlException) e;
            } else {
                throw new HsqlException(
                    e, Error.getMessage(ErrorCode.GENERAL_IO_ERROR),
                    ErrorCode.GENERAL_IO_ERROR);
            }
        }

        database.logger.appLog.logContext(SimpleLog.LOG_NORMAL, "end");
    }
1274888
protected void decrOriginalSegmentLoad(int index) {
        try {
            long address = getAddress(index);
            int segPos = _addressFormat.getOffset(address);
            int segInd = _addressFormat.getSegment(address);
            int length = _addressFormat.getDataSize(address);
            
            if (segPos >= Segment.dataStartPosition) {
                // get data segment
                Segment seg = _segmentManager.getSegment(segInd);
                
                // read data length
                if(seg != null) seg.decrLoadSize(4 + ((length == 0) ? seg.readInt(segPos) : length));
            }
        }
        catch(IOException e1) {}
        catch(IndexOutOfBoundsException e2) {}
    }
307468
protected synchronized void skipForward(int eventsToSkip)
			throws IOException {
		int offset = 0;
		for (int i = 0; i < eventsToSkip; i++) {
			// adjust position for reading offset
			storage.seek(position);
			// read forward skip offset
			offset = storage.readInt();
			// set file pointer to next event position
			position += offset;
			// adjust index
			index++;
		}
	}
1272331
private void _fill () throws IOException
  {
    int nDstOfs = 0;
    if (m_nMarkedChar > UNMARKED)
    {
      // Marked
      final int nDelta = m_nNextCharIndex - m_nMarkedChar;
      if (nDelta >= m_nReadAheadLimit)
      {
        // Gone past read-ahead limit: Invalidate mark
        m_nMarkedChar = INVALIDATED;
        m_nReadAheadLimit = 0;
      }
      else
      {
        if (m_nReadAheadLimit <= m_aBuf.length)
        {
          // Shuffle in the current buffer
          System.arraycopy (m_aBuf, m_nMarkedChar, m_aBuf, 0, nDelta);
          m_nMarkedChar = 0;
          nDstOfs = nDelta;
        }
        else
        {
          // Reallocate buffer to accommodate read-ahead limit
          final char [] aNewBuf = new char [m_nReadAheadLimit];
          System.arraycopy (m_aBuf, m_nMarkedChar, aNewBuf, 0, nDelta);
          m_aBuf = aNewBuf;
          m_nMarkedChar = 0;
          nDstOfs = nDelta;
        }
        m_nNextCharIndex = nDelta;
        m_nChars = nDelta;
      }
    }

    int nBytesRead;
    do
    {
      nBytesRead = m_aReader.read (m_aBuf, nDstOfs, m_aBuf.length - nDstOfs);
    } while (nBytesRead == 0);
    if (nBytesRead > 0)
    {
      m_nChars = nDstOfs + nBytesRead;
      m_nNextCharIndex = nDstOfs;
    }
  }
1356847
public void update(ByteBuffer buffer) {
    length += buffer.remaining();
    //Save current position to leave given buffer unchanged
    int position = buffer.position();
    
    //Complete the final buffer if needed
    completeFinalBuffer(buffer);
    
    while(buffer.remaining() >= 64) {
      transform(buffer);
    }
    
    if(buffer.remaining() != 0) {
      finalBuffer.put(buffer);
    }
    
    buffer.position(position);
  }
473457
public synchronized boolean replace(XEvent event, int index)
			throws IOException {
		// check for index sanity
		if (index < 0 || index >= size) {
			throw new IndexOutOfBoundsException();
		}
		// determine and set appropriate file pointer position
		navigateToIndex(index);
		storage.seek(position);
		long atePosition = position;
		// read navigation data
		int fwd = storage.readInt();
		// skip backwards pointer and payload size, not relevant
		storage.skipBytes(8);
		int segmentSize = fwd - 12;
		// encode event
		byte[] evtEnc = encode(event);
		boolean success = false;
		if (evtEnc.length <= segmentSize) {
			// overwrite event
			storage.seek(atePosition + 8);
			storage.writeInt(evtEnc.length);
			// insert new padding
			byte segmentPadding[] = new byte[segmentSize - evtEnc.length];
			Arrays.fill(segmentPadding, (byte) 0);
			storage.write(evtEnc);
			storage.write(segmentPadding);
			success = true;
		} else {
			success = false;
		}
		// return to prior position
		this.position = atePosition;
		storage.seek(this.position);
		return success;
	}