-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.c
88 lines (71 loc) · 1.67 KB
/
user.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include "user.h"
#include <stdlib.h>
#include <string.h>
user *user_create(char *name)
{
if (name == NULL) return NULL;
size_t name_len = strlen(name) + 1;
user *u = (user *)calloc(1, sizeof(user));
if (u == NULL) {
return NULL;
}
u->name = (char *)calloc(name_len, sizeof(char));
if (u->name == NULL) {
free(u);
return NULL;
}
u->name = strncpy(u->name, name, name_len);
u->objects = list_create(object_compare, object_destroy, object_dump);
return u;
}
object *user_search_object(user *u, void *name)
{
if (name == NULL) return NULL;
return (object *)list_search_unsafe(u->objects, name);
}
list_result user_insert_object(user *u, char *name, size_t len)
{
if (u == NULL) return list_null;
object *obj = object_create(name, len);
return list_insert_unsafe(u->objects, obj);
}
object *user_delete_object(user *u, void *name)
{
if (u == NULL || name == NULL) {
return NULL;
}
return list_delete_unsafe(u->objects, name);
}
int user_compare(void *usr, void *usr_name)
{
user *u = (user *)usr;
char *username = (char *)usr_name;
if (u == NULL && username == NULL) return 0;
if (u == NULL) return 1;
if (username == NULL) return -1;
return strcmp(u->name, username);
}
void user_dump(void *usr, FILE *f)
{
if (usr == NULL) return;
user *u = (user *)usr;
if (u->name == NULL) {
fprintf(f, "0\n");
} else {
fprintf(f, "%zu\n", strlen(u->name));
fprintf(f, "%s\n", u->name);
}
if (u->objects == NULL) {
fprintf(f, "0\n");
} else {
list_dump(u->objects, f);
}
}
void user_destroy(void *usr)
{
if (usr == NULL) return;
user *u = (user *)usr;
if (u->name != NULL) free(u->name);
if (u->objects != NULL) list_destroy(u->objects);
free(u);
}