1 // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
2 // This source code is licensed under both the GPLv2 (found in the
3 // COPYING file in the root directory) and Apache 2.0 License
4 // (found in the LICENSE.Apache file in the root directory).
5
6 #include <memory>
7
8 #include "logging/logging.h"
9 #include "rocksdb/env.h"
10 #include "rocksdb/merge_operator.h"
11 #include "rocksdb/slice.h"
12 #include "util/coding.h"
13 #include "utilities/merge_operators.h"
14
15 using namespace ROCKSDB_NAMESPACE;
16
17 namespace { // anonymous namespace
18
19 // A 'model' merge operator with uint64 addition semantics
20 // Implemented as an AssociativeMergeOperator for simplicity and example.
21 class UInt64AddOperator : public AssociativeMergeOperator {
22 public:
Merge(const Slice &,const Slice * existing_value,const Slice & value,std::string * new_value,Logger * logger) const23 bool Merge(const Slice& /*key*/, const Slice* existing_value,
24 const Slice& value, std::string* new_value,
25 Logger* logger) const override {
26 uint64_t orig_value = 0;
27 if (existing_value){
28 orig_value = DecodeInteger(*existing_value, logger);
29 }
30 uint64_t operand = DecodeInteger(value, logger);
31
32 assert(new_value);
33 new_value->clear();
34 PutFixed64(new_value, orig_value + operand);
35
36 return true; // Return true always since corruption will be treated as 0
37 }
38
kClassName()39 static const char* kClassName() { return "UInt64AddOperator"; }
kNickName()40 static const char* kNickName() { return "uint64add"; }
Name() const41 const char* Name() const override { return kClassName(); }
NickName() const42 const char* NickName() const override { return kNickName(); }
43
44 private:
45 // Takes the string and decodes it into a uint64_t
46 // On error, prints a message and returns 0
DecodeInteger(const Slice & value,Logger * logger) const47 uint64_t DecodeInteger(const Slice& value, Logger* logger) const {
48 uint64_t result = 0;
49
50 if (value.size() == sizeof(uint64_t)) {
51 result = DecodeFixed64(value.data());
52 } else if (logger != nullptr) {
53 // If value is corrupted, treat it as 0
54 ROCKS_LOG_ERROR(logger, "uint64 value corruption, size: %" ROCKSDB_PRIszt
55 " > %" ROCKSDB_PRIszt,
56 value.size(), sizeof(uint64_t));
57 }
58
59 return result;
60 }
61
62 };
63
64 }
65
66 namespace ROCKSDB_NAMESPACE {
67
CreateUInt64AddOperator()68 std::shared_ptr<MergeOperator> MergeOperators::CreateUInt64AddOperator() {
69 return std::make_shared<UInt64AddOperator>();
70 }
71
72 } // namespace ROCKSDB_NAMESPACE
73