-
Notifications
You must be signed in to change notification settings - Fork 0
/
str.c
81 lines (67 loc) · 2.15 KB
/
str.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
79
80
81
/*
* Project: Compiler for imperative programing language IFJ20
*
* File: str.c
* Brief: Implementation of dynamic string.
* Source: Jednoduchy interpret - http://www.fit.vutbr.cz/study/courses/IFJ/public/project/
*
* Authors: Hladký Tomáš xhladk15@stud.fit.vutbr.cz
* Kostolányi Adam xkosto04@stud.fit.vutbr.cz
* Makiš Jozef xmakis00@stud.fit.vutbr.cz
* Bartko Jakub xbartk07@stud.fit.vutbr.cz
*/
#include "str.h"
#include "error.h"
#include <stdlib.h>
#include <string.h>
void str_init(string *s) {
//allocates string to char len size
s->str = (char *) malloc(STR_LEN_INC);
if (s->str == NULL) {
error(99,"str.c", "str_init(string *s)", "Internal error");
}
s->str[0] = '\0';
s->str_lenght = 8;
s->str_alloc_size = STR_LEN_INC;
}
void str_free(string *s) {
free(s->str);
}
void str_clear(string *s) {
s->str[0] = '\0';
s->str_lenght = 0;
}
void str_add_char(string *s, char c) {
if (s->str_lenght + 1 >= s->str_alloc_size) {
//if there is not enoguh memory, we reallocate
s->str = (char *) realloc(s->str, s->str_lenght + STR_LEN_INC);
if (s->str == NULL) {
error(99,"str.c", "str_add_char(string *s, char c)", "Internal error");
}
s->str_alloc_size = s->str_lenght + STR_LEN_INC;
}
//adds char and increments lenght for '\0'
s->str[s->str_lenght] = c;
s->str_lenght++;
s->str[s->str_lenght] = '\0';
}
void str_copy(string *s1, string *s2) {
int new_str_lenght = s2->str_lenght;
//if there is not enoguh memory, we reallocate
if (new_str_lenght >= s1->str_alloc_size) {
s1->str = (char *) realloc(s1->str, new_str_lenght + 1);
if (s1->str == NULL) {
error(99,"str.c", "str_copy(string *s1, string *s2)", "Internal error");
}
s1->str_alloc_size = new_str_lenght + 1;
}
//copies string and and changes new lenght
strcpy(s1->str, s2->str);
s1->str_lenght = new_str_lenght;
}
int str_cmp_cons(string *s, char *s_const) {
return strcmp(s->str, s_const);
}
int str_cmp(string *s1, string *s2) {
return strcmp(s1->str, s2->str);
}