作者: 韩晨旭 10225101440 李畅 10225102463
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.

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