lxy-9602 commented on code in PR #364:
URL: https://github.com/apache/paimon-cpp/pull/364#discussion_r4051868938


##########
src/paimon/common/utils/optimized_roaring_bitmap64.h:
##########
@@ -0,0 +1,115 @@
+/*
+ * 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.
+ */
+
+/* This file is based on source code from the Iceberg Project 
(http://iceberg.apache.org/),
+ * licensed by the Apache Software Foundation (ASF) under the Apache License, 
Version 2.0. See the
+ * NOTICE file distributed with this work for additional information regarding 
copyright
+ * ownership. */
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <functional>
+#include <limits>
+#include <memory>
+
+#include "paimon/io/byte_array_input_stream.h"
+#include "paimon/memory/bytes.h"
+#include "paimon/memory/memory_pool.h"
+#include "paimon/result.h"
+#include "paimon/status.h"
+#include "paimon/utils/roaring_bitmap32.h"
+
+namespace paimon {
+
+/// A bitmap for non-negative 64-bit positions that uses the high 32 bits as 
an array index
+/// and stores the low 32 bits in a 32-bit Roaring bitmap.
+///
+/// This layout is compatible with Java Paimon's `OptimizedRoaringBitmap64` 
and is optimized for
+/// positions whose high 32 bits are small, in particular file-local row 
positions.
+class OptimizedRoaringBitmap64 {
+ public:
+    static constexpr int64_t kMaxValue =
+        (static_cast<int64_t>(std::numeric_limits<int32_t>::max() - 1) << 32) |
+        static_cast<uint32_t>(std::numeric_limits<int32_t>::min());
+
+    OptimizedRoaringBitmap64();
+    ~OptimizedRoaringBitmap64();
+
+    OptimizedRoaringBitmap64(const OptimizedRoaringBitmap64& other);
+    OptimizedRoaringBitmap64& operator=(const OptimizedRoaringBitmap64& other);
+
+    OptimizedRoaringBitmap64(OptimizedRoaringBitmap64&& other) noexcept;
+    OptimizedRoaringBitmap64& operator=(OptimizedRoaringBitmap64&& other) 
noexcept;
+
+    /// Create an optimized 64-bit bitmap containing all positions from a 
32-bit bitmap.
+    static OptimizedRoaringBitmap64 FromRoaringBitmap32(const RoaringBitmap32& 
bitmap);
+
+    /// Add a position.
+    Status Add(int64_t position);
+
+    /// Add all positions in the half-open interval [start, end).
+    Status AddRange(int64_t start, int64_t end);
+
+    /// Union another bitmap into this bitmap.
+    OptimizedRoaringBitmap64& operator|=(const OptimizedRoaringBitmap64& 
other);
+
+    /// Return whether the bitmap contains a position.
+    Result<bool> Contains(int64_t position) const;
+
+    /// Return whether the bitmap is empty.
+    bool IsEmpty() const;
+
+    /// Return the number of positions in the bitmap.
+    int64_t Cardinality() const;
+
+    /// Apply run-length encoding to inner bitmaps when it is more space 
efficient.
+    bool RunLengthEncode();
+
+    /// Visit positions in ascending order.
+    void ForEach(const std::function<void(int64_t)>& consumer) const;
+
+    /// Return the number of allocated inner 32-bit bitmaps.
+    size_t GetAllocatedBitmapCount() const;
+
+    /// Return the number of bytes required by the portable serialized form.
+    size_t GetSizeInBytes() const;
+
+    /// Serialize using the Java-compatible little-endian portable format.
+    PAIMON_UNIQUE_PTR<Bytes> Serialize(MemoryPool* pool) const;
+
+    /// Deserialize from the current position of an input stream.
+    Status Deserialize(ByteArrayInputStream* input_stream);
+
+    /// Deserialize from a buffer.
+    Status Deserialize(const char* begin, size_t length);
+
+    bool operator==(const OptimizedRoaringBitmap64& other) const noexcept;
+
+ private:
+    class Impl;
+
+    static Status CheckPosition(int64_t position);
+    void AllocateBitmapsIfNeeded(size_t required_length);
+
+    std::unique_ptr<Impl> impl_;

Review Comment:
   Is the `Impl` design here intended to make it easier to expose 
`OptimizedRoaringBitmap64` in the header later on?



##########
src/paimon/common/utils/optimized_roaring_bitmap64.cpp:
##########
@@ -0,0 +1,269 @@
+/*
+ * 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.
+ */
+
+/* This file is based on source code from the Iceberg Project 
(http://iceberg.apache.org/),
+ * licensed by the Apache Software Foundation (ASF) under the Apache License, 
Version 2.0. See the
+ * NOTICE file distributed with this work for additional information regarding 
copyright
+ * ownership. */
+
+#include "paimon/common/utils/optimized_roaring_bitmap64.h"
+
+#include <cstring>
+#include <utility>
+#include <vector>
+
+#include "fmt/format.h"
+#include "paimon/common/utils/math.h"
+#include "paimon/result.h"
+#include "roaring.hh"  // NOLINT(build/include_subdir)
+
+namespace paimon {
+namespace {
+
+constexpr size_t kBitmapCountSizeBytes = sizeof(int64_t);
+constexpr size_t kBitmapKeySizeBytes = sizeof(int32_t);
+
+template <typename T>
+void WriteLittleEndian(T value, char** output) {
+    T little_endian = ToLittleEndian(value);
+    std::memcpy(*output, &little_endian, sizeof(T));
+    *output += sizeof(T);
+}
+
+template <typename T>
+Result<T> ReadLittleEndian(ByteArrayInputStream* input_stream) {
+    T little_endian = 0;
+    PAIMON_ASSIGN_OR_RAISE(int64_t read_size,
+                           
input_stream->Read(reinterpret_cast<char*>(&little_endian), sizeof(T)));
+    if (read_size != sizeof(T)) {
+        return Status::Invalid(
+            fmt::format("Failed to read {} bytes, only read {}", sizeof(T), 
read_size));
+    }
+    return FromLittleEndian(little_endian);
+}
+
+}  // namespace
+
+class OptimizedRoaringBitmap64::Impl {
+ public:
+    std::vector<roaring::Roaring> bitmaps;
+};
+
+OptimizedRoaringBitmap64::OptimizedRoaringBitmap64() : 
impl_(std::make_unique<Impl>()) {}
+
+OptimizedRoaringBitmap64::~OptimizedRoaringBitmap64() = default;
+
+OptimizedRoaringBitmap64::OptimizedRoaringBitmap64(const 
OptimizedRoaringBitmap64& other)
+    : impl_(std::make_unique<Impl>(*other.impl_)) {}
+
+OptimizedRoaringBitmap64& OptimizedRoaringBitmap64::operator=(
+    const OptimizedRoaringBitmap64& other) {
+    if (this != &other) {
+        if (impl_ == nullptr) {
+            impl_ = std::make_unique<Impl>(*other.impl_);
+        } else {
+            *impl_ = *other.impl_;
+        }
+    }
+    return *this;
+}
+
+OptimizedRoaringBitmap64::OptimizedRoaringBitmap64(OptimizedRoaringBitmap64&& 
other) noexcept
+    : impl_(std::move(other.impl_)) {}
+
+OptimizedRoaringBitmap64& OptimizedRoaringBitmap64::operator=(
+    OptimizedRoaringBitmap64&& other) noexcept {
+    if (this != &other) {
+        impl_ = std::move(other.impl_);
+    }
+    return *this;
+}
+
+OptimizedRoaringBitmap64 OptimizedRoaringBitmap64::FromRoaringBitmap32(
+    const RoaringBitmap32& bitmap) {
+    OptimizedRoaringBitmap64 result;
+    const auto* roaring_bitmap = static_cast<const 
roaring::Roaring*>(bitmap.roaring_bitmap_);
+    result.impl_->bitmaps.push_back(*roaring_bitmap);
+    return result;
+}
+
+Status OptimizedRoaringBitmap64::Add(int64_t position) {
+    PAIMON_RETURN_NOT_OK(CheckPosition(position));
+    const auto key = static_cast<int32_t>(position >> 32);
+    const auto position32 = static_cast<uint32_t>(position);
+    AllocateBitmapsIfNeeded(static_cast<size_t>(key) + 1);
+    impl_->bitmaps[key].add(position32);
+    return Status::OK();
+}
+
+Status OptimizedRoaringBitmap64::AddRange(int64_t start, int64_t end) {
+    for (int64_t position = start; position < end; ++position) {
+        PAIMON_RETURN_NOT_OK(Add(position));
+    }
+    return Status::OK();
+}
+
+OptimizedRoaringBitmap64& OptimizedRoaringBitmap64::operator|=(
+    const OptimizedRoaringBitmap64& other) {
+    AllocateBitmapsIfNeeded(other.impl_->bitmaps.size());
+    for (size_t key = 0; key < other.impl_->bitmaps.size(); ++key) {
+        impl_->bitmaps[key] |= other.impl_->bitmaps[key];
+    }
+    return *this;
+}
+
+Result<bool> OptimizedRoaringBitmap64::Contains(int64_t position) const {
+    PAIMON_RETURN_NOT_OK(CheckPosition(position));
+    const auto key = static_cast<int32_t>(position >> 32);
+    const auto position32 = static_cast<uint32_t>(position);
+    return static_cast<size_t>(key) < impl_->bitmaps.size() &&
+           impl_->bitmaps[key].contains(position32);
+}
+
+bool OptimizedRoaringBitmap64::IsEmpty() const {
+    return Cardinality() == 0;
+}
+
+int64_t OptimizedRoaringBitmap64::Cardinality() const {
+    int64_t cardinality = 0;
+    for (const roaring::Roaring& bitmap : impl_->bitmaps) {
+        cardinality += static_cast<int64_t>(bitmap.cardinality());
+    }
+    return cardinality;
+}
+
+bool OptimizedRoaringBitmap64::RunLengthEncode() {
+    bool changed = false;
+    for (roaring::Roaring& bitmap : impl_->bitmaps) {
+        changed |= bitmap.runOptimize();
+    }
+    return changed;
+}
+
+void OptimizedRoaringBitmap64::ForEach(const std::function<void(int64_t)>& 
consumer) const {
+    for (size_t key = 0; key < impl_->bitmaps.size(); ++key) {
+        for (uint32_t position32 : impl_->bitmaps[key]) {
+            const uint64_t position = (static_cast<uint64_t>(key) << 32) | 
position32;
+            consumer(static_cast<int64_t>(position));
+        }
+    }
+}
+
+size_t OptimizedRoaringBitmap64::GetAllocatedBitmapCount() const {
+    return impl_->bitmaps.size();
+}
+
+size_t OptimizedRoaringBitmap64::GetSizeInBytes() const {
+    size_t size = kBitmapCountSizeBytes;
+    for (const roaring::Roaring& bitmap : impl_->bitmaps) {
+        size += kBitmapKeySizeBytes + bitmap.getSizeInBytes();
+    }
+    return size;
+}
+
+PAIMON_UNIQUE_PTR<Bytes> OptimizedRoaringBitmap64::Serialize(MemoryPool* pool) 
const {
+    if (pool == nullptr) {
+        pool = GetDefaultPool().get();
+    }
+    PAIMON_UNIQUE_PTR<Bytes> bytes = Bytes::AllocateBytes(GetSizeInBytes(), 
pool);
+    char* output = bytes->data();
+    WriteLittleEndian(static_cast<int64_t>(impl_->bitmaps.size()), &output);
+    for (size_t key = 0; key < impl_->bitmaps.size(); ++key) {
+        WriteLittleEndian(static_cast<int32_t>(key), &output);
+        output += impl_->bitmaps[key].write(output);
+    }
+    return bytes;
+}
+
+Status OptimizedRoaringBitmap64::Deserialize(ByteArrayInputStream* 
input_stream) {
+    if (input_stream == nullptr) {
+        return Status::Invalid("Cannot deserialize OptimizedRoaringBitmap64 
from a null stream");
+    }
+
+    PAIMON_ASSIGN_OR_RAISE(int64_t bitmap_count, 
ReadLittleEndian<int64_t>(input_stream));
+    if (bitmap_count < 0 || bitmap_count > 
std::numeric_limits<int32_t>::max()) {
+        return Status::Invalid(fmt::format("Invalid bitmap count: {}", 
bitmap_count));
+    }

Review Comment:
   Please use `ValidateValueInRange` in `math.h`



##########
LICENSE:
##########
@@ -228,6 +228,9 @@ This product includes code from Apache Iceberg C++.
   * src/paimon/format/avro/avro_direct_encoder.cpp
   * src/paimon/format/avro/avro_direct_encoder.h
 * Avro input stream in src/paimon/format/avro/avro_input_stream_impl.cpp
+* Optimized 64-bit Roaring bitmap:
+  * src/paimon/common/utils/optimized_roaring_bitmap64.h
+  * src/paimon/common/utils/optimized_roaring_bitmap64.cpp

Review Comment:
   Could you confirm whether `optimized_roaring_bitmap64` is based on the 
Iceberg C++ implementation or the Iceberg Java one? Also, please make sure to 
add the corresponding NOTICE update as well.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to