-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.c
More file actions
101 lines (77 loc) · 2.39 KB
/
string.c
File metadata and controls
101 lines (77 loc) · 2.39 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/* IFJ20 - String Library
* Authors:
* Michal Slesar, xslesa01
*/
#include "string.h"
#include <stdbool.h>
#include <string.h>
#include <malloc.h>
#include <stdio.h>
#include "error.h"
bool string_init(String *string) {
string->ptr = malloc(STRING_BLOCK_SIZE);
if(string->ptr == NULL)
throw_error_fatal(INTERNAL_ERROR, "%s", "Memory allocation error");
string->length = 0;
string->size = STRING_BLOCK_SIZE;
string->ptr[0] = '\0';
return true;
}
bool string_free(String *string) {
if(string->ptr == NULL)
return false;
free(string->ptr);
string->ptr = NULL;
string->length = 0;
string->size = 0;
return true;
}
bool string_clear(String *string) {
if(string->ptr == NULL)
return false;
string->ptr[0] = '\0';
string->length = 0;
return true;
}
bool string_append_string(String *string, const char *source) {
if(string->ptr == NULL || source == NULL)
return false;
size_t source_length = strlen(source);
/** We need to allocate more blocks if needed */
if(string->length + source_length >= string->size) {
size_t new_size = ((string->length + source_length) / STRING_BLOCK_SIZE + 1) * STRING_BLOCK_SIZE;
string->ptr = realloc(string->ptr, new_size);
if(string->ptr == NULL) {
string->length = 0;
string->size = 0;
throw_error_fatal(INTERNAL_ERROR, "%s", "Memory allocation error");
}
string->size = new_size;
}
for(size_t i = 0; i < source_length + 1; i++)
string->ptr[string->length + i] = source[i];
string->length += source_length;
return true;
}
bool string_append_char(String *string, char c) {
if(string->ptr == NULL)
return false;
/** We need to allocate more blocks if needed */
if(string->length + 1 >= string->size) {
size_t new_size = string->size + STRING_BLOCK_SIZE;
string->ptr = realloc(string->ptr, new_size);
if(string->ptr == NULL) {
string->length = 0;
string->size = 0;
throw_error_fatal(INTERNAL_ERROR, "%s", "Memory allocation error");
}
string->size = new_size;
}
string->ptr[string->length] = c;
string->length++;
string->ptr[string->length] = '\0';
return true;
}
bool string_compare(String *string1, const char *string2) {
return strcmp(string1->ptr, string2) == 0;
}