From 488607317464314c9866ea14d56ce43e8d8fdb32 Mon Sep 17 00:00:00 2001 From: Yoshinori Matsunobu Date: Mon, 14 Sep 2015 17:23:39 -0700 Subject: [PATCH] Adding Slice::difference_offset() function Summary: There are some use cases in MyRocks to compare two slices and to return the first byte where they differ. It may be useful to add it as a RocksDB Slice function. Test Plan: db_test Reviewers: sdong, rven, igor Reviewed By: igor Subscribers: jkedgar, dhruba Differential Revision: https://reviews.facebook.net/D46935 --- db/db_test.cc | 2 ++ include/rocksdb/slice.h | 12 ++++++++++++ 2 files changed, 14 insertions(+) diff --git a/db/db_test.cc b/db/db_test.cc index 6f2307889..7b45fd8e1 100644 --- a/db/db_test.cc +++ b/db/db_test.cc @@ -5937,6 +5937,8 @@ TEST_F(DBTest, PrefixScan) { snprintf(buf, sizeof(buf), "03______:"); prefix = Slice(buf, 8); key = Slice(buf, 9); + ASSERT_EQ(key.difference_offset(prefix), 8); + ASSERT_EQ(prefix.difference_offset(key), 8); // db configs env_->count_random_reads_ = true; Options options = CurrentOptions(); diff --git a/include/rocksdb/slice.h b/include/rocksdb/slice.h index 084e846e7..ae3139cfd 100644 --- a/include/rocksdb/slice.h +++ b/include/rocksdb/slice.h @@ -88,6 +88,9 @@ class Slice { (memcmp(data_, x.data_, x.size_) == 0)); } + // Compare two slices and returns the first byte where they differ + size_t difference_offset(const Slice& b) const; + // private: make these public for rocksdbjni access const char* data_; size_t size_; @@ -125,6 +128,15 @@ inline int Slice::compare(const Slice& b) const { return r; } +inline size_t Slice::difference_offset(const Slice& b) const { + size_t off = 0; + const size_t len = (size_ < b.size_) ? size_ : b.size_; + for (; off < len; off++) { + if (data_[off] != b.data_[off]) break; + } + return off; +} + } // namespace rocksdb #endif // STORAGE_ROCKSDB_INCLUDE_SLICE_H_