作者: 韩晨旭 10225101440 李畅 10225102463
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

76 řádky
2.0 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 {
  18. return "leveldb.BytewiseComparator";
  19. }
  20. virtual int Compare(const Slice& a, const Slice& b) const {
  21. return a.compare(b);
  22. }
  23. virtual void FindShortestSeparator(
  24. std::string* start,
  25. const Slice& limit) const {
  26. // Find length of common prefix
  27. size_t min_length = std::min(start->size(), limit.size());
  28. size_t diff_index = 0;
  29. while ((diff_index < min_length) &&
  30. ((*start)[diff_index] == limit[diff_index])) {
  31. diff_index++;
  32. }
  33. if (diff_index >= min_length) {
  34. // Do not shorten if one string is a prefix of the other
  35. } else {
  36. uint8_t diff_byte = static_cast<uint8_t>((*start)[diff_index]);
  37. if (diff_byte < static_cast<uint8_t>(0xff) &&
  38. diff_byte + 1 < static_cast<uint8_t>(limit[diff_index])) {
  39. (*start)[diff_index]++;
  40. start->resize(diff_index + 1);
  41. assert(Compare(*start, limit) < 0);
  42. }
  43. }
  44. }
  45. virtual void FindShortSuccessor(std::string* key) const {
  46. // Find first character that can be incremented
  47. size_t n = key->size();
  48. for (size_t i = 0; i < n; i++) {
  49. const uint8_t byte = (*key)[i];
  50. if (byte != static_cast<uint8_t>(0xff)) {
  51. (*key)[i] = byte + 1;
  52. key->resize(i+1);
  53. return;
  54. }
  55. }
  56. // *key is a run of 0xffs. Leave it alone.
  57. }
  58. };
  59. } // namespace
  60. const Comparator* BytewiseComparator() {
  61. static NoDestructor<BytewiseComparatorImpl> singleton;
  62. return singleton.get();
  63. }
  64. } // namespace leveldb