home · contact · privacy
Removed indirection in control.c and therefore unused is_command_id_shortdsc().
[plomrogue] / src / client / command_db.c
1 /* src/client/command_db.c */
2
3 #include "command_db.h"
4 #include <stdint.h> /* uint8_t, uint32_t */
5 #include <stdio.h> /* FILE */
6 #include <stdlib.h> /* free() */
7 #include <string.h> /* memcpy(), strlen(), strtok(), strcmp() */
8 #include "../common/readwrite.h" /* try_fopen(), try_fclose(), try_fgets()
9                                   * textfile_sizes()
10                                   */
11 #include "../common/try_malloc.h" /* try_malloc() */
12 #include "cleanup.h" /* set_cleanup_flag() */
13 #include "world.h" /* global world */
14
15
16
17 /* Build string pointed to by "ch_ptr" from next token delimited by "delim". */
18 static void copy_tokenized_string(char ** ch_ptr, char * delim);
19
20
21
22 static void copy_tokenized_string(char ** ch_ptr, char * delim)
23 {
24     char * f_name = "copy_tokenized_string()";
25     char * dsc_ptr = strtok(NULL, delim);
26     * ch_ptr = try_malloc(strlen(dsc_ptr) + 1, f_name);
27     memcpy(* ch_ptr, dsc_ptr, strlen(dsc_ptr) + 1);
28 }
29
30
31
32 extern uint8_t get_command_id(char * dsc_short)
33 {
34     struct Command * cmd_ptr = world.cmd_db.cmds;
35     while (1)
36     {
37         if (0 == strcmp(dsc_short, cmd_ptr->dsc_short))
38         {
39             return cmd_ptr->id;
40         }
41         cmd_ptr = &cmd_ptr[1];
42     }
43 }
44
45
46
47 extern char * get_command_longdsc(char * dsc_short)
48 {
49     struct Command * cmd_ptr = world.cmd_db.cmds;
50     while (1)
51     {
52         if (0 == strcmp(dsc_short, cmd_ptr->dsc_short))
53         {
54             return cmd_ptr->dsc_long;
55         }
56         cmd_ptr = &cmd_ptr[1];
57     }
58 }
59
60
61
62 extern void init_command_db()
63 {
64     char * f_name = "init_command_db()";
65     char * path = "confclient/commands";
66     FILE * file = try_fopen(path, "r", f_name);
67     uint32_t lines;
68     uint32_t linemax = textfile_sizes(file, &lines);
69     char line[linemax + 1];
70     world.cmd_db.cmds = try_malloc(lines * sizeof(struct Command), f_name);
71     uint8_t i = 0;
72     while (try_fgets(line, linemax + 1, file, f_name))
73     {
74         if ('\n' == line[0] || 0 == line[0])
75         {
76             break;
77         }
78         world.cmd_db.cmds[i].id = atoi(strtok(line, " "));
79         copy_tokenized_string(&world.cmd_db.cmds[i].dsc_short, " ");
80         copy_tokenized_string(&world.cmd_db.cmds[i].dsc_long, "\n");
81         i++;
82     }
83     try_fclose(file, f_name);
84     world.cmd_db.n = lines;
85     set_cleanup_flag(CLEANUP_COMMANDS);
86 }
87
88
89
90 extern void free_command_db()
91 {
92     uint8_t i = 0;
93     while (i < world.cmd_db.n)
94     {
95         free(world.cmd_db.cmds[i].dsc_short);
96         free(world.cmd_db.cmds[i].dsc_long);
97         i++;
98     }
99     free(world.cmd_db.cmds);
100 }