private long allocateSpaceForChunk(int totalChunkLength) throws IOException {
    int pageSize = storage.pageSize();
    if (totalChunkLength > pageSize) {
      throw new AssertionError("totalRecordLength(=" + totalChunkLength + ") must fit the page(=" + pageSize + ")");
    }

    long chunkOffsetInFile = header.firstUnAllocatedOffset();
    long firstUnCommittedOffset = header.firstUnCommittedOffset();
    if (chunkOffsetInFile != firstUnCommittedOffset) {
      throw new AssertionError(
        "Invariant violation: " +
        "firstUnAllocatedCursor(=" + chunkOffsetInFile + ") must be == firstUnCommitted(=" + firstUnCommittedOffset + ")");
    }

    int chunkOffsetInPage = storage.toOffsetInPage(chunkOffsetInFile);
    int remainingOnPage = pageSize - chunkOffsetInPage;
    if (totalChunkLength <= remainingOnPage) {
      header.updateFirstUnAllocatedOffset(chunkOffsetInFile + totalChunkLength);
      return chunkOffsetInFile;
    }

    //not enough room on page for a chunk => fill page up with padding chunk
    // and try again on the next page:
    if (remainingOnPage >= LogChunkImpl.HEADER_SIZE) {
      //FIXME RC: could it be there is >2k leftover on the page, so remainsToPad > max chunk capacity?
      //          Actually, since padding chunks don't utilize allocated/committed cursors, that space in header could
      //          be re-used for larger length -- but first we need to find out do we really need larger padding chunks?

      header.updateFirstUnAllocatedOffset(chunkOffsetInFile + remainingOnPage);
      MMappedFileStorage.Page page = storage.pageByOffset(chunkOffsetInFile);
      LogChunkImpl.putPaddingChunk(remainingOnPage, page.rawPageBuffer(), chunkOffsetInPage, chunkOffsetInFile);
      header.updateFirstUnCommittedOffset(chunkOffsetInFile + remainingOnPage);

      return allocateSpaceForChunk(totalChunkLength);
    }

    //With chunk offsets AND lengths AND pageSize all 64b-aligned -- it could be either 0 or 8 bytes at the end
    // of the page -- all those options are processed above -- but never [1..8) bytes.
    throw new AssertionError(
      "Bug: remainingOnPage(=" + remainingOnPage + ") < RECORD_HEADER(=" + LogChunkImpl.HEADER_SIZE + ")," +
      "but chunks must be 64b-aligned, so it must never happen. " +
      "chunkOffsetInFile(=" + chunkOffsetInFile + "), " +
      "recordOffsetInPage(=" + chunkOffsetInPage + "), " +
      "totalRecordLength(=" + totalChunkLength + ")");
  }
private long allocateSpaceForChunk(int totalChunkLength)