小组成员: 曹可心-10223903406 朴祉燕-10224602413
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.

73 lines
2.1 KiB

  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 <algorithm>
  5. #include <cstdint>
  6. #include <string>
  7. #include "leveldb/comparator.h"
  8. #include "leveldb/slice.h"
  9. #include "util/logging.h"
  10. #include "util/no_destructor.h"
  11. namespace leveldb {
  12. Comparator::~Comparator() {}
  13. namespace {
  14. class BytewiseComparatorImpl : public Comparator {
  15. public:
  16. BytewiseComparatorImpl() {}
  17. virtual const char* Name() const { return "leveldb.BytewiseComparator"; }
  18. virtual int Compare(const Slice& a, const Slice& b) const {
  19. return a.compare(b);
  20. }
  21. virtual void FindShortestSeparator(std::string* start,
  22. const Slice& limit) const {
  23. // Find length of common prefix
  24. size_t min_length = std::min(start->size(), limit.size());
  25. size_t diff_index = 0;
  26. while ((diff_index < min_length) &&
  27. ((*start)[diff_index] == limit[diff_index])) {
  28. diff_index++;
  29. }
  30. if (diff_index >= min_length) {
  31. // Do not shorten if one string is a prefix of the other
  32. } else {
  33. uint8_t diff_byte = static_cast<uint8_t>((*start)[diff_index]);
  34. if (diff_byte < static_cast<uint8_t>(0xff) &&
  35. diff_byte + 1 < static_cast<uint8_t>(limit[diff_index])) {
  36. (*start)[diff_index]++;
  37. start->resize(diff_index + 1);
  38. assert(Compare(*start, limit) < 0);
  39. }
  40. }
  41. }
  42. virtual void FindShortSuccessor(std::string* key) const {
  43. // Find first character that can be incremented
  44. size_t n = key->size();
  45. for (size_t i = 0; i < n; i++) {
  46. const uint8_t byte = (*key)[i];
  47. if (byte != static_cast<uint8_t>(0xff)) {
  48. (*key)[i] = byte + 1;
  49. key->resize(i + 1);
  50. return;
  51. }
  52. }
  53. // *key is a run of 0xffs. Leave it alone.
  54. }
  55. };
  56. } // namespace
  57. const Comparator* BytewiseComparator() {
  58. static NoDestructor<BytewiseComparatorImpl> singleton;
  59. return singleton.get();
  60. }
  61. } // namespace leveldb