Use the printf channel in our main example.
[cascardo/sgp.git] / src / group.c
index 3566557..d8046a1 100644 (file)
 #include <sgp/group.h>
 #include <sgp/friend.h>
 #include <stdlib.h>
+#include <errno.h>
 
 struct sgp_group {
+       char *name;
        struct sgp_friend **friends;
        int nr_friends;
 };
 
-struct sgp_group * sgp_group_new()
+struct sgp_group * sgp_group_new(char *name)
 {
        struct sgp_group *group;
        group = malloc(sizeof(*group));
+       if (!group)
+               return NULL;
+       group->name = strdup(name);
+       if (!group->name)
+               goto out;
        group->nr_friends = 0;
        group->friends = NULL;
        return group;
+out:
+       free(group);
+       return NULL;
 }
 
+void sgp_group_destroy(struct sgp_group *group)
+{
+       if (group->friends)
+               free(group->friends);
+       free(group->name);
+       free(group);
+}
+
+char * sgp_group_get_name(struct sgp_group *group)
+{
+       return group->name;
+}
+
+/*
+ * TODO: start using references. The group can't take it if we want to
+ * add a friend to more groups. A single global reference for all
+ * friends may be good enough.
+ */
 int sgp_group_add_friend(struct sgp_group *group, struct sgp_friend *friend)
 {
+       struct sgp_friend **old_friends;
+       old_friends = group->friends;
+       group->nr_friends++;
+       group->friends = realloc(old_friends,
+                               group->nr_friends * sizeof(friend));
+       if (!group->friends) {
+               group->friends = old_friends;
+               group->nr_friends--;
+               return -ENOMEM;
+       }
+       group->friends[group->nr_friends - 1] = friend;
        return 0;
 }