From 11ff809614169d26efaf9c0d0a30185cf971730c Mon Sep 17 00:00:00 2001
From: Jon Bergli Heier <snakebite@jvnv.net>
Date: Fri, 14 Aug 2009 15:31:16 +0200
Subject: Added a user struct which is stored in a hash table. User nicks are
 hashed using the sdbm hash function.

---
 Makefile |  2 +-
 user.c   | 43 +++++++++++++++++++++++++++++++++++++++++++
 user.h   | 20 ++++++++++++++++++++
 3 files changed, 64 insertions(+), 1 deletion(-)
 create mode 100644 user.c
 create mode 100644 user.h

diff --git a/Makefile b/Makefile
index 92d2043..680b520 100644
--- a/Makefile
+++ b/Makefile
@@ -6,7 +6,7 @@ CFLAGS += $(shell pkg-config --cflags libconfig)
 CFLAGS += $(shell pcre-config --cflags)
 LDFLAGS += $(shell pkg-config --libs libconfig)
 LDFLAGS += $(shell pcre-config --libs)
-OBJECTS = main.o config.o regexset.o channel.o
+OBJECTS = main.o config.o regexset.o channel.o user.o
 TARGET = ircstats
 
 all: $(TARGET)
diff --git a/user.c b/user.c
new file mode 100644
index 0000000..00e44da
--- /dev/null
+++ b/user.c
@@ -0,0 +1,43 @@
+#include <stdlib.h>
+#include <string.h>
+
+#include "user.h"
+
+struct user_t *users;
+
+void user_init() {
+	users = malloc(sizeof(struct user_t) * USERS_MAX);
+	memset(users, 0, sizeof(struct user_t) * USERS_MAX);
+}
+
+static unsigned long sdbm(char *str) {
+	unsigned long hash = 0;
+	int c;
+	while(c = *str++) {
+		hash = c + (hash << 6) + (hash << 16) - hash;
+	}
+	return hash;
+}
+
+struct user_t *user_get(char *nick) {
+	unsigned long hash = sdbm(nick);
+	int index = hash % USERS_MAX;
+
+	struct user_t *user = &users[index];
+	while(user->next && user->hash != hash) user = user->next;
+	if(user->hash != hash) {
+		struct user_t *temp_user = malloc(sizeof(struct user_t));
+		user->next = temp_user;
+		user = temp_user;
+	}
+	if(!user->nick) {
+		user->hash = hash;
+		user->nick = strdup(nick);
+		user->lines = user->words = 0;
+		user->next = NULL;
+	}
+}
+
+void user_free() {
+	free(users);
+}
diff --git a/user.h b/user.h
new file mode 100644
index 0000000..b0e602b
--- /dev/null
+++ b/user.h
@@ -0,0 +1,20 @@
+#ifndef _USER_H_
+#define _USER_H_
+
+#define USERS_MAX 100
+
+struct user_t {
+	unsigned long hash;
+	char *nick;
+	unsigned long lines;
+	unsigned long long words;
+	struct user_t *next;
+};
+
+void user_init();
+struct user_t *user_get(char *nick);
+void user_free();
+
+extern struct user_t *users;
+
+#endif
-- 
cgit v1.2.3