stringappend.cc 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright (c) Meta Platforms, Inc. and affiliates.
  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. // A MergeOperator for rocksdb that implements string append.
  7. #include "stringappend.h"
  8. #include <cassert>
  9. #include <memory>
  10. #include "rocksdb/merge_operator.h"
  11. #include "rocksdb/slice.h"
  12. #include "rocksdb/utilities/options_type.h"
  13. #include "utilities/merge_operators.h"
  14. namespace ROCKSDB_NAMESPACE {
  15. namespace {
  16. static std::unordered_map<std::string, OptionTypeInfo>
  17. stringappend_merge_type_info = {
  18. {"delimiter",
  19. {0, OptionType::kString, OptionVerificationType::kNormal,
  20. OptionTypeFlags::kNone}},
  21. };
  22. } // namespace
  23. // Constructor: also specify the delimiter character.
  24. StringAppendOperator::StringAppendOperator(char delim_char)
  25. : delim_(1, delim_char) {
  26. RegisterOptions("Delimiter", &delim_, &stringappend_merge_type_info);
  27. }
  28. StringAppendOperator::StringAppendOperator(const std::string& delim)
  29. : delim_(delim) {
  30. RegisterOptions("Delimiter", &delim_, &stringappend_merge_type_info);
  31. }
  32. // Implementation for the merge operation (concatenates two strings)
  33. bool StringAppendOperator::Merge(const Slice& /*key*/,
  34. const Slice* existing_value,
  35. const Slice& value, std::string* new_value,
  36. Logger* /*logger*/) const {
  37. // Clear the *new_value for writing.
  38. assert(new_value);
  39. new_value->clear();
  40. if (!existing_value) {
  41. // No existing_value. Set *new_value = value
  42. new_value->assign(value.data(), value.size());
  43. } else {
  44. // Generic append (existing_value != null).
  45. // Reserve *new_value to correct size, and apply concatenation.
  46. new_value->reserve(existing_value->size() + delim_.size() + value.size());
  47. new_value->assign(existing_value->data(), existing_value->size());
  48. new_value->append(delim_);
  49. new_value->append(value.data(), value.size());
  50. }
  51. return true;
  52. }
  53. std::shared_ptr<MergeOperator> MergeOperators::CreateStringAppendOperator() {
  54. return std::make_shared<StringAppendOperator>(',');
  55. }
  56. std::shared_ptr<MergeOperator> MergeOperators::CreateStringAppendOperator(
  57. char delim_char) {
  58. return std::make_shared<StringAppendOperator>(delim_char);
  59. }
  60. std::shared_ptr<MergeOperator> MergeOperators::CreateStringAppendOperator(
  61. const std::string& delim) {
  62. return std::make_shared<StringAppendOperator>(delim);
  63. }
  64. } // namespace ROCKSDB_NAMESPACE