1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-28 20:17:34 +00:00

ls: Cache the user and group names instead of looking up every time

This commit is contained in:
Andreas Kling 2020-01-11 13:30:17 +01:00
parent d0a708fda4
commit 73788d7305

View file

@ -1,3 +1,4 @@
#include <AK/HashMap.h>
#include <AK/QuickSort.h> #include <AK/QuickSort.h>
#include <AK/String.h> #include <AK/String.h>
#include <AK/StringBuilder.h> #include <AK/StringBuilder.h>
@ -32,6 +33,9 @@ static size_t terminal_rows = 0;
static size_t terminal_columns = 0; static size_t terminal_columns = 0;
static bool output_is_terminal = false; static bool output_is_terminal = false;
static HashMap<uid_t, String> users;
static HashMap<gid_t, String> groups;
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
struct winsize ws; struct winsize ws;
@ -76,6 +80,17 @@ int main(int argc, char** argv)
} }
} }
if (flag_long) {
setpwent();
for (auto* pwd = getpwent(); pwd; pwd = getpwent())
users.set(pwd->pw_uid, pwd->pw_name);
endpwent();
setgrent();
for (auto* grp = getgrent(); grp; grp = getgrent())
groups.set(grp->gr_gid, grp->gr_name);
endgrent();
}
auto do_file_system_object = [&](const char* path) { auto do_file_system_object = [&](const char* path) {
if (flag_long) if (flag_long)
return do_file_system_object_long(path); return do_file_system_object_long(path);
@ -196,15 +211,15 @@ bool print_filesystem_object(const String& path, const String& name, const struc
else else
printf("%c", st.st_mode & S_IXOTH ? 'x' : '-'); printf("%c", st.st_mode & S_IXOTH ? 'x' : '-');
passwd* pwd = getpwuid(st.st_uid); auto username = users.get(st.st_uid);
group* grp = getgrgid(st.st_gid); auto groupname = groups.get(st.st_gid);
if (!flag_print_numeric && pwd) { if (!flag_print_numeric && username.has_value()) {
printf(" %7s", pwd->pw_name); printf(" %7s", username.value().characters());
} else { } else {
printf(" %7u", st.st_uid); printf(" %7u", st.st_uid);
} }
if (!flag_print_numeric && grp) { if (!flag_print_numeric && groupname.has_value()) {
printf(" %7s", grp->gr_name); printf(" %7s", groupname.value().characters());
} else { } else {
printf(" %7u", st.st_gid); printf(" %7u", st.st_gid);
} }