Merge pull request #30 from rmntgx/code-formatting

Address code formatting rules
This commit is contained in:
javalsai 2025-06-06 20:51:51 +02:00 committed by GitHub
commit 230c8558a7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
20 changed files with 262 additions and 275 deletions

View File

@ -1,2 +1,4 @@
BasedOnStyle: LLVM BasedOnStyle: Chromium
IndentWidth: 2 IndentWidth: 2
SpacesBeforeTrailingComments: 1
AllowShortIfStatementsOnASingleLine: WithoutElse

View File

@ -14,7 +14,7 @@ For small fixes or incremental improvements simply fork the repo and follow the
- Configure clangd LSP by generating `compile_commands.json` (e.g. `bear -- make` or `compiledb make`) - Configure clangd LSP by generating `compile_commands.json` (e.g. `bear -- make` or `compiledb make`)
- Implement your feature. - Implement your feature.
- Check your code works as expected. - Check your code works as expected.
- Run the code formatter: `clang-format -i $(git ls-files "*.cpp" "*.h")` - Run the code formatter: `clang-format -i $(git ls-files "*.c" "*.h")`
3. Commit your changes to a new branch (not `master`, one change per branch) and push it: 3. Commit your changes to a new branch (not `master`, one change per branch) and push it:
- Commit messages should: - Commit messages should:

View File

@ -6,6 +6,10 @@
#include "config.h" #include "config.h"
#include "sessions.h" #include "sessions.h"
bool launch(char *user, char *passwd, struct session session, void (*cb)(void), struct behavior* behavior); bool launch(char* user,
char* passwd,
struct session session,
void (*cb)(void),
struct behavior* behavior);
#endif #endif

View File

@ -20,6 +20,6 @@ int chvt(int n);
* @param str virtual terminal number (string) * @param str virtual terminal number (string)
* @return int non-negative value on success * @return int non-negative value on success
*/ */
int chvt_str(char *str); int chvt_str(char* str);
#endif #endif

View File

@ -10,32 +10,32 @@
// should be ansi escape codes under \x1b[...m // should be ansi escape codes under \x1b[...m
// if not prepared accordingly, it might break // if not prepared accordingly, it might break
struct theme_colors { struct theme_colors {
char *bg; char* bg;
char *fg; char* fg;
char *err; char* err;
char *s_wayland; char* s_wayland;
char *s_xorg; char* s_xorg;
char *s_shell; char* s_shell;
char *e_hostname; char* e_hostname;
char *e_date; char* e_date;
char *e_box; char* e_box;
char *e_header; char* e_header;
char *e_user; char* e_user;
char *e_passwd; char* e_passwd;
char *e_badpasswd; char* e_badpasswd;
char *e_key; char* e_key;
}; };
// even if they're multiple bytes long // even if they're multiple bytes long
// they should only take up 1 char size on display // they should only take up 1 char size on display
struct theme_chars { struct theme_chars {
char *hb; char* hb;
char *vb; char* vb;
char *ctl; char* ctl;
char *ctr; char* ctr;
char *cbl; char* cbl;
char *cbr; char* cbr;
}; };
struct theme { struct theme {
@ -50,14 +50,14 @@ struct functions {
}; };
struct strings { struct strings {
char *f_poweroff; char* f_poweroff;
char *f_reboot; char* f_reboot;
char *f_refresh; char* f_refresh;
char *e_user; char* e_user;
char *e_passwd; char* e_passwd;
char *s_wayland; char* s_wayland;
char *s_xorg; char* s_xorg;
char *s_shell; char* s_shell;
}; };
struct behavior { struct behavior {
@ -74,9 +74,10 @@ struct config {
}; };
bool line_parser( bool line_parser(
FILE *fd, ssize_t *blksize, FILE* fd,
u_char (*cb)(char *key, ssize_t* blksize,
char *value)); // might use this for parsing .desktop files too u_char (*cb)(char* key,
struct config *parse_config(char *path); char* value)); // might use this for parsing .desktop files too
struct config* parse_config(char* path);
#endif #endif

View File

@ -10,9 +10,9 @@ struct editable_field {
char content[255]; char content[255];
}; };
struct editable_field field_new(char *); struct editable_field field_new(char*);
void field_trim(struct editable_field *, u_char); void field_trim(struct editable_field*, u_char);
void field_update(struct editable_field *, char *); void field_update(struct editable_field*, char*);
bool field_seek(struct editable_field *, char); bool field_seek(struct editable_field*, char);
#endif #endif

View File

@ -34,7 +34,7 @@ enum keys {
PAGE_DOWN, PAGE_DOWN,
}; };
static const char *const key_names[] = { static const char* const key_names[] = {
[ESC] = "ESC", [ESC] = "ESC",
[F1] = "F1", [F1] = "F1",
[F2] = "F2", [F2] = "F2",
@ -67,7 +67,7 @@ static const char *const key_names[] = {
struct key_mapping { struct key_mapping {
enum keys key; enum keys key;
const char *sequences[3]; const char* sequences[3];
}; };
static const struct key_mapping key_mappings[] = { static const struct key_mapping key_mappings[] = {

View File

@ -12,9 +12,9 @@ enum session_type {
}; };
struct session { struct session {
char *name; char* name;
char *exec; char* exec;
char *tryexec; char* tryexec;
enum session_type type; enum session_type type;
}; };

View File

@ -5,8 +5,8 @@
#include "util.h" #include "util.h"
void setup(struct config); void setup(struct config);
int load(struct Vector * users, struct Vector * sessions); int load(struct Vector* users, struct Vector* sessions);
void print_err(const char *); void print_err(const char*);
void print_errno(const char *); void print_errno(const char*);
#endif #endif

View File

@ -6,9 +6,9 @@
#include "util.h" #include "util.h"
struct user { struct user {
char *shell; char* shell;
char *username; char* username;
char *display_name; char* display_name;
}; };
struct Vector get_human_users(); struct Vector get_human_users();

View File

@ -8,26 +8,26 @@
#include "keys.h" #include "keys.h"
enum keys find_keyname(char *); enum keys find_keyname(char*);
enum keys find_ansi(char *); enum keys find_ansi(char*);
void read_press(u_char *, char *); void read_press(u_char*, char*);
void strcln(char **dest, const char *source); void strcln(char** dest, const char* source);
struct Vector { struct Vector {
uint32_t length; uint32_t length;
uint32_t capacity; uint32_t capacity;
void **pages; void** pages;
}; };
struct Vector vec_new(); struct Vector vec_new();
int vec_resize(struct Vector *, size_t size); int vec_resize(struct Vector*, size_t size);
int vec_reserve(struct Vector *, size_t size); int vec_reserve(struct Vector*, size_t size);
int vec_reserve_exact(struct Vector *, size_t size); int vec_reserve_exact(struct Vector*, size_t size);
int vec_push(struct Vector *, void *item); int vec_push(struct Vector*, void* item);
void vec_free(struct Vector *); void vec_free(struct Vector*);
void vec_clear(struct Vector *); void vec_clear(struct Vector*);
void vec_reset(struct Vector *); void vec_reset(struct Vector*);
void *vec_pop(struct Vector *); // won't free it, nor shrink vec list space void* vec_pop(struct Vector*); // won't free it, nor shrink vec list space
void *vec_get(struct Vector *, size_t index); void* vec_get(struct Vector*, size_t index);
#endif #endif

View File

@ -15,16 +15,18 @@
#include "unistd.h" #include "unistd.h"
#include "util.h" #include "util.h"
int pam_conversation(int num_msg, const struct pam_message **msg, int pam_conversation(int num_msg,
struct pam_response **resp, void *appdata_ptr) { const struct pam_message** msg,
struct pam_response *reply = struct pam_response** resp,
(struct pam_response *)malloc(sizeof(struct pam_response) * num_msg); void* appdata_ptr) {
struct pam_response* reply =
(struct pam_response*)malloc(sizeof(struct pam_response) * num_msg);
for (size_t i = 0; i < num_msg; i++) { for (size_t i = 0; i < num_msg; i++) {
reply[i].resp = NULL; reply[i].resp = NULL;
reply[i].resp_retcode = 0; reply[i].resp_retcode = 0;
if (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF || if (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF ||
msg[i]->msg_style == PAM_PROMPT_ECHO_ON) { msg[i]->msg_style == PAM_PROMPT_ECHO_ON) {
char *input = (char *)appdata_ptr; char* input = (char*)appdata_ptr;
reply[i].resp = strdup(input); reply[i].resp = strdup(input);
} }
} }
@ -39,11 +41,13 @@ int pam_conversation(int num_msg, const struct pam_message **msg,
return NULL; \ return NULL; \
} }
void clear_screen() { printf("\x1b[H\x1b[J"); } void clear_screen() {
printf("\x1b[H\x1b[J");
}
pam_handle_t *get_pamh(char *user, char *passwd) { pam_handle_t* get_pamh(char* user, char* passwd) {
pam_handle_t *pamh = NULL; pam_handle_t* pamh = NULL;
struct pam_conv pamc = {pam_conversation, (void *)passwd}; struct pam_conv pamc = {pam_conversation, (void*)passwd};
int ret; int ret;
CHECK_PAM_RET(pam_start("login", user, &pamc, &pamh)) CHECK_PAM_RET(pam_start("login", user, &pamc, &pamh))
@ -57,25 +61,22 @@ pam_handle_t *get_pamh(char *user, char *passwd) {
} }
#undef CHECK_PAM_RET #undef CHECK_PAM_RET
void *shmalloc(size_t size) { void* shmalloc(size_t size) {
return mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, return mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS,
-1, 0); -1, 0);
} }
void sourceFileTry(char *file) { void sourceFileTry(char* file) {
FILE *file2source = fopen(file, "r"); FILE* file2source = fopen(file, "r");
if (file2source == NULL) if (file2source == NULL) return;
return;
char *line = NULL; char* line = NULL;
size_t len = 0; size_t len = 0;
ssize_t read; ssize_t read;
while ((read = getline(&line, &len, file2source)) != -1) { while ((read = getline(&line, &len, file2source)) != -1) {
if (read == 0 || (read > 0 && *line == '#')) if (read == 0 || (read > 0 && *line == '#')) continue;
continue; if (line[read - 1] == '\n') line[read - 1] = '\0';
if (line[read - 1] == '\n')
line[read - 1] = '\0';
/* printf("Retrieved line of length %zu:\n", read); */ /* printf("Retrieved line of length %zu:\n", read); */
/* printf("%s\n", line); */ /* printf("%s\n", line); */
@ -89,15 +90,15 @@ void sourceFileTry(char *file) {
} }
} }
if (line) if (line) free(line);
free(line);
fclose(file2source); fclose(file2source);
} }
void moarEnv(char *user, struct session session, struct passwd *pw, void moarEnv(char* user,
struct behavior *behavior) { struct session session,
if (chdir(pw->pw_dir) == -1) struct passwd* pw,
print_errno("can't chdir to user home"); struct behavior* behavior) {
if (chdir(pw->pw_dir) == -1) print_errno("can't chdir to user home");
setenv("HOME", pw->pw_dir, true); setenv("HOME", pw->pw_dir, true);
setenv("USER", pw->pw_name, true); setenv("USER", pw->pw_name, true);
@ -108,30 +109,26 @@ void moarEnv(char *user, struct session session, struct passwd *pw,
// PATH? // PATH?
char *xdg_session_type; char* xdg_session_type;
if (session.type == SHELL) if (session.type == SHELL) xdg_session_type = "tty";
xdg_session_type = "tty"; if (session.type == XORG) xdg_session_type = "x11";
if (session.type == XORG) if (session.type == WAYLAND) xdg_session_type = "wayland";
xdg_session_type = "x11";
if (session.type == WAYLAND)
xdg_session_type = "wayland";
setenv("XDG_SESSION_TYPE", xdg_session_type, true); setenv("XDG_SESSION_TYPE", xdg_session_type, true);
printf("\n\n\n\n\x1b[1m"); printf("\n\n\n\n\x1b[1m");
for (size_t i = 0; i < behavior->source.length; i++) { for (size_t i = 0; i < behavior->source.length; i++) {
/* printf("DEBUG(source)!!!! %d %s\n", i, (char*)vec_get(&behavior->source, /* printf("DEBUG(source)!!!! %d %s\n", i, (char*)vec_get(&behavior->source,
* i)); */ * i)); */
sourceFileTry((char *)vec_get(&behavior->source, i)); sourceFileTry((char*)vec_get(&behavior->source, i));
} }
/* printf("\n"); */ /* printf("\n"); */
if (pw->pw_dir) { if (pw->pw_dir) {
uint home_len = strlen(pw->pw_dir); uint home_len = strlen(pw->pw_dir);
for (size_t i = 0; i < behavior->user_source.length; i++) { for (size_t i = 0; i < behavior->user_source.length; i++) {
char *file2sourcepath = (char *)vec_get(&behavior->user_source, i); char* file2sourcepath = (char*)vec_get(&behavior->user_source, i);
char *newbuf = char* newbuf =
malloc(home_len + strlen(file2sourcepath) + 2); // nullbyte and slash malloc(home_len + strlen(file2sourcepath) + 2); // nullbyte and slash
if (newbuf == NULL) if (newbuf == NULL) continue; // can't bother
continue; // can't bother
strcpy(newbuf, pw->pw_dir); strcpy(newbuf, pw->pw_dir);
newbuf[home_len] = '/'; // assume pw_dir doesn't start with '/' :P newbuf[home_len] = '/'; // assume pw_dir doesn't start with '/' :P
strcpy(&newbuf[home_len + 1], file2sourcepath); strcpy(&newbuf[home_len + 1], file2sourcepath);
@ -153,21 +150,24 @@ void moarEnv(char *user, struct session session, struct passwd *pw,
/*setenv("XDG_SEAT", "seat0", true);*/ /*setenv("XDG_SEAT", "seat0", true);*/
} }
bool launch(char *user, char *passwd, struct session session, void (*cb)(void), bool launch(char* user,
struct behavior *behavior) { char* passwd,
struct passwd *pw = getpwnam(user); struct session session,
void (*cb)(void),
struct behavior* behavior) {
struct passwd* pw = getpwnam(user);
if (pw == NULL) { if (pw == NULL) {
print_err("could not get user info"); print_err("could not get user info");
return false; return false;
} }
pam_handle_t *pamh = get_pamh(user, passwd); pam_handle_t* pamh = get_pamh(user, passwd);
if (pamh == NULL) { if (pamh == NULL) {
print_err("error on pam authentication"); print_err("error on pam authentication");
return false; return false;
} }
bool *reach_session = shmalloc(sizeof(bool)); bool* reach_session = shmalloc(sizeof(bool));
if (reach_session == NULL) { if (reach_session == NULL) {
perror("error allocating shared memory"); perror("error allocating shared memory");
return false; return false;
@ -176,16 +176,15 @@ bool launch(char *user, char *passwd, struct session session, void (*cb)(void),
uint pid = fork(); uint pid = fork();
if (pid == 0) { // child if (pid == 0) { // child
char *TERM = NULL; char* TERM = NULL;
char *_GETTERM = getenv("TERM"); char* _GETTERM = getenv("TERM");
if (_GETTERM != NULL) if (_GETTERM != NULL) strcln(&TERM, _GETTERM);
strcln(&TERM, _GETTERM);
if (clearenv() != 0) { if (clearenv() != 0) {
print_errno("clearenv"); print_errno("clearenv");
_exit(EXIT_FAILURE); _exit(EXIT_FAILURE);
} }
char **envlist = pam_getenvlist(pamh); char** envlist = pam_getenvlist(pamh);
if (envlist == NULL) { if (envlist == NULL) {
print_errno("pam_getenvlist"); print_errno("pam_getenvlist");
_exit(EXIT_FAILURE); _exit(EXIT_FAILURE);
@ -222,8 +221,7 @@ bool launch(char *user, char *passwd, struct session session, void (*cb)(void),
_exit(EXIT_FAILURE); _exit(EXIT_FAILURE);
} }
if (cb != NULL) if (cb != NULL) cb();
cb();
*reach_session = true; *reach_session = true;

View File

@ -5,11 +5,11 @@
#include "chvt.h" #include "chvt.h"
static char *vterms[] = {"/dev/tty", "/dev/tty0", "/dev/vc/0", "/dev/systty", static char* vterms[] = {"/dev/tty", "/dev/tty0", "/dev/vc/0", "/dev/systty",
"/dev/console"}; "/dev/console"};
int chvt_str(char *str) { int chvt_str(char* str) {
char *err; char* err;
errno = 0; errno = 0;
long i = strtol(str, &err, 10); long i = strtol(str, &err, 10);
if (errno) { if (errno) {
@ -17,8 +17,7 @@ int chvt_str(char *str) {
return -1; return -1;
} }
// I'm not gonna elaborate on this.... // I'm not gonna elaborate on this....
if (i > INT_MAX || i < INT_MIN || *err) if (i > INT_MAX || i < INT_MIN || *err) return -1;
return -1;
return chvt((int)i); return chvt((int)i);
} }

View File

@ -11,18 +11,18 @@
// 0b0100: free the key // 0b0100: free the key
// 0b1000: break out of parsing (returning false) // 0b1000: break out of parsing (returning false)
// //
// This would return true if everything goes fine, false otherwise (malloc error, broke parsing, etc) // This would return true if everything goes fine, false otherwise (malloc
bool line_parser(FILE *fd, ssize_t *blksize, // error, broke parsing, etc)
u_char (*cb)(char *key, char *value)) { bool line_parser(FILE* fd,
ssize_t* blksize,
u_char (*cb)(char* key, char* value)) {
size_t opt_size = 4096; size_t opt_size = 4096;
if (blksize != NULL) if (blksize != NULL) opt_size = *blksize;
opt_size = *blksize;
while (true) { while (true) {
size_t alloc_size = opt_size; size_t alloc_size = opt_size;
char *buf = malloc(alloc_size); char* buf = malloc(alloc_size);
if (buf == NULL) if (buf == NULL) return false;
return false;
ssize_t read_size = getline(&buf, &alloc_size, fd); ssize_t read_size = getline(&buf, &alloc_size, fd);
if (read_size == -1) { if (read_size == -1) {
free(buf); free(buf);
@ -30,22 +30,20 @@ bool line_parser(FILE *fd, ssize_t *blksize,
} }
uint read; uint read;
char *key = malloc(read_size); char* key = malloc(read_size);
if (key == NULL) { if (key == NULL) {
free(buf); free(buf);
return false; return false;
} }
char *value = malloc(read_size); char* value = malloc(read_size);
if (value == NULL) { if (value == NULL) {
free(buf); free(buf);
return false; return false;
} }
if ((read = sscanf(buf, "%[^ ] = %[^\n]\n", key, value)) != 0) { if ((read = sscanf(buf, "%[^ ] = %[^\n]\n", key, value)) != 0) {
u_char ret = cb(key, value); u_char ret = cb(key, value);
if (ret & 0b0100) if (ret & 0b0100) free(key);
free(key); if (ret & 0b0010) free(value);
if (ret & 0b0010)
free(value);
if (ret & 0b1000) { if (ret & 0b1000) {
free(buf); free(buf);
return false; return false;
@ -61,9 +59,9 @@ bool line_parser(FILE *fd, ssize_t *blksize,
return true; return true;
} }
struct config *__config; struct config* __config;
// Yanderedev code (wanna fix this with a table or smth) // Yanderedev code (wanna fix this with a table or smth)
u_char config_line_handler(char *k, char *v) { u_char config_line_handler(char* k, char* v) {
if (strcmp(k, "colors.bg") == 0) if (strcmp(k, "colors.bg") == 0)
__config->theme.colors.bg = v; __config->theme.colors.bg = v;
else if (strcmp(k, "colors.fg") == 0) else if (strcmp(k, "colors.fg") == 0)
@ -142,9 +140,9 @@ u_char config_line_handler(char *k, char *v) {
return 0b0100; return 0b0100;
} }
struct config *parse_config(char *path) { struct config* parse_config(char* path) {
struct stat sb; struct stat sb;
FILE *fd = fopen(path, "r"); FILE* fd = fopen(path, "r");
if (fd == NULL || (stat(path, &sb) == -1)) { if (fd == NULL || (stat(path, &sb) == -1)) {
perror("fopen"); perror("fopen");
return NULL; return NULL;
@ -154,9 +152,8 @@ struct config *parse_config(char *path) {
__config->behavior.source = vec_new(); __config->behavior.source = vec_new();
__config->behavior.user_source = vec_new(); __config->behavior.user_source = vec_new();
if (__config == NULL) if (__config == NULL) return NULL;
return NULL; bool ret = line_parser(fd, (ssize_t*)&sb.st_blksize, config_line_handler);
bool ret = line_parser(fd, (ssize_t *)&sb.st_blksize, config_line_handler);
if (!ret) { if (!ret) {
free(__config); free(__config);
return NULL; return NULL;

View File

@ -3,7 +3,7 @@
#include "efield.h" #include "efield.h"
#include "ui.h" #include "ui.h"
struct editable_field field_new(char *content) { struct editable_field field_new(char* content) {
struct editable_field __efield; struct editable_field __efield;
if (content != NULL) { if (content != NULL) {
__efield.length = __efield.pos = strlen(content); __efield.length = __efield.pos = strlen(content);
@ -15,23 +15,20 @@ struct editable_field field_new(char *content) {
return __efield; return __efield;
} }
void field_trim(struct editable_field *field, u_char pos) { void field_trim(struct editable_field* field, u_char pos) {
field->length = field->pos = pos; field->length = field->pos = pos;
field->content[field->length] = '\0'; field->content[field->length] = '\0';
} }
void field_update(struct editable_field *field, char *update) { void field_update(struct editable_field* field, char* update) {
u_char insert_len = strlen(update); u_char insert_len = strlen(update);
if (insert_len == 0) if (insert_len == 0) return;
return;
if (field->pos > field->length) if (field->pos > field->length) field->pos = field->length; // WTF
field->pos = field->length; // WTF
if (insert_len == 1) { if (insert_len == 1) {
// backspace // backspace
if (*update == 127) { if (*update == 127) {
if (field->pos == 0) if (field->pos == 0) return;
return;
if (field->pos < field->length) { if (field->pos < field->length) {
memmove(&field->content[field->pos - 1], &field->content[field->pos], memmove(&field->content[field->pos - 1], &field->content[field->pos],
field->length - field->pos); field->length - field->pos);
@ -60,9 +57,8 @@ void field_update(struct editable_field *field, char *update) {
} }
// returns bool depending if it was able to "use" the seek // returns bool depending if it was able to "use" the seek
bool field_seek(struct editable_field *field, char seek) { bool field_seek(struct editable_field* field, char seek) {
if (field->length == 0) if (field->length == 0) return false;
return false;
if (seek < 0 && -seek > field->pos) if (seek < 0 && -seek > field->pos)
field->pos = 0; field->pos = 0;
@ -71,8 +67,7 @@ bool field_seek(struct editable_field *field, char seek) {
else else
field->pos += seek; field->pos += seek;
if (field->pos > field->length) if (field->pos > field->length) field->pos = field->length;
field->pos = field->length;
return true; return true;
} }

View File

@ -11,12 +11,11 @@
#include "users.h" #include "users.h"
#include "util.h" #include "util.h"
int main(int argc, char *argv[]) { int main(int argc, char* argv[]) {
if (argc == 2) if (argc == 2) chvt_str(argv[1]);
chvt_str(argv[1]);
char *conf_override = getenv("LIDM_CONF"); char* conf_override = getenv("LIDM_CONF");
struct config *config = struct config* config =
parse_config(conf_override == NULL ? "/etc/lidm.ini" : conf_override); parse_config(conf_override == NULL ? "/etc/lidm.ini" : conf_override);
if (config == NULL) { if (config == NULL) {
fprintf(stderr, "error parsing config\n"); fprintf(stderr, "error parsing config\n");
@ -28,6 +27,5 @@ int main(int argc, char *argv[]) {
struct Vector sessions = get_avaliable_sessions(); struct Vector sessions = get_avaliable_sessions();
int ret = load(&users, &sessions); int ret = load(&users, &sessions);
if (ret == 0) if (ret == 0) execl(argv[0], argv[0], NULL);
execl(argv[0], argv[0], NULL);
} }

View File

@ -12,15 +12,17 @@
struct source_dir { struct source_dir {
enum session_type type; enum session_type type;
char *dir; char* dir;
}; };
static const struct source_dir sources[] = { static const struct source_dir sources[] = {
{XORG, "/usr/share/xsessions"}, {XORG, "/usr/share/xsessions"},
{WAYLAND, "/usr/share/wayland-sessions"}, {WAYLAND, "/usr/share/wayland-sessions"},
}; };
static struct session __new_session(enum session_type type, char *name, static struct session __new_session(enum session_type type,
const char *exec, const char *tryexec) { char* name,
const char* exec,
const char* tryexec) {
struct session __session; struct session __session;
__session.type = type; __session.type = type;
strcln(&__session.name, name); strcln(&__session.name, name);
@ -30,17 +32,16 @@ static struct session __new_session(enum session_type type, char *name,
return __session; return __session;
} }
static struct Vector *cb_sessions = NULL; static struct Vector* cb_sessions = NULL;
// NOTE: commented printf's here would be nice to have debug logs if I ever // NOTE: commented printf's here would be nice to have debug logs if I ever
// implement it // implement it
static enum session_type session_type; static enum session_type session_type;
static int fn(const char *fpath, const struct stat *sb, int typeflag) { static int fn(const char* fpath, const struct stat* sb, int typeflag) {
if (sb == NULL || !S_ISREG(sb->st_mode)) if (sb == NULL || !S_ISREG(sb->st_mode)) return 0;
return 0;
/*printf("gonna open %s\n", fpath);*/ /*printf("gonna open %s\n", fpath);*/
FILE *fd = fopen(fpath, "r"); FILE* fd = fopen(fpath, "r");
if (fd == NULL) { if (fd == NULL) {
perror("fopen"); perror("fopen");
fprintf(stderr, "error opening file (r) '%s'\n", fpath); fprintf(stderr, "error opening file (r) '%s'\n", fpath);
@ -50,13 +51,14 @@ static int fn(const char *fpath, const struct stat *sb, int typeflag) {
u_char found = 0; u_char found = 0;
size_t alloc_size = sb->st_blksize; size_t alloc_size = sb->st_blksize;
char *name_buf = NULL; char* name_buf = NULL;
char *exec_buf = NULL; char* exec_buf = NULL;
char *tryexec_buf = NULL; char* tryexec_buf = NULL;
// This should be made a specific function // This should be made a specific function
// Emm, if anything goes wrong just free the inner loop and `break;` fd and the rest is handled after // Emm, if anything goes wrong just free the inner loop and `break;` fd and
// the rest is handled after
while (true) { while (true) {
char *buf = malloc(sb->st_blksize); char* buf = malloc(sb->st_blksize);
ssize_t read_size = getline(&buf, &alloc_size, fd); ssize_t read_size = getline(&buf, &alloc_size, fd);
if (read_size == -1) { if (read_size == -1) {
free(buf); free(buf);
@ -64,14 +66,14 @@ static int fn(const char *fpath, const struct stat *sb, int typeflag) {
} }
uint read; uint read;
char *key = malloc(read_size + sizeof(char)); char* key = malloc(read_size + sizeof(char));
if(key == NULL) { if (key == NULL) {
free(buf); free(buf);
// TODO: more sophisticated error handling?? // TODO: more sophisticated error handling??
break; break;
} }
char *value = malloc(read_size + sizeof(char)); char* value = malloc(read_size + sizeof(char));
if(value == NULL) { if (value == NULL) {
free(buf); free(buf);
free(key); free(key);
// TODO: more sophisticated error handling?? // TODO: more sophisticated error handling??
@ -106,18 +108,15 @@ static int fn(const char *fpath, const struct stat *sb, int typeflag) {
// just add this to the list // just add this to the list
if (name_buf != NULL && exec_buf != NULL) { if (name_buf != NULL && exec_buf != NULL) {
struct session *session_i = malloc(sizeof (struct session)); struct session* session_i = malloc(sizeof(struct session));
*session_i = __new_session(session_type, name_buf, exec_buf, *session_i = __new_session(session_type, name_buf, exec_buf,
tryexec_buf == NULL ? "" : tryexec_buf); tryexec_buf == NULL ? "" : tryexec_buf);
vec_push(cb_sessions, session_i); vec_push(cb_sessions, session_i);
} }
if (name_buf != NULL) if (name_buf != NULL) free(name_buf);
free(name_buf); if (exec_buf != NULL) free(exec_buf);
if (exec_buf != NULL) if (tryexec_buf != NULL) free(tryexec_buf);
free(exec_buf);
if (tryexec_buf != NULL)
free(tryexec_buf);
return 0; return 0;
} }

100
src/ui.c
View File

@ -90,7 +90,7 @@ static struct uint_point box_start() {
return __start; return __start;
} }
static char *fmt_time() { static char* fmt_time() {
time_t t = time(NULL); time_t t = time(NULL);
struct tm tm = *localtime(&t); struct tm tm = *localtime(&t);
@ -98,7 +98,7 @@ static char *fmt_time() {
snprintf(NULL, 0, "%d-%02d-%02d %02d:%02d:%02d", tm.tm_year + 1900, snprintf(NULL, 0, "%d-%02d-%02d %02d:%02d:%02d", tm.tm_year + 1900,
tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec) + tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec) +
1; 1;
char *buf = malloc(bsize); char* buf = malloc(bsize);
snprintf(buf, bsize, "%d-%02d-%02d %02d:%02d:%02d", tm.tm_year + 1900, snprintf(buf, bsize, "%d-%02d-%02d %02d:%02d:%02d", tm.tm_year + 1900,
tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
return buf; return buf;
@ -116,7 +116,7 @@ struct opt_field {
uint current_opt; // 0 is edit mode btw uint current_opt; // 0 is edit mode btw
struct editable_field efield; struct editable_field efield;
}; };
void print_ofield(struct opt_field *focused_input); void print_ofield(struct opt_field* focused_input);
static struct opt_field ofield_new(uint opts) { static struct opt_field ofield_new(uint opts) {
struct opt_field __field; struct opt_field __field;
@ -128,17 +128,16 @@ static struct opt_field ofield_new(uint opts) {
} }
return __field; return __field;
} }
static void ofield_toedit(struct opt_field *ofield, char *init) { static void ofield_toedit(struct opt_field* ofield, char* init) {
ofield->current_opt = 0; ofield->current_opt = 0;
ofield->efield = field_new(init); ofield->efield = field_new(init);
} }
static void ofield_type(struct opt_field *ofield, char *new, char *startstr) { static void ofield_type(struct opt_field* ofield, char* new, char* startstr) {
if (ofield->current_opt != 0) if (ofield->current_opt != 0) ofield_toedit(ofield, startstr);
ofield_toedit(ofield, startstr);
field_update(&ofield->efield, new); field_update(&ofield->efield, new);
} }
// true if it changed anything, single opt fields return false // true if it changed anything, single opt fields return false
static bool ofield_opt_seek(struct opt_field *ofield, char seek) { static bool ofield_opt_seek(struct opt_field* ofield, char seek) {
// TODO: think this // TODO: think this
if (ofield->opts == 0 || (ofield->opts == 1 && ofield->current_opt != 0)) if (ofield->opts == 0 || (ofield->opts == 1 && ofield->current_opt != 0))
return false; return false;
@ -151,22 +150,21 @@ static bool ofield_opt_seek(struct opt_field *ofield, char seek) {
} }
// true in case it was able to "use" the seek (a empty only editable field // true in case it was able to "use" the seek (a empty only editable field
// wouldn't) // wouldn't)
static bool ofield_seek(struct opt_field *ofield, char seek) { static bool ofield_seek(struct opt_field* ofield, char seek) {
if (ofield->current_opt == 0) { if (ofield->current_opt == 0) {
if (field_seek(&ofield->efield, seek)) { if (field_seek(&ofield->efield, seek)) {
return true; return true;
} }
} }
if (ofield->opts == 0) if (ofield->opts == 0) return false;
return false;
ofield_opt_seek(ofield, seek); ofield_opt_seek(ofield, seek);
return true; return true;
} }
static u_char ofield_max_displ_pos(struct opt_field *ofield) { static u_char ofield_max_displ_pos(struct opt_field* ofield) {
// TODO: set max cursor pos too // TODO: set max cursor pos too
// keep in mind that also have to keep in mind scrolling and ughhh, mentally // keep in mind that also have to keep in mind scrolling and ughhh, mentally
// blocked, but this is complex // blocked, but this is complex
@ -181,17 +179,14 @@ struct opt_field of_session;
struct opt_field of_user; struct opt_field of_user;
struct opt_field of_passwd; struct opt_field of_passwd;
struct Vector *gusers; struct Vector* gusers;
struct Vector *gsessions; struct Vector* gsessions;
// not *that* OF tho // not *that* OF tho
struct opt_field *get_of(enum input from) { struct opt_field* get_of(enum input from) {
if (from == SESSION) if (from == SESSION) return &of_session;
return &of_session; if (from == USER) return &of_user;
if (from == USER) if (from == PASSWD) return &of_passwd;
return &of_user;
if (from == PASSWD)
return &of_passwd;
return NULL; return NULL;
} }
@ -210,7 +205,7 @@ void ffield_cursor_focus() {
} else if (focused_input == PASSWD) } else if (focused_input == PASSWD)
line += 9; line += 9;
struct opt_field *ofield = get_of(focused_input); struct opt_field* ofield = get_of(focused_input);
row += ofield->current_opt == 0 ? ofield_max_displ_pos(ofield) : 0; row += ofield->current_opt == 0 ? ofield_max_displ_pos(ofield) : 0;
printf("\x1b[%d;%dH", line, row); printf("\x1b[%d;%dH", line, row);
@ -219,7 +214,7 @@ void ffield_cursor_focus() {
struct user get_current_user() { struct user get_current_user() {
if (of_user.current_opt != 0) if (of_user.current_opt != 0)
return *(struct user*)vec_get(gusers, of_user.current_opt - 1); return *(struct user *)vec_get(gusers, of_user.current_opt - 1);
else { else {
struct user custom_user; struct user custom_user;
custom_user.shell = "/usr/bin/bash"; custom_user.shell = "/usr/bin/bash";
@ -239,7 +234,7 @@ struct session get_current_session() {
shell_session.exec = shell_session.name = get_current_user().shell; shell_session.exec = shell_session.name = get_current_user().shell;
return shell_session; return shell_session;
} else } else
return *(struct session*)vec_get(gsessions, of_session.current_opt - 1); return *(struct session *)vec_get(gsessions, of_session.current_opt - 1);
} else { } else {
struct session custom_session; struct session custom_session;
custom_session.type = SHELL; custom_session.type = SHELL;
@ -263,8 +258,10 @@ void print_field(enum input focused_input) {
ffield_cursor_focus(); ffield_cursor_focus();
} }
void print_ffield() { print_field(focused_input); } void print_ffield() {
void print_ofield(struct opt_field *ofield) { print_field(focused_input);
}
void print_ofield(struct opt_field* ofield) {
enum input input; enum input input;
if (ofield == &of_session) if (ofield == &of_session)
input = SESSION; input = SESSION;
@ -290,9 +287,8 @@ void ffield_move(bool direction) {
// tf I'm doing // tf I'm doing
void ffield_change_opt(bool direction) { void ffield_change_opt(bool direction) {
struct opt_field *ffield = get_of(focused_input); struct opt_field* ffield = get_of(focused_input);
if (focused_input == PASSWD) if (focused_input == PASSWD) ffield = &of_session;
ffield = &of_session;
if (!ofield_opt_seek(ffield, direction ? 1 : -1)) { if (!ofield_opt_seek(ffield, direction ? 1 : -1)) {
if (focused_input == PASSWD || focused_input == SESSION) if (focused_input == PASSWD || focused_input == SESSION)
ofield_opt_seek(&of_user, direction ? 1 : -1); ofield_opt_seek(&of_user, direction ? 1 : -1);
@ -301,7 +297,7 @@ void ffield_change_opt(bool direction) {
} }
} }
void ffield_change_pos(bool direction) { void ffield_change_pos(bool direction) {
struct opt_field *ffield = get_of(focused_input); struct opt_field* ffield = get_of(focused_input);
if (!ofield_seek(ffield, direction ? 1 : -1)) if (!ofield_seek(ffield, direction ? 1 : -1))
if (!ofield_opt_seek(&of_session, direction ? 1 : -1)) if (!ofield_opt_seek(&of_session, direction ? 1 : -1))
ofield_opt_seek(&of_user, direction ? 1 : -1); ofield_opt_seek(&of_user, direction ? 1 : -1);
@ -309,9 +305,9 @@ void ffield_change_pos(bool direction) {
ffield_cursor_focus(); ffield_cursor_focus();
} }
void ffield_type(char *text) { void ffield_type(char* text) {
struct opt_field *field = get_of(focused_input); struct opt_field* field = get_of(focused_input);
char *start = ""; char* start = "";
if (focused_input == USER && of_user.current_opt != 0) if (focused_input == USER && of_user.current_opt != 0)
start = get_current_user().username; start = get_current_user().username;
if (focused_input == SESSION && of_session.current_opt != 0 && if (focused_input == SESSION && of_session.current_opt != 0 &&
@ -323,13 +319,13 @@ void ffield_type(char *text) {
} }
static char* unknown_str = "unknown"; static char* unknown_str = "unknown";
int load(struct Vector *users, struct Vector *sessions) { int load(struct Vector* users, struct Vector* sessions) {
/// SETUP /// SETUP
gusers = users; gusers = users;
gsessions = sessions; gsessions = sessions;
// hostnames larger won't render properly // hostnames larger won't render properly
char *hostname = malloc(16); char* hostname = malloc(16);
if (gethostname(hostname, 16) != 0) { if (gethostname(hostname, 16) != 0) {
free(hostname); free(hostname);
hostname = unknown_str; hostname = unknown_str;
@ -351,10 +347,10 @@ int load(struct Vector *users, struct Vector *sessions) {
printf("\x1b[%d;%dH\x1b[%sm%s\x1b[%sm", boxstart.y + 2, printf("\x1b[%d;%dH\x1b[%sm%s\x1b[%sm", boxstart.y + 2,
boxstart.x + 12 - (uint)strlen(hostname), theme.colors.e_hostname, boxstart.x + 12 - (uint)strlen(hostname), theme.colors.e_hostname,
hostname, theme.colors.fg); hostname, theme.colors.fg);
if(hostname != unknown_str) free(hostname); if (hostname != unknown_str) free(hostname);
// put date // put date
char *fmtd_time = fmt_time(); char* fmtd_time = fmt_time();
printf("\x1b[%d;%dH\x1b[%sm%s\x1b[%sm", boxstart.y + 2, printf("\x1b[%d;%dH\x1b[%sm%s\x1b[%sm", boxstart.y + 2,
boxstart.x + boxw - 3 - (uint)strlen(fmtd_time), theme.colors.e_date, boxstart.x + boxw - 3 - (uint)strlen(fmtd_time), theme.colors.e_date,
fmtd_time, theme.colors.fg); fmtd_time, theme.colors.fg);
@ -407,12 +403,11 @@ int load(struct Vector *users, struct Vector *sessions) {
ffield_type(seq); ffield_type(seq);
} }
if (esc != 0) if (esc != 0) esc--;
esc--;
} }
} }
static char *line_cleaner = NULL; static char* line_cleaner = NULL;
static void clean_line(struct uint_point origin, uint line) { static void clean_line(struct uint_point origin, uint line) {
if (line_cleaner == NULL) { if (line_cleaner == NULL) {
line_cleaner = malloc((boxw - 2) * sizeof(char) + 1); line_cleaner = malloc((boxw - 2) * sizeof(char) + 1);
@ -424,10 +419,11 @@ static void clean_line(struct uint_point origin, uint line) {
} }
// TODO: session_len > 32 // TODO: session_len > 32
static void print_session(struct uint_point origin, struct session session, static void print_session(struct uint_point origin,
struct session session,
bool multiple) { bool multiple) {
clean_line(origin, 5); clean_line(origin, 5);
const char *session_type; const char* session_type;
if (session.type == XORG) { if (session.type == XORG) {
session_type = strings.s_xorg; session_type = strings.s_xorg;
} else if (session.type == WAYLAND) { } else if (session.type == WAYLAND) {
@ -439,7 +435,7 @@ static void print_session(struct uint_point origin, struct session session,
(ulong)(origin.x + 11 - strlen(session_type)), theme.colors.e_header, (ulong)(origin.x + 11 - strlen(session_type)), theme.colors.e_header,
session_type, theme.colors.fg); session_type, theme.colors.fg);
char *session_color; char* session_color;
if (session.type == XORG) { if (session.type == XORG) {
session_color = theme.colors.s_xorg; session_color = theme.colors.s_xorg;
} else if (session.type == WAYLAND) { } else if (session.type == WAYLAND) {
@ -458,14 +454,15 @@ static void print_session(struct uint_point origin, struct session session,
} }
// TODO: user_len > 32 // TODO: user_len > 32
static void print_user(struct uint_point origin, struct user user, static void print_user(struct uint_point origin,
struct user user,
bool multiple) { bool multiple) {
clean_line(origin, 7); clean_line(origin, 7);
printf("\r\x1b[%luC\x1b[%sm%s\x1b[%sm", printf("\r\x1b[%luC\x1b[%sm%s\x1b[%sm",
(ulong)(origin.x + 11 - strlen(strings.e_user)), theme.colors.e_header, (ulong)(origin.x + 11 - strlen(strings.e_user)), theme.colors.e_header,
strings.e_user, theme.colors.fg); strings.e_user, theme.colors.fg);
char *user_color = theme.colors.e_user; char* user_color = theme.colors.e_user;
if (multiple) { if (multiple) {
printf("\r\x1b[%dC< \x1b[%sm%s\x1b[%sm >", origin.x + 14, user_color, printf("\r\x1b[%dC< \x1b[%sm%s\x1b[%sm >", origin.x + 14, user_color,
@ -484,7 +481,7 @@ static void print_passwd(struct uint_point origin, uint length, bool err) {
(ulong)(origin.x + 11 - strlen(strings.e_passwd)), (ulong)(origin.x + 11 - strlen(strings.e_passwd)),
theme.colors.e_header, strings.e_passwd, theme.colors.fg); theme.colors.e_header, strings.e_passwd, theme.colors.fg);
char *pass_color; char* pass_color;
if (err) if (err)
pass_color = theme.colors.e_badpasswd; pass_color = theme.colors.e_badpasswd;
else else
@ -502,13 +499,13 @@ static void print_passwd(struct uint_point origin, uint length, bool err) {
printf("\x1b[%sm", theme.colors.fg); printf("\x1b[%sm", theme.colors.fg);
} }
static void print_empty_row(uint w, uint n, char *edge1, char *edge2) { static void print_empty_row(uint w, uint n, char* edge1, char* edge2) {
for (size_t i = 0; i < n; i++) { for (size_t i = 0; i < n; i++) {
printf("%s\x1b[%dC%s\x1b[%dD\x1b[1B", edge1, w, edge2, w + 2); printf("%s\x1b[%dC%s\x1b[%dD\x1b[1B", edge1, w, edge2, w + 2);
} }
} }
static void print_row(uint w, uint n, char *edge1, char *edge2, char *filler) { static void print_row(uint w, uint n, char* edge1, char* edge2, char* filler) {
for (size_t i = 0; i < n; i++) { for (size_t i = 0; i < n; i++) {
printf("%s", edge1); printf("%s", edge1);
for (size_t i = 0; i < w; i++) { for (size_t i = 0; i < w; i++) {
@ -539,7 +536,8 @@ static void print_footer() {
uint row = window.ws_row - 1; uint row = window.ws_row - 1;
uint col = window.ws_col - 2 - bsize; uint col = window.ws_col - 2 - bsize;
printf("\x1b[%3$d;%4$dH%8$s \x1b[%1$sm%5$s\x1b[%2$sm %9$s " printf(
"\x1b[%3$d;%4$dH%8$s \x1b[%1$sm%5$s\x1b[%2$sm %9$s "
"\x1b[%1$sm%6$s\x1b[%2$sm %10$s \x1b[%1$sm%7$s\x1b[%2$sm", "\x1b[%1$sm%6$s\x1b[%2$sm %10$s \x1b[%1$sm%7$s\x1b[%2$sm",
theme.colors.e_key, theme.colors.fg, row, col, theme.colors.e_key, theme.colors.fg, row, col,
key_names[functions.poweroff], key_names[functions.reboot], key_names[functions.poweroff], key_names[functions.reboot],
@ -548,13 +546,13 @@ static void print_footer() {
fflush(stdout); fflush(stdout);
} }
void print_err(const char *msg) { void print_err(const char* msg) {
struct uint_point origin = box_start(); struct uint_point origin = box_start();
fprintf(stderr, "\x1b[%d;%dH%s(%d): %s", origin.y - 1, origin.x, msg, errno, fprintf(stderr, "\x1b[%d;%dH%s(%d): %s", origin.y - 1, origin.x, msg, errno,
strerror(errno)); strerror(errno));
} }
void print_errno(const char *descr) { void print_errno(const char* descr) {
struct uint_point origin = box_start(); struct uint_point origin = box_start();
if (descr == NULL) if (descr == NULL)
fprintf(stderr, "\x1b[%d;%dH\x1b[%smunknown error(%d): %s", origin.y - 1, fprintf(stderr, "\x1b[%d;%dH\x1b[%smunknown error(%d): %s", origin.y - 1,

View File

@ -8,7 +8,7 @@
#include "users.h" #include "users.h"
#include "util.h" #include "util.h"
static struct user __new_user(struct passwd *p) { static struct user __new_user(struct passwd* p) {
struct user __user; struct user __user;
strcln(&__user.shell, p->pw_shell); strcln(&__user.shell, p->pw_shell);
strcln(&__user.username, p->pw_name); strcln(&__user.username, p->pw_name);
@ -25,12 +25,11 @@ struct Vector get_human_users() {
struct Vector users = vec_new(); struct Vector users = vec_new();
vec_reserve(&users, 4); vec_reserve(&users, 4);
struct passwd *pwd; struct passwd* pwd;
while ((pwd = getpwent()) != NULL) { while ((pwd = getpwent()) != NULL) {
if (!(pwd->pw_dir && strncmp(pwd->pw_dir, "/home/", 6) == 0)) if (!(pwd->pw_dir && strncmp(pwd->pw_dir, "/home/", 6) == 0)) continue;
continue;
struct user *user_i = malloc(sizeof(struct user)); struct user* user_i = malloc(sizeof(struct user));
*user_i = __new_user(pwd); *user_i = __new_user(pwd);
vec_push(&users, user_i); vec_push(&users, user_i);
} }

View File

@ -11,22 +11,21 @@
static int selret_magic(); static int selret_magic();
void strcln(char **dest, const char *source) { void strcln(char** dest, const char* source) {
*dest = malloc(strlen(source) + sizeof(char)); *dest = malloc(strlen(source) + sizeof(char));
strcpy(*dest, source); strcpy(*dest, source);
} }
enum keys find_keyname(char *name) { enum keys find_keyname(char* name) {
for (size_t i = 0; i < sizeof(key_mappings) / sizeof(key_mappings[0]); i++) { for (size_t i = 0; i < sizeof(key_mappings) / sizeof(key_mappings[0]); i++) {
if (strcmp(key_names[i], name) == 0) if (strcmp(key_names[i], name) == 0) return (enum keys)i;
return (enum keys)i;
} }
perror("key not found"); perror("key not found");
exit(1); exit(1);
} }
enum keys find_ansi(char *seq) { enum keys find_ansi(char* seq) {
for (size_t i = 0; i < sizeof(key_mappings) / sizeof(key_mappings[0]); i++) { for (size_t i = 0; i < sizeof(key_mappings) / sizeof(key_mappings[0]); i++) {
struct key_mapping mapping = key_mappings[i]; struct key_mapping mapping = key_mappings[i];
for (size_t j = 0; mapping.sequences[j] != NULL; j++) { for (size_t j = 0; mapping.sequences[j] != NULL; j++) {
@ -39,7 +38,7 @@ enum keys find_ansi(char *seq) {
} }
// https://stackoverflow.com/a/48040042 // https://stackoverflow.com/a/48040042
void read_press(u_char *length, char *out) { void read_press(u_char* length, char* out) {
*length = 0; *length = 0;
while (true) { while (true) {
@ -75,11 +74,10 @@ struct Vector vec_new() {
return vec; return vec;
} }
int vec_resize(struct Vector *vec, size_t size) { int vec_resize(struct Vector* vec, size_t size) {
void **new_location = realloc(vec->pages, size * sizeof(void*)); void** new_location = realloc(vec->pages, size * sizeof(void*));
if (new_location != NULL) { if (new_location != NULL) {
if (vec->length > size) if (vec->length > size) vec->length = size;
vec->length = size;
vec->capacity = size; vec->capacity = size;
vec->pages = new_location; vec->pages = new_location;
} else { } else {
@ -88,15 +86,16 @@ int vec_resize(struct Vector *vec, size_t size) {
return 0; return 0;
} }
int vec_reserve(struct Vector *vec, size_t size) { int vec_reserve(struct Vector* vec, size_t size) {
uint32_t new_capacity = vec->capacity; uint32_t new_capacity = vec->capacity;
while (vec->length + size > new_capacity) { while (vec->length + size > new_capacity) {
new_capacity = new_capacity + (new_capacity >> 1) + 1; // cap * 1.5 + 1; 0 1 2 4 7 11... new_capacity = new_capacity + (new_capacity >> 1) +
1; // cap * 1.5 + 1; 0 1 2 4 7 11...
} }
return vec_resize(vec, new_capacity); return vec_resize(vec, new_capacity);
} }
int vec_reserve_exact(struct Vector *vec, size_t size) { int vec_reserve_exact(struct Vector* vec, size_t size) {
uint32_t needed_capacity = vec->length + size; uint32_t needed_capacity = vec->length + size;
if (vec->capacity < needed_capacity) { if (vec->capacity < needed_capacity) {
return vec_resize(vec, needed_capacity); return vec_resize(vec, needed_capacity);
@ -105,42 +104,40 @@ int vec_reserve_exact(struct Vector *vec, size_t size) {
} }
} }
int vec_push(struct Vector *vec, void *item) { int vec_push(struct Vector* vec, void* item) {
int res_ret = vec_reserve(vec, 1); int res_ret = vec_reserve(vec, 1);
if(res_ret != 0) return res_ret; if (res_ret != 0) return res_ret;
vec->pages[vec->length++] = item; vec->pages[vec->length++] = item;
return 0; return 0;
} }
void vec_free(struct Vector *vec) { void vec_free(struct Vector* vec) {
while (vec->length > 0) while (vec->length > 0)
free(vec->pages[--vec->length]); free(vec->pages[--vec->length]);
vec_clear(vec); vec_clear(vec);
} }
void vec_clear(struct Vector *vec) { void vec_clear(struct Vector* vec) {
free(vec->pages); free(vec->pages);
vec_reset(vec); vec_reset(vec);
} }
void vec_reset(struct Vector *vec) { void vec_reset(struct Vector* vec) {
vec->length = 0; vec->length = 0;
vec->capacity = 0; vec->capacity = 0;
vec->pages = NULL; vec->pages = NULL;
} }
void *vec_pop(struct Vector *vec) { void* vec_pop(struct Vector* vec) {
if (vec->length == 0) if (vec->length == 0) return NULL;
return NULL;
return vec->pages[--vec->length]; return vec->pages[--vec->length];
} }
void *vec_get(struct Vector *vec, size_t index) { void* vec_get(struct Vector* vec, size_t index) {
if (index >= vec->length) if (index >= vec->length) return NULL;
return NULL;
return vec->pages[index]; return vec->pages[index];
} }