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


##########
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:
   fixed



-- 
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