2011-03-19 06:37:00 +08:00
|
|
|
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
|
|
// found in the LICENSE file. See the AUTHORS file for names of contributors.
|
|
|
|
|
2011-07-20 07:36:47 +08:00
|
|
|
#include <algorithm>
|
2018-09-11 06:38:12 +08:00
|
|
|
#include <cstdint>
|
|
|
|
#include <string>
|
|
|
|
|
2011-03-31 02:35:40 +08:00
|
|
|
#include "leveldb/comparator.h"
|
|
|
|
#include "leveldb/slice.h"
|
2011-03-19 06:37:00 +08:00
|
|
|
#include "util/logging.h"
|
2018-09-11 06:38:12 +08:00
|
|
|
#include "util/no_destructor.h"
|
2011-03-19 06:37:00 +08:00
|
|
|
|
|
|
|
namespace leveldb {
|
|
|
|
|
|
|
|
Comparator::~Comparator() { }
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
class BytewiseComparatorImpl : public Comparator {
|
|
|
|
public:
|
|
|
|
BytewiseComparatorImpl() { }
|
|
|
|
|
|
|
|
virtual const char* Name() const {
|
|
|
|
return "leveldb.BytewiseComparator";
|
|
|
|
}
|
|
|
|
|
|
|
|
virtual int Compare(const Slice& a, const Slice& b) const {
|
|
|
|
return a.compare(b);
|
|
|
|
}
|
|
|
|
|
|
|
|
virtual void FindShortestSeparator(
|
|
|
|
std::string* start,
|
|
|
|
const Slice& limit) const {
|
|
|
|
// Find length of common prefix
|
|
|
|
size_t min_length = std::min(start->size(), limit.size());
|
|
|
|
size_t diff_index = 0;
|
|
|
|
while ((diff_index < min_length) &&
|
|
|
|
((*start)[diff_index] == limit[diff_index])) {
|
|
|
|
diff_index++;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (diff_index >= min_length) {
|
|
|
|
// Do not shorten if one string is a prefix of the other
|
|
|
|
} else {
|
|
|
|
uint8_t diff_byte = static_cast<uint8_t>((*start)[diff_index]);
|
|
|
|
if (diff_byte < static_cast<uint8_t>(0xff) &&
|
|
|
|
diff_byte + 1 < static_cast<uint8_t>(limit[diff_index])) {
|
|
|
|
(*start)[diff_index]++;
|
|
|
|
start->resize(diff_index + 1);
|
|
|
|
assert(Compare(*start, limit) < 0);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
virtual void FindShortSuccessor(std::string* key) const {
|
|
|
|
// Find first character that can be incremented
|
|
|
|
size_t n = key->size();
|
2011-04-21 06:48:11 +08:00
|
|
|
for (size_t i = 0; i < n; i++) {
|
2011-03-19 06:37:00 +08:00
|
|
|
const uint8_t byte = (*key)[i];
|
|
|
|
if (byte != static_cast<uint8_t>(0xff)) {
|
|
|
|
(*key)[i] = byte + 1;
|
|
|
|
key->resize(i+1);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// *key is a run of 0xffs. Leave it alone.
|
|
|
|
}
|
|
|
|
};
|
2011-11-01 01:22:06 +08:00
|
|
|
} // namespace
|
2011-11-15 01:06:16 +08:00
|
|
|
|
2011-03-19 06:37:00 +08:00
|
|
|
const Comparator* BytewiseComparator() {
|
2018-09-11 06:38:12 +08:00
|
|
|
static NoDestructor<BytewiseComparatorImpl> singleton;
|
|
|
|
return singleton.get();
|
2011-03-19 06:37:00 +08:00
|
|
|
}
|
|
|
|
|
2011-11-01 01:22:06 +08:00
|
|
|
} // namespace leveldb
|