diff --git a/server/src/chat.c b/server/src/chat.c index 229c69e..ce74fff 100644 --- a/server/src/chat.c +++ b/server/src/chat.c @@ -1,4 +1,5 @@ #include "include/chat.h" +#include "include/data.h" #include "include/session.h" #include @@ -8,6 +9,38 @@ #include #include +MsgData* chat_history[CHAT_HISTORY_SZ] = {NULL}; +size_t chat_history_head = 0; + +MsgData* chat_history_msg_add(MsgData* msg) { + if (chat_history_head < CHAT_HISTORY_SZ - 1) { + chat_history[chat_history_head] = msg; + chat_history_head++; + } else if (chat_history_head == CHAT_HISTORY_SZ - 1) { + chat_history[chat_history_head] = msg; + chat_history_head = 0; + } else { + exit(132); // Bad. + } + + return msg; +} + +MsgData** chat_history_nice(void) { + MsgData** msgs = calloc(CHAT_HISTORY_SZ, sizeof(MsgData*)); + + size_t i = chat_history_head, j = 0; + while (true) { + if (!chat_history[i]) break; + msgs[j] = chat_history[i]; + i = (i + 1) % CHAT_HISTORY_SZ; + j++; + if (chat_history_head == i) break; + } + + return msgs; +} + static size_t next_msg_id = 1; // History buffer for last 100 messages. diff --git a/server/src/include/chat.h b/server/src/include/chat.h index 6e6a5b6..4af0f49 100644 --- a/server/src/include/chat.h +++ b/server/src/include/chat.h @@ -1,7 +1,23 @@ #ifndef CHAT_H #define CHAT_H +#include "data.h" + #include +#include +#include + +// Message history (ring). +#define CHAT_HISTORY_SZ 128 +extern MsgData* chat_history[CHAT_HISTORY_SZ]; +extern size_t chat_history_head; // Points to the oldest message, or NULL. + +// Add message to history ring. +MsgData* chat_history_msg_add(MsgData* msg); + +// Get a list of messages in order. +MsgData** chat_history_nice(void); + /** * cb_chat - libwebsockets protocol callback for COMS chat.