@Override
    public void write(TileEncodingResult encodingResult) {
      numAddressedTiles++;
      boolean writeTileData;
      long offset;
      OptionalLong tileDataHashOpt = encodingResult.tileDataHash();
      var data = encodingResult.tileData();
      TileCoord coord = encodingResult.coord();

      long tileId = coord.hilbertEncoded();

      if (!entries.isEmpty()) {
        if (tileId < lastEntry.tileId()) {
          isClustered = false;
        } else if (tileId == lastEntry.tileId()) {
          LOGGER.error("Duplicate tile detected in writer");
        }
      }

      if (tileDataHashOpt.isPresent()) {
        long tileDataHash = tileDataHashOpt.getAsLong();
        if (hashToOffset.containsKey(tileDataHash)) {
          offset = hashToOffset.get(tileDataHash);
          writeTileData = false;
          if (lastEntry != null && lastEntry.tileId() + lastEntry.runLength() == tileId &&
            lastEntry.offset() == offset) {
            lastEntry.runLength++;
            return;
          }
        } else {
          hashToOffset.put(tileDataHash, currentOffset);
          offset = currentOffset;
          writeTileData = true;
        }
      } else {
        numUnhashedTiles++;
        offset = currentOffset;
        writeTileData = true;
      }

      var newEntry = new Pmtiles.Entry(tileId, offset, data.length, 1);
      entries.add(newEntry);
      lastEntry = newEntry;

      if (writeTileData) {
        try {
          out.write(ByteBuffer.wrap(data));
        } catch (IOException e) {
          throw new UncheckedIOException(e);
        }
        currentOffset += data.length;
      }
    }
Serialize all entries into bytes, choosing the # of leaf directories to ensure the header+root fits in 16 KB.

@param entries a sorted ObjectArrayList of all entries in the tileset.
@return byte arrays of the root and all leaf directories, and the # of leaves.
@throws IOException if compression fails
planetiler-core/src/main/java/com/onthegomap/planetiler/pmtiles/WriteablePmtiles.java