-
Notifications
You must be signed in to change notification settings - Fork 0
/
library.c
78 lines (68 loc) · 1.97 KB
/
library.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
#include "library.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*
* Brief: Allocate dynamic storage long enough to store
* [meta data] + [original string]
* This will copy passed string into dynamically allocated storage
* and store length of a string in meta-data
*
* Args: constant pointer to character string
*
* Returns: NCS string containing meta-data + original string. Pointer is
* pointing to starting of a string. So, that normal C string functions
* works just fine out of box.
*/
char* ncs_new(const char *str)
{
size_t len = strlen(str);
char *new_str = (char *)malloc(sizeof(size_t) + len + 1);
size_t *lptr = (size_t *)new_str;
*lptr = len;
new_str = (char *)++lptr;
strcpy(new_str, str);
return new_str;
}
/*
* Brief: Find length of a NCS string from the meta-data.
* Args: NCS string [Caution: passing normal string might result in an incorrect data or a crash]
* Returns: Length of a string
*/
size_t ncs_len(const char *str)
{
size_t *lptr = (size_t *)str;
--lptr;
return *lptr;
}
/*
* Brief: Concatenate C string into NCS string
* Arg1: NCS string [Caution: passing normal string might result in an incorrect data or a crash]
* Arg2: C string [You can also pass NCS string]
* Returns: New concatenated NCS string
*/
char* ncs_cat(const char *nstr, const char *str)
{
size_t *ncs_lptr = (size_t *)nstr;
--ncs_lptr;
size_t new_len = *ncs_lptr + strlen(str);
char *ncs_cat_str = (char *)malloc(sizeof(size_t) + new_len + 1);
size_t *lptr = (size_t *)ncs_cat_str;
*lptr = new_len;
ncs_cat_str = (char *)++lptr;
strcpy(ncs_cat_str, nstr);
strcat(ncs_cat_str, str);
return ncs_cat_str;
}
/*
* Brief: Deallocate NCS string by calling system free() call
* Args: Pointer to NCS string [Caution: Passing normal string might result in a crash]
* Returns: Nothing
*/
void ncs_free(const char *str)
{
size_t *lptr = (size_t *)str;
lptr--;
free(lptr);
return;
}