post.c 1.06 KB
Newer Older
Matúš Sulír's avatar
Matúš Sulír committed
1
2
3
4
5
6
7
8
9
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
# include "post.h"

post_t *create_post(char *text) {
    if (strlen(text) <= MAX_POST_LENGTH) {
        post_t *post = malloc(sizeof(post_t));
        strcpy(post->text, text);
10
        post->like_count = 0;
Matúš Sulír's avatar
Matúš Sulír committed
11
12
13
14
15
16
17
18
19
20
21
        return post;
    } else {
        return NULL;
    }
}

void destroy_post(post_t *post) {
    free(post);
}

void like_post(post_t *post) {
22
    post->like_count++;
Matúš Sulír's avatar
Matúš Sulír committed
23
24
25
}

void unlike_post(post_t *post) {
26
27
    if (post->like_count > 0)
        post->like_count--;
Matúš Sulír's avatar
Matúš Sulír committed
28
29
}

30
31
32
33
34
35
36
/*
 * Returns a text representing the number of likes of the post, taking
 * singular/plural forms into account.
 * 
 * post - the post of interest
 * buf - a buffer at least 30 bytes long (if int is 64-bit)
 * 
Matúš Sulír's avatar
Matúš Sulír committed
37
 * This function is intentionally awful - it is a candidate for refactoring.
38
 */
Matúš Sulír's avatar
Matúš Sulír committed
39
char *like_count_text(post_t *post, char *buf) {
40
41
    int var1 = post->like_count;
    int var2 = (var1 == 1);
Matúš Sulír's avatar
Matúš Sulír committed
42
    sprintf(buf, "%d likes", var1);
43
44
    int len = strlen(buf);
    if (var2) {
Matúš Sulír's avatar
Matúš Sulír committed
45
        sprintf(buf, "%d like", var1);
Matúš Sulír's avatar
Matúš Sulír committed
46
47
48
    }
    return buf;
}