Exemplo n.º 1
0
  /**
   * Method that encodes given input using provided {@link ChunkEncoder}, and aggregating it into a
   * single byte array and returning that.
   *
   * <p>NOTE: method does NOT call {@link ChunkEncoder#close}; caller is responsible for doing that
   * after it is done using the encoder.
   */
  public static byte[] encode(ChunkEncoder enc, byte[] data, int offset, int length) {
    int left = length;
    int chunkLen = Math.min(LZFChunk.MAX_CHUNK_LEN, left);
    LZFChunk first = enc.encodeChunk(data, offset, chunkLen);
    left -= chunkLen;
    // shortcut: if it all fit in, no need to coalesce:
    if (left < 1) {
      return first.getData();
    }
    // otherwise need to get other chunks:
    int resultBytes = first.length();
    offset += chunkLen;
    LZFChunk last = first;

    do {
      chunkLen = Math.min(left, LZFChunk.MAX_CHUNK_LEN);
      LZFChunk chunk = enc.encodeChunk(data, offset, chunkLen);
      offset += chunkLen;
      left -= chunkLen;
      resultBytes += chunk.length();
      last.setNext(chunk);
      last = chunk;
    } while (left > 0);
    // and then coalesce returns into single contiguous byte array
    byte[] result = new byte[resultBytes];
    int ptr = 0;
    for (; first != null; first = first.next()) {
      ptr = first.copyTo(result, ptr);
    }
    return result;
  }