LevelDB project 1 10225501460 林子骥 10211900416 郭夏辉
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.3 KiB

1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #include "leveldb/comparator.h"
  5. #include <algorithm>
  6. #include <cstdint>
  7. #include <string>
  8. #include <type_traits>
  9. #include "leveldb/slice.h"
  10. #include "util/logging.h"
  11. #include "util/no_destructor.h"
  12. namespace leveldb {
  13. Comparator::~Comparator() = default;
  14. namespace {
  15. class BytewiseComparatorImpl : public Comparator {
  16. public:
  17. BytewiseComparatorImpl() = default;
  18. const char* Name() const override { return "leveldb.BytewiseComparator"; }
  19. int Compare(const Slice& a, const Slice& b) const override {
  20. return a.compare(b);
  21. }
  22. //最终生成的 start 将是一个有效的、更短的键,仍然在 limit 范围内;能够这么运行的前提:数据按key有序输入
  23. void FindShortestSeparator(std::string* start,
  24. const Slice& limit) const override {
  25. // Find length of common prefix
  26. size_t min_length = std::min(start->size(), limit.size());
  27. size_t diff_index = 0;
  28. while ((diff_index < min_length) &&
  29. ((*start)[diff_index] == limit[diff_index])) {
  30. diff_index++;
  31. }
  32. if (diff_index >= min_length) {
  33. // Do not shorten if one string is a prefix of the other
  34. } else {
  35. uint8_t diff_byte = static_cast<uint8_t>((*start)[diff_index]);
  36. if (diff_byte < static_cast<uint8_t>(0xff) &&
  37. diff_byte + 1 < static_cast<uint8_t>(limit[diff_index])) {
  38. (*start)[diff_index]++;
  39. start->resize(diff_index + 1);
  40. assert(Compare(*start, limit) < 0);
  41. }
  42. }
  43. }
  44. void FindShortSuccessor(std::string* key) const override {
  45. // Find first character that can be incremented
  46. size_t n = key->size();
  47. for (size_t i = 0; i < n; i++) {
  48. const uint8_t byte = (*key)[i];
  49. if (byte != static_cast<uint8_t>(0xff)) {
  50. (*key)[i] = byte + 1;
  51. key->resize(i + 1);
  52. return;
  53. }
  54. }
  55. // *key is a run of 0xffs. Leave it alone.
  56. }
  57. };
  58. } // namespace
  59. const Comparator* BytewiseComparator() {
  60. static NoDestructor<BytewiseComparatorImpl> singleton;
  61. return singleton.get();
  62. }
  63. } // namespace leveldb