Coverage Report

Created: 2026-04-01 06:40

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/leveldb/util/comparator.cc
Line
Count
Source
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
5
#include "leveldb/comparator.h"
6
7
#include <algorithm>
8
#include <cstdint>
9
#include <string>
10
#include <type_traits>
11
12
#include "leveldb/slice.h"
13
#include "util/logging.h"
14
#include "util/no_destructor.h"
15
16
namespace leveldb {
17
18
942k
Comparator::~Comparator() = default;
19
20
namespace {
21
class BytewiseComparatorImpl : public Comparator {
22
 public:
23
1
  BytewiseComparatorImpl() = default;
24
25
233k
  const char* Name() const override { return "leveldb.BytewiseComparator"; }
26
27
38.0M
  int Compare(const Slice& a, const Slice& b) const override {
28
38.0M
    return a.compare(b);
29
38.0M
  }
30
31
  void FindShortestSeparator(std::string* start,
32
18.9k
                             const Slice& limit) const override {
33
    // Find length of common prefix
34
18.9k
    size_t min_length = std::min(start->size(), limit.size());
35
18.9k
    size_t diff_index = 0;
36
2.51M
    while ((diff_index < min_length) &&
37
2.51M
           ((*start)[diff_index] == limit[diff_index])) {
38
2.49M
      diff_index++;
39
2.49M
    }
40
41
18.9k
    if (diff_index >= min_length) {
42
      // Do not shorten if one string is a prefix of the other
43
15.8k
    } else {
44
15.8k
      uint8_t diff_byte = static_cast<uint8_t>((*start)[diff_index]);
45
15.8k
      if (diff_byte < static_cast<uint8_t>(0xff) &&
46
15.8k
          diff_byte + 1 < static_cast<uint8_t>(limit[diff_index])) {
47
12.4k
        (*start)[diff_index]++;
48
12.4k
        start->resize(diff_index + 1);
49
12.4k
        assert(Compare(*start, limit) < 0);
50
12.4k
      }
51
15.8k
    }
52
18.9k
  }
53
54
69.4k
  void FindShortSuccessor(std::string* key) const override {
55
    // Find first character that can be incremented
56
69.4k
    size_t n = key->size();
57
142k
    for (size_t i = 0; i < n; i++) {
58
122k
      const uint8_t byte = (*key)[i];
59
122k
      if (byte != static_cast<uint8_t>(0xff)) {
60
49.2k
        (*key)[i] = byte + 1;
61
49.2k
        key->resize(i + 1);
62
49.2k
        return;
63
49.2k
      }
64
122k
    }
65
    // *key is a run of 0xffs.  Leave it alone.
66
69.4k
  }
67
};
68
}  // namespace
69
70
645k
const Comparator* BytewiseComparator() {
71
645k
  static NoDestructor<BytewiseComparatorImpl> singleton;
72
645k
  return singleton.get();
73
645k
}
74
75
}  // namespace leveldb