Commit f10944b0 authored by captainwong's avatar captainwong

update human_readble_byte_count algo

parent 0759f146
#pragma once #pragma once
#include <string> #include <string>
#include <cmath>
#include <iomanip>
#include <sstream>
namespace jlib { namespace jlib {
static std::string format_space(uintmax_t bytes) enum PositionalNotation {
{ //! Used for memory size or Microsoft disk space
static constexpr uintmax_t FACTOR = 1024; Binary,
static constexpr uintmax_t KB = FACTOR; //! Usually used by Disk Space
static constexpr uintmax_t MB = KB * FACTOR; Decimal,
static constexpr uintmax_t GB = MB * FACTOR; };
static constexpr uintmax_t TB = GB * FACTOR;
uintmax_t kb = bytes / FACTOR; /**
uintmax_t mb = kb / FACTOR; * @brief Format byte count to human readable string
uintmax_t gb = mb / FACTOR; * @note bytes must less than 1DB(DoggaByte)
uintmax_t tb = gb / FACTOR; */
static std::string human_readable_byte_count(uintmax_t bytes, PositionalNotation po = PositionalNotation::Binary)
{
// http://programming.guide/java/formatting-byte-size-to-human-readable-format.html
std::string s; auto unit = po == PositionalNotation::Binary ? 1024 : 1000;
if (tb > 0) { if (bytes < unit) { return std::to_string(bytes) + "B"; }
gb -= tb * FACTOR; auto exp = static_cast<int>(std::log(bytes) / std::log(unit));
gb = gb * 1000 / FACTOR; auto pre = std::string("KMGTPEZYBND").at(exp - 1) + std::string(po == PositionalNotation::Binary ? "i" : "");
gb /= 10; auto var = bytes / std::pow(unit, exp);
return std::to_string(tb) + "." + std::to_string(gb) + "T"; std::stringstream ss;
} else if (gb > 0) { ss << std::fixed << std::setprecision(1) << var << pre << "B";
mb -= gb * FACTOR; return ss.str();
mb = mb * 1000 / FACTOR;
mb /= 10;
return std::to_string(gb) + "." + std::to_string(mb) + "G";
} else if (mb > 0) {
kb -= mb * FACTOR;
kb = kb * 1000 / FACTOR;
kb /= 10;
return std::to_string(mb) + "." + std::to_string(kb) + "M";
} else if (kb > 0) {
bytes -= kb * FACTOR;
bytes = bytes * 1000 / FACTOR;
bytes /= 10;
return std::to_string(kb) + "." + std::to_string(bytes) + "K";
} else {
return std::to_string(bytes) + "B";
}
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment