-
Notifications
You must be signed in to change notification settings - Fork 0
/
istream.c
100 lines (82 loc) · 2.06 KB
/
istream.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
* Project name:
* Implementace interpretu imperativního jazyka IFJ14
*
* Repository:
* https://github.com/Dasio/IFJ
*
* Team:
* Dávid Mikuš (xmikus15)
* Peter Hostačný (xhosta03)
* Tomáš Kello (xkello00)
* Adam Lučanský (xlucan01)
* Michaela Lukášová (xlukas09)
*/
#include "istream.h"
IStream initIStream() {
IStream stream = {
.src_type = IStream_NONE,
.src_file = NULL,
.src_string = NULL,
.current_char = NULL
};
return stream;
}
void destroyIStream(IStream *stream) {
assert(stream);
if(stream->src_type == IStream_FILE && stream->src_file != NULL) {
fclose(stream->src_file);
}
if(stream->src_type == IStream_STRING) {
stream->src_string = NULL;
stream->current_char = NULL;
}
stream->src_type = IStream_NONE;
// if src_type == IStream_NONE, nothing happens
}
bool assignFile(IStream *stream, char *input_file) {
assert(stream);
assert(input_file);
assert(stream->src_type == IStream_NONE);
stream->src_type = IStream_FILE;
stream->src_file = fopen(input_file, "r");
if(stream->src_file == NULL)
setError(ERR_CannotOpenFile);
return stream->src_file;
}
void assignString(IStream *stream, char *array_of_chars) {
assert(stream);
assert(array_of_chars);
assert(stream->src_type == IStream_NONE);
stream->src_type = IStream_STRING;
stream->src_string = array_of_chars;
stream->current_char = array_of_chars;
}
int nextChar(IStream *stream) {
assert(stream);
assert(stream->src_type != IStream_NONE);
if(stream->src_type == IStream_FILE) {
assert(stream->src_file);
return fgetc(stream->src_file);
} else {
// IStream_STRING
if(*(stream->current_char) != (char) 0) {
// SIDE EFFECT INCREMENT !!
return (int) *(stream->current_char++);
} else {
return EOF;
}
}
}
void returnChar(IStream *stream, int c) {
assert(stream);
assert(stream->src_type != IStream_NONE);
assert(c != EOF && "returned character cannot be EOF");
if(stream->src_type == IStream_FILE) {
ungetc(c, stream->src_file);
} else {
// string
if(stream->current_char > stream->src_string)
stream->current_char--;
}
}