]> git.cworth.org Git - wordgame/blobdiff - dict.c
Complete the dict layer by adding dict_cursor_t and dict_entry_t
[wordgame] / dict.c
diff --git a/dict.c b/dict.c
index 98c9476ce08ba09c99043d1c770249e8a3b929ac..715e48f8deaa52c73bf499a3aae856dcc16a1e24 100644 (file)
--- a/dict.c
+++ b/dict.c
@@ -116,6 +116,19 @@ trie_init (trie_t *trie)
        trie->next[i] = NULL;
 }
 
+void
+trie_destroy (trie_t *trie);
+
+static void
+trie_fini (trie_t *trie)
+{
+    int i;
+
+    for (i = 0; i < 26; i++)
+       if (trie->next[i])
+           trie_destroy (trie->next[i]);
+}
+
 trie_t *
 trie_create (void)
 {
@@ -131,11 +144,7 @@ trie_create (void)
 void
 trie_destroy (trie_t *trie)
 {
-    int i;
-
-    for (i = 0; i < 26; i++)
-       if (trie->next[i])
-           trie_destroy (trie->next[i]);
+    trie_fini (trie);
 
     free (trie);
 }
@@ -227,8 +236,27 @@ trie_print_unseen (trie_t *trie, string_t *word)
 }
 
 void
-dict_init (dict_t      *dict,
-          const char   *filename)
+dict_init (dict_t *dict)
+{
+    trie_init (dict);
+}
+
+void
+dict_fini (dict_t *dict)
+{
+    trie_fini (dict);
+}
+
+void
+dict_add_word (dict_t          *dict,
+              const char       *word)
+{
+    trie_add (dict, word);
+}
+
+void
+dict_add_words_from_file (dict_t       *dict,
+                         const char    *filename)
 {
     FILE *file;
     char *line = NULL;
@@ -242,14 +270,12 @@ dict_init (dict_t         *dict,
        exit (1);
     }
 
-    dict->trie = trie_create ();
-
     while (1) {
        bytes_read = getline (&line, &line_size, file);
        if (bytes_read == -1)
            break;
        chomp (line);
-       trie_add (dict->trie, line);
+       dict_add_word (dict, line);
     }
     if (line)
        free (line);
@@ -257,10 +283,50 @@ dict_init (dict_t         *dict,
     fclose (file);
 }
 
-void
-dict_fini (dict_t *dict)
+dict_entry_t *
+dict_lookup (dict_t    *dict,
+            const char *word)
+{
+    trie_t *trie;
+
+    trie = trie_find (dict, word);
+    if (trie == NULL)
+       return NULL;
+    else
+       return &trie->flags;
+}
+
+/* Yes, this function is rather silly. I have it here in the hope that
+ * it could be used for some better type-checking, (if only C had such
+ * a thing). */
+dict_cursor_t
+dict_root (dict_t *dict)
+{
+    return dict;
+}
+
+dict_cursor_t
+dict_cursor_next (dict_cursor_t cursor,
+                 char          next)
+{
+    trie_t *trie = cursor;
+
+    if (trie == NULL)
+       return DICT_CURSOR_NIL;
+
+    return trie->next[TRIE_CHAR_TO_INDEX (next)];
+}
+
+dict_entry_t *
+dict_cursor_resolve (dict_cursor_t cursor)
 {
-    trie_destroy (dict->trie);
+    trie_t *trie;
+
+    if (cursor == DICT_CURSOR_NIL)
+       return NULL;
+
+    trie = cursor;
+    return &trie->flags;
 }
 
 void
@@ -270,7 +336,7 @@ dict_print (dict_t *dict)
 
     string_init (&string);
 
-    trie_print (dict->trie, &string, NULL);
+    trie_print (dict, &string, NULL);
 
     string_fini (&string);
 }