mapleFU commented on code in PR #2142:
URL: https://github.com/apache/kvrocks/pull/2142#discussion_r1573293664
##########
src/storage/redis_metadata.cc:
##########
@@ -489,3 +489,20 @@ rocksdb::Status SearchMetadata::Decode(Slice *input) {
return rocksdb::Status::OK();
}
+
+void HyperloglogMetadata::Encode(std::string *dst) const {
+ Metadata::Encode(dst);
+ PutFixed8(dst, static_cast<uint8_t>(encode_type_));
+}
+
+rocksdb::Status HyperloglogMetadata::Decode(Slice *input) {
+ if (auto s = Metadata::Decode(input); !s.ok()) {
+ return s;
+ }
+
+ if (!GetFixed8(input, reinterpret_cast<uint8_t *>(&encode_type_))) {
Review Comment:
@PragmaTwice Is this casting a valid cast? Since `encode_type_` supports
less than `uint8_t`'s domain?
##########
src/types/hyperloglog.cc:
##########
@@ -0,0 +1,256 @@
+/*
+ * 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.
+ *
+ */
+
+/* Redis HyperLogLog probabilistic cardinality approximation.
+ * This file implements the algorithm and the exported Redis commands.
+ *
+ * Copyright (c) 2014, Salvatore Sanfilippo <antirez at gmail dot com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * Neither the name of Redis nor the names of its contributors may be used
+ * to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+// NOTE: this file is copy from redis's source: `src/hyperloglog.c`
+
+#include "hyperloglog.h"
+
+#include "murmurhash2.h"
+
+/* Store the value of the register at position 'index' into variable 'val'.
+ * 'registers' is an array of unsigned bytes. */
+void HllDenseGetRegister(uint8_t *val, uint8_t *registers, uint32_t index) {
+ uint32_t byte = index * kHyperLogLogBits / 8;
+ uint8_t fb = index * kHyperLogLogBits & 7;
+ uint8_t fb8 = 8 - fb;
+ uint8_t b0 = registers[byte];
+ uint8_t b1 = registers[byte + 1];
+ *val = ((b0 >> fb) | (b1 << fb8)) & kHyperLogLogRegisterMax;
+}
+
+/* Set the value of the register at position 'index' to 'val'.
+ * 'registers' is an array of unsigned bytes. */
+void HllDenseSetRegister(uint8_t *registers, uint32_t index, uint8_t val) {
+ uint32_t byte = index * kHyperLogLogBits / 8;
+ uint8_t fb = index * kHyperLogLogBits & 7;
+ uint8_t fb8 = 8 - fb;
+ uint8_t v = val;
+ registers[byte] &= ~(kHyperLogLogRegisterMax << fb);
+ registers[byte] |= v << fb;
+ registers[byte + 1] &= ~(kHyperLogLogRegisterMax >> fb8);
+ registers[byte + 1] |= v >> fb8;
+}
+
+/* ========================= HyperLogLog algorithm =========================
*/
+
+/* Given a string element to add to the HyperLogLog, returns the length
+ * of the pattern 000..1 of the element hash. As a side effect
'register_index' is
+ * set which the element hashes to. */
+uint8_t HllPatLen(const std::vector<uint8_t> &element, uint32_t
*register_index) {
+ int elesize = static_cast<int>(element.size());
+ uint64_t hash = 0, bit = 0, index = 0;
+ int count = 0;
+
+ /* Count the number of zeroes starting from bit kHyperLogLogRegisterCount
+ * (that is a power of two corresponding to the first bit we don't use
+ * as index). The max run can be 64-kHyperLogLogRegisterCountPow+1 =
kHyperLogLogHashBitCount+1 bits.
+ *
+ * Note that the final "1" ending the sequence of zeroes must be
+ * included in the count, so if we find "001" the count is 3, and
+ * the smallest count possible is no zeroes at all, just a 1 bit
+ * at the first position, that is a count of 1.
+ *
+ * This may sound like inefficient, but actually in the average case
+ * there are high probabilities to find a 1 after a few iterations. */
+ hash = MurmurHash64A(element.data(), elesize, 0xadc83b19ULL);
+ index = hash & kHyperLogLogRegisterCountMask; /* Register index. */
+ hash >>= kHyperLogLogRegisterCountPow; /* Remove bits used to
address the register. */
+ hash |= ((uint64_t)1 << kHyperLogLogHashBitCount); /* Make sure the loop
terminates
+ and count will be <=
kHyperLogLogHashBitCount+1. */
+ bit = 1;
+ count = 1; /* Initialized to 1 since we count the "00000...1" pattern. */
+ while ((hash & bit) == 0) {
+ count++;
+ bit <<= 1;
+ }
+ *register_index = (int)index;
+ return count;
+}
+
+/* Compute the register histogram in the dense representation. */
+void HllDenseRegHisto(uint8_t *registers, int *reghisto) {
+ /* Redis default is to use 16384 registers 6 bits each. The code works
+ * with other values by modifying the defines, but for our target value
+ * we take a faster path with unrolled loops. */
+ if (kHyperLogLogRegisterCount == 16384 && kHyperLogLogBits == 6) {
+ uint8_t *r = registers;
+ unsigned long r0 = 0, r1 = 0, r2 = 0, r3 = 0, r4 = 0, r5 = 0, r6 = 0, r7 =
0, r8 = 0, r9 = 0, r10 = 0, r11 = 0,
+ r12 = 0, r13 = 0, r14 = 0, r15 = 0;
+ for (auto j = 0; j < 1024; j++) {
Review Comment:
This code is a bit hacking, can we change `63` to `kHyperLogLogRegisterMax` ?
##########
src/types/redis_hyperloglog.cc:
##########
@@ -0,0 +1,154 @@
+/*
+ * 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.
+ *
+ */
+
+#include "redis_hyperloglog.h"
+
+#include <db_util.h>
+#include <stdint.h>
+
+namespace redis {
+
+rocksdb::Status HyperLogLog::GetMetadata(Database::GetOptions get_options,
const Slice &ns_key,
+ HyperloglogMetadata *metadata) {
+ return Database::GetMetadata(get_options, {kRedisHyperLogLog}, ns_key,
metadata);
+}
+
+/* the max 0 pattern counter of the subset the element belongs to is
incremented if needed */
+rocksdb::Status HyperLogLog::Add(const Slice &user_key, const
std::vector<Slice> &elements, uint64_t *ret) {
+ *ret = 0;
+ std::string ns_key = AppendNamespacePrefix(user_key);
+
+ LockGuard guard(storage_->GetLockManager(), ns_key);
+ HyperloglogMetadata metadata;
+ rocksdb::Status s = GetMetadata(GetOptions(), ns_key, &metadata);
+ if (!s.ok() && !s.IsNotFound()) return s;
+
+ auto batch = storage_->GetWriteBatchBase();
+ WriteBatchLogData log_data(kRedisHyperLogLog);
+ batch->PutLogData(log_data.Encode());
+
+ Bitmap::SegmentCacheStore cache(storage_, metadata_cf_handle_, ns_key,
&metadata);
+ for (const auto &element : elements) {
+ uint32_t register_index = 0;
+ auto ele_str = element.ToString();
+ std::vector<uint8_t> ele(ele_str.begin(), ele_str.end());
+ uint8_t count = HllPatLen(ele, ®ister_index);
+ uint32_t segment_index = register_index /
kHyperLogLogRegisterCountPerSegment;
+ uint32_t register_index_in_segment = register_index %
kHyperLogLogRegisterCountPerSegment;
+
+ std::string *segment = nullptr;
+ auto s = cache.GetMut(segment_index, &segment);
+ if (!s.ok()) return s;
+ if (segment->size() == 0) {
+ segment->resize(kHyperLogLogRegisterBytesPerSegment, 0);
+ }
+
+ uint8_t old_count = 0;
+ HllDenseGetRegister(&old_count, reinterpret_cast<uint8_t
*>(segment->data()), register_index_in_segment);
+ if (count > old_count) {
+ HllDenseSetRegister(reinterpret_cast<uint8_t *>(segment->data()),
register_index_in_segment, count);
+ *ret = 1;
+ }
+ }
+ cache.BatchForFlush(batch);
+ return storage_->Write(storage_->DefaultWriteOptions(),
batch->GetWriteBatch());
+}
+
+rocksdb::Status HyperLogLog::Count(const Slice &user_key, uint64_t *ret) {
+ *ret = 0;
+ std::vector<uint8_t> registers(kHyperLogLogRegisterBytes);
+ auto s = getRegisters(user_key, ®isters);
+ if (!s.ok()) return s;
+ *ret = HllCount(registers);
+ return rocksdb::Status::OK();
+}
+
+rocksdb::Status HyperLogLog::Merge(const std::vector<Slice> &user_keys) {
+ std::vector<uint8_t> max(kHyperLogLogRegisterBytes);
+ for (const auto &user_key : user_keys) {
+ std::vector<uint8_t> registers(kHyperLogLogRegisterBytes);
+ auto s = getRegisters(user_key, ®isters);
+ if (!s.ok()) return s;
+ HllMerge(&max, registers);
+ }
+
+ std::string ns_key = AppendNamespacePrefix(user_keys[0]);
+ LockGuard guard(storage_->GetLockManager(), ns_key);
+ HyperloglogMetadata metadata;
+ rocksdb::Status s = GetMetadata(GetOptions(), ns_key, &metadata);
+ if (!s.ok() && !s.IsNotFound()) return s;
+
+ auto batch = storage_->GetWriteBatchBase();
+ WriteBatchLogData log_data(kRedisHyperLogLog);
+ batch->PutLogData(log_data.Encode());
+
+ Bitmap::SegmentCacheStore cache(storage_, metadata_cf_handle_, ns_key,
&metadata);
+ for (uint32_t segment_index = 0; segment_index < kHyperLogLogSegmentCount;
segment_index++) {
+ std::string *segment = nullptr;
+ s = cache.GetMut(segment_index, &segment);
+ if (!s.ok()) return s;
+ (*segment).assign(reinterpret_cast<const char *>(max.data()) +
segment_index * kHyperLogLogRegisterBytesPerSegment,
+ kHyperLogLogRegisterBytesPerSegment);
+ }
+ cache.BatchForFlush(batch);
+ return storage_->Write(storage_->DefaultWriteOptions(),
batch->GetWriteBatch());
+}
+
+rocksdb::Status HyperLogLog::getRegisters(const Slice &user_key,
std::vector<uint8_t> *registers) {
+ std::string ns_key = AppendNamespacePrefix(user_key);
+
+ HyperloglogMetadata metadata;
+ LatestSnapShot ss(storage_);
+
+ rocksdb::Status s = GetMetadata(Database::GetOptions{ss.GetSnapShot()},
ns_key, &metadata);
+ if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
+
+ std::string prefix = InternalKey(ns_key, "", metadata.version,
storage_->IsSlotIdEncoded()).Encode();
+ std::string next_version_prefix = InternalKey(ns_key, "", metadata.version +
1, storage_->IsSlotIdEncoded()).Encode();
+
+ rocksdb::ReadOptions read_options = storage_->DefaultScanOptions();
+ read_options.snapshot = ss.GetSnapShot();
+ rocksdb::Slice upper_bound(next_version_prefix);
+ read_options.iterate_upper_bound = &upper_bound;
+
+ auto iter = util::UniqueIterator(storage_, read_options);
+ for (iter->Seek(prefix); iter->Valid() && iter->key().starts_with(prefix);
iter->Next()) {
+ InternalKey ikey(iter->key(), storage_->IsSlotIdEncoded());
+
+ int register_index = std::stoi(ikey.GetSubKey().ToString());
+ if (register_index / kHyperLogLogRegisterCountPerSegment < 0 ||
+ register_index / kHyperLogLogRegisterCountPerSegment >=
kHyperLogLogSegmentCount ||
+ register_index % kHyperLogLogRegisterCountPerSegment != 0) {
+ return rocksdb::Status::Corruption("invalid subkey index: idx=" +
ikey.GetSubKey().ToString());
+ }
+ auto val = iter->value().ToString();
Review Comment:
nit:
```
std::string_view val = iter->value();
```
This can avoid a around of materialize to `std::string`
##########
src/types/redis_hyperloglog.h:
##########
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ *
+ */
+
+#pragma once
+
+#include "hyperloglog.h"
+#include "storage/redis_db.h"
+#include "storage/redis_metadata.h"
+
+namespace redis {
+
+class HyperLogLog : public Database {
+ public:
+ explicit HyperLogLog(engine::Storage *storage, const std::string &ns) :
Database(storage, ns) {}
+ rocksdb::Status Add(const Slice &user_key, const std::vector<Slice>
&elements, uint64_t *ret);
+ rocksdb::Status Count(const Slice &user_key, uint64_t *ret);
+ rocksdb::Status Merge(const std::vector<Slice> &user_keys);
+
+ private:
+ rocksdb::Status GetMetadata(Database::GetOptions get_options, const Slice
&ns_key, HyperloglogMetadata *metadata);
+ rocksdb::Status getRegisters(const Slice &user_key, std::vector<uint8_t>
*registers);
Review Comment:
Nit: you can add a todo, and optimizing the return value for `getRegisters`
##########
src/types/redis_hyperloglog.cc:
##########
@@ -0,0 +1,154 @@
+/*
+ * 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.
+ *
+ */
+
+#include "redis_hyperloglog.h"
+
+#include <db_util.h>
+#include <stdint.h>
+
+namespace redis {
+
+rocksdb::Status HyperLogLog::GetMetadata(Database::GetOptions get_options,
const Slice &ns_key,
+ HyperloglogMetadata *metadata) {
+ return Database::GetMetadata(get_options, {kRedisHyperLogLog}, ns_key,
metadata);
+}
+
+/* the max 0 pattern counter of the subset the element belongs to is
incremented if needed */
+rocksdb::Status HyperLogLog::Add(const Slice &user_key, const
std::vector<Slice> &elements, uint64_t *ret) {
+ *ret = 0;
+ std::string ns_key = AppendNamespacePrefix(user_key);
+
+ LockGuard guard(storage_->GetLockManager(), ns_key);
+ HyperloglogMetadata metadata;
+ rocksdb::Status s = GetMetadata(GetOptions(), ns_key, &metadata);
+ if (!s.ok() && !s.IsNotFound()) return s;
+
+ auto batch = storage_->GetWriteBatchBase();
+ WriteBatchLogData log_data(kRedisHyperLogLog);
+ batch->PutLogData(log_data.Encode());
+
+ Bitmap::SegmentCacheStore cache(storage_, metadata_cf_handle_, ns_key,
&metadata);
+ for (const auto &element : elements) {
+ uint32_t register_index = 0;
+ auto ele_str = element.ToString();
+ std::vector<uint8_t> ele(ele_str.begin(), ele_str.end());
+ uint8_t count = HllPatLen(ele, ®ister_index);
+ uint32_t segment_index = register_index /
kHyperLogLogRegisterCountPerSegment;
+ uint32_t register_index_in_segment = register_index %
kHyperLogLogRegisterCountPerSegment;
+
+ std::string *segment = nullptr;
+ auto s = cache.GetMut(segment_index, &segment);
+ if (!s.ok()) return s;
+ if (segment->size() == 0) {
Review Comment:
if `segment->size() != 0`, should we check it's size is equal to
`kHyperLogLogRegisterBytesPerSegment` before `HllDenseGetResgister`?
##########
src/types/redis_hyperloglog.cc:
##########
@@ -0,0 +1,154 @@
+/*
+ * 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.
+ *
+ */
+
+#include "redis_hyperloglog.h"
+
+#include <db_util.h>
+#include <stdint.h>
+
+namespace redis {
+
+rocksdb::Status HyperLogLog::GetMetadata(Database::GetOptions get_options,
const Slice &ns_key,
+ HyperloglogMetadata *metadata) {
+ return Database::GetMetadata(get_options, {kRedisHyperLogLog}, ns_key,
metadata);
+}
+
+/* the max 0 pattern counter of the subset the element belongs to is
incremented if needed */
+rocksdb::Status HyperLogLog::Add(const Slice &user_key, const
std::vector<Slice> &elements, uint64_t *ret) {
+ *ret = 0;
+ std::string ns_key = AppendNamespacePrefix(user_key);
+
+ LockGuard guard(storage_->GetLockManager(), ns_key);
+ HyperloglogMetadata metadata;
+ rocksdb::Status s = GetMetadata(GetOptions(), ns_key, &metadata);
+ if (!s.ok() && !s.IsNotFound()) return s;
+
+ auto batch = storage_->GetWriteBatchBase();
+ WriteBatchLogData log_data(kRedisHyperLogLog);
+ batch->PutLogData(log_data.Encode());
+
+ Bitmap::SegmentCacheStore cache(storage_, metadata_cf_handle_, ns_key,
&metadata);
+ for (const auto &element : elements) {
+ uint32_t register_index = 0;
+ auto ele_str = element.ToString();
+ std::vector<uint8_t> ele(ele_str.begin(), ele_str.end());
+ uint8_t count = HllPatLen(ele, ®ister_index);
+ uint32_t segment_index = register_index /
kHyperLogLogRegisterCountPerSegment;
+ uint32_t register_index_in_segment = register_index %
kHyperLogLogRegisterCountPerSegment;
+
+ std::string *segment = nullptr;
+ auto s = cache.GetMut(segment_index, &segment);
+ if (!s.ok()) return s;
+ if (segment->size() == 0) {
+ segment->resize(kHyperLogLogRegisterBytesPerSegment, 0);
+ }
+
+ uint8_t old_count = 0;
+ HllDenseGetRegister(&old_count, reinterpret_cast<uint8_t
*>(segment->data()), register_index_in_segment);
+ if (count > old_count) {
+ HllDenseSetRegister(reinterpret_cast<uint8_t *>(segment->data()),
register_index_in_segment, count);
+ *ret = 1;
+ }
+ }
+ cache.BatchForFlush(batch);
+ return storage_->Write(storage_->DefaultWriteOptions(),
batch->GetWriteBatch());
+}
+
+rocksdb::Status HyperLogLog::Count(const Slice &user_key, uint64_t *ret) {
+ *ret = 0;
+ std::vector<uint8_t> registers(kHyperLogLogRegisterBytes);
+ auto s = getRegisters(user_key, ®isters);
+ if (!s.ok()) return s;
+ *ret = HllCount(registers);
+ return rocksdb::Status::OK();
+}
+
+rocksdb::Status HyperLogLog::Merge(const std::vector<Slice> &user_keys) {
+ std::vector<uint8_t> max(kHyperLogLogRegisterBytes);
+ for (const auto &user_key : user_keys) {
+ std::vector<uint8_t> registers(kHyperLogLogRegisterBytes);
+ auto s = getRegisters(user_key, ®isters);
+ if (!s.ok()) return s;
+ HllMerge(&max, registers);
+ }
+
+ std::string ns_key = AppendNamespacePrefix(user_keys[0]);
+ LockGuard guard(storage_->GetLockManager(), ns_key);
+ HyperloglogMetadata metadata;
+ rocksdb::Status s = GetMetadata(GetOptions(), ns_key, &metadata);
+ if (!s.ok() && !s.IsNotFound()) return s;
+
+ auto batch = storage_->GetWriteBatchBase();
+ WriteBatchLogData log_data(kRedisHyperLogLog);
+ batch->PutLogData(log_data.Encode());
+
+ Bitmap::SegmentCacheStore cache(storage_, metadata_cf_handle_, ns_key,
&metadata);
+ for (uint32_t segment_index = 0; segment_index < kHyperLogLogSegmentCount;
segment_index++) {
+ std::string *segment = nullptr;
+ s = cache.GetMut(segment_index, &segment);
+ if (!s.ok()) return s;
+ (*segment).assign(reinterpret_cast<const char *>(max.data()) +
segment_index * kHyperLogLogRegisterBytesPerSegment,
+ kHyperLogLogRegisterBytesPerSegment);
+ }
+ cache.BatchForFlush(batch);
+ return storage_->Write(storage_->DefaultWriteOptions(),
batch->GetWriteBatch());
+}
+
+rocksdb::Status HyperLogLog::getRegisters(const Slice &user_key,
std::vector<uint8_t> *registers) {
+ std::string ns_key = AppendNamespacePrefix(user_key);
+
+ HyperloglogMetadata metadata;
+ LatestSnapShot ss(storage_);
+
+ rocksdb::Status s = GetMetadata(Database::GetOptions{ss.GetSnapShot()},
ns_key, &metadata);
+ if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s;
+
+ std::string prefix = InternalKey(ns_key, "", metadata.version,
storage_->IsSlotIdEncoded()).Encode();
+ std::string next_version_prefix = InternalKey(ns_key, "", metadata.version +
1, storage_->IsSlotIdEncoded()).Encode();
+
+ rocksdb::ReadOptions read_options = storage_->DefaultScanOptions();
+ read_options.snapshot = ss.GetSnapShot();
+ rocksdb::Slice upper_bound(next_version_prefix);
+ read_options.iterate_upper_bound = &upper_bound;
+
+ auto iter = util::UniqueIterator(storage_, read_options);
+ for (iter->Seek(prefix); iter->Valid() && iter->key().starts_with(prefix);
iter->Next()) {
+ InternalKey ikey(iter->key(), storage_->IsSlotIdEncoded());
+
+ int register_index = std::stoi(ikey.GetSubKey().ToString());
Review Comment:
nit: kvrocks already has parseInt, we can unify using that rather than
`std::stoi`
##########
src/types/redis_hyperloglog.cc:
##########
@@ -0,0 +1,154 @@
+/*
+ * 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.
+ *
+ */
+
+#include "redis_hyperloglog.h"
+
+#include <db_util.h>
+#include <stdint.h>
+
+namespace redis {
+
+rocksdb::Status HyperLogLog::GetMetadata(Database::GetOptions get_options,
const Slice &ns_key,
+ HyperloglogMetadata *metadata) {
+ return Database::GetMetadata(get_options, {kRedisHyperLogLog}, ns_key,
metadata);
+}
+
+/* the max 0 pattern counter of the subset the element belongs to is
incremented if needed */
+rocksdb::Status HyperLogLog::Add(const Slice &user_key, const
std::vector<Slice> &elements, uint64_t *ret) {
+ *ret = 0;
+ std::string ns_key = AppendNamespacePrefix(user_key);
+
+ LockGuard guard(storage_->GetLockManager(), ns_key);
+ HyperloglogMetadata metadata;
+ rocksdb::Status s = GetMetadata(GetOptions(), ns_key, &metadata);
+ if (!s.ok() && !s.IsNotFound()) return s;
+
+ auto batch = storage_->GetWriteBatchBase();
+ WriteBatchLogData log_data(kRedisHyperLogLog);
+ batch->PutLogData(log_data.Encode());
+
+ Bitmap::SegmentCacheStore cache(storage_, metadata_cf_handle_, ns_key,
&metadata);
+ for (const auto &element : elements) {
+ uint32_t register_index = 0;
+ auto ele_str = element.ToString();
+ std::vector<uint8_t> ele(ele_str.begin(), ele_str.end());
Review Comment:
nit: how about using `std::string_view` here?
##########
src/types/hyperloglog.cc:
##########
@@ -0,0 +1,256 @@
+/*
+ * 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.
+ *
+ */
+
+/* Redis HyperLogLog probabilistic cardinality approximation.
+ * This file implements the algorithm and the exported Redis commands.
+ *
+ * Copyright (c) 2014, Salvatore Sanfilippo <antirez at gmail dot com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * Neither the name of Redis nor the names of its contributors may be used
+ * to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+// NOTE: this file is copy from redis's source: `src/hyperloglog.c`
+
+#include "hyperloglog.h"
+
+#include "murmurhash2.h"
+
+/* Store the value of the register at position 'index' into variable 'val'.
+ * 'registers' is an array of unsigned bytes. */
+void HllDenseGetRegister(uint8_t *val, uint8_t *registers, uint32_t index) {
+ uint32_t byte = index * kHyperLogLogBits / 8;
+ uint8_t fb = index * kHyperLogLogBits & 7;
+ uint8_t fb8 = 8 - fb;
+ uint8_t b0 = registers[byte];
+ uint8_t b1 = registers[byte + 1];
+ *val = ((b0 >> fb) | (b1 << fb8)) & kHyperLogLogRegisterMax;
+}
+
+/* Set the value of the register at position 'index' to 'val'.
+ * 'registers' is an array of unsigned bytes. */
+void HllDenseSetRegister(uint8_t *registers, uint32_t index, uint8_t val) {
+ uint32_t byte = index * kHyperLogLogBits / 8;
+ uint8_t fb = index * kHyperLogLogBits & 7;
+ uint8_t fb8 = 8 - fb;
+ uint8_t v = val;
+ registers[byte] &= ~(kHyperLogLogRegisterMax << fb);
+ registers[byte] |= v << fb;
+ registers[byte + 1] &= ~(kHyperLogLogRegisterMax >> fb8);
+ registers[byte + 1] |= v >> fb8;
+}
+
+/* ========================= HyperLogLog algorithm =========================
*/
+
+/* Given a string element to add to the HyperLogLog, returns the length
+ * of the pattern 000..1 of the element hash. As a side effect
'register_index' is
+ * set which the element hashes to. */
+uint8_t HllPatLen(const std::vector<uint8_t> &element, uint32_t
*register_index) {
+ int elesize = static_cast<int>(element.size());
+ uint64_t hash = 0, bit = 0, index = 0;
+ int count = 0;
+
+ /* Count the number of zeroes starting from bit kHyperLogLogRegisterCount
+ * (that is a power of two corresponding to the first bit we don't use
+ * as index). The max run can be 64-kHyperLogLogRegisterCountPow+1 =
kHyperLogLogHashBitCount+1 bits.
+ *
+ * Note that the final "1" ending the sequence of zeroes must be
+ * included in the count, so if we find "001" the count is 3, and
+ * the smallest count possible is no zeroes at all, just a 1 bit
+ * at the first position, that is a count of 1.
+ *
+ * This may sound like inefficient, but actually in the average case
+ * there are high probabilities to find a 1 after a few iterations. */
+ hash = MurmurHash64A(element.data(), elesize, 0xadc83b19ULL);
+ index = hash & kHyperLogLogRegisterCountMask; /* Register index. */
+ hash >>= kHyperLogLogRegisterCountPow; /* Remove bits used to
address the register. */
+ hash |= ((uint64_t)1 << kHyperLogLogHashBitCount); /* Make sure the loop
terminates
+ and count will be <=
kHyperLogLogHashBitCount+1. */
+ bit = 1;
+ count = 1; /* Initialized to 1 since we count the "00000...1" pattern. */
+ while ((hash & bit) == 0) {
+ count++;
+ bit <<= 1;
+ }
+ *register_index = (int)index;
+ return count;
+}
+
+/* Compute the register histogram in the dense representation. */
+void HllDenseRegHisto(uint8_t *registers, int *reghisto) {
Review Comment:
registers -> const uint8_t*
##########
src/types/hyperloglog.cc:
##########
@@ -0,0 +1,256 @@
+/*
+ * 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.
+ *
+ */
+
+/* Redis HyperLogLog probabilistic cardinality approximation.
+ * This file implements the algorithm and the exported Redis commands.
+ *
+ * Copyright (c) 2014, Salvatore Sanfilippo <antirez at gmail dot com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * Neither the name of Redis nor the names of its contributors may be used
+ * to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+// NOTE: this file is copy from redis's source: `src/hyperloglog.c`
+
+#include "hyperloglog.h"
+
+#include "murmurhash2.h"
+
+/* Store the value of the register at position 'index' into variable 'val'.
+ * 'registers' is an array of unsigned bytes. */
+void HllDenseGetRegister(uint8_t *val, uint8_t *registers, uint32_t index) {
Review Comment:
```suggestion
uint8_t HllDenseGetRegister(const uint8_t *registers, uint32_t index) {
```
What about changing to this?
##########
src/types/hyperloglog.cc:
##########
@@ -0,0 +1,256 @@
+/*
+ * 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.
+ *
+ */
+
+/* Redis HyperLogLog probabilistic cardinality approximation.
+ * This file implements the algorithm and the exported Redis commands.
+ *
+ * Copyright (c) 2014, Salvatore Sanfilippo <antirez at gmail dot com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * Neither the name of Redis nor the names of its contributors may be used
+ * to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+// NOTE: this file is copy from redis's source: `src/hyperloglog.c`
+
+#include "hyperloglog.h"
+
+#include "murmurhash2.h"
+
+/* Store the value of the register at position 'index' into variable 'val'.
+ * 'registers' is an array of unsigned bytes. */
+void HllDenseGetRegister(uint8_t *val, uint8_t *registers, uint32_t index) {
+ uint32_t byte = index * kHyperLogLogBits / 8;
+ uint8_t fb = index * kHyperLogLogBits & 7;
+ uint8_t fb8 = 8 - fb;
+ uint8_t b0 = registers[byte];
+ uint8_t b1 = registers[byte + 1];
+ *val = ((b0 >> fb) | (b1 << fb8)) & kHyperLogLogRegisterMax;
+}
+
+/* Set the value of the register at position 'index' to 'val'.
+ * 'registers' is an array of unsigned bytes. */
+void HllDenseSetRegister(uint8_t *registers, uint32_t index, uint8_t val) {
+ uint32_t byte = index * kHyperLogLogBits / 8;
+ uint8_t fb = index * kHyperLogLogBits & 7;
+ uint8_t fb8 = 8 - fb;
+ uint8_t v = val;
+ registers[byte] &= ~(kHyperLogLogRegisterMax << fb);
+ registers[byte] |= v << fb;
+ registers[byte + 1] &= ~(kHyperLogLogRegisterMax >> fb8);
+ registers[byte + 1] |= v >> fb8;
+}
+
+/* ========================= HyperLogLog algorithm =========================
*/
+
+/* Given a string element to add to the HyperLogLog, returns the length
+ * of the pattern 000..1 of the element hash. As a side effect
'register_index' is
+ * set which the element hashes to. */
+uint8_t HllPatLen(const std::vector<uint8_t> &element, uint32_t
*register_index) {
+ int elesize = static_cast<int>(element.size());
+ uint64_t hash = 0, bit = 0, index = 0;
+ int count = 0;
+
+ /* Count the number of zeroes starting from bit kHyperLogLogRegisterCount
+ * (that is a power of two corresponding to the first bit we don't use
+ * as index). The max run can be 64-kHyperLogLogRegisterCountPow+1 =
kHyperLogLogHashBitCount+1 bits.
+ *
+ * Note that the final "1" ending the sequence of zeroes must be
+ * included in the count, so if we find "001" the count is 3, and
+ * the smallest count possible is no zeroes at all, just a 1 bit
+ * at the first position, that is a count of 1.
+ *
+ * This may sound like inefficient, but actually in the average case
+ * there are high probabilities to find a 1 after a few iterations. */
+ hash = MurmurHash64A(element.data(), elesize, 0xadc83b19ULL);
Review Comment:
Nit: we can extract this hash to a constant rather than hard code a magic
number?
##########
src/types/hyperloglog.cc:
##########
@@ -0,0 +1,256 @@
+/*
+ * 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.
+ *
+ */
+
+/* Redis HyperLogLog probabilistic cardinality approximation.
+ * This file implements the algorithm and the exported Redis commands.
+ *
+ * Copyright (c) 2014, Salvatore Sanfilippo <antirez at gmail dot com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * Neither the name of Redis nor the names of its contributors may be used
+ * to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+// NOTE: this file is copy from redis's source: `src/hyperloglog.c`
+
+#include "hyperloglog.h"
+
+#include "murmurhash2.h"
+
+/* Store the value of the register at position 'index' into variable 'val'.
+ * 'registers' is an array of unsigned bytes. */
+void HllDenseGetRegister(uint8_t *val, uint8_t *registers, uint32_t index) {
+ uint32_t byte = index * kHyperLogLogBits / 8;
+ uint8_t fb = index * kHyperLogLogBits & 7;
+ uint8_t fb8 = 8 - fb;
+ uint8_t b0 = registers[byte];
+ uint8_t b1 = registers[byte + 1];
+ *val = ((b0 >> fb) | (b1 << fb8)) & kHyperLogLogRegisterMax;
+}
+
+/* Set the value of the register at position 'index' to 'val'.
+ * 'registers' is an array of unsigned bytes. */
+void HllDenseSetRegister(uint8_t *registers, uint32_t index, uint8_t val) {
+ uint32_t byte = index * kHyperLogLogBits / 8;
+ uint8_t fb = index * kHyperLogLogBits & 7;
+ uint8_t fb8 = 8 - fb;
+ uint8_t v = val;
+ registers[byte] &= ~(kHyperLogLogRegisterMax << fb);
+ registers[byte] |= v << fb;
+ registers[byte + 1] &= ~(kHyperLogLogRegisterMax >> fb8);
+ registers[byte + 1] |= v >> fb8;
+}
+
+/* ========================= HyperLogLog algorithm =========================
*/
+
+/* Given a string element to add to the HyperLogLog, returns the length
+ * of the pattern 000..1 of the element hash. As a side effect
'register_index' is
+ * set which the element hashes to. */
+uint8_t HllPatLen(const std::vector<uint8_t> &element, uint32_t
*register_index) {
+ int elesize = static_cast<int>(element.size());
+ uint64_t hash = 0, bit = 0, index = 0;
+ int count = 0;
+
+ /* Count the number of zeroes starting from bit kHyperLogLogRegisterCount
+ * (that is a power of two corresponding to the first bit we don't use
+ * as index). The max run can be 64-kHyperLogLogRegisterCountPow+1 =
kHyperLogLogHashBitCount+1 bits.
+ *
+ * Note that the final "1" ending the sequence of zeroes must be
+ * included in the count, so if we find "001" the count is 3, and
+ * the smallest count possible is no zeroes at all, just a 1 bit
+ * at the first position, that is a count of 1.
+ *
+ * This may sound like inefficient, but actually in the average case
+ * there are high probabilities to find a 1 after a few iterations. */
+ hash = MurmurHash64A(element.data(), elesize, 0xadc83b19ULL);
+ index = hash & kHyperLogLogRegisterCountMask; /* Register index. */
+ hash >>= kHyperLogLogRegisterCountPow; /* Remove bits used to
address the register. */
+ hash |= ((uint64_t)1 << kHyperLogLogHashBitCount); /* Make sure the loop
terminates
+ and count will be <=
kHyperLogLogHashBitCount+1. */
+ bit = 1;
+ count = 1; /* Initialized to 1 since we count the "00000...1" pattern. */
+ while ((hash & bit) == 0) {
+ count++;
+ bit <<= 1;
+ }
+ *register_index = (int)index;
+ return count;
+}
+
+/* Compute the register histogram in the dense representation. */
+void HllDenseRegHisto(uint8_t *registers, int *reghisto) {
+ /* Redis default is to use 16384 registers 6 bits each. The code works
+ * with other values by modifying the defines, but for our target value
+ * we take a faster path with unrolled loops. */
+ if (kHyperLogLogRegisterCount == 16384 && kHyperLogLogBits == 6) {
Review Comment:
Can we remove `if` since else would never happens?
--
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]