-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.c
More file actions
80 lines (66 loc) · 1.43 KB
/
string.c
File metadata and controls
80 lines (66 loc) · 1.43 KB
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
#include "strings.h"
/**
* string_dup - copies a `view_string` data type into a `string` data type.
* @data: the string to duplicate.
*
* Return: pointer to the duplicated string.
*/
void *string_dup(const void *const data)
{
const view_string * const src = data;
string *dup;
if (!src)
return (NULL);
dup = _calloc(1, sizeof(*dup));
if (!dup)
return (NULL);
dup->size = src->size;
dup->s = _strdup(src->s, src->size);
if (!dup->s)
return (_free(dup));
dup->s[dup->size] = '\0';
return (dup);
}
/**
* string_to_cstr - extract a C string from a `string` type.
* @data: pointer to the `string` type.
*
* Return: pointer to the duplicated string, NULL on failure.
*/
void *string_to_cstr(const void *const data)
{
const string *const s = data;
if (!s || !s->s || s->size < 1)
return (NULL);
return (_strdup(s->s, s->size));
}
/**
* cstr_to_string - instantiate a string type with a C string.
* @cstr: a null terminated char array.
*
* Return: pointer to the created string type, NULL on error.
*/
void *cstr_to_string(const char *const cstr)
{
view_string str = {0};
if (!cstr)
return (NULL);
str.s = cstr;
str.size = _strlen(cstr) + 1;
return (string_dup(&str));
}
/**
* string_delete - frees a `string` data type from memory.
* @data: pointer to the string to free.
*/
void string_delete(void *const data)
{
string *s = data;
if (s)
{
s->s = _free(s->s);
s->i = 0;
s->size = 0;
}
_free(s);
}