72 lines
1.9 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 <stdint.h>
  5. #include "leveldb/comparator.h"
  6. #include "leveldb/slice.h"
  7. #include "util/logging.h"
  8. namespace leveldb {
  9. Comparator::~Comparator() { }
  10. namespace {
  11. class BytewiseComparatorImpl : public Comparator {
  12. public:
  13. BytewiseComparatorImpl() { }
  14. virtual const char* Name() const {
  15. return "leveldb.BytewiseComparator";
  16. }
  17. virtual int Compare(const Slice& a, const Slice& b) const {
  18. return a.compare(b);
  19. }
  20. virtual void FindShortestSeparator(
  21. 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. }
  57. static const BytewiseComparatorImpl bytewise;
  58. const Comparator* BytewiseComparator() {
  59. return &bytewise;
  60. }
  61. }