jt2594838 commented on code in PR #560:
URL: https://github.com/apache/tsfile/pull/560#discussion_r2247652833


##########
java/tsfile/src/main/java/org/apache/tsfile/common/bitStream/BitInputStream.java:
##########
@@ -0,0 +1,264 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tsfile.common.bitStream;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+
+/** A stream for reading individual bits or groups of bits from an 
InputStream. */
+public class BitInputStream extends BitStream {
+
+  protected InputStream in;
+  protected int buffer;
+  protected int bufferBitCount;
+  protected final long totalBits; // Total valid bits
+  protected long bitsRead = 0; // Number of bits read so far
+
+  protected int markedBuffer = 0;
+  protected int markedBufferBitCount = 0;
+  protected long markedBitsRead = 0;
+
+  /**
+   * Constructs a BitInputStream with a given InputStream and total number of 
valid bits.
+   *
+   * @param in the underlying InputStream
+   * @param totalBits the total number of valid bits to read
+   */
+  public BitInputStream(InputStream in, long totalBits) {
+    this.in = in;
+    this.totalBits = totalBits;
+    this.bufferBitCount = 0;
+  }
+
+  /**
+   * Reads an integer value using the specified number of bits. If fewer bits 
are available, only
+   * the available bits are returned.
+   *
+   * @param numBits the number of bits to read (≤ 32)
+   * @return an integer whose lower bits contain the read value
+   * @throws EOFException if no data is available to read
+   * @throws IOException if an I/O error occurs
+   */
+  public int readInt(int numBits) throws IOException {
+    if (availableBits() <= 0) {
+      throw new EOFException();
+    }
+
+    bitsRead += numBits;
+    int result = 0;
+    boolean hasReadData = false;
+
+    while (numBits > 0) {
+      if (bufferBitCount == 0) {
+        buffer = in.read();
+        if (buffer < 0) {
+          if (!hasReadData) {
+            throw new EOFException();
+          }
+          return result;
+        }
+        bufferBitCount = BITS_PER_BYTE;
+      }
+
+      if (bufferBitCount > numBits) {
+        result = ((buffer >> (bufferBitCount - numBits)) & MASKS[numBits]) | 
result;
+        bufferBitCount -= numBits;
+        numBits = 0;
+      } else {
+        result = ((buffer & MASKS[bufferBitCount]) << (numBits - 
bufferBitCount)) | result;
+        numBits -= bufferBitCount;
+        bufferBitCount = 0;
+      }
+
+      hasReadData = true;
+    }
+
+    return result;
+  }
+
+  /**
+   * Reads a long value using the specified number of bits.
+   *
+   * @param numBits the number of bits to read (0 to 64)
+   * @return a long value containing the read bits
+   * @throws EOFException if no data is available to read
+   * @throws IOException if an I/O error occurs
+   */
+  public long readLong(int numBits) throws IOException {
+    if (availableBits() <= 0) {
+      throw new EOFException();
+    }
+    bitsRead += numBits;
+    if (numBits > 64 || numBits < 0) {
+      throw new IllegalArgumentException("numBits must be between 0 and 64");
+    }
+
+    long result = 0;
+    boolean hasReadData = false;
+
+    while (numBits > 0) {
+      if (bufferBitCount == 0) {
+        buffer = in.read();
+        if (buffer < 0) {
+          if (!hasReadData) {
+            throw new EOFException();
+          }
+          return result;
+        }
+        bufferBitCount = BITS_PER_BYTE;
+      }
+
+      if (bufferBitCount > numBits) {
+        int shift = bufferBitCount - numBits;
+        result = (result << numBits) | ((buffer >> shift) & MASKS[numBits]);
+        bufferBitCount -= numBits;
+        buffer &= MASKS[bufferBitCount];
+        numBits = 0;
+      } else {
+        result = (result << bufferBitCount) | (buffer & MASKS[bufferBitCount]);
+        numBits -= bufferBitCount;
+        bufferBitCount = 0;
+      }
+
+      hasReadData = true;
+    }
+
+    return result;
+  }
+
+  public static int readVarInt(BitInputStream in) throws IOException {
+    int result = 0;
+    int shift = 0;
+
+    while (true) {
+      int chunk = in.readInt(7);
+      boolean hasNext = in.readBit();
+      result |= chunk << shift;
+      if (!hasNext) break;

Review Comment:
   Mind the code style (if with only one line still should use `{}`)



##########
java/tsfile/src/main/java/org/apache/tsfile/common/bitStream/BitInputStream.java:
##########
@@ -0,0 +1,264 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tsfile.common.bitStream;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+
+/** A stream for reading individual bits or groups of bits from an 
InputStream. */
+public class BitInputStream extends BitStream {
+
+  protected InputStream in;
+  protected int buffer;
+  protected int bufferBitCount;
+  protected final long totalBits; // Total valid bits
+  protected long bitsRead = 0; // Number of bits read so far
+
+  protected int markedBuffer = 0;
+  protected int markedBufferBitCount = 0;
+  protected long markedBitsRead = 0;
+
+  /**
+   * Constructs a BitInputStream with a given InputStream and total number of 
valid bits.
+   *
+   * @param in the underlying InputStream
+   * @param totalBits the total number of valid bits to read
+   */
+  public BitInputStream(InputStream in, long totalBits) {
+    this.in = in;
+    this.totalBits = totalBits;
+    this.bufferBitCount = 0;
+  }
+
+  /**
+   * Reads an integer value using the specified number of bits. If fewer bits 
are available, only
+   * the available bits are returned.
+   *
+   * @param numBits the number of bits to read (≤ 32)
+   * @return an integer whose lower bits contain the read value
+   * @throws EOFException if no data is available to read
+   * @throws IOException if an I/O error occurs
+   */
+  public int readInt(int numBits) throws IOException {
+    if (availableBits() <= 0) {
+      throw new EOFException();
+    }
+
+    bitsRead += numBits;
+    int result = 0;
+    boolean hasReadData = false;
+
+    while (numBits > 0) {
+      if (bufferBitCount == 0) {
+        buffer = in.read();
+        if (buffer < 0) {
+          if (!hasReadData) {
+            throw new EOFException();
+          }
+          return result;
+        }
+        bufferBitCount = BITS_PER_BYTE;
+      }
+
+      if (bufferBitCount > numBits) {
+        result = ((buffer >> (bufferBitCount - numBits)) & MASKS[numBits]) | 
result;
+        bufferBitCount -= numBits;
+        numBits = 0;
+      } else {
+        result = ((buffer & MASKS[bufferBitCount]) << (numBits - 
bufferBitCount)) | result;
+        numBits -= bufferBitCount;
+        bufferBitCount = 0;
+      }
+
+      hasReadData = true;
+    }
+
+    return result;
+  }
+
+  /**
+   * Reads a long value using the specified number of bits.
+   *
+   * @param numBits the number of bits to read (0 to 64)
+   * @return a long value containing the read bits
+   * @throws EOFException if no data is available to read
+   * @throws IOException if an I/O error occurs
+   */
+  public long readLong(int numBits) throws IOException {
+    if (availableBits() <= 0) {
+      throw new EOFException();
+    }
+    bitsRead += numBits;
+    if (numBits > 64 || numBits < 0) {
+      throw new IllegalArgumentException("numBits must be between 0 and 64");
+    }

Review Comment:
   Add this for readInt()?



##########
java/tsfile/src/main/java/org/apache/tsfile/encoding/decoder/CamelDecoder.java:
##########
@@ -0,0 +1,273 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tsfile.encoding.decoder;
+
+import org.apache.tsfile.common.bitStream.BitInputStream;
+import org.apache.tsfile.common.bitStream.ByteBufferBackedInputStream;
+import org.apache.tsfile.exception.encoding.TsFileDecodingException;
+import org.apache.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.tsfile.utils.ReadWriteForEncodingUtils;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+import java.util.LinkedList;
+import java.util.List;
+
+public class CamelDecoder extends Decoder {
+  // === Constants for decoding ===
+  private static final int BITS_FOR_SIGN = 1;
+  private static final int BITS_FOR_TYPE = 1;
+  private static final int BITS_FOR_FIRST_VALUE = 64;
+  private static final int BITS_FOR_LEADING_ZEROS = 6;
+  private static final int BITS_FOR_SIGNIFICANT_BITS = 6;
+  private static final int BITS_FOR_DECIMAL_COUNT = 4;
+  private static final int DOUBLE_TOTAL_BITS = 64;
+  private static final int DOUBLE_MANTISSA_BITS = 52;
+  private static final int DECIMAL_MAX_COUNT = 15;
+
+  // === Camel state ===
+  private long previousValue = 0;
+  private boolean isFirst = true;
+  private long storedVal = 0;
+
+  // === Precomputed tables ===
+  public static final long[] powers = new long[DECIMAL_MAX_COUNT];
+  public static final long[] threshold = new long[DECIMAL_MAX_COUNT];
+  public static final int[] mValueBits = new int[DECIMAL_MAX_COUNT];
+
+  static {
+    for (int l = 1; l <= DECIMAL_MAX_COUNT; l++) {
+      int idx = l - 1;
+      powers[idx] = (long) Math.pow(10, l);
+      long divisor = 1L << l;
+      threshold[idx] = powers[idx] / divisor;
+      mValueBits[idx] = (int) Math.ceil(Math.log(threshold[idx]) / 
Math.log(2));
+    }
+  }
+
+  private BitInputStream in;
+  private final GorillaDecoder gorillaDecoder;
+
+  public CamelDecoder(InputStream inputStream, long totalBits) {
+    super(TSEncoding.CAMEL);
+    // Initialize bit-level reader and nested Gorilla decoder
+    this.in = new BitInputStream(inputStream, totalBits);
+    this.gorillaDecoder = new GorillaDecoder();
+  }
+
+  public CamelDecoder() {
+    super(TSEncoding.CAMEL);
+    this.gorillaDecoder = new GorillaDecoder();
+  }
+
+  @Override
+  public boolean hasNext(ByteBuffer buffer) throws IOException {
+    if (cacheIndex < valueCache.size()) {
+      return true;
+    }
+    if (in != null && in.availableBits() > 0) {
+      return true;
+    }
+    return buffer.hasRemaining();
+  }
+
+  @Override
+  public void reset() {
+    this.in = null;
+    this.isFirst = true;
+    this.previousValue = 0L;
+    this.storedVal = 0L;
+    this.gorillaDecoder.leadingZeros = Integer.MAX_VALUE;
+    this.gorillaDecoder.trailingZeros = 0;
+  }
+
+  // Cache for batch decoding
+  private List<Double> valueCache = new LinkedList<>();
+  private int cacheIndex = 0;
+
+  @Override
+  public double readDouble(ByteBuffer buffer) {
+    try {
+      // If the current block has been fully read, load the next block
+      if (cacheIndex >= valueCache.size()) {
+        // If no BitInputStream is available or all bits have been consumed
+        if (in == null || in.availableBits() == 0) {
+          if (!buffer.hasRemaining()) {
+            throw new TsFileDecodingException("No more data to decode");
+          }
+
+          ByteBuffer slice = buffer.slice(); // Keep this
+          ByteBufferBackedInputStream bais = new 
ByteBufferBackedInputStream(slice);
+
+          // Read the number of bits in the current block
+          int blockBits = ReadWriteForEncodingUtils.readVarInt(bais);
+          this.in = new BitInputStream(bais, blockBits);
+
+          // Reset decoder state for the new block
+          this.isFirst = true;
+          this.storedVal = 0L;
+          this.previousValue = 0L;
+          this.gorillaDecoder.leadingZeros = Integer.MAX_VALUE;
+          this.gorillaDecoder.trailingZeros = 0;
+
+          // Decode the entire block into a temporary value cache
+          List<Double> newValues = getValues();
+          if (newValues.isEmpty()) {
+            throw new TsFileDecodingException("Unexpected empty block");
+          }
+          valueCache = newValues;
+          cacheIndex = 0;
+
+          // Advance the buffer position by the number of bytes consumed
+          // int consumed = temp.length - bais.available();
+          int consumed = bais.getConsumed();
+
+          buffer.position(buffer.position() + consumed);
+        }
+      }
+
+      // Return the next decoded value from the cache
+      return valueCache.get(cacheIndex++);
+    } catch (IOException e) {
+      throw new TsFileDecodingException(e.getMessage());
+    }
+  }
+
+  /** Nested class to handle fallback encoding (Gorilla) for double values. */
+  public class GorillaDecoder {
+    private int leadingZeros = Integer.MAX_VALUE;
+    private int trailingZeros = 0;
+
+    /** Decode next value using Gorilla algorithm. */
+    public double decode(BitInputStream in) throws IOException {
+      if (isFirst) {
+        previousValue = in.readLong(BITS_FOR_FIRST_VALUE);
+        isFirst = false;
+        return Double.longBitsToDouble(previousValue);
+      }
+
+      boolean controlBit = in.readBit();
+      if (!controlBit) {
+        return Double.longBitsToDouble(previousValue);
+      }
+
+      boolean reuseBlock = !in.readBit();
+      long xor;
+      if (reuseBlock) {
+        int sigBits = DOUBLE_TOTAL_BITS - leadingZeros - trailingZeros;
+        if (sigBits == 0) {
+          return Double.longBitsToDouble(previousValue);
+        }
+        xor = in.readLong(sigBits) << trailingZeros;
+      } else {
+        leadingZeros = in.readInt(BITS_FOR_LEADING_ZEROS);
+        int sigBits = in.readInt(BITS_FOR_SIGNIFICANT_BITS) + 1;
+        trailingZeros = DOUBLE_TOTAL_BITS - leadingZeros - sigBits;
+        xor = in.readLong(sigBits) << trailingZeros;
+      }
+
+      previousValue ^= xor;
+      return Double.longBitsToDouble(previousValue);
+    }
+  }
+
+  /** Retrieve nested GorillaDecoder. */
+  public GorillaDecoder getGorillaDecoder() {
+    return gorillaDecoder;
+  }
+
+  /** Read all values until stream is exhausted. */
+  public List<Double> getValues() throws IOException {
+    List<Double> list = new LinkedList<>();
+    Double val;
+    while ((val = next()) != null) {
+      list.add(val);
+    }
+    return list;
+  }
+
+  /** Decode next available value, return null if no more bits. */
+  private Double next() throws IOException {
+    if (in.availableBits() <= 0) {
+      return null;
+    }

Review Comment:
   Avoid using Double. Maybe you can use a field to indicate whether there is a 
next value.



##########
java/tsfile/src/main/java/org/apache/tsfile/common/bitStream/BitInputStream.java:
##########
@@ -0,0 +1,264 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tsfile.common.bitStream;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+
+/** A stream for reading individual bits or groups of bits from an 
InputStream. */
+public class BitInputStream extends BitStream {
+
+  protected InputStream in;
+  protected int buffer;
+  protected int bufferBitCount;
+  protected final long totalBits; // Total valid bits
+  protected long bitsRead = 0; // Number of bits read so far
+
+  protected int markedBuffer = 0;
+  protected int markedBufferBitCount = 0;
+  protected long markedBitsRead = 0;
+
+  /**
+   * Constructs a BitInputStream with a given InputStream and total number of 
valid bits.
+   *
+   * @param in the underlying InputStream
+   * @param totalBits the total number of valid bits to read
+   */
+  public BitInputStream(InputStream in, long totalBits) {
+    this.in = in;
+    this.totalBits = totalBits;
+    this.bufferBitCount = 0;
+  }
+
+  /**
+   * Reads an integer value using the specified number of bits. If fewer bits 
are available, only
+   * the available bits are returned.
+   *
+   * @param numBits the number of bits to read (≤ 32)
+   * @return an integer whose lower bits contain the read value
+   * @throws EOFException if no data is available to read
+   * @throws IOException if an I/O error occurs
+   */
+  public int readInt(int numBits) throws IOException {
+    if (availableBits() <= 0) {
+      throw new EOFException();
+    }
+
+    bitsRead += numBits;
+    int result = 0;
+    boolean hasReadData = false;
+
+    while (numBits > 0) {
+      if (bufferBitCount == 0) {
+        buffer = in.read();
+        if (buffer < 0) {
+          if (!hasReadData) {
+            throw new EOFException();
+          }
+          return result;
+        }
+        bufferBitCount = BITS_PER_BYTE;
+      }
+
+      if (bufferBitCount > numBits) {
+        result = ((buffer >> (bufferBitCount - numBits)) & MASKS[numBits]) | 
result;
+        bufferBitCount -= numBits;
+        numBits = 0;
+      } else {
+        result = ((buffer & MASKS[bufferBitCount]) << (numBits - 
bufferBitCount)) | result;
+        numBits -= bufferBitCount;
+        bufferBitCount = 0;
+      }
+
+      hasReadData = true;
+    }
+
+    return result;
+  }
+
+  /**
+   * Reads a long value using the specified number of bits.
+   *
+   * @param numBits the number of bits to read (0 to 64)
+   * @return a long value containing the read bits
+   * @throws EOFException if no data is available to read
+   * @throws IOException if an I/O error occurs
+   */
+  public long readLong(int numBits) throws IOException {
+    if (availableBits() <= 0) {
+      throw new EOFException();
+    }
+    bitsRead += numBits;
+    if (numBits > 64 || numBits < 0) {
+      throw new IllegalArgumentException("numBits must be between 0 and 64");
+    }
+
+    long result = 0;
+    boolean hasReadData = false;
+
+    while (numBits > 0) {
+      if (bufferBitCount == 0) {
+        buffer = in.read();
+        if (buffer < 0) {
+          if (!hasReadData) {
+            throw new EOFException();
+          }
+          return result;
+        }
+        bufferBitCount = BITS_PER_BYTE;
+      }
+
+      if (bufferBitCount > numBits) {
+        int shift = bufferBitCount - numBits;
+        result = (result << numBits) | ((buffer >> shift) & MASKS[numBits]);
+        bufferBitCount -= numBits;
+        buffer &= MASKS[bufferBitCount];
+        numBits = 0;
+      } else {
+        result = (result << bufferBitCount) | (buffer & MASKS[bufferBitCount]);
+        numBits -= bufferBitCount;
+        bufferBitCount = 0;
+      }
+
+      hasReadData = true;
+    }
+
+    return result;
+  }
+
+  public static int readVarInt(BitInputStream in) throws IOException {
+    int result = 0;
+    int shift = 0;
+
+    while (true) {
+      int chunk = in.readInt(7);
+      boolean hasNext = in.readBit();
+      result |= chunk << shift;
+      if (!hasNext) break;
+      shift += 7;
+      if (shift >= 32) throw new IOException("VarInt too long");
+    }
+
+    return (result >>> 1) ^ -(result & 1);
+  }
+
+  public static long readVarLong(BitInputStream in) throws IOException {
+    long result = 0;
+    int shift = 0;
+
+    while (true) {
+      long chunk = in.readInt(7);
+      boolean hasNext = in.readBit();
+
+      result |= (chunk) << shift;
+      shift += 7;
+
+      if (!hasNext) {
+        break;
+      }
+
+      if (shift >= 64) {
+        throw new IOException("VarLong too long: overflow");
+      }
+    }
+
+    // ZigZag 解码

Review Comment:
   Mind this.



##########
java/tsfile/src/main/java/org/apache/tsfile/encoding/decoder/CamelDecoder.java:
##########
@@ -0,0 +1,273 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tsfile.encoding.decoder;
+
+import org.apache.tsfile.common.bitStream.BitInputStream;
+import org.apache.tsfile.common.bitStream.ByteBufferBackedInputStream;
+import org.apache.tsfile.exception.encoding.TsFileDecodingException;
+import org.apache.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.tsfile.utils.ReadWriteForEncodingUtils;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+import java.util.LinkedList;
+import java.util.List;
+
+public class CamelDecoder extends Decoder {
+  // === Constants for decoding ===
+  private static final int BITS_FOR_SIGN = 1;
+  private static final int BITS_FOR_TYPE = 1;
+  private static final int BITS_FOR_FIRST_VALUE = 64;
+  private static final int BITS_FOR_LEADING_ZEROS = 6;
+  private static final int BITS_FOR_SIGNIFICANT_BITS = 6;
+  private static final int BITS_FOR_DECIMAL_COUNT = 4;
+  private static final int DOUBLE_TOTAL_BITS = 64;
+  private static final int DOUBLE_MANTISSA_BITS = 52;
+  private static final int DECIMAL_MAX_COUNT = 15;
+
+  // === Camel state ===
+  private long previousValue = 0;
+  private boolean isFirst = true;
+  private long storedVal = 0;
+
+  // === Precomputed tables ===
+  public static final long[] powers = new long[DECIMAL_MAX_COUNT];
+  public static final long[] threshold = new long[DECIMAL_MAX_COUNT];
+  public static final int[] mValueBits = new int[DECIMAL_MAX_COUNT];
+
+  static {
+    for (int l = 1; l <= DECIMAL_MAX_COUNT; l++) {
+      int idx = l - 1;
+      powers[idx] = (long) Math.pow(10, l);
+      long divisor = 1L << l;
+      threshold[idx] = powers[idx] / divisor;
+      mValueBits[idx] = (int) Math.ceil(Math.log(threshold[idx]) / 
Math.log(2));
+    }
+  }
+
+  private BitInputStream in;
+  private final GorillaDecoder gorillaDecoder;
+
+  public CamelDecoder(InputStream inputStream, long totalBits) {
+    super(TSEncoding.CAMEL);
+    // Initialize bit-level reader and nested Gorilla decoder
+    this.in = new BitInputStream(inputStream, totalBits);
+    this.gorillaDecoder = new GorillaDecoder();
+  }
+
+  public CamelDecoder() {
+    super(TSEncoding.CAMEL);
+    this.gorillaDecoder = new GorillaDecoder();
+  }
+
+  @Override
+  public boolean hasNext(ByteBuffer buffer) throws IOException {
+    if (cacheIndex < valueCache.size()) {
+      return true;
+    }
+    if (in != null && in.availableBits() > 0) {
+      return true;
+    }
+    return buffer.hasRemaining();
+  }
+
+  @Override
+  public void reset() {
+    this.in = null;
+    this.isFirst = true;
+    this.previousValue = 0L;
+    this.storedVal = 0L;
+    this.gorillaDecoder.leadingZeros = Integer.MAX_VALUE;
+    this.gorillaDecoder.trailingZeros = 0;
+  }
+
+  // Cache for batch decoding
+  private List<Double> valueCache = new LinkedList<>();
+  private int cacheIndex = 0;
+
+  @Override
+  public double readDouble(ByteBuffer buffer) {
+    try {
+      // If the current block has been fully read, load the next block
+      if (cacheIndex >= valueCache.size()) {
+        // If no BitInputStream is available or all bits have been consumed
+        if (in == null || in.availableBits() == 0) {
+          if (!buffer.hasRemaining()) {
+            throw new TsFileDecodingException("No more data to decode");
+          }
+
+          ByteBuffer slice = buffer.slice(); // Keep this
+          ByteBufferBackedInputStream bais = new 
ByteBufferBackedInputStream(slice);
+
+          // Read the number of bits in the current block
+          int blockBits = ReadWriteForEncodingUtils.readVarInt(bais);
+          this.in = new BitInputStream(bais, blockBits);
+
+          // Reset decoder state for the new block
+          this.isFirst = true;
+          this.storedVal = 0L;
+          this.previousValue = 0L;
+          this.gorillaDecoder.leadingZeros = Integer.MAX_VALUE;
+          this.gorillaDecoder.trailingZeros = 0;
+
+          // Decode the entire block into a temporary value cache
+          List<Double> newValues = getValues();
+          if (newValues.isEmpty()) {
+            throw new TsFileDecodingException("Unexpected empty block");
+          }
+          valueCache = newValues;
+          cacheIndex = 0;
+
+          // Advance the buffer position by the number of bytes consumed
+          // int consumed = temp.length - bais.available();
+          int consumed = bais.getConsumed();
+
+          buffer.position(buffer.position() + consumed);
+        }
+      }
+
+      // Return the next decoded value from the cache
+      return valueCache.get(cacheIndex++);
+    } catch (IOException e) {
+      throw new TsFileDecodingException(e.getMessage());
+    }
+  }
+
+  /** Nested class to handle fallback encoding (Gorilla) for double values. */
+  public class GorillaDecoder {
+    private int leadingZeros = Integer.MAX_VALUE;
+    private int trailingZeros = 0;
+
+    /** Decode next value using Gorilla algorithm. */
+    public double decode(BitInputStream in) throws IOException {
+      if (isFirst) {
+        previousValue = in.readLong(BITS_FOR_FIRST_VALUE);
+        isFirst = false;
+        return Double.longBitsToDouble(previousValue);
+      }
+
+      boolean controlBit = in.readBit();
+      if (!controlBit) {
+        return Double.longBitsToDouble(previousValue);
+      }
+
+      boolean reuseBlock = !in.readBit();
+      long xor;
+      if (reuseBlock) {
+        int sigBits = DOUBLE_TOTAL_BITS - leadingZeros - trailingZeros;
+        if (sigBits == 0) {
+          return Double.longBitsToDouble(previousValue);
+        }
+        xor = in.readLong(sigBits) << trailingZeros;
+      } else {
+        leadingZeros = in.readInt(BITS_FOR_LEADING_ZEROS);
+        int sigBits = in.readInt(BITS_FOR_SIGNIFICANT_BITS) + 1;
+        trailingZeros = DOUBLE_TOTAL_BITS - leadingZeros - sigBits;
+        xor = in.readLong(sigBits) << trailingZeros;
+      }
+
+      previousValue ^= xor;
+      return Double.longBitsToDouble(previousValue);
+    }
+  }
+
+  /** Retrieve nested GorillaDecoder. */
+  public GorillaDecoder getGorillaDecoder() {
+    return gorillaDecoder;
+  }
+
+  /** Read all values until stream is exhausted. */
+  public List<Double> getValues() throws IOException {
+    List<Double> list = new LinkedList<>();
+    Double val;
+    while ((val = next()) != null) {
+      list.add(val);
+    }
+    return list;
+  }

Review Comment:
   LinkedList<Double> is too heavy for this task. 
   Try your best to use double[] (a reused field, do not new it every time).
   



##########
java/tsfile/src/main/java/org/apache/tsfile/encoding/encoder/CamelEncoder.java:
##########
@@ -0,0 +1,297 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tsfile.encoding.encoder;
+
+import org.apache.tsfile.common.bitStream.BitOutputStream;
+import org.apache.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.tsfile.utils.ReadWriteForEncodingUtils;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+
+public class CamelEncoder extends Encoder {
+  private final GorillaEncoder gorillaEncoder;
+
+  // === Constants for encoding ===
+  private static final int BITS_FOR_SIGN = 1;
+  private static final int BITS_FOR_TYPE = 1;
+  private static final int BITS_FOR_FIRST_VALUE = 64;
+  private static final int BITS_FOR_LEADING_ZEROS = 6;
+  private static final int BITS_FOR_SIGNIFICANT_BITS = 6;
+  private static final int BITS_FOR_DECIMAL_COUNT = 4;
+  private static final int DOUBLE_TOTAL_BITS = 64;
+  private static final int DOUBLE_MANTISSA_BITS = 52;
+  private static final int DECIMAL_MAX_COUNT = 10;
+
+  // === Camel state ===
+  private long storedVal = 0;
+  private boolean isFirst = true;
+  private int decimalCount = 0;
+  long previousValue = 0;
+  private boolean hasPending = false; // guard for empty or duplicate flush
+
+  // === Precomputed tables ===
+  public static final long[] powers = new long[DECIMAL_MAX_COUNT];
+  public static final long[] threshold = new long[DECIMAL_MAX_COUNT];
+  public static final int[] mValueBits = new int[DECIMAL_MAX_COUNT];
+
+  private final BitOutputStream out;
+  private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+  public CamelEncoder() {
+    super(TSEncoding.CAMEL);
+    for (int l = 1; l <= DECIMAL_MAX_COUNT; l++) {
+      int idx = l - 1;
+      powers[idx] = (long) Math.pow(10, l);
+      long divisor = 1L << l;
+      threshold[idx] = powers[idx] / divisor;
+      mValueBits[idx] = (int) Math.ceil(Math.log(threshold[idx]) / 
Math.log(2));
+    }

Review Comment:
   Use static initialization.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscr...@tsfile.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to