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 
Name() const39   const char* Name() const override { return "UInt64AddOperator"; }
40 
41  private:
42   // Takes the string and decodes it into a uint64_t
43   // On error, prints a message and returns 0
DecodeInteger(const Slice & value,Logger * logger) const44   uint64_t DecodeInteger(const Slice& value, Logger* logger) const {
45     uint64_t result = 0;
46 
47     if (value.size() == sizeof(uint64_t)) {
48       result = DecodeFixed64(value.data());
49     } else if (logger != nullptr) {
50       // If value is corrupted, treat it as 0
51       ROCKS_LOG_ERROR(logger, "uint64 value corruption, size: %" ROCKSDB_PRIszt
52                               " > %" ROCKSDB_PRIszt,
53                       value.size(), sizeof(uint64_t));
54     }
55 
56     return result;
57   }
58 
59 };
60 
61 }
62 
63 namespace ROCKSDB_NAMESPACE {
64 
CreateUInt64AddOperator()65 std::shared_ptr<MergeOperator> MergeOperators::CreateUInt64AddOperator() {
66   return std::make_shared<UInt64AddOperator>();
67 }
68 
69 }  // namespace ROCKSDB_NAMESPACE
70