#include "traffic.h" #include #include namespace roro::net { namespace { constexpr size_t kUsers = static_cast(User::Count); std::atomic in_[kUsers], out_[kUsers]; } // namespace const char* userName(User user) { switch (user) { case User::Irc: return "IRC"; case User::Gemini: return "Gemini"; case User::DebugConsole: return "Debug Console"; case User::Updates: return "Updates"; default: return "?"; } } void received(User user, size_t bytes) { in_[static_cast(user)] += static_cast(bytes); } void sent(User user, size_t bytes) { out_[static_cast(user)] += static_cast(bytes); } Traffic traffic(User user) { return {in_[static_cast(user)], out_[static_cast(user)]}; } void resetTraffic() { for (size_t i = 0; i < kUsers; i++) in_[i] = out_[i] = 0; } uint32_t bytesPerSecond(uint32_t before, uint32_t now, uint32_t elapsedMs) { if (!elapsedMs) return 0; return static_cast(static_cast(now - before) * 1000 / elapsedMs); // wraps with the counter } std::string formatTraffic(uint32_t bytes) { char s[16]; if (bytes < 1000) std::snprintf(s, sizeof s, "%u B", static_cast(bytes)); else if (bytes < 10 * 1024) std::snprintf(s, sizeof s, "%.1f KB", bytes / 1024.0); else if (bytes < 1000 * 1024) std::snprintf(s, sizeof s, "%u KB", static_cast(bytes / 1024)); else if (bytes < 10u * 1024 * 1024) std::snprintf(s, sizeof s, "%.1f MB", bytes / 1048576.0); else std::snprintf(s, sizeof s, "%u MB", static_cast(bytes / 1048576)); return s; } } // namespace roro::net