AmendHub

Download:

jcs

/

subtext

/

amendments

/

136

session: Turn sessions array into a static array of pointers

This doesn't need to keep moving around and resizing, walking it is
easy

jcs made amendment 136 over 2 years ago
--- session.c Wed Jun 8 21:55:55 2022 +++ session.c Sun Jun 12 09:38:55 2022 @@ -35,7 +35,7 @@ #include "console.h" -struct session **sessions = NULL; +struct session *sessions[MAX_SESSIONS] = { 0 }; short nsessions = 0; void session_run(struct uthread *uthread, void *arg); @@ -50,7 +50,13 @@ struct session * session_create(char *node, char *via, struct node_funcs *node_funcs) { struct session *session; + size_t n; + + if (nsessions >= MAX_SESSIONS) + return NULL; + nsessions++; + session = xmalloczero(sizeof(struct session)); session->uthread = uthread_add(session_run, session); if (!session->uthread) { @@ -64,11 +70,15 @@ session_create(char *node, char *via, struct node_func strlcpy(session->via, via, sizeof(session->via)); session->last_input_at = Time; - nsessions++; - sessions = xreallocarray(sessions, nsessions, sizeof(struct session)); - sessions[nsessions - 1] = session; + for (n = 0; n < MAX_SESSIONS; n++) { + if (sessions[n] == NULL) { + sessions[n] = session; + return session; + } + } - return session; + panic("session_create failed to find slot for new session (%d)", + nsessions); } void @@ -258,9 +268,9 @@ get_another_char: void session_close(struct session *session) { - struct session **newsessions; unsigned long now; - short newnsessions, n; + short n; + bool found; if (!session->ending) { /* give 1 second to flush output */ @@ -287,23 +297,20 @@ session_close(struct session *session) session->node_funcs->close(session); /* remove session from sessions */ - newnsessions = nsessions - 1; - if (newnsessions) { - newsessions = xcalloc(newnsessions, sizeof(struct session)); - nsessions = 0; - for (n = 0; n < newnsessions; n++) { - if (sessions[n] == session) - continue; - newsessions[nsessions++] = sessions[n]; + found = false; + for (n = 0; n < MAX_SESSIONS; n++) { + if (sessions[n] == session) { + sessions[n] = NULL; + found = true; + break; } - } else { - nsessions = 0; - newsessions = NULL; } - free(sessions); - sessions = newsessions; - free(session); + if (!found) + panic("session_close failed to find session to remove"); + + nsessions--; + free(sessions); } void @@ -1199,7 +1206,10 @@ session_who(struct session *s) "{{B}}Node User Via Speed Idle{{/B}}\r\n"); session_flush(s); - for (n = 0; n < nsessions; n++) { + for (n = 0; n < MAX_SESSIONS; n++) { + if (sessions[n] == NULL) + continue; + idle = Time - sessions[n]->last_input_at; if (idle < 60) sprintf(idle_s, "%lds", idle); --- session.h Tue Jun 7 21:21:41 2022 +++ session.h Sun Jun 12 09:24:34 2022 @@ -97,7 +97,8 @@ struct session { struct uthread *uthread; }; -extern struct session **sessions; +#define MAX_SESSIONS 20 +extern struct session *sessions[MAX_SESSIONS]; extern short nsessions; struct session_tally {