uint64add.cc 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. #include <memory>
  6. #include "logging/logging.h"
  7. #include "rocksdb/env.h"
  8. #include "rocksdb/merge_operator.h"
  9. #include "rocksdb/slice.h"
  10. #include "util/coding.h"
  11. #include "utilities/merge_operators.h"
  12. using namespace ROCKSDB_NAMESPACE;
  13. namespace { // anonymous namespace
  14. // A 'model' merge operator with uint64 addition semantics
  15. // Implemented as an AssociativeMergeOperator for simplicity and example.
  16. class UInt64AddOperator : public AssociativeMergeOperator {
  17. public:
  18. bool Merge(const Slice& /*key*/, const Slice* existing_value,
  19. const Slice& value, std::string* new_value,
  20. Logger* logger) const override {
  21. uint64_t orig_value = 0;
  22. if (existing_value){
  23. orig_value = DecodeInteger(*existing_value, logger);
  24. }
  25. uint64_t operand = DecodeInteger(value, logger);
  26. assert(new_value);
  27. new_value->clear();
  28. PutFixed64(new_value, orig_value + operand);
  29. return true; // Return true always since corruption will be treated as 0
  30. }
  31. const char* Name() const override { return "UInt64AddOperator"; }
  32. private:
  33. // Takes the string and decodes it into a uint64_t
  34. // On error, prints a message and returns 0
  35. uint64_t DecodeInteger(const Slice& value, Logger* logger) const {
  36. uint64_t result = 0;
  37. if (value.size() == sizeof(uint64_t)) {
  38. result = DecodeFixed64(value.data());
  39. } else if (logger != nullptr) {
  40. // If value is corrupted, treat it as 0
  41. ROCKS_LOG_ERROR(logger, "uint64 value corruption, size: %" ROCKSDB_PRIszt
  42. " > %" ROCKSDB_PRIszt,
  43. value.size(), sizeof(uint64_t));
  44. }
  45. return result;
  46. }
  47. };
  48. }
  49. namespace ROCKSDB_NAMESPACE {
  50. std::shared_ptr<MergeOperator> MergeOperators::CreateUInt64AddOperator() {
  51. return std::make_shared<UInt64AddOperator>();
  52. }
  53. } // namespace ROCKSDB_NAMESPACE