]> git.lizzy.rs Git - nothing.git/blob - src/system/line_stream.c
Merge pull request #464 from tsoding/458
[nothing.git] / src / system / line_stream.c
1 #include <assert.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4
5 #include "error.h"
6 #include "line_stream.h"
7 #include "lt.h"
8 #include "lt/lt_adapters.h"
9
10 struct LineStream
11 {
12     Lt *lt;
13     FILE *stream;
14     char *buffer;
15     size_t capacity;
16 };
17
18 LineStream *create_line_stream(const char *filename,
19                                const char *mode,
20                                size_t capacity)
21 {
22     assert(filename);
23     assert(mode);
24
25     Lt *lt = create_lt();
26     if (lt == NULL) {
27         return NULL;
28     }
29
30     LineStream *line_stream = PUSH_LT(
31         lt,
32         malloc(sizeof(LineStream)),
33         free);
34     if (line_stream == NULL) {
35         throw_error(ERROR_TYPE_LIBC);
36         RETURN_LT(lt, NULL);
37     }
38     line_stream->lt = lt;
39
40     line_stream->stream = PUSH_LT(
41         lt,
42         fopen(filename, mode),
43         fclose_lt);
44     if (line_stream->stream == NULL) {
45         throw_error(ERROR_TYPE_LIBC);
46         RETURN_LT(lt, NULL);
47     }
48
49     line_stream->buffer = PUSH_LT(
50         lt,
51         malloc(sizeof(char) * capacity),
52         free);
53     if (line_stream->buffer == NULL) {
54         throw_error(ERROR_TYPE_LIBC);
55         RETURN_LT(lt, NULL);
56     }
57
58     line_stream->capacity = capacity;
59
60     return line_stream;
61 }
62
63 void destroy_line_stream(LineStream *line_stream)
64 {
65     assert(line_stream);
66
67     RETURN_LT0(line_stream->lt);
68 }
69
70 const char *line_stream_next(LineStream *line_stream)
71 {
72     assert(line_stream);
73     return fgets(line_stream->buffer,
74                  (int) line_stream->capacity,
75                  line_stream->stream);
76 }