Add some std:: qualifiers to types and functions.

PiperOrigin-RevId: 309110431
This commit is contained in:
Victor Costan 2020-04-29 22:31:41 +00:00
parent 3f934e3705
commit a6b3a2012e
34 changed files with 345 additions and 314 deletions

View File

@ -221,8 +221,8 @@ class Stats {
double micros = now - last_op_finish_; double micros = now - last_op_finish_;
hist_.Add(micros); hist_.Add(micros);
if (micros > 20000) { if (micros > 20000) {
fprintf(stderr, "long op: %.1f micros%30s\r", micros, ""); std::fprintf(stderr, "long op: %.1f micros%30s\r", micros, "");
fflush(stderr); std::fflush(stderr);
} }
last_op_finish_ = now; last_op_finish_ = now;
} }
@ -243,8 +243,8 @@ class Stats {
next_report_ += 50000; next_report_ += 50000;
else else
next_report_ += 100000; next_report_ += 100000;
fprintf(stderr, "... finished %d ops%30s\r", done_, ""); std::fprintf(stderr, "... finished %d ops%30s\r", done_, "");
fflush(stderr); std::fflush(stderr);
} }
} }
@ -261,18 +261,20 @@ class Stats {
// elapsed times. // elapsed times.
double elapsed = (finish_ - start_) * 1e-6; double elapsed = (finish_ - start_) * 1e-6;
char rate[100]; char rate[100];
snprintf(rate, sizeof(rate), "%6.1f MB/s", std::snprintf(rate, sizeof(rate), "%6.1f MB/s",
(bytes_ / 1048576.0) / elapsed); (bytes_ / 1048576.0) / elapsed);
extra = rate; extra = rate;
} }
AppendWithSpace(&extra, message_); AppendWithSpace(&extra, message_);
fprintf(stdout, "%-12s : %11.3f micros/op;%s%s\n", name.ToString().c_str(), std::fprintf(stdout, "%-12s : %11.3f micros/op;%s%s\n",
seconds_ * 1e6 / done_, (extra.empty() ? "" : " "), extra.c_str()); name.ToString().c_str(), seconds_ * 1e6 / done_,
(extra.empty() ? "" : " "), extra.c_str());
if (FLAGS_histogram) { if (FLAGS_histogram) {
fprintf(stdout, "Microseconds per op:\n%s\n", hist_.ToString().c_str()); std::fprintf(stdout, "Microseconds per op:\n%s\n",
hist_.ToString().c_str());
} }
fflush(stdout); std::fflush(stdout);
} }
}; };
@ -323,51 +325,55 @@ class Benchmark {
void PrintHeader() { void PrintHeader() {
const int kKeySize = 16; const int kKeySize = 16;
PrintEnvironment(); PrintEnvironment();
fprintf(stdout, "Keys: %d bytes each\n", kKeySize); std::fprintf(stdout, "Keys: %d bytes each\n", kKeySize);
fprintf(stdout, "Values: %d bytes each (%d bytes after compression)\n", std::fprintf(
FLAGS_value_size, stdout, "Values: %d bytes each (%d bytes after compression)\n",
static_cast<int>(FLAGS_value_size * FLAGS_compression_ratio + 0.5)); FLAGS_value_size,
fprintf(stdout, "Entries: %d\n", num_); static_cast<int>(FLAGS_value_size * FLAGS_compression_ratio + 0.5));
fprintf(stdout, "RawSize: %.1f MB (estimated)\n", std::fprintf(stdout, "Entries: %d\n", num_);
((static_cast<int64_t>(kKeySize + FLAGS_value_size) * num_) / std::fprintf(stdout, "RawSize: %.1f MB (estimated)\n",
1048576.0)); ((static_cast<int64_t>(kKeySize + FLAGS_value_size) * num_) /
fprintf(stdout, "FileSize: %.1f MB (estimated)\n", 1048576.0));
(((kKeySize + FLAGS_value_size * FLAGS_compression_ratio) * num_) / std::fprintf(
1048576.0)); stdout, "FileSize: %.1f MB (estimated)\n",
(((kKeySize + FLAGS_value_size * FLAGS_compression_ratio) * num_) /
1048576.0));
PrintWarnings(); PrintWarnings();
fprintf(stdout, "------------------------------------------------\n"); std::fprintf(stdout, "------------------------------------------------\n");
} }
void PrintWarnings() { void PrintWarnings() {
#if defined(__GNUC__) && !defined(__OPTIMIZE__) #if defined(__GNUC__) && !defined(__OPTIMIZE__)
fprintf( std::fprintf(
stdout, stdout,
"WARNING: Optimization is disabled: benchmarks unnecessarily slow\n"); "WARNING: Optimization is disabled: benchmarks unnecessarily slow\n");
#endif #endif
#ifndef NDEBUG #ifndef NDEBUG
fprintf(stdout, std::fprintf(
"WARNING: Assertions are enabled; benchmarks unnecessarily slow\n"); stdout,
"WARNING: Assertions are enabled; benchmarks unnecessarily slow\n");
#endif #endif
// See if snappy is working by attempting to compress a compressible string // See if snappy is working by attempting to compress a compressible string
const char text[] = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"; const char text[] = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy";
std::string compressed; std::string compressed;
if (!port::Snappy_Compress(text, sizeof(text), &compressed)) { if (!port::Snappy_Compress(text, sizeof(text), &compressed)) {
fprintf(stdout, "WARNING: Snappy compression is not enabled\n"); std::fprintf(stdout, "WARNING: Snappy compression is not enabled\n");
} else if (compressed.size() >= sizeof(text)) { } else if (compressed.size() >= sizeof(text)) {
fprintf(stdout, "WARNING: Snappy compression is not effective\n"); std::fprintf(stdout, "WARNING: Snappy compression is not effective\n");
} }
} }
void PrintEnvironment() { void PrintEnvironment() {
fprintf(stderr, "LevelDB: version %d.%d\n", kMajorVersion, std::fprintf(stderr, "LevelDB: version %d.%d\n", kMajorVersion,
kMinorVersion); kMinorVersion);
#if defined(__linux) #if defined(__linux)
time_t now = time(nullptr); time_t now = time(nullptr);
fprintf(stderr, "Date: %s", ctime(&now)); // ctime() adds newline std::fprintf(stderr, "Date: %s",
ctime(&now)); // ctime() adds newline
FILE* cpuinfo = fopen("/proc/cpuinfo", "r"); FILE* cpuinfo = std::fopen("/proc/cpuinfo", "r");
if (cpuinfo != nullptr) { if (cpuinfo != nullptr) {
char line[1000]; char line[1000];
int num_cpus = 0; int num_cpus = 0;
@ -387,9 +393,9 @@ class Benchmark {
cache_size = val.ToString(); cache_size = val.ToString();
} }
} }
fclose(cpuinfo); std::fclose(cpuinfo);
fprintf(stderr, "CPU: %d * %s\n", num_cpus, cpu_type.c_str()); std::fprintf(stderr, "CPU: %d * %s\n", num_cpus, cpu_type.c_str());
fprintf(stderr, "CPUCache: %s\n", cache_size.c_str()); std::fprintf(stderr, "CPUCache: %s\n", cache_size.c_str());
} }
#endif #endif
} }
@ -516,14 +522,15 @@ class Benchmark {
PrintStats("leveldb.sstables"); PrintStats("leveldb.sstables");
} else { } else {
if (!name.empty()) { // No error message for empty name if (!name.empty()) { // No error message for empty name
fprintf(stderr, "unknown benchmark '%s'\n", name.ToString().c_str()); std::fprintf(stderr, "unknown benchmark '%s'\n",
name.ToString().c_str());
} }
} }
if (fresh_db) { if (fresh_db) {
if (FLAGS_use_existing_db) { if (FLAGS_use_existing_db) {
fprintf(stdout, "%-12s : skipped (--use_existing_db is true)\n", std::fprintf(stdout, "%-12s : skipped (--use_existing_db is true)\n",
name.ToString().c_str()); name.ToString().c_str());
method = nullptr; method = nullptr;
} else { } else {
delete db_; delete db_;
@ -625,7 +632,7 @@ class Benchmark {
bytes += size; bytes += size;
} }
// Print so result is not dead // Print so result is not dead
fprintf(stderr, "... crc=0x%x\r", static_cast<unsigned int>(crc)); std::fprintf(stderr, "... crc=0x%x\r", static_cast<unsigned int>(crc));
thread->stats.AddBytes(bytes); thread->stats.AddBytes(bytes);
thread->stats.AddMessage(label); thread->stats.AddMessage(label);
@ -649,8 +656,8 @@ class Benchmark {
thread->stats.AddMessage("(snappy failure)"); thread->stats.AddMessage("(snappy failure)");
} else { } else {
char buf[100]; char buf[100];
snprintf(buf, sizeof(buf), "(output: %.1f%%)", std::snprintf(buf, sizeof(buf), "(output: %.1f%%)",
(produced * 100.0) / bytes); (produced * 100.0) / bytes);
thread->stats.AddMessage(buf); thread->stats.AddMessage(buf);
thread->stats.AddBytes(bytes); thread->stats.AddBytes(bytes);
} }
@ -692,8 +699,8 @@ class Benchmark {
options.reuse_logs = FLAGS_reuse_logs; options.reuse_logs = FLAGS_reuse_logs;
Status s = DB::Open(options, FLAGS_db, &db_); Status s = DB::Open(options, FLAGS_db, &db_);
if (!s.ok()) { if (!s.ok()) {
fprintf(stderr, "open error: %s\n", s.ToString().c_str()); std::fprintf(stderr, "open error: %s\n", s.ToString().c_str());
exit(1); std::exit(1);
} }
} }
@ -712,7 +719,7 @@ class Benchmark {
void DoWrite(ThreadState* thread, bool seq) { void DoWrite(ThreadState* thread, bool seq) {
if (num_ != FLAGS_num) { if (num_ != FLAGS_num) {
char msg[100]; char msg[100];
snprintf(msg, sizeof(msg), "(%d ops)", num_); std::snprintf(msg, sizeof(msg), "(%d ops)", num_);
thread->stats.AddMessage(msg); thread->stats.AddMessage(msg);
} }
@ -725,15 +732,15 @@ class Benchmark {
for (int j = 0; j < entries_per_batch_; j++) { for (int j = 0; j < entries_per_batch_; j++) {
const int k = seq ? i + j : (thread->rand.Next() % FLAGS_num); const int k = seq ? i + j : (thread->rand.Next() % FLAGS_num);
char key[100]; char key[100];
snprintf(key, sizeof(key), "%016d", k); std::snprintf(key, sizeof(key), "%016d", k);
batch.Put(key, gen.Generate(value_size_)); batch.Put(key, gen.Generate(value_size_));
bytes += value_size_ + strlen(key); bytes += value_size_ + strlen(key);
thread->stats.FinishedSingleOp(); thread->stats.FinishedSingleOp();
} }
s = db_->Write(write_options_, &batch); s = db_->Write(write_options_, &batch);
if (!s.ok()) { if (!s.ok()) {
fprintf(stderr, "put error: %s\n", s.ToString().c_str()); std::fprintf(stderr, "put error: %s\n", s.ToString().c_str());
exit(1); std::exit(1);
} }
} }
thread->stats.AddBytes(bytes); thread->stats.AddBytes(bytes);
@ -772,14 +779,14 @@ class Benchmark {
for (int i = 0; i < reads_; i++) { for (int i = 0; i < reads_; i++) {
char key[100]; char key[100];
const int k = thread->rand.Next() % FLAGS_num; const int k = thread->rand.Next() % FLAGS_num;
snprintf(key, sizeof(key), "%016d", k); std::snprintf(key, sizeof(key), "%016d", k);
if (db_->Get(options, key, &value).ok()) { if (db_->Get(options, key, &value).ok()) {
found++; found++;
} }
thread->stats.FinishedSingleOp(); thread->stats.FinishedSingleOp();
} }
char msg[100]; char msg[100];
snprintf(msg, sizeof(msg), "(%d of %d found)", found, num_); std::snprintf(msg, sizeof(msg), "(%d of %d found)", found, num_);
thread->stats.AddMessage(msg); thread->stats.AddMessage(msg);
} }
@ -789,7 +796,7 @@ class Benchmark {
for (int i = 0; i < reads_; i++) { for (int i = 0; i < reads_; i++) {
char key[100]; char key[100];
const int k = thread->rand.Next() % FLAGS_num; const int k = thread->rand.Next() % FLAGS_num;
snprintf(key, sizeof(key), "%016d.", k); std::snprintf(key, sizeof(key), "%016d.", k);
db_->Get(options, key, &value); db_->Get(options, key, &value);
thread->stats.FinishedSingleOp(); thread->stats.FinishedSingleOp();
} }
@ -802,7 +809,7 @@ class Benchmark {
for (int i = 0; i < reads_; i++) { for (int i = 0; i < reads_; i++) {
char key[100]; char key[100];
const int k = thread->rand.Next() % range; const int k = thread->rand.Next() % range;
snprintf(key, sizeof(key), "%016d", k); std::snprintf(key, sizeof(key), "%016d", k);
db_->Get(options, key, &value); db_->Get(options, key, &value);
thread->stats.FinishedSingleOp(); thread->stats.FinishedSingleOp();
} }
@ -815,14 +822,14 @@ class Benchmark {
Iterator* iter = db_->NewIterator(options); Iterator* iter = db_->NewIterator(options);
char key[100]; char key[100];
const int k = thread->rand.Next() % FLAGS_num; const int k = thread->rand.Next() % FLAGS_num;
snprintf(key, sizeof(key), "%016d", k); std::snprintf(key, sizeof(key), "%016d", k);
iter->Seek(key); iter->Seek(key);
if (iter->Valid() && iter->key() == key) found++; if (iter->Valid() && iter->key() == key) found++;
delete iter; delete iter;
thread->stats.FinishedSingleOp(); thread->stats.FinishedSingleOp();
} }
char msg[100]; char msg[100];
snprintf(msg, sizeof(msg), "(%d of %d found)", found, num_); std::snprintf(msg, sizeof(msg), "(%d of %d found)", found, num_);
thread->stats.AddMessage(msg); thread->stats.AddMessage(msg);
} }
@ -835,14 +842,14 @@ class Benchmark {
for (int j = 0; j < entries_per_batch_; j++) { for (int j = 0; j < entries_per_batch_; j++) {
const int k = seq ? i + j : (thread->rand.Next() % FLAGS_num); const int k = seq ? i + j : (thread->rand.Next() % FLAGS_num);
char key[100]; char key[100];
snprintf(key, sizeof(key), "%016d", k); std::snprintf(key, sizeof(key), "%016d", k);
batch.Delete(key); batch.Delete(key);
thread->stats.FinishedSingleOp(); thread->stats.FinishedSingleOp();
} }
s = db_->Write(write_options_, &batch); s = db_->Write(write_options_, &batch);
if (!s.ok()) { if (!s.ok()) {
fprintf(stderr, "del error: %s\n", s.ToString().c_str()); std::fprintf(stderr, "del error: %s\n", s.ToString().c_str());
exit(1); std::exit(1);
} }
} }
} }
@ -868,11 +875,11 @@ class Benchmark {
const int k = thread->rand.Next() % FLAGS_num; const int k = thread->rand.Next() % FLAGS_num;
char key[100]; char key[100];
snprintf(key, sizeof(key), "%016d", k); std::snprintf(key, sizeof(key), "%016d", k);
Status s = db_->Put(write_options_, key, gen.Generate(value_size_)); Status s = db_->Put(write_options_, key, gen.Generate(value_size_));
if (!s.ok()) { if (!s.ok()) {
fprintf(stderr, "put error: %s\n", s.ToString().c_str()); std::fprintf(stderr, "put error: %s\n", s.ToString().c_str());
exit(1); std::exit(1);
} }
} }
@ -888,7 +895,7 @@ class Benchmark {
if (!db_->GetProperty(key, &stats)) { if (!db_->GetProperty(key, &stats)) {
stats = "(failed)"; stats = "(failed)";
} }
fprintf(stdout, "\n%s\n", stats.c_str()); std::fprintf(stdout, "\n%s\n", stats.c_str());
} }
static void WriteToFile(void* arg, const char* buf, int n) { static void WriteToFile(void* arg, const char* buf, int n) {
@ -897,17 +904,18 @@ class Benchmark {
void HeapProfile() { void HeapProfile() {
char fname[100]; char fname[100];
snprintf(fname, sizeof(fname), "%s/heap-%04d", FLAGS_db, ++heap_counter_); std::snprintf(fname, sizeof(fname), "%s/heap-%04d", FLAGS_db,
++heap_counter_);
WritableFile* file; WritableFile* file;
Status s = g_env->NewWritableFile(fname, &file); Status s = g_env->NewWritableFile(fname, &file);
if (!s.ok()) { if (!s.ok()) {
fprintf(stderr, "%s\n", s.ToString().c_str()); std::fprintf(stderr, "%s\n", s.ToString().c_str());
return; return;
} }
bool ok = port::GetHeapProfile(WriteToFile, file); bool ok = port::GetHeapProfile(WriteToFile, file);
delete file; delete file;
if (!ok) { if (!ok) {
fprintf(stderr, "heap profiling not supported\n"); std::fprintf(stderr, "heap profiling not supported\n");
g_env->RemoveFile(fname); g_env->RemoveFile(fname);
} }
} }
@ -962,8 +970,8 @@ int main(int argc, char** argv) {
} else if (strncmp(argv[i], "--db=", 5) == 0) { } else if (strncmp(argv[i], "--db=", 5) == 0) {
FLAGS_db = argv[i] + 5; FLAGS_db = argv[i] + 5;
} else { } else {
fprintf(stderr, "Invalid flag '%s'\n", argv[i]); std::fprintf(stderr, "Invalid flag '%s'\n", argv[i]);
exit(1); std::exit(1);
} }
} }

View File

@ -84,23 +84,23 @@ static const char* FLAGS_db = nullptr;
inline static void ExecErrorCheck(int status, char* err_msg) { inline static void ExecErrorCheck(int status, char* err_msg) {
if (status != SQLITE_OK) { if (status != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", err_msg); std::fprintf(stderr, "SQL error: %s\n", err_msg);
sqlite3_free(err_msg); sqlite3_free(err_msg);
exit(1); std::exit(1);
} }
} }
inline static void StepErrorCheck(int status) { inline static void StepErrorCheck(int status) {
if (status != SQLITE_DONE) { if (status != SQLITE_DONE) {
fprintf(stderr, "SQL step error: status = %d\n", status); std::fprintf(stderr, "SQL step error: status = %d\n", status);
exit(1); std::exit(1);
} }
} }
inline static void ErrorCheck(int status) { inline static void ErrorCheck(int status) {
if (status != SQLITE_OK) { if (status != SQLITE_OK) {
fprintf(stderr, "sqlite3 error: status = %d\n", status); std::fprintf(stderr, "sqlite3 error: status = %d\n", status);
exit(1); std::exit(1);
} }
} }
@ -182,36 +182,38 @@ class Benchmark {
void PrintHeader() { void PrintHeader() {
const int kKeySize = 16; const int kKeySize = 16;
PrintEnvironment(); PrintEnvironment();
fprintf(stdout, "Keys: %d bytes each\n", kKeySize); std::fprintf(stdout, "Keys: %d bytes each\n", kKeySize);
fprintf(stdout, "Values: %d bytes each\n", FLAGS_value_size); std::fprintf(stdout, "Values: %d bytes each\n", FLAGS_value_size);
fprintf(stdout, "Entries: %d\n", num_); std::fprintf(stdout, "Entries: %d\n", num_);
fprintf(stdout, "RawSize: %.1f MB (estimated)\n", std::fprintf(stdout, "RawSize: %.1f MB (estimated)\n",
((static_cast<int64_t>(kKeySize + FLAGS_value_size) * num_) / ((static_cast<int64_t>(kKeySize + FLAGS_value_size) * num_) /
1048576.0)); 1048576.0));
PrintWarnings(); PrintWarnings();
fprintf(stdout, "------------------------------------------------\n"); std::fprintf(stdout, "------------------------------------------------\n");
} }
void PrintWarnings() { void PrintWarnings() {
#if defined(__GNUC__) && !defined(__OPTIMIZE__) #if defined(__GNUC__) && !defined(__OPTIMIZE__)
fprintf( std::fprintf(
stdout, stdout,
"WARNING: Optimization is disabled: benchmarks unnecessarily slow\n"); "WARNING: Optimization is disabled: benchmarks unnecessarily slow\n");
#endif #endif
#ifndef NDEBUG #ifndef NDEBUG
fprintf(stdout, std::fprintf(
"WARNING: Assertions are enabled; benchmarks unnecessarily slow\n"); stdout,
"WARNING: Assertions are enabled; benchmarks unnecessarily slow\n");
#endif #endif
} }
void PrintEnvironment() { void PrintEnvironment() {
fprintf(stderr, "SQLite: version %s\n", SQLITE_VERSION); std::fprintf(stderr, "SQLite: version %s\n", SQLITE_VERSION);
#if defined(__linux) #if defined(__linux)
time_t now = time(nullptr); time_t now = time(nullptr);
fprintf(stderr, "Date: %s", ctime(&now)); // ctime() adds newline std::fprintf(stderr, "Date: %s",
ctime(&now)); // ctime() adds newline
FILE* cpuinfo = fopen("/proc/cpuinfo", "r"); FILE* cpuinfo = std::fopen("/proc/cpuinfo", "r");
if (cpuinfo != nullptr) { if (cpuinfo != nullptr) {
char line[1000]; char line[1000];
int num_cpus = 0; int num_cpus = 0;
@ -231,9 +233,9 @@ class Benchmark {
cache_size = val.ToString(); cache_size = val.ToString();
} }
} }
fclose(cpuinfo); std::fclose(cpuinfo);
fprintf(stderr, "CPU: %d * %s\n", num_cpus, cpu_type.c_str()); std::fprintf(stderr, "CPU: %d * %s\n", num_cpus, cpu_type.c_str());
fprintf(stderr, "CPUCache: %s\n", cache_size.c_str()); std::fprintf(stderr, "CPUCache: %s\n", cache_size.c_str());
} }
#endif #endif
} }
@ -254,8 +256,8 @@ class Benchmark {
double micros = (now - last_op_finish_) * 1e6; double micros = (now - last_op_finish_) * 1e6;
hist_.Add(micros); hist_.Add(micros);
if (micros > 20000) { if (micros > 20000) {
fprintf(stderr, "long op: %.1f micros%30s\r", micros, ""); std::fprintf(stderr, "long op: %.1f micros%30s\r", micros, "");
fflush(stderr); std::fflush(stderr);
} }
last_op_finish_ = now; last_op_finish_ = now;
} }
@ -276,8 +278,8 @@ class Benchmark {
next_report_ += 50000; next_report_ += 50000;
else else
next_report_ += 100000; next_report_ += 100000;
fprintf(stderr, "... finished %d ops%30s\r", done_, ""); std::fprintf(stderr, "... finished %d ops%30s\r", done_, "");
fflush(stderr); std::fflush(stderr);
} }
} }
@ -290,8 +292,8 @@ class Benchmark {
if (bytes_ > 0) { if (bytes_ > 0) {
char rate[100]; char rate[100];
snprintf(rate, sizeof(rate), "%6.1f MB/s", std::snprintf(rate, sizeof(rate), "%6.1f MB/s",
(bytes_ / 1048576.0) / (finish - start_)); (bytes_ / 1048576.0) / (finish - start_));
if (!message_.empty()) { if (!message_.empty()) {
message_ = std::string(rate) + " " + message_; message_ = std::string(rate) + " " + message_;
} else { } else {
@ -299,13 +301,14 @@ class Benchmark {
} }
} }
fprintf(stdout, "%-12s : %11.3f micros/op;%s%s\n", name.ToString().c_str(), std::fprintf(stdout, "%-12s : %11.3f micros/op;%s%s\n",
(finish - start_) * 1e6 / done_, (message_.empty() ? "" : " "), name.ToString().c_str(), (finish - start_) * 1e6 / done_,
message_.c_str()); (message_.empty() ? "" : " "), message_.c_str());
if (FLAGS_histogram) { if (FLAGS_histogram) {
fprintf(stdout, "Microseconds per op:\n%s\n", hist_.ToString().c_str()); std::fprintf(stdout, "Microseconds per op:\n%s\n",
hist_.ToString().c_str());
} }
fflush(stdout); std::fflush(stdout);
} }
public: public:
@ -405,7 +408,8 @@ class Benchmark {
} else { } else {
known = false; known = false;
if (name != Slice()) { // No error message for empty name if (name != Slice()) { // No error message for empty name
fprintf(stderr, "unknown benchmark '%s'\n", name.ToString().c_str()); std::fprintf(stderr, "unknown benchmark '%s'\n",
name.ToString().c_str());
} }
} }
if (known) { if (known) {
@ -425,26 +429,26 @@ class Benchmark {
// Open database // Open database
std::string tmp_dir; std::string tmp_dir;
Env::Default()->GetTestDirectory(&tmp_dir); Env::Default()->GetTestDirectory(&tmp_dir);
snprintf(file_name, sizeof(file_name), "%s/dbbench_sqlite3-%d.db", std::snprintf(file_name, sizeof(file_name), "%s/dbbench_sqlite3-%d.db",
tmp_dir.c_str(), db_num_); tmp_dir.c_str(), db_num_);
status = sqlite3_open(file_name, &db_); status = sqlite3_open(file_name, &db_);
if (status) { if (status) {
fprintf(stderr, "open error: %s\n", sqlite3_errmsg(db_)); std::fprintf(stderr, "open error: %s\n", sqlite3_errmsg(db_));
exit(1); std::exit(1);
} }
// Change SQLite cache size // Change SQLite cache size
char cache_size[100]; char cache_size[100];
snprintf(cache_size, sizeof(cache_size), "PRAGMA cache_size = %d", std::snprintf(cache_size, sizeof(cache_size), "PRAGMA cache_size = %d",
FLAGS_num_pages); FLAGS_num_pages);
status = sqlite3_exec(db_, cache_size, nullptr, nullptr, &err_msg); status = sqlite3_exec(db_, cache_size, nullptr, nullptr, &err_msg);
ExecErrorCheck(status, err_msg); ExecErrorCheck(status, err_msg);
// FLAGS_page_size is defaulted to 1024 // FLAGS_page_size is defaulted to 1024
if (FLAGS_page_size != 1024) { if (FLAGS_page_size != 1024) {
char page_size[100]; char page_size[100];
snprintf(page_size, sizeof(page_size), "PRAGMA page_size = %d", std::snprintf(page_size, sizeof(page_size), "PRAGMA page_size = %d",
FLAGS_page_size); FLAGS_page_size);
status = sqlite3_exec(db_, page_size, nullptr, nullptr, &err_msg); status = sqlite3_exec(db_, page_size, nullptr, nullptr, &err_msg);
ExecErrorCheck(status, err_msg); ExecErrorCheck(status, err_msg);
} }
@ -492,7 +496,7 @@ class Benchmark {
if (num_entries != num_) { if (num_entries != num_) {
char msg[100]; char msg[100];
snprintf(msg, sizeof(msg), "(%d ops)", num_entries); std::snprintf(msg, sizeof(msg), "(%d ops)", num_entries);
message_ = msg; message_ = msg;
} }
@ -539,7 +543,7 @@ class Benchmark {
const int k = const int k =
(order == SEQUENTIAL) ? i + j : (rand_.Next() % num_entries); (order == SEQUENTIAL) ? i + j : (rand_.Next() % num_entries);
char key[100]; char key[100];
snprintf(key, sizeof(key), "%016d", k); std::snprintf(key, sizeof(key), "%016d", k);
// Bind KV values into replace_stmt // Bind KV values into replace_stmt
status = sqlite3_bind_blob(replace_stmt, 1, key, 16, SQLITE_STATIC); status = sqlite3_bind_blob(replace_stmt, 1, key, 16, SQLITE_STATIC);
@ -612,7 +616,7 @@ class Benchmark {
// Create key value // Create key value
char key[100]; char key[100];
int k = (order == SEQUENTIAL) ? i + j : (rand_.Next() % reads_); int k = (order == SEQUENTIAL) ? i + j : (rand_.Next() % reads_);
snprintf(key, sizeof(key), "%016d", k); std::snprintf(key, sizeof(key), "%016d", k);
// Bind key value into read_stmt // Bind key value into read_stmt
status = sqlite3_bind_blob(read_stmt, 1, key, 16, SQLITE_STATIC); status = sqlite3_bind_blob(read_stmt, 1, key, 16, SQLITE_STATIC);
@ -704,8 +708,8 @@ int main(int argc, char** argv) {
} else if (strncmp(argv[i], "--db=", 5) == 0) { } else if (strncmp(argv[i], "--db=", 5) == 0) {
FLAGS_db = argv[i] + 5; FLAGS_db = argv[i] + 5;
} else { } else {
fprintf(stderr, "Invalid flag '%s'\n", argv[i]); std::fprintf(stderr, "Invalid flag '%s'\n", argv[i]);
exit(1); std::exit(1);
} }
} }

View File

@ -75,7 +75,7 @@ static const char* FLAGS_db = nullptr;
inline static void DBSynchronize(kyotocabinet::TreeDB* db_) { inline static void DBSynchronize(kyotocabinet::TreeDB* db_) {
// Synchronize will flush writes to disk // Synchronize will flush writes to disk
if (!db_->synchronize()) { if (!db_->synchronize()) {
fprintf(stderr, "synchronize error: %s\n", db_->error().name()); std::fprintf(stderr, "synchronize error: %s\n", db_->error().name());
} }
} }
@ -150,42 +150,47 @@ class Benchmark {
void PrintHeader() { void PrintHeader() {
const int kKeySize = 16; const int kKeySize = 16;
PrintEnvironment(); PrintEnvironment();
fprintf(stdout, "Keys: %d bytes each\n", kKeySize); std::fprintf(stdout, "Keys: %d bytes each\n", kKeySize);
fprintf(stdout, "Values: %d bytes each (%d bytes after compression)\n", std::fprintf(
FLAGS_value_size, stdout, "Values: %d bytes each (%d bytes after compression)\n",
static_cast<int>(FLAGS_value_size * FLAGS_compression_ratio + 0.5)); FLAGS_value_size,
fprintf(stdout, "Entries: %d\n", num_); static_cast<int>(FLAGS_value_size * FLAGS_compression_ratio + 0.5));
fprintf(stdout, "RawSize: %.1f MB (estimated)\n", std::fprintf(stdout, "Entries: %d\n", num_);
((static_cast<int64_t>(kKeySize + FLAGS_value_size) * num_) / std::fprintf(stdout, "RawSize: %.1f MB (estimated)\n",
1048576.0)); ((static_cast<int64_t>(kKeySize + FLAGS_value_size) * num_) /
fprintf(stdout, "FileSize: %.1f MB (estimated)\n", 1048576.0));
(((kKeySize + FLAGS_value_size * FLAGS_compression_ratio) * num_) / std::fprintf(
1048576.0)); stdout, "FileSize: %.1f MB (estimated)\n",
(((kKeySize + FLAGS_value_size * FLAGS_compression_ratio) * num_) /
1048576.0));
PrintWarnings(); PrintWarnings();
fprintf(stdout, "------------------------------------------------\n"); std::fprintf(stdout, "------------------------------------------------\n");
} }
void PrintWarnings() { void PrintWarnings() {
#if defined(__GNUC__) && !defined(__OPTIMIZE__) #if defined(__GNUC__) && !defined(__OPTIMIZE__)
fprintf( std::fprintf(
stdout, stdout,
"WARNING: Optimization is disabled: benchmarks unnecessarily slow\n"); "WARNING: Optimization is disabled: benchmarks unnecessarily slow\n");
#endif #endif
#ifndef NDEBUG #ifndef NDEBUG
fprintf(stdout, std::fprintf(
"WARNING: Assertions are enabled; benchmarks unnecessarily slow\n"); stdout,
"WARNING: Assertions are enabled; benchmarks unnecessarily slow\n");
#endif #endif
} }
void PrintEnvironment() { void PrintEnvironment() {
fprintf(stderr, "Kyoto Cabinet: version %s, lib ver %d, lib rev %d\n", std::fprintf(
kyotocabinet::VERSION, kyotocabinet::LIBVER, kyotocabinet::LIBREV); stderr, "Kyoto Cabinet: version %s, lib ver %d, lib rev %d\n",
kyotocabinet::VERSION, kyotocabinet::LIBVER, kyotocabinet::LIBREV);
#if defined(__linux) #if defined(__linux)
time_t now = time(nullptr); time_t now = time(nullptr);
fprintf(stderr, "Date: %s", ctime(&now)); // ctime() adds newline std::fprintf(stderr, "Date: %s",
ctime(&now)); // ctime() adds newline
FILE* cpuinfo = fopen("/proc/cpuinfo", "r"); FILE* cpuinfo = std::fopen("/proc/cpuinfo", "r");
if (cpuinfo != nullptr) { if (cpuinfo != nullptr) {
char line[1000]; char line[1000];
int num_cpus = 0; int num_cpus = 0;
@ -205,9 +210,10 @@ class Benchmark {
cache_size = val.ToString(); cache_size = val.ToString();
} }
} }
fclose(cpuinfo); std::fclose(cpuinfo);
fprintf(stderr, "CPU: %d * %s\n", num_cpus, cpu_type.c_str()); std::fprintf(stderr, "CPU: %d * %s\n", num_cpus,
fprintf(stderr, "CPUCache: %s\n", cache_size.c_str()); cpu_type.c_str());
std::fprintf(stderr, "CPUCache: %s\n", cache_size.c_str());
} }
#endif #endif
} }
@ -228,8 +234,8 @@ class Benchmark {
double micros = (now - last_op_finish_) * 1e6; double micros = (now - last_op_finish_) * 1e6;
hist_.Add(micros); hist_.Add(micros);
if (micros > 20000) { if (micros > 20000) {
fprintf(stderr, "long op: %.1f micros%30s\r", micros, ""); std::fprintf(stderr, "long op: %.1f micros%30s\r", micros, "");
fflush(stderr); std::fflush(stderr);
} }
last_op_finish_ = now; last_op_finish_ = now;
} }
@ -250,8 +256,8 @@ class Benchmark {
next_report_ += 50000; next_report_ += 50000;
else else
next_report_ += 100000; next_report_ += 100000;
fprintf(stderr, "... finished %d ops%30s\r", done_, ""); std::fprintf(stderr, "... finished %d ops%30s\r", done_, "");
fflush(stderr); std::fflush(stderr);
} }
} }
@ -264,8 +270,8 @@ class Benchmark {
if (bytes_ > 0) { if (bytes_ > 0) {
char rate[100]; char rate[100];
snprintf(rate, sizeof(rate), "%6.1f MB/s", std::snprintf(rate, sizeof(rate), "%6.1f MB/s",
(bytes_ / 1048576.0) / (finish - start_)); (bytes_ / 1048576.0) / (finish - start_));
if (!message_.empty()) { if (!message_.empty()) {
message_ = std::string(rate) + " " + message_; message_ = std::string(rate) + " " + message_;
} else { } else {
@ -273,13 +279,14 @@ class Benchmark {
} }
} }
fprintf(stdout, "%-12s : %11.3f micros/op;%s%s\n", name.ToString().c_str(), std::fprintf(stdout, "%-12s : %11.3f micros/op;%s%s\n",
(finish - start_) * 1e6 / done_, (message_.empty() ? "" : " "), name.ToString().c_str(), (finish - start_) * 1e6 / done_,
message_.c_str()); (message_.empty() ? "" : " "), message_.c_str());
if (FLAGS_histogram) { if (FLAGS_histogram) {
fprintf(stdout, "Microseconds per op:\n%s\n", hist_.ToString().c_str()); std::fprintf(stdout, "Microseconds per op:\n%s\n",
hist_.ToString().c_str());
} }
fflush(stdout); std::fflush(stdout);
} }
public: public:
@ -310,7 +317,7 @@ class Benchmark {
~Benchmark() { ~Benchmark() {
if (!db_->close()) { if (!db_->close()) {
fprintf(stderr, "close error: %s\n", db_->error().name()); std::fprintf(stderr, "close error: %s\n", db_->error().name());
} }
} }
@ -374,7 +381,8 @@ class Benchmark {
} else { } else {
known = false; known = false;
if (name != Slice()) { // No error message for empty name if (name != Slice()) { // No error message for empty name
fprintf(stderr, "unknown benchmark '%s'\n", name.ToString().c_str()); std::fprintf(stderr, "unknown benchmark '%s'\n",
name.ToString().c_str());
} }
} }
if (known) { if (known) {
@ -393,8 +401,8 @@ class Benchmark {
db_num_++; db_num_++;
std::string test_dir; std::string test_dir;
Env::Default()->GetTestDirectory(&test_dir); Env::Default()->GetTestDirectory(&test_dir);
snprintf(file_name, sizeof(file_name), "%s/dbbench_polyDB-%d.kct", std::snprintf(file_name, sizeof(file_name), "%s/dbbench_polyDB-%d.kct",
test_dir.c_str(), db_num_); test_dir.c_str(), db_num_);
// Create tuning options and open the database // Create tuning options and open the database
int open_options = int open_options =
@ -413,7 +421,7 @@ class Benchmark {
open_options |= kyotocabinet::PolyDB::OAUTOSYNC; open_options |= kyotocabinet::PolyDB::OAUTOSYNC;
} }
if (!db_->open(file_name, open_options)) { if (!db_->open(file_name, open_options)) {
fprintf(stderr, "open error: %s\n", db_->error().name()); std::fprintf(stderr, "open error: %s\n", db_->error().name());
} }
} }
@ -433,7 +441,7 @@ class Benchmark {
if (num_entries != num_) { if (num_entries != num_) {
char msg[100]; char msg[100];
snprintf(msg, sizeof(msg), "(%d ops)", num_entries); std::snprintf(msg, sizeof(msg), "(%d ops)", num_entries);
message_ = msg; message_ = msg;
} }
@ -441,11 +449,11 @@ class Benchmark {
for (int i = 0; i < num_entries; i++) { for (int i = 0; i < num_entries; i++) {
const int k = (order == SEQUENTIAL) ? i : (rand_.Next() % num_entries); const int k = (order == SEQUENTIAL) ? i : (rand_.Next() % num_entries);
char key[100]; char key[100];
snprintf(key, sizeof(key), "%016d", k); std::snprintf(key, sizeof(key), "%016d", k);
bytes_ += value_size + strlen(key); bytes_ += value_size + strlen(key);
std::string cpp_key = key; std::string cpp_key = key;
if (!db_->set(cpp_key, gen_.Generate(value_size).ToString())) { if (!db_->set(cpp_key, gen_.Generate(value_size).ToString())) {
fprintf(stderr, "set error: %s\n", db_->error().name()); std::fprintf(stderr, "set error: %s\n", db_->error().name());
} }
FinishedSingleOp(); FinishedSingleOp();
} }
@ -467,7 +475,7 @@ class Benchmark {
for (int i = 0; i < reads_; i++) { for (int i = 0; i < reads_; i++) {
char key[100]; char key[100];
const int k = rand_.Next() % reads_; const int k = rand_.Next() % reads_;
snprintf(key, sizeof(key), "%016d", k); std::snprintf(key, sizeof(key), "%016d", k);
db_->get(key, &value); db_->get(key, &value);
FinishedSingleOp(); FinishedSingleOp();
} }
@ -505,8 +513,8 @@ int main(int argc, char** argv) {
} else if (strncmp(argv[i], "--db=", 5) == 0) { } else if (strncmp(argv[i], "--db=", 5) == 0) {
FLAGS_db = argv[i] + 5; FLAGS_db = argv[i] + 5;
} else { } else {
fprintf(stderr, "Invalid flag '%s'\n", argv[i]); std::fprintf(stderr, "Invalid flag '%s'\n", argv[i]);
exit(1); std::exit(1);
} }
} }

View File

@ -30,7 +30,7 @@ class AutoCompactTest : public testing::Test {
std::string Key(int i) { std::string Key(int i) {
char buf[100]; char buf[100];
snprintf(buf, sizeof(buf), "key%06d", i); std::snprintf(buf, sizeof(buf), "key%06d", i);
return std::string(buf); return std::string(buf);
} }
@ -89,8 +89,8 @@ void AutoCompactTest::DoReads(int n) {
// Wait a little bit to allow any triggered compactions to complete. // Wait a little bit to allow any triggered compactions to complete.
Env::Default()->SleepForMicroseconds(1000000); Env::Default()->SleepForMicroseconds(1000000);
uint64_t size = Size(Key(0), Key(n)); uint64_t size = Size(Key(0), Key(n));
fprintf(stderr, "iter %3d => %7.3f MB [other %7.3f MB]\n", read + 1, std::fprintf(stderr, "iter %3d => %7.3f MB [other %7.3f MB]\n", read + 1,
size / 1048576.0, Size(Key(n), Key(kCount)) / 1048576.0); size / 1048576.0, Size(Key(n), Key(kCount)) / 1048576.0);
if (size <= initial_size / 10) { if (size <= initial_size / 10) {
break; break;
} }

View File

@ -158,7 +158,7 @@ static bool SaveError(char** errptr, const Status& s) {
static char* CopyString(const std::string& str) { static char* CopyString(const std::string& str) {
char* result = reinterpret_cast<char*>(malloc(sizeof(char) * str.size())); char* result = reinterpret_cast<char*>(malloc(sizeof(char) * str.size()));
memcpy(result, str.data(), sizeof(char) * str.size()); std::memcpy(result, str.data(), sizeof(char) * str.size());
return result; return result;
} }
@ -548,7 +548,7 @@ char* leveldb_env_get_test_directory(leveldb_env_t* env) {
} }
char* buffer = static_cast<char*>(malloc(result.size() + 1)); char* buffer = static_cast<char*>(malloc(result.size() + 1));
memcpy(buffer, result.data(), result.size()); std::memcpy(buffer, result.data(), result.size());
buffer[result.size()] = '\0'; buffer[result.size()] = '\0';
return buffer; return buffer;
} }

View File

@ -58,7 +58,7 @@ class CorruptionTest : public testing::Test {
std::string key_space, value_space; std::string key_space, value_space;
WriteBatch batch; WriteBatch batch;
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
// if ((i % 100) == 0) fprintf(stderr, "@ %d of %d\n", i, n); // if ((i % 100) == 0) std::fprintf(stderr, "@ %d of %d\n", i, n);
Slice key = Key(i, &key_space); Slice key = Key(i, &key_space);
batch.Clear(); batch.Clear();
batch.Put(key, Value(i, &value_space)); batch.Put(key, Value(i, &value_space));
@ -102,9 +102,10 @@ class CorruptionTest : public testing::Test {
} }
delete iter; delete iter;
fprintf(stderr, std::fprintf(
"expected=%d..%d; got=%d; bad_keys=%d; bad_values=%d; missed=%d\n", stderr,
min_expected, max_expected, correct, bad_keys, bad_values, missed); "expected=%d..%d; got=%d; bad_keys=%d; bad_values=%d; missed=%d\n",
min_expected, max_expected, correct, bad_keys, bad_values, missed);
ASSERT_LE(min_expected, correct); ASSERT_LE(min_expected, correct);
ASSERT_GE(max_expected, correct); ASSERT_GE(max_expected, correct);
} }
@ -169,7 +170,7 @@ class CorruptionTest : public testing::Test {
// Return the ith key // Return the ith key
Slice Key(int i, std::string* storage) { Slice Key(int i, std::string* storage) {
char buf[100]; char buf[100];
snprintf(buf, sizeof(buf), "%016d", i); std::snprintf(buf, sizeof(buf), "%016d", i);
storage->assign(buf, strlen(buf)); storage->assign(buf, strlen(buf));
return Slice(*storage); return Slice(*storage);
} }

View File

@ -350,8 +350,8 @@ Status DBImpl::Recover(VersionEdit* edit, bool* save_manifest) {
} }
if (!expected.empty()) { if (!expected.empty()) {
char buf[50]; char buf[50];
snprintf(buf, sizeof(buf), "%d missing files; e.g.", std::snprintf(buf, sizeof(buf), "%d missing files; e.g.",
static_cast<int>(expected.size())); static_cast<int>(expected.size()));
return Status::Corruption(buf, TableFileName(dbname_, *(expected.begin()))); return Status::Corruption(buf, TableFileName(dbname_, *(expected.begin())));
} }
@ -1396,26 +1396,26 @@ bool DBImpl::GetProperty(const Slice& property, std::string* value) {
return false; return false;
} else { } else {
char buf[100]; char buf[100];
snprintf(buf, sizeof(buf), "%d", std::snprintf(buf, sizeof(buf), "%d",
versions_->NumLevelFiles(static_cast<int>(level))); versions_->NumLevelFiles(static_cast<int>(level)));
*value = buf; *value = buf;
return true; return true;
} }
} else if (in == "stats") { } else if (in == "stats") {
char buf[200]; char buf[200];
snprintf(buf, sizeof(buf), std::snprintf(buf, sizeof(buf),
" Compactions\n" " Compactions\n"
"Level Files Size(MB) Time(sec) Read(MB) Write(MB)\n" "Level Files Size(MB) Time(sec) Read(MB) Write(MB)\n"
"--------------------------------------------------\n"); "--------------------------------------------------\n");
value->append(buf); value->append(buf);
for (int level = 0; level < config::kNumLevels; level++) { for (int level = 0; level < config::kNumLevels; level++) {
int files = versions_->NumLevelFiles(level); int files = versions_->NumLevelFiles(level);
if (stats_[level].micros > 0 || files > 0) { if (stats_[level].micros > 0 || files > 0) {
snprintf(buf, sizeof(buf), "%3d %8d %8.0f %9.0f %8.0f %9.0f\n", level, std::snprintf(buf, sizeof(buf), "%3d %8d %8.0f %9.0f %8.0f %9.0f\n",
files, versions_->NumLevelBytes(level) / 1048576.0, level, files, versions_->NumLevelBytes(level) / 1048576.0,
stats_[level].micros / 1e6, stats_[level].micros / 1e6,
stats_[level].bytes_read / 1048576.0, stats_[level].bytes_read / 1048576.0,
stats_[level].bytes_written / 1048576.0); stats_[level].bytes_written / 1048576.0);
value->append(buf); value->append(buf);
} }
} }
@ -1432,8 +1432,8 @@ bool DBImpl::GetProperty(const Slice& property, std::string* value) {
total_usage += imm_->ApproximateMemoryUsage(); total_usage += imm_->ApproximateMemoryUsage();
} }
char buf[50]; char buf[50];
snprintf(buf, sizeof(buf), "%llu", std::snprintf(buf, sizeof(buf), "%llu",
static_cast<unsigned long long>(total_usage)); static_cast<unsigned long long>(total_usage));
value->append(buf); value->append(buf);
return true; return true;
} }

View File

@ -21,9 +21,9 @@ static void DumpInternalIter(Iterator* iter) {
for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
ParsedInternalKey k; ParsedInternalKey k;
if (!ParseInternalKey(iter->key(), &k)) { if (!ParseInternalKey(iter->key(), &k)) {
fprintf(stderr, "Corrupt '%s'\n", EscapeString(iter->key()).c_str()); std::fprintf(stderr, "Corrupt '%s'\n", EscapeString(iter->key()).c_str());
} else { } else {
fprintf(stderr, "@ '%s'\n", k.DebugString().c_str()); std::fprintf(stderr, "@ '%s'\n", k.DebugString().c_str());
} }
} }
} }

View File

@ -424,7 +424,7 @@ class DBTest : public testing::Test {
for (int level = 0; level < config::kNumLevels; level++) { for (int level = 0; level < config::kNumLevels; level++) {
int f = NumTableFilesAtLevel(level); int f = NumTableFilesAtLevel(level);
char buf[100]; char buf[100];
snprintf(buf, sizeof(buf), "%s%d", (level ? "," : ""), f); std::snprintf(buf, sizeof(buf), "%s%d", (level ? "," : ""), f);
result += buf; result += buf;
if (f > 0) { if (f > 0) {
last_non_zero_offset = result.size(); last_non_zero_offset = result.size();
@ -469,14 +469,14 @@ class DBTest : public testing::Test {
} }
void DumpFileCounts(const char* label) { void DumpFileCounts(const char* label) {
fprintf(stderr, "---\n%s:\n", label); std::fprintf(stderr, "---\n%s:\n", label);
fprintf( std::fprintf(
stderr, "maxoverlap: %lld\n", stderr, "maxoverlap: %lld\n",
static_cast<long long>(dbfull()->TEST_MaxNextLevelOverlappingBytes())); static_cast<long long>(dbfull()->TEST_MaxNextLevelOverlappingBytes()));
for (int level = 0; level < config::kNumLevels; level++) { for (int level = 0; level < config::kNumLevels; level++) {
int num = NumTableFilesAtLevel(level); int num = NumTableFilesAtLevel(level);
if (num > 0) { if (num > 0) {
fprintf(stderr, " level %3d : %d files\n", level, num); std::fprintf(stderr, " level %3d : %d files\n", level, num);
} }
} }
} }
@ -1024,7 +1024,7 @@ TEST_F(DBTest, RecoverDuringMemtableCompaction) {
static std::string Key(int i) { static std::string Key(int i) {
char buf[100]; char buf[100];
snprintf(buf, sizeof(buf), "key%06d", i); std::snprintf(buf, sizeof(buf), "key%06d", i);
return std::string(buf); return std::string(buf);
} }
@ -1118,7 +1118,7 @@ TEST_F(DBTest, RepeatedWritesToSameKey) {
for (int i = 0; i < 5 * kMaxFiles; i++) { for (int i = 0; i < 5 * kMaxFiles; i++) {
Put("key", value); Put("key", value);
ASSERT_LE(TotalTableFiles(), kMaxFiles); ASSERT_LE(TotalTableFiles(), kMaxFiles);
fprintf(stderr, "after %d: %d files\n", i + 1, TotalTableFiles()); std::fprintf(stderr, "after %d: %d files\n", i + 1, TotalTableFiles());
} }
} }
@ -1140,7 +1140,7 @@ TEST_F(DBTest, SparseMerge) {
// Write approximately 100MB of "B" values // Write approximately 100MB of "B" values
for (int i = 0; i < 100000; i++) { for (int i = 0; i < 100000; i++) {
char key[100]; char key[100];
snprintf(key, sizeof(key), "B%010d", i); std::snprintf(key, sizeof(key), "B%010d", i);
Put(key, value); Put(key, value);
} }
Put("C", "vc"); Put("C", "vc");
@ -1165,9 +1165,9 @@ TEST_F(DBTest, SparseMerge) {
static bool Between(uint64_t val, uint64_t low, uint64_t high) { static bool Between(uint64_t val, uint64_t low, uint64_t high) {
bool result = (val >= low) && (val <= high); bool result = (val >= low) && (val <= high);
if (!result) { if (!result) {
fprintf(stderr, "Value %llu is not in range [%llu, %llu]\n", std::fprintf(stderr, "Value %llu is not in range [%llu, %llu]\n",
(unsigned long long)(val), (unsigned long long)(low), (unsigned long long)(val), (unsigned long long)(low),
(unsigned long long)(high)); (unsigned long long)(high));
} }
return result; return result;
} }
@ -1501,7 +1501,7 @@ TEST_F(DBTest, Fflush_Issue474) {
static const int kNum = 100000; static const int kNum = 100000;
Random rnd(test::RandomSeed()); Random rnd(test::RandomSeed());
for (int i = 0; i < kNum; i++) { for (int i = 0; i < kNum; i++) {
fflush(nullptr); std::fflush(nullptr);
ASSERT_LEVELDB_OK(Put(RandomKey(&rnd), RandomString(&rnd, 100))); ASSERT_LEVELDB_OK(Put(RandomKey(&rnd), RandomString(&rnd, 100)));
} }
} }
@ -1578,7 +1578,7 @@ TEST_F(DBTest, CustomComparator) {
for (int run = 0; run < 2; run++) { for (int run = 0; run < 2; run++) {
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
char buf[100]; char buf[100];
snprintf(buf, sizeof(buf), "[%d]", i * 10); std::snprintf(buf, sizeof(buf), "[%d]", i * 10);
ASSERT_LEVELDB_OK(Put(buf, buf)); ASSERT_LEVELDB_OK(Put(buf, buf));
} }
Compact("[0]", "[1000000]"); Compact("[0]", "[1000000]");
@ -1748,7 +1748,7 @@ TEST_F(DBTest, NonWritableFileSystem) {
std::string big(100000, 'x'); std::string big(100000, 'x');
int errors = 0; int errors = 0;
for (int i = 0; i < 20; i++) { for (int i = 0; i < 20; i++) {
fprintf(stderr, "iter %d; errors %d\n", i, errors); std::fprintf(stderr, "iter %d; errors %d\n", i, errors);
if (!Put("foo", big).ok()) { if (!Put("foo", big).ok()) {
errors++; errors++;
DelayMilliseconds(100); DelayMilliseconds(100);
@ -1901,7 +1901,7 @@ TEST_F(DBTest, BloomFilter) {
ASSERT_EQ(Key(i), Get(Key(i))); ASSERT_EQ(Key(i), Get(Key(i)));
} }
int reads = env_->random_read_counter_.Read(); int reads = env_->random_read_counter_.Read();
fprintf(stderr, "%d present => %d reads\n", N, reads); std::fprintf(stderr, "%d present => %d reads\n", N, reads);
ASSERT_GE(reads, N); ASSERT_GE(reads, N);
ASSERT_LE(reads, N + 2 * N / 100); ASSERT_LE(reads, N + 2 * N / 100);
@ -1911,7 +1911,7 @@ TEST_F(DBTest, BloomFilter) {
ASSERT_EQ("NOT_FOUND", Get(Key(i) + ".missing")); ASSERT_EQ("NOT_FOUND", Get(Key(i) + ".missing"));
} }
reads = env_->random_read_counter_.Read(); reads = env_->random_read_counter_.Read();
fprintf(stderr, "%d missing => %d reads\n", N, reads); std::fprintf(stderr, "%d missing => %d reads\n", N, reads);
ASSERT_LE(reads, 3 * N / 100); ASSERT_LE(reads, 3 * N / 100);
env_->delay_data_sync_.store(false, std::memory_order_release); env_->delay_data_sync_.store(false, std::memory_order_release);
@ -1944,7 +1944,7 @@ static void MTThreadBody(void* arg) {
int id = t->id; int id = t->id;
DB* db = t->state->test->db_; DB* db = t->state->test->db_;
int counter = 0; int counter = 0;
fprintf(stderr, "... starting thread %d\n", id); std::fprintf(stderr, "... starting thread %d\n", id);
Random rnd(1000 + id); Random rnd(1000 + id);
std::string value; std::string value;
char valbuf[1500]; char valbuf[1500];
@ -1953,13 +1953,13 @@ static void MTThreadBody(void* arg) {
int key = rnd.Uniform(kNumKeys); int key = rnd.Uniform(kNumKeys);
char keybuf[20]; char keybuf[20];
snprintf(keybuf, sizeof(keybuf), "%016d", key); std::snprintf(keybuf, sizeof(keybuf), "%016d", key);
if (rnd.OneIn(2)) { if (rnd.OneIn(2)) {
// Write values of the form <key, my id, counter>. // Write values of the form <key, my id, counter>.
// We add some padding for force compactions. // We add some padding for force compactions.
snprintf(valbuf, sizeof(valbuf), "%d.%d.%-1000d", key, id, std::snprintf(valbuf, sizeof(valbuf), "%d.%d.%-1000d", key, id,
static_cast<int>(counter)); static_cast<int>(counter));
ASSERT_LEVELDB_OK(db->Put(WriteOptions(), Slice(keybuf), Slice(valbuf))); ASSERT_LEVELDB_OK(db->Put(WriteOptions(), Slice(keybuf), Slice(valbuf)));
} else { } else {
// Read a value and verify that it matches the pattern written above. // Read a value and verify that it matches the pattern written above.
@ -1980,7 +1980,7 @@ static void MTThreadBody(void* arg) {
counter++; counter++;
} }
t->state->thread_done[id].store(true, std::memory_order_release); t->state->thread_done[id].store(true, std::memory_order_release);
fprintf(stderr, "... stopping thread %d after %d ops\n", id, counter); std::fprintf(stderr, "... stopping thread %d after %d ops\n", id, counter);
} }
} // namespace } // namespace
@ -2134,30 +2134,31 @@ static bool CompareIterators(int step, DB* model, DB* db,
ok && miter->Valid() && dbiter->Valid(); miter->Next(), dbiter->Next()) { ok && miter->Valid() && dbiter->Valid(); miter->Next(), dbiter->Next()) {
count++; count++;
if (miter->key().compare(dbiter->key()) != 0) { if (miter->key().compare(dbiter->key()) != 0) {
fprintf(stderr, "step %d: Key mismatch: '%s' vs. '%s'\n", step, std::fprintf(stderr, "step %d: Key mismatch: '%s' vs. '%s'\n", step,
EscapeString(miter->key()).c_str(), EscapeString(miter->key()).c_str(),
EscapeString(dbiter->key()).c_str()); EscapeString(dbiter->key()).c_str());
ok = false; ok = false;
break; break;
} }
if (miter->value().compare(dbiter->value()) != 0) { if (miter->value().compare(dbiter->value()) != 0) {
fprintf(stderr, "step %d: Value mismatch for key '%s': '%s' vs. '%s'\n", std::fprintf(stderr,
step, EscapeString(miter->key()).c_str(), "step %d: Value mismatch for key '%s': '%s' vs. '%s'\n",
EscapeString(miter->value()).c_str(), step, EscapeString(miter->key()).c_str(),
EscapeString(miter->value()).c_str()); EscapeString(miter->value()).c_str(),
EscapeString(miter->value()).c_str());
ok = false; ok = false;
} }
} }
if (ok) { if (ok) {
if (miter->Valid() != dbiter->Valid()) { if (miter->Valid() != dbiter->Valid()) {
fprintf(stderr, "step %d: Mismatch at end of iterators: %d vs. %d\n", std::fprintf(stderr, "step %d: Mismatch at end of iterators: %d vs. %d\n",
step, miter->Valid(), dbiter->Valid()); step, miter->Valid(), dbiter->Valid());
ok = false; ok = false;
} }
} }
fprintf(stderr, "%d entries compared: ok=%d\n", count, ok); std::fprintf(stderr, "%d entries compared: ok=%d\n", count, ok);
delete miter; delete miter;
delete dbiter; delete dbiter;
return ok; return ok;
@ -2173,7 +2174,7 @@ TEST_F(DBTest, Randomized) {
std::string k, v; std::string k, v;
for (int step = 0; step < N; step++) { for (int step = 0; step < N; step++) {
if (step % 100 == 0) { if (step % 100 == 0) {
fprintf(stderr, "Step %d of %d\n", step, N); std::fprintf(stderr, "Step %d of %d\n", step, N);
} }
// TODO(sanjay): Test Get() works // TODO(sanjay): Test Get() works
int p = rnd.Uniform(100); int p = rnd.Uniform(100);
@ -2233,7 +2234,7 @@ TEST_F(DBTest, Randomized) {
std::string MakeKey(unsigned int num) { std::string MakeKey(unsigned int num) {
char buf[30]; char buf[30];
snprintf(buf, sizeof(buf), "%016u", num); std::snprintf(buf, sizeof(buf), "%016u", num);
return std::string(buf); return std::string(buf);
} }
@ -2283,10 +2284,10 @@ void BM_LogAndApply(int iters, int num_base_files) {
uint64_t stop_micros = env->NowMicros(); uint64_t stop_micros = env->NowMicros();
unsigned int us = stop_micros - start_micros; unsigned int us = stop_micros - start_micros;
char buf[16]; char buf[16];
snprintf(buf, sizeof(buf), "%d", num_base_files); std::snprintf(buf, sizeof(buf), "%d", num_base_files);
fprintf(stderr, std::fprintf(stderr,
"BM_LogAndApply/%-6s %8d iters : %9u us (%7.0f us / iter)\n", buf, "BM_LogAndApply/%-6s %8d iters : %9u us (%7.0f us / iter)\n",
iters, us, ((float)us) / iters); buf, iters, us, ((float)us) / iters);
} }
} // namespace leveldb } // namespace leveldb

View File

@ -126,7 +126,7 @@ LookupKey::LookupKey(const Slice& user_key, SequenceNumber s) {
start_ = dst; start_ = dst;
dst = EncodeVarint32(dst, usize + 8); dst = EncodeVarint32(dst, usize + 8);
kstart_ = dst; kstart_ = dst;
memcpy(dst, user_key.data(), usize); std::memcpy(dst, user_key.data(), usize);
dst += usize; dst += usize;
EncodeFixed64(dst, PackSequenceAndType(s, kValueTypeForSeek)); EncodeFixed64(dst, PackSequenceAndType(s, kValueTypeForSeek));
dst += 8; dst += 8;

View File

@ -427,7 +427,7 @@ class FaultInjectionTest : public testing::Test {
EXPECT_EQ(value_space, val); EXPECT_EQ(value_space, val);
} }
} else if (s.ok()) { } else if (s.ok()) {
fprintf(stderr, "Expected an error at %d, but was OK\n", i); std::fprintf(stderr, "Expected an error at %d, but was OK\n", i);
s = Status::IOError(dbname_, "Expected value error:"); s = Status::IOError(dbname_, "Expected value error:");
} else { } else {
s = Status::OK(); // An expected error s = Status::OK(); // An expected error
@ -439,7 +439,7 @@ class FaultInjectionTest : public testing::Test {
// Return the ith key // Return the ith key
Slice Key(int i, std::string* storage) const { Slice Key(int i, std::string* storage) const {
char buf[100]; char buf[100];
snprintf(buf, sizeof(buf), "%016d", i); std::snprintf(buf, sizeof(buf), "%016d", i);
storage->assign(buf, strlen(buf)); storage->assign(buf, strlen(buf));
return Slice(*storage); return Slice(*storage);
} }

View File

@ -20,8 +20,8 @@ Status WriteStringToFileSync(Env* env, const Slice& data,
static std::string MakeFileName(const std::string& dbname, uint64_t number, static std::string MakeFileName(const std::string& dbname, uint64_t number,
const char* suffix) { const char* suffix) {
char buf[100]; char buf[100];
snprintf(buf, sizeof(buf), "/%06llu.%s", std::snprintf(buf, sizeof(buf), "/%06llu.%s",
static_cast<unsigned long long>(number), suffix); static_cast<unsigned long long>(number), suffix);
return dbname + buf; return dbname + buf;
} }
@ -43,8 +43,8 @@ std::string SSTTableFileName(const std::string& dbname, uint64_t number) {
std::string DescriptorFileName(const std::string& dbname, uint64_t number) { std::string DescriptorFileName(const std::string& dbname, uint64_t number) {
assert(number > 0); assert(number > 0);
char buf[100]; char buf[100];
snprintf(buf, sizeof(buf), "/MANIFEST-%06llu", std::snprintf(buf, sizeof(buf), "/MANIFEST-%06llu",
static_cast<unsigned long long>(number)); static_cast<unsigned long long>(number));
return dbname + buf; return dbname + buf;
} }

View File

@ -28,7 +28,7 @@ bool HandleDumpCommand(Env* env, char** files, int num) {
for (int i = 0; i < num; i++) { for (int i = 0; i < num; i++) {
Status s = DumpFile(env, files[i], &printer); Status s = DumpFile(env, files[i], &printer);
if (!s.ok()) { if (!s.ok()) {
fprintf(stderr, "%s\n", s.ToString().c_str()); std::fprintf(stderr, "%s\n", s.ToString().c_str());
ok = false; ok = false;
} }
} }
@ -39,9 +39,10 @@ bool HandleDumpCommand(Env* env, char** files, int num) {
} // namespace leveldb } // namespace leveldb
static void Usage() { static void Usage() {
fprintf(stderr, std::fprintf(
"Usage: leveldbutil command...\n" stderr,
" dump files... -- dump contents of specified files\n"); "Usage: leveldbutil command...\n"
" dump files... -- dump contents of specified files\n");
} }
int main(int argc, char** argv) { int main(int argc, char** argv) {

View File

@ -160,7 +160,7 @@ bool Reader::ReadRecord(Slice* record, std::string* scratch) {
default: { default: {
char buf[40]; char buf[40];
snprintf(buf, sizeof(buf), "unknown record type %u", record_type); std::snprintf(buf, sizeof(buf), "unknown record type %u", record_type);
ReportCorruption( ReportCorruption(
(fragment.size() + (in_fragmented_record ? scratch->size() : 0)), (fragment.size() + (in_fragmented_record ? scratch->size() : 0)),
buf); buf);

View File

@ -27,7 +27,7 @@ static std::string BigString(const std::string& partial_string, size_t n) {
// Construct a string from a number // Construct a string from a number
static std::string NumberString(int n) { static std::string NumberString(int n) {
char buf[50]; char buf[50];
snprintf(buf, sizeof(buf), "%d.", n); std::snprintf(buf, sizeof(buf), "%d.", n);
return std::string(buf); return std::string(buf);
} }

View File

@ -88,12 +88,12 @@ void MemTable::Add(SequenceNumber s, ValueType type, const Slice& key,
val_size; val_size;
char* buf = arena_.Allocate(encoded_len); char* buf = arena_.Allocate(encoded_len);
char* p = EncodeVarint32(buf, internal_key_size); char* p = EncodeVarint32(buf, internal_key_size);
memcpy(p, key.data(), key_size); std::memcpy(p, key.data(), key_size);
p += key_size; p += key_size;
EncodeFixed64(p, (s << 8) | type); EncodeFixed64(p, (s << 8) | type);
p += 8; p += 8;
p = EncodeVarint32(p, val_size); p = EncodeVarint32(p, val_size);
memcpy(p, value.data(), val_size); std::memcpy(p, value.data(), val_size);
assert(p + val_size == buf + encoded_len); assert(p + val_size == buf + encoded_len);
table_.Insert(buf); table_.Insert(buf);
} }

View File

@ -160,7 +160,8 @@ class RecoveryTest : public testing::Test {
TEST_F(RecoveryTest, ManifestReused) { TEST_F(RecoveryTest, ManifestReused) {
if (!CanAppend()) { if (!CanAppend()) {
fprintf(stderr, "skipping test because env does not support appending\n"); std::fprintf(stderr,
"skipping test because env does not support appending\n");
return; return;
} }
ASSERT_LEVELDB_OK(Put("foo", "bar")); ASSERT_LEVELDB_OK(Put("foo", "bar"));
@ -176,7 +177,8 @@ TEST_F(RecoveryTest, ManifestReused) {
TEST_F(RecoveryTest, LargeManifestCompacted) { TEST_F(RecoveryTest, LargeManifestCompacted) {
if (!CanAppend()) { if (!CanAppend()) {
fprintf(stderr, "skipping test because env does not support appending\n"); std::fprintf(stderr,
"skipping test because env does not support appending\n");
return; return;
} }
ASSERT_LEVELDB_OK(Put("foo", "bar")); ASSERT_LEVELDB_OK(Put("foo", "bar"));
@ -216,7 +218,8 @@ TEST_F(RecoveryTest, NoLogFiles) {
TEST_F(RecoveryTest, LogFileReuse) { TEST_F(RecoveryTest, LogFileReuse) {
if (!CanAppend()) { if (!CanAppend()) {
fprintf(stderr, "skipping test because env does not support appending\n"); std::fprintf(stderr,
"skipping test because env does not support appending\n");
return; return;
} }
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
@ -249,7 +252,7 @@ TEST_F(RecoveryTest, MultipleMemTables) {
const int kNum = 1000; const int kNum = 1000;
for (int i = 0; i < kNum; i++) { for (int i = 0; i < kNum; i++) {
char buf[100]; char buf[100];
snprintf(buf, sizeof(buf), "%050d", i); std::snprintf(buf, sizeof(buf), "%050d", i);
ASSERT_LEVELDB_OK(Put(buf, buf)); ASSERT_LEVELDB_OK(Put(buf, buf));
} }
ASSERT_EQ(0, NumTables()); ASSERT_EQ(0, NumTables());
@ -268,7 +271,7 @@ TEST_F(RecoveryTest, MultipleMemTables) {
ASSERT_NE(old_log_file, FirstLogFile()) << "must not reuse log"; ASSERT_NE(old_log_file, FirstLogFile()) << "must not reuse log";
for (int i = 0; i < kNum; i++) { for (int i = 0; i < kNum; i++) {
char buf[100]; char buf[100];
snprintf(buf, sizeof(buf), "%050d", i); std::snprintf(buf, sizeof(buf), "%050d", i);
ASSERT_EQ(buf, Get(buf)); ASSERT_EQ(buf, Get(buf));
} }
} }

View File

@ -372,7 +372,8 @@ class Repairer {
t.meta.largest); t.meta.largest);
} }
// fprintf(stderr, "NewDescriptor:\n%s\n", edit_.DebugString().c_str()); // std::fprintf(stderr,
// "NewDescriptor:\n%s\n", edit_.DebugString().c_str());
{ {
log::Writer log(file); log::Writer log(file);
std::string record; std::string record;

View File

@ -346,7 +346,7 @@ static void RunConcurrent(int run) {
const int kSize = 1000; const int kSize = 1000;
for (int i = 0; i < N; i++) { for (int i = 0; i < N; i++) {
if ((i % 100) == 0) { if ((i % 100) == 0) {
fprintf(stderr, "Run %d of %d\n", i, N); std::fprintf(stderr, "Run %d of %d\n", i, N);
} }
TestState state(seed + 1); TestState state(seed + 1);
Env::Default()->Schedule(ConcurrentReader, &state); Env::Default()->Schedule(ConcurrentReader, &state);

View File

@ -703,10 +703,10 @@ class VersionSet::Builder {
const InternalKey& prev_end = v->files_[level][i - 1]->largest; const InternalKey& prev_end = v->files_[level][i - 1]->largest;
const InternalKey& this_begin = v->files_[level][i]->smallest; const InternalKey& this_begin = v->files_[level][i]->smallest;
if (vset_->icmp_.Compare(prev_end, this_begin) >= 0) { if (vset_->icmp_.Compare(prev_end, this_begin) >= 0) {
fprintf(stderr, "overlapping ranges in same level %s vs. %s\n", std::fprintf(stderr, "overlapping ranges in same level %s vs. %s\n",
prev_end.DebugString().c_str(), prev_end.DebugString().c_str(),
this_begin.DebugString().c_str()); this_begin.DebugString().c_str());
abort(); std::abort();
} }
} }
} }
@ -1100,11 +1100,12 @@ int VersionSet::NumLevelFiles(int level) const {
const char* VersionSet::LevelSummary(LevelSummaryStorage* scratch) const { const char* VersionSet::LevelSummary(LevelSummaryStorage* scratch) const {
// Update code if kNumLevels changes // Update code if kNumLevels changes
static_assert(config::kNumLevels == 7, ""); static_assert(config::kNumLevels == 7, "");
snprintf(scratch->buffer, sizeof(scratch->buffer), std::snprintf(
"files[ %d %d %d %d %d %d %d ]", int(current_->files_[0].size()), scratch->buffer, sizeof(scratch->buffer), "files[ %d %d %d %d %d %d %d ]",
int(current_->files_[1].size()), int(current_->files_[2].size()), int(current_->files_[0].size()), int(current_->files_[1].size()),
int(current_->files_[3].size()), int(current_->files_[4].size()), int(current_->files_[2].size()), int(current_->files_[3].size()),
int(current_->files_[5].size()), int(current_->files_[6].size())); int(current_->files_[4].size()), int(current_->files_[5].size()),
int(current_->files_[6].size()));
return scratch->buffer; return scratch->buffer;
} }

View File

@ -93,7 +93,7 @@ class FileState {
if (avail > bytes_to_copy) { if (avail > bytes_to_copy) {
avail = bytes_to_copy; avail = bytes_to_copy;
} }
memcpy(dst, blocks_[block] + block_offset, avail); std::memcpy(dst, blocks_[block] + block_offset, avail);
bytes_to_copy -= avail; bytes_to_copy -= avail;
dst += avail; dst += avail;
@ -126,7 +126,7 @@ class FileState {
if (avail > src_len) { if (avail > src_len) {
avail = src_len; avail = src_len;
} }
memcpy(blocks_.back() + offset, src, avail); std::memcpy(blocks_.back() + offset, src, avail);
src_len -= avail; src_len -= avail;
src += avail; src += avail;
size_ += avail; size_ += avail;
@ -215,7 +215,7 @@ class WritableFileImpl : public WritableFile {
class NoOpLogger : public Logger { class NoOpLogger : public Logger {
public: public:
void Logv(const char* format, va_list ap) override {} void Logv(const char* format, std::va_list ap) override {}
}; };
class InMemoryEnv : public EnvWrapper { class InMemoryEnv : public EnvWrapper {

View File

@ -300,7 +300,7 @@ class LEVELDB_EXPORT Logger {
virtual ~Logger(); virtual ~Logger();
// Write an entry to the log file with the specified format. // Write an entry to the log file with the specified format.
virtual void Logv(const char* format, va_list ap) = 0; virtual void Logv(const char* format, std::va_list ap) = 0;
}; };
// Identifies a locked file. // Identifies a locked file.

View File

@ -18,7 +18,7 @@ const int kNumKeys = 1100000;
std::string Key1(int i) { std::string Key1(int i) {
char buf[100]; char buf[100];
snprintf(buf, sizeof(buf), "my_key_%d", i); std::snprintf(buf, sizeof(buf), "my_key_%d", i);
return buf; return buf;
} }

View File

@ -123,7 +123,7 @@ class StringSource : public RandomAccessFile {
if (offset + n > contents_.size()) { if (offset + n > contents_.size()) {
n = contents_.size() - offset; n = contents_.size() - offset;
} }
memcpy(scratch, &contents_[offset], n); std::memcpy(scratch, &contents_[offset], n);
*result = Slice(scratch, n); *result = Slice(scratch, n);
return Status::OK(); return Status::OK();
} }
@ -485,13 +485,13 @@ class Harness : public testing::Test {
Iterator* iter = constructor_->NewIterator(); Iterator* iter = constructor_->NewIterator();
ASSERT_TRUE(!iter->Valid()); ASSERT_TRUE(!iter->Valid());
KVMap::const_iterator model_iter = data.begin(); KVMap::const_iterator model_iter = data.begin();
if (kVerbose) fprintf(stderr, "---\n"); if (kVerbose) std::fprintf(stderr, "---\n");
for (int i = 0; i < 200; i++) { for (int i = 0; i < 200; i++) {
const int toss = rnd->Uniform(5); const int toss = rnd->Uniform(5);
switch (toss) { switch (toss) {
case 0: { case 0: {
if (iter->Valid()) { if (iter->Valid()) {
if (kVerbose) fprintf(stderr, "Next\n"); if (kVerbose) std::fprintf(stderr, "Next\n");
iter->Next(); iter->Next();
++model_iter; ++model_iter;
ASSERT_EQ(ToString(data, model_iter), ToString(iter)); ASSERT_EQ(ToString(data, model_iter), ToString(iter));
@ -500,7 +500,7 @@ class Harness : public testing::Test {
} }
case 1: { case 1: {
if (kVerbose) fprintf(stderr, "SeekToFirst\n"); if (kVerbose) std::fprintf(stderr, "SeekToFirst\n");
iter->SeekToFirst(); iter->SeekToFirst();
model_iter = data.begin(); model_iter = data.begin();
ASSERT_EQ(ToString(data, model_iter), ToString(iter)); ASSERT_EQ(ToString(data, model_iter), ToString(iter));
@ -511,7 +511,7 @@ class Harness : public testing::Test {
std::string key = PickRandomKey(rnd, keys); std::string key = PickRandomKey(rnd, keys);
model_iter = data.lower_bound(key); model_iter = data.lower_bound(key);
if (kVerbose) if (kVerbose)
fprintf(stderr, "Seek '%s'\n", EscapeString(key).c_str()); std::fprintf(stderr, "Seek '%s'\n", EscapeString(key).c_str());
iter->Seek(Slice(key)); iter->Seek(Slice(key));
ASSERT_EQ(ToString(data, model_iter), ToString(iter)); ASSERT_EQ(ToString(data, model_iter), ToString(iter));
break; break;
@ -519,7 +519,7 @@ class Harness : public testing::Test {
case 3: { case 3: {
if (iter->Valid()) { if (iter->Valid()) {
if (kVerbose) fprintf(stderr, "Prev\n"); if (kVerbose) std::fprintf(stderr, "Prev\n");
iter->Prev(); iter->Prev();
if (model_iter == data.begin()) { if (model_iter == data.begin()) {
model_iter = data.end(); // Wrap around to invalid value model_iter = data.end(); // Wrap around to invalid value
@ -532,7 +532,7 @@ class Harness : public testing::Test {
} }
case 4: { case 4: {
if (kVerbose) fprintf(stderr, "SeekToLast\n"); if (kVerbose) std::fprintf(stderr, "SeekToLast\n");
iter->SeekToLast(); iter->SeekToLast();
if (keys.empty()) { if (keys.empty()) {
model_iter = data.end(); model_iter = data.end();
@ -684,8 +684,8 @@ TEST_F(Harness, Randomized) {
for (int num_entries = 0; num_entries < 2000; for (int num_entries = 0; num_entries < 2000;
num_entries += (num_entries < 50 ? 1 : 200)) { num_entries += (num_entries < 50 ? 1 : 200)) {
if ((num_entries % 10) == 0) { if ((num_entries % 10) == 0) {
fprintf(stderr, "case %d of %d: num_entries = %d\n", (i + 1), std::fprintf(stderr, "case %d of %d: num_entries = %d\n", (i + 1),
int(kNumTestArgs), num_entries); int(kNumTestArgs), num_entries);
} }
for (int e = 0; e < num_entries; e++) { for (int e = 0; e < num_entries; e++) {
std::string v; std::string v;
@ -714,7 +714,7 @@ TEST_F(Harness, RandomizedLongDB) {
for (int level = 0; level < config::kNumLevels; level++) { for (int level = 0; level < config::kNumLevels; level++) {
std::string value; std::string value;
char name[100]; char name[100];
snprintf(name, sizeof(name), "leveldb.num-files-at-level%d", level); std::snprintf(name, sizeof(name), "leveldb.num-files-at-level%d", level);
ASSERT_TRUE(db()->GetProperty(name, &value)); ASSERT_TRUE(db()->GetProperty(name, &value));
files += atoi(value.c_str()); files += atoi(value.c_str());
} }
@ -736,8 +736,8 @@ TEST(MemTableTest, Simple) {
Iterator* iter = memtable->NewIterator(); Iterator* iter = memtable->NewIterator();
iter->SeekToFirst(); iter->SeekToFirst();
while (iter->Valid()) { while (iter->Valid()) {
fprintf(stderr, "key: '%s' -> '%s'\n", iter->key().ToString().c_str(), std::fprintf(stderr, "key: '%s' -> '%s'\n", iter->key().ToString().c_str(),
iter->value().ToString().c_str()); iter->value().ToString().c_str());
iter->Next(); iter->Next();
} }
@ -748,9 +748,9 @@ TEST(MemTableTest, Simple) {
static bool Between(uint64_t val, uint64_t low, uint64_t high) { static bool Between(uint64_t val, uint64_t low, uint64_t high) {
bool result = (val >= low) && (val <= high); bool result = (val >= low) && (val <= high);
if (!result) { if (!result) {
fprintf(stderr, "Value %llu is not in range [%llu, %llu]\n", std::fprintf(stderr, "Value %llu is not in range [%llu, %llu]\n",
(unsigned long long)(val), (unsigned long long)(low), (unsigned long long)(val), (unsigned long long)(low),
(unsigned long long)(high)); (unsigned long long)(high));
} }
return result; return result;
} }
@ -792,7 +792,7 @@ static bool SnappyCompressionSupported() {
TEST(TableTest, ApproximateOffsetOfCompressed) { TEST(TableTest, ApproximateOffsetOfCompressed) {
if (!SnappyCompressionSupported()) { if (!SnappyCompressionSupported()) {
fprintf(stderr, "skipping compression tests\n"); std::fprintf(stderr, "skipping compression tests\n");
return; return;
} }

View File

@ -45,14 +45,14 @@ class BloomTest : public testing::Test {
size_t FilterSize() const { return filter_.size(); } size_t FilterSize() const { return filter_.size(); }
void DumpFilter() { void DumpFilter() {
fprintf(stderr, "F("); std::fprintf(stderr, "F(");
for (size_t i = 0; i + 1 < filter_.size(); i++) { for (size_t i = 0; i + 1 < filter_.size(); i++) {
const unsigned int c = static_cast<unsigned int>(filter_[i]); const unsigned int c = static_cast<unsigned int>(filter_[i]);
for (int j = 0; j < 8; j++) { for (int j = 0; j < 8; j++) {
fprintf(stderr, "%c", (c & (1 << j)) ? '1' : '.'); std::fprintf(stderr, "%c", (c & (1 << j)) ? '1' : '.');
} }
} }
fprintf(stderr, ")\n"); std::fprintf(stderr, ")\n");
} }
bool Matches(const Slice& s) { bool Matches(const Slice& s) {
@ -132,8 +132,9 @@ TEST_F(BloomTest, VaryingLengths) {
// Check false positive rate // Check false positive rate
double rate = FalsePositiveRate(); double rate = FalsePositiveRate();
if (kVerbose >= 1) { if (kVerbose >= 1) {
fprintf(stderr, "False positives: %5.2f%% @ length = %6d ; bytes = %6d\n", std::fprintf(stderr,
rate * 100.0, length, static_cast<int>(FilterSize())); "False positives: %5.2f%% @ length = %6d ; bytes = %6d\n",
rate * 100.0, length, static_cast<int>(FilterSize()));
} }
ASSERT_LE(rate, 0.02); // Must not be over 2% ASSERT_LE(rate, 0.02); // Must not be over 2%
if (rate > 0.0125) if (rate > 0.0125)
@ -142,8 +143,8 @@ TEST_F(BloomTest, VaryingLengths) {
good_filters++; good_filters++;
} }
if (kVerbose >= 1) { if (kVerbose >= 1) {
fprintf(stderr, "Filters: %d good, %d mediocre\n", good_filters, std::fprintf(stderr, "Filters: %d good, %d mediocre\n", good_filters,
mediocre_filters); mediocre_filters);
} }
ASSERT_LE(mediocre_filters, good_filters / 5); ASSERT_LE(mediocre_filters, good_filters / 5);
} }

View File

@ -279,7 +279,7 @@ Cache::Handle* LRUCache::Insert(const Slice& key, uint32_t hash, void* value,
e->hash = hash; e->hash = hash;
e->in_cache = false; e->in_cache = false;
e->refs = 1; // for the returned handle. e->refs = 1; // for the returned handle.
memcpy(e->key_data, key.data(), key.size()); std::memcpy(e->key_data, key.data(), key.size());
if (capacity_ > 0) { if (capacity_ > 0) {
e->refs++; // for the cache's reference. e->refs++; // for the cache's reference.

View File

@ -4,6 +4,8 @@
#include "leveldb/env.h" #include "leveldb/env.h"
#include <cstdarg>
// This workaround can be removed when leveldb::Env::DeleteFile is removed. // This workaround can be removed when leveldb::Env::DeleteFile is removed.
// See env.h for justification. // See env.h for justification.
#if defined(_WIN32) && defined(LEVELDB_DELETEFILE_UNDEFINED) #if defined(_WIN32) && defined(LEVELDB_DELETEFILE_UNDEFINED)
@ -38,7 +40,7 @@ FileLock::~FileLock() = default;
void Log(Logger* info_log, const char* format, ...) { void Log(Logger* info_log, const char* format, ...) {
if (info_log != nullptr) { if (info_log != nullptr) {
va_list ap; std::va_list ap;
va_start(ap, format); va_start(ap, format);
info_log->Logv(format, ap); info_log->Logv(format, ap);
va_end(ap); va_end(ap);

View File

@ -149,7 +149,7 @@ void CheckCloseOnExecDoesNotLeakFDs(
if (child_pid == kForkInChildProcessReturnValue) { if (child_pid == kForkInChildProcessReturnValue) {
::execv(child_argv[0], child_argv); ::execv(child_argv[0], child_argv);
std::fprintf(stderr, "Error spawning child process: %s\n", strerror(errno)); std::fprintf(stderr, "Error spawning child process: %s\n", strerror(errno));
std::exit(kTextCloseOnExecHelperExecFailedCode); std::std::exit(kTextCloseOnExecHelperExecFailedCode);
} }
int child_status = 0; int child_status = 0;
@ -187,11 +187,11 @@ TEST_F(EnvPosixTest, TestOpenOnRead) {
ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir)); ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir));
std::string test_file = test_dir + "/open_on_read.txt"; std::string test_file = test_dir + "/open_on_read.txt";
FILE* f = fopen(test_file.c_str(), "we"); FILE* f = std::fopen(test_file.c_str(), "we");
ASSERT_TRUE(f != nullptr); ASSERT_TRUE(f != nullptr);
const char kFileData[] = "abcdefghijklmnopqrstuvwxyz"; const char kFileData[] = "abcdefghijklmnopqrstuvwxyz";
fputs(kFileData, f); fputs(kFileData, f);
fclose(f); std::fclose(f);
// Open test file some number above the sum of the two limits to force // Open test file some number above the sum of the two limits to force
// open-on-read behavior of POSIX Env leveldb::RandomAccessFile. // open-on-read behavior of POSIX Env leveldb::RandomAccessFile.

View File

@ -29,11 +29,11 @@ TEST_F(EnvWindowsTest, TestOpenOnRead) {
ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir)); ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir));
std::string test_file = test_dir + "/open_on_read.txt"; std::string test_file = test_dir + "/open_on_read.txt";
FILE* f = fopen(test_file.c_str(), "w"); FILE* f = std::fopen(test_file.c_str(), "w");
ASSERT_TRUE(f != nullptr); ASSERT_TRUE(f != nullptr);
const char kFileData[] = "abcdefghijklmnopqrstuvwxyz"; const char kFileData[] = "abcdefghijklmnopqrstuvwxyz";
fputs(kFileData, f); fputs(kFileData, f);
fclose(f); std::fclose(f);
// Open test file some number above the sum of the two limits to force // Open test file some number above the sum of the two limits to force
// leveldb::WindowsEnv to switch from mapping the file into memory // leveldb::WindowsEnv to switch from mapping the file into memory

View File

@ -241,11 +241,11 @@ double Histogram::StandardDeviation() const {
std::string Histogram::ToString() const { std::string Histogram::ToString() const {
std::string r; std::string r;
char buf[200]; char buf[200];
snprintf(buf, sizeof(buf), "Count: %.0f Average: %.4f StdDev: %.2f\n", num_, std::snprintf(buf, sizeof(buf), "Count: %.0f Average: %.4f StdDev: %.2f\n",
Average(), StandardDeviation()); num_, Average(), StandardDeviation());
r.append(buf); r.append(buf);
snprintf(buf, sizeof(buf), "Min: %.4f Median: %.4f Max: %.4f\n", std::snprintf(buf, sizeof(buf), "Min: %.4f Median: %.4f Max: %.4f\n",
(num_ == 0.0 ? 0.0 : min_), Median(), max_); (num_ == 0.0 ? 0.0 : min_), Median(), max_);
r.append(buf); r.append(buf);
r.append("------------------------------------------------------\n"); r.append("------------------------------------------------------\n");
const double mult = 100.0 / num_; const double mult = 100.0 / num_;
@ -253,12 +253,12 @@ std::string Histogram::ToString() const {
for (int b = 0; b < kNumBuckets; b++) { for (int b = 0; b < kNumBuckets; b++) {
if (buckets_[b] <= 0.0) continue; if (buckets_[b] <= 0.0) continue;
sum += buckets_[b]; sum += buckets_[b];
snprintf(buf, sizeof(buf), "[ %7.0f, %7.0f ) %7.0f %7.3f%% %7.3f%% ", std::snprintf(buf, sizeof(buf), "[ %7.0f, %7.0f ) %7.0f %7.3f%% %7.3f%% ",
((b == 0) ? 0.0 : kBucketLimit[b - 1]), // left ((b == 0) ? 0.0 : kBucketLimit[b - 1]), // left
kBucketLimit[b], // right kBucketLimit[b], // right
buckets_[b], // count buckets_[b], // count
mult * buckets_[b], // percentage mult * buckets_[b], // percentage
mult * sum); // cumulative percentage mult * sum); // cumulative percentage
r.append(buf); r.append(buf);
// Add hash marks based on percentage; 20 marks for 100%. // Add hash marks based on percentage; 20 marks for 100%.

View File

@ -16,7 +16,7 @@ namespace leveldb {
void AppendNumberTo(std::string* str, uint64_t num) { void AppendNumberTo(std::string* str, uint64_t num) {
char buf[30]; char buf[30];
snprintf(buf, sizeof(buf), "%llu", (unsigned long long)num); std::snprintf(buf, sizeof(buf), "%llu", static_cast<unsigned long long>(num));
str->append(buf); str->append(buf);
} }
@ -27,8 +27,8 @@ void AppendEscapedStringTo(std::string* str, const Slice& value) {
str->push_back(c); str->push_back(c);
} else { } else {
char buf[10]; char buf[10];
snprintf(buf, sizeof(buf), "\\x%02x", std::snprintf(buf, sizeof(buf), "\\x%02x",
static_cast<unsigned int>(c) & 0xff); static_cast<unsigned int>(c) & 0xff);
str->append(buf); str->append(buf);
} }
} }

View File

@ -30,7 +30,7 @@ class PosixLogger final : public Logger {
~PosixLogger() override { std::fclose(fp_); } ~PosixLogger() override { std::fclose(fp_); }
void Logv(const char* format, va_list arguments) override { void Logv(const char* format, std::va_list arguments) override {
// Record the time as close to the Logv() call as possible. // Record the time as close to the Logv() call as possible.
struct ::timeval now_timeval; struct ::timeval now_timeval;
::gettimeofday(&now_timeval, nullptr); ::gettimeofday(&now_timeval, nullptr);
@ -62,7 +62,7 @@ class PosixLogger final : public Logger {
(iteration == 0) ? stack_buffer : new char[dynamic_buffer_size]; (iteration == 0) ? stack_buffer : new char[dynamic_buffer_size];
// Print the header into the buffer. // Print the header into the buffer.
int buffer_offset = snprintf( int buffer_offset = std::snprintf(
buffer, buffer_size, "%04d/%02d/%02d-%02d:%02d:%02d.%06d %s ", buffer, buffer_size, "%04d/%02d/%02d-%02d:%02d:%02d.%06d %s ",
now_components.tm_year + 1900, now_components.tm_mon + 1, now_components.tm_year + 1900, now_components.tm_mon + 1,
now_components.tm_mday, now_components.tm_hour, now_components.tm_min, now_components.tm_mday, now_components.tm_hour, now_components.tm_min,
@ -98,8 +98,8 @@ class PosixLogger final : public Logger {
} }
// The dynamically-allocated buffer was incorrectly sized. This should // The dynamically-allocated buffer was incorrectly sized. This should
// not happen, assuming a correct implementation of (v)snprintf. Fail // not happen, assuming a correct implementation of std::(v)snprintf.
// in tests, recover by truncating the log message in production. // Fail in tests, recover by truncating the log message in production.
assert(false); assert(false);
buffer_offset = buffer_size - 1; buffer_offset = buffer_size - 1;
} }

View File

@ -12,9 +12,9 @@ namespace leveldb {
const char* Status::CopyState(const char* state) { const char* Status::CopyState(const char* state) {
uint32_t size; uint32_t size;
memcpy(&size, state, sizeof(size)); std::memcpy(&size, state, sizeof(size));
char* result = new char[size + 5]; char* result = new char[size + 5];
memcpy(result, state, size + 5); std::memcpy(result, state, size + 5);
return result; return result;
} }
@ -24,13 +24,13 @@ Status::Status(Code code, const Slice& msg, const Slice& msg2) {
const uint32_t len2 = static_cast<uint32_t>(msg2.size()); const uint32_t len2 = static_cast<uint32_t>(msg2.size());
const uint32_t size = len1 + (len2 ? (2 + len2) : 0); const uint32_t size = len1 + (len2 ? (2 + len2) : 0);
char* result = new char[size + 5]; char* result = new char[size + 5];
memcpy(result, &size, sizeof(size)); std::memcpy(result, &size, sizeof(size));
result[4] = static_cast<char>(code); result[4] = static_cast<char>(code);
memcpy(result + 5, msg.data(), len1); std::memcpy(result + 5, msg.data(), len1);
if (len2) { if (len2) {
result[5 + len1] = ':'; result[5 + len1] = ':';
result[6 + len1] = ' '; result[6 + len1] = ' ';
memcpy(result + 7 + len1, msg2.data(), len2); std::memcpy(result + 7 + len1, msg2.data(), len2);
} }
state_ = result; state_ = result;
} }
@ -61,14 +61,14 @@ std::string Status::ToString() const {
type = "IO error: "; type = "IO error: ";
break; break;
default: default:
snprintf(tmp, sizeof(tmp), std::snprintf(tmp, sizeof(tmp),
"Unknown code(%d): ", static_cast<int>(code())); "Unknown code(%d): ", static_cast<int>(code()));
type = tmp; type = tmp;
break; break;
} }
std::string result(type); std::string result(type);
uint32_t length; uint32_t length;
memcpy(&length, state_, sizeof(length)); std::memcpy(&length, state_, sizeof(length));
result.append(state_ + 5, length); result.append(state_ + 5, length);
return result; return result;
} }

View File

@ -27,7 +27,7 @@ class WindowsLogger final : public Logger {
~WindowsLogger() override { std::fclose(fp_); } ~WindowsLogger() override { std::fclose(fp_); }
void Logv(const char* format, va_list arguments) override { void Logv(const char* format, std::va_list arguments) override {
// Record the time as close to the Logv() call as possible. // Record the time as close to the Logv() call as possible.
SYSTEMTIME now_components; SYSTEMTIME now_components;
::GetLocalTime(&now_components); ::GetLocalTime(&now_components);
@ -56,7 +56,7 @@ class WindowsLogger final : public Logger {
(iteration == 0) ? stack_buffer : new char[dynamic_buffer_size]; (iteration == 0) ? stack_buffer : new char[dynamic_buffer_size];
// Print the header into the buffer. // Print the header into the buffer.
int buffer_offset = snprintf( int buffer_offset = std::snprintf(
buffer, buffer_size, "%04d/%02d/%02d-%02d:%02d:%02d.%06d %s ", buffer, buffer_size, "%04d/%02d/%02d-%02d:%02d:%02d.%06d %s ",
now_components.wYear, now_components.wMonth, now_components.wDay, now_components.wYear, now_components.wMonth, now_components.wDay,
now_components.wHour, now_components.wMinute, now_components.wSecond, now_components.wHour, now_components.wMinute, now_components.wSecond,
@ -92,8 +92,8 @@ class WindowsLogger final : public Logger {
} }
// The dynamically-allocated buffer was incorrectly sized. This should // The dynamically-allocated buffer was incorrectly sized. This should
// not happen, assuming a correct implementation of (v)snprintf. Fail // not happen, assuming a correct implementation of std::(v)snprintf.
// in tests, recover by truncating the log message in production. // Fail in tests, recover by truncating the log message in production.
assert(false); assert(false);
buffer_offset = buffer_size - 1; buffer_offset = buffer_size - 1;
} }