Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Assorted minor optimizations #931

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
17 changes: 9 additions & 8 deletions src/btop_config.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -581,12 +581,12 @@ namespace Config {
}

string getAsString(const std::string_view name) {
if (bools.contains(name))
return (bools.at(name) ? "True" : "False");
else if (ints.contains(name))
return to_string(ints.at(name));
else if (strings.contains(name))
return strings.at(name);
if (auto it = bools.find(name); it != bools.end())
return it->second ? "True" : "False";
if (auto it = ints.find(name); it != ints.end())
return to_string(it->second);
if (auto it = strings.find(name); it != strings.end())
return it->second;
return "";
}

Expand Down Expand Up @@ -689,7 +689,8 @@ namespace Config {
std::ifstream cread(conf_file);
if (cread.good()) {
vector<string> valid_names;
for (auto &n : descriptions)
valid_names.reserve(descriptions.size());
for (const auto &n : descriptions)
valid_names.push_back(n[0]);
if (string v_string; cread.peek() != '#' or (getline(cread, v_string, '\n') and not s_contains(v_string, Global::Version)))
write_new = true;
Expand Down Expand Up @@ -752,7 +753,7 @@ namespace Config {
std::ofstream cwrite(conf_file, std::ios::trunc);
if (cwrite.good()) {
cwrite << "#? Config file for btop v. " << Global::Version << "\n";
for (auto [name, description] : descriptions) {
for (const auto& [name, description] : descriptions) {
cwrite << "\n" << (description.empty() ? "" : description + "\n")
<< name << " = ";
if (strings.contains(name))
Expand Down
6 changes: 3 additions & 3 deletions src/btop_draw.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1866,10 +1866,10 @@ namespace Proc {
width_left -= (ulen(p.name) + 1);
}
if (width_left > 7) {
const string& cmd = width_left > 40 ? rtrim(p.cmd) : p.short_cmd;
const string_view cmd = width_left > 40 ? rtrim(p.cmd) : p.short_cmd;
if (not cmd.empty() and cmd != p.name) {
out += g_color + '(' + uresize(cmd, width_left - 3, p_wide_cmd[p.pid]) + ") ";
width_left -= (ulen(cmd, true) + 3);
out += g_color + '(' + uresize(string{cmd}, width_left - 3, p_wide_cmd[p.pid]) + ") ";
width_left -= (ulen(string{cmd}, true) + 3);
}
}
out += string(max(0, width_left), ' ') + Mv::to(y+2+lc, x+2+tree_size);
Expand Down
4 changes: 2 additions & 2 deletions src/btop_input.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,8 @@ namespace Input {
}

}
else if (Key_escapes.contains(key))
key = Key_escapes.at(key);
else if (auto it = Key_escapes.find(key); it != Key_escapes.end())
key = it->second;
else if (ulen(key) > 1)
key.clear();

Expand Down
14 changes: 7 additions & 7 deletions src/btop_menu.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -787,7 +787,7 @@ namespace Menu {
};

msgBox::msgBox() {}
msgBox::msgBox(int width, int boxtype, vector<string> content, string title)
msgBox::msgBox(int width, int boxtype, const vector<string>& content, string title)
: width(width), boxtype(boxtype) {
auto tty_mode = Config::getB("tty_mode");
auto rounded = Config::getB("rounded_corners");
Expand Down Expand Up @@ -867,8 +867,8 @@ namespace Menu {
button_left.shrink_to_fit();
button_right.clear();
button_right.shrink_to_fit();
if (mouse_mappings.contains("button1")) mouse_mappings.erase("button1");
if (mouse_mappings.contains("button2")) mouse_mappings.erase("button2");
mouse_mappings.erase("button1");
mouse_mappings.erase("button2");
}

enum menuReturnCodes {
Expand Down Expand Up @@ -988,10 +988,10 @@ namespace Menu {

int sizeError(const string& key) {
if (redraw) {
vector<string> cont_vec;
cont_vec.push_back(Fx::b + Theme::g("used")[100] + "Error:" + Theme::c("main_fg") + Fx::ub);
cont_vec.push_back("Terminal size to small to" + Fx::reset);
cont_vec.push_back("display menu or box!" + Fx::reset);
vector<string> cont_vec {
Fx::b + Theme::g("used")[100] + "Error:" + Theme::c("main_fg") + Fx::ub,
"Terminal size to small to" + Fx::reset,
"display menu or box!" + Fx::reset };

messageBox = Menu::msgBox{45, 0, cont_vec, "error"};
Global::overlay = messageBox();
Expand Down
2 changes: 1 addition & 1 deletion src/btop_menu.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ namespace Menu {
Select
};
msgBox();
msgBox(int width, int boxtype, vector<string> content, string title);
msgBox(int width, int boxtype, const vector<string>& content, string title);

//? Draw and return box as a string
string operator()();
Expand Down
6 changes: 3 additions & 3 deletions src/btop_theme.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ namespace Theme {

for (const auto& [name, source_arr] : rgbs) {
if (not name.ends_with("_start")) continue;
const string color_name = rtrim(name, "_start");
const string color_name { rtrim(name, "_start") };

//? input_colors[start,mid,end][red,green,blue]
const array<array<int, 3>, 3> input_colors = {
Expand Down Expand Up @@ -357,7 +357,7 @@ namespace Theme {

for (const auto& c : colors) {
if (not c.first.ends_with("_start")) continue;
const string base_name = rtrim(c.first, "_start");
const string base_name { rtrim(c.first, "_start") };
string section = "_start";
int split = colors.at(base_name + "_mid").empty() ? 50 : 33;
for (int i : iota(0, 101)) {
Expand All @@ -372,13 +372,13 @@ namespace Theme {

//* Load a .theme file from disk
auto loadFile(const string& filename) {
std::unordered_map<string, string> theme_out;
const fs::path filepath = filename;
if (not fs::exists(filepath))
return Default_theme;

std::ifstream themefile(filepath);
if (themefile.good()) {
std::unordered_map<string, string> theme_out;
Logger::debug("Loading theme file: " + filename);
while (not themefile.bad()) {
if (themefile.peek() == '#') {
Expand Down
4 changes: 2 additions & 2 deletions src/btop_theme.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,9 @@ namespace Theme {
inline const string& c(const string& name) { return colors.at(name); }

//* Return array of escape codes for color gradient <name>
inline const array<string, 101>& g(string name) { return gradients.at(name); }
inline const array<string, 101>& g(const string& name) { return gradients.at(name); }

//* Return array of red, green and blue in decimal for color <name>
inline const std::array<int, 3>& dec(string name) { return rgbs.at(name); }
inline const std::array<int, 3>& dec(const string& name) { return rgbs.at(name); }

}
18 changes: 8 additions & 10 deletions src/btop_tools.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -296,20 +296,18 @@ namespace Tools {
return out;
}

string ltrim(const string& str, const string& t_str) {
std::string_view str_v{str};
while (str_v.starts_with(t_str))
str_v.remove_prefix(t_str.size());
string_view ltrim(string_view str, const string_view t_str) {
while (str.starts_with(t_str))
str.remove_prefix(t_str.size());

return string{str_v};
return str;
}

string rtrim(const string& str, const string& t_str) {
std::string_view str_v{str};
while (str_v.ends_with(t_str))
str_v.remove_suffix(t_str.size());
string_view rtrim(string_view str, const string_view t_str) {
while (str.ends_with(t_str))
str.remove_suffix(t_str.size());

return string{str_v};
return str;
}

auto ssplit(const string& str, const char& delim) -> vector<string> {
Expand Down
16 changes: 9 additions & 7 deletions src/btop_tools.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ tab-size = 4
#include <ranges>
#include <regex>
#include <string>
#include <string_view>
#include <thread>
#include <tuple>
#include <vector>
Expand All @@ -54,6 +55,7 @@ using std::array;
using std::atomic;
using std::string;
using std::to_string;
using std::string_view;
using std::tuple;
using std::vector;
using namespace fmt::literals;
Expand Down Expand Up @@ -292,13 +294,13 @@ namespace Tools {
}

//* Left-trim <t_str> from <str> and return new string
string ltrim(const string& str, const string& t_str = " ");
string_view ltrim(string_view str, string_view t_str = " ");

//* Right-trim <t_str> from <str> and return new string
string rtrim(const string& str, const string& t_str = " ");
string_view rtrim(string_view str, string_view t_str = " ");

//* Left/right-trim <t_str> from <str> and return new string
inline string trim(const string& str, const string& t_str = " ") {
inline string_view trim(string_view str, string_view t_str = " ") {
return ltrim(rtrim(str, t_str), t_str);
}

Expand Down Expand Up @@ -342,17 +344,17 @@ namespace Tools {
template <typename K, typename T>
#ifdef BTOP_DEBUG
const T& safeVal(const std::unordered_map<K, T>& map, const K& key, const T& fallback = T{}, std::source_location loc = std::source_location::current()) {
if (map.contains(key)) {
return map.at(key);
if (auto it = map.find(key); it != map.end()) {
return it->second;
} else {
Logger::error(fmt::format("safeVal() called with invalid key: [{}] in file: {} on line: {}", key, loc.file_name(), loc.line()));
return fallback;
}
};
#else
const T& safeVal(const std::unordered_map<K, T>& map, const K& key, const T& fallback = T{}) {
if (map.contains(key)) {
return map.at(key);
if (auto it = map.find(key); it != map.end()) {
return it->second;
} else {
Logger::error(fmt::format("safeVal() called with invalid key: [{}] (Compile btop with DEBUG=true for more extensive logging!)", key));
return fallback;
Expand Down
29 changes: 14 additions & 15 deletions src/linux/btop_collect.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,7 @@ namespace Cpu {

struct Sensor {
fs::path path;
string label;
int64_t temp{};
int64_t high{};
int64_t crit{};
};

Expand Down Expand Up @@ -430,7 +428,7 @@ namespace Cpu {
got_coretemp = true;

for (const auto & file : fs::directory_iterator(add_path)) {
if (string(file.path().filename()) == "device") {
if (file.path().filename() == "device") {
for (const auto & dev_file : fs::directory_iterator(file.path())) {
string dev_filename = dev_file.path().filename();
if (dev_filename.starts_with("temp") and dev_filename.ends_with("_input")) {
Expand Down Expand Up @@ -479,10 +477,9 @@ namespace Cpu {
const string label = readfile(fs::path(basepath + "label"), "temp" + to_string(file_id));
const string sensor_name = pname + "/" + label;
const int64_t temp = stol(readfile(fs::path(basepath + "input"), "0")) / 1000;
const int64_t high = stol(readfile(fs::path(basepath + "max"), "80000")) / 1000;
const int64_t crit = stol(readfile(fs::path(basepath + "crit"), "95000")) / 1000;

found_sensors[sensor_name] = {fs::path(basepath + "input"), label, temp, high, crit};
found_sensors[sensor_name] = {fs::path(basepath + "input"), temp, crit};

if (not got_cpu and (label.starts_with("Package id") or label.starts_with("Tdie"))) {
got_cpu = true;
Expand Down Expand Up @@ -515,7 +512,7 @@ namespace Cpu {
if (high < 1) high = 80;
if (crit < 1) crit = 95;

found_sensors[sensor_name] = {basepath / "temp", label, temp, high, crit};
found_sensors[sensor_name] = {basepath / "temp", temp, crit};
}
}

Expand Down Expand Up @@ -559,8 +556,7 @@ namespace Cpu {
if (current_cpu.temp.at(0).size() > 20) current_cpu.temp.at(0).pop_front();

if (Config::getB("show_coretemp") and not cpu_temp_only) {
vector<string> done;
for (const auto& sensor : core_sensors) {
for (vector<string_view> done; const auto& sensor : core_sensors) {
if (v_contains(done, sensor)) continue;
found_sensors.at(sensor).temp = stol(readfile(found_sensors.at(sensor).path, "0")) / 1000;
done.push_back(sensor);
Expand Down Expand Up @@ -2420,13 +2416,14 @@ namespace Net {

//? Get total received and transmitted bytes + device address if no ip was found
for (const auto& iface : interfaces) {
if (net.at(iface).ipv4.empty() and net.at(iface).ipv6.empty())
net.at(iface).ipv4 = readfile("/sys/class/net/" + iface + "/address");
auto& netif = net.at(iface);
if (netif.ipv4.empty() and netif.ipv6.empty())
netif.ipv4 = readfile("/sys/class/net/" + iface + "/address");

for (const string dir : {"download", "upload"}) {
const fs::path sys_file = "/sys/class/net/" + iface + "/statistics/" + (dir == "download" ? "rx_bytes" : "tx_bytes");
auto& saved_stat = net.at(iface).stat.at(dir);
auto& bandwidth = net.at(iface).bandwidth.at(dir);
auto& saved_stat = netif.stat.at(dir);
auto& bandwidth = netif.bandwidth.at(dir);

uint64_t val{};
try { val = (uint64_t)stoull(readfile(sys_file, "0")); }
Expand Down Expand Up @@ -2454,7 +2451,7 @@ namespace Net {

//? Set counters for auto scaling
if (net_auto and selected_iface == iface) {
if (net_sync and saved_stat.speed < net.at(iface).stat.at(dir == "download" ? "upload" : "download").speed) continue;
if (net_sync and saved_stat.speed < netif.stat.at(dir == "download" ? "upload" : "download").speed) continue;
if (saved_stat.speed > graph_max[dir]) {
++max_count[dir][0];
if (max_count[dir][1] > 0) --max_count[dir][1];
Expand Down Expand Up @@ -2501,8 +2498,10 @@ namespace Net {
selected_iface.clear();
//? Try to set to a connected interface
for (const auto& iface : sorted_interfaces) {
if (net.at(iface).connected) selected_iface = iface;
break;
if (net.at(iface).connected) {
selected_iface = iface;
break;
}
}
//? If no interface is connected set to first available
if (selected_iface.empty() and not sorted_interfaces.empty()) selected_iface = sorted_interfaces.at(0);
Expand Down
Loading