123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- #include <stdlib.h>
- #include <stddef.h>
- #include <string.h>
-
- #include "cms_post.h"
- #include "cms_err.h"
-
- #define PREFIX_LENGTH 5
-
- cms_post* cms_post_create()
- {
- cms_post* post = malloc(sizeof(cms_post));
- post->_str = NULL;
- post->title = NULL;
- post->slug = NULL;
- post->html = NULL;
- return post;
- }
-
- cms_err* cms_post_parse(cms_post* post, char* str, char* slugstr)
- {
- //Adding 1 because strlen() returns the length without \0
- size_t len = strlen(str) + 1;
-
- post->_str = malloc(len * sizeof(char));
- if (post->_str == NULL)
- return cms_err_create(CMS_ERR_ALLOC, NULL);
-
- memcpy(post->_str, str, len * sizeof(char));
-
- //The post's title will be the first line.
- post->title = post->_str;
-
- size_t line = 0;
- for (size_t i = 0; i < len; ++i)
- {
- char c = str[i];
-
- switch (c)
- {
- case '\n':
- line += 1;
- if (line == 2)
- {
- post->html = (post->_str + i + 1);
- }
-
- //falls through
-
- case '\r':
- post->_str[i] = '\0';
- break;
- }
-
- if (line == 2)
- break;
- }
-
- //Strip out the leading "xxxx-" from slugstr (the filename)
- //to get the real slug
- size_t slugstrlen = strlen(slugstr);
- post->slug = malloc((slugstrlen + 1 - PREFIX_LENGTH) * sizeof(char));
- if (post->slug == NULL)
- return cms_err_create(CMS_ERR_ALLOC, NULL);
-
- memcpy(post->slug, slugstr + PREFIX_LENGTH, (slugstrlen - PREFIX_LENGTH));
-
- //Add \0 to the end of the string
- post->slug[slugstrlen - PREFIX_LENGTH] = '\0';
-
- if (line >= 2)
- return cms_err_create(CMS_ERR_NONE, NULL);
- else
- return cms_err_create(CMS_ERR_PARSE, slugstr);
- }
|