小组成员:10215300402-朱维清 & 10222140408 谷杰
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

81 líneas
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 "port/port.h"
  9. #include "util/logging.h"
  10. namespace leveldb {
  11. Comparator::~Comparator() { }
  12. namespace {
  13. class BytewiseComparatorImpl : public Comparator {
  14. public:
  15. BytewiseComparatorImpl() { }
  16. virtual const char* Name() const {
  17. return "leveldb.BytewiseComparator";
  18. }
  19. virtual int Compare(const Slice& a, const Slice& b) const {
  20. return a.compare(b);
  21. }
  22. virtual void FindShortestSeparator(
  23. std::string* start,
  24. const Slice& limit) const {
  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. virtual void FindShortSuccessor(std::string* key) const {
  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. static port::OnceType once = LEVELDB_ONCE_INIT;
  60. static const Comparator* bytewise;
  61. static void InitModule() {
  62. bytewise = new BytewiseComparatorImpl;
  63. }
  64. const Comparator* BytewiseComparator() {
  65. port::InitOnce(&once, InitModule);
  66. return bytewise;
  67. }
  68. } // namespace leveldb