Files
scylladb/utils/pretty_printers.cc
Kefu Chai 567b453689 utils: avoid using out-of-range index in pretty_printers
before this change, if the formatter size is greater than a pettabyte,
`exp` would be 6. but we still use it as the index to find the suffix
in `suffixes`, but the array's size is 6. so we would be referencing
random bits after "PB" for the suffix of the formatted size.

in this change

* loop in the suffix for better readability. and to avoid
  the off-by-one errors.
* add tests for both pretty printers

Branches: 5.1,5.2,5.3
Fixes #14702
Signed-off-by: Kefu Chai <kefu.chai@scylladb.com>

Closes #14713
2023-07-16 18:46:09 +03:00

37 lines
865 B
C++

/*
* Copyright (C) 2023-present ScyllaDB
*/
/*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#include "pretty_printers.hh"
namespace utils {
std::ostream& operator<<(std::ostream& os, pretty_printed_data_size data) {
static constexpr const char * suffixes[] = {" bytes", "kB", "MB", "GB", "TB", "PB"};
const char* suffix = nullptr;
uint64_t size = data._size;
uint64_t next_size = size;
for (auto s : suffixes) {
suffix = s;
size = next_size;
next_size = size / 1000;
if (next_size == 0) {
break;
}
}
return os << size << suffix;
}
std::ostream& operator<<(std::ostream& os, pretty_printed_throughput tp) {
uint64_t throughput = tp._duration.count() > 0 ? tp._size / tp._duration.count() : 0;
os << pretty_printed_data_size(throughput) << "/s";
return os;
}
}