Rework pool_tok_seq and pool_print_seq.
[svn-fe.git] / line_buffer.c
blob1b0f70c7326e8a7010a76e29e121f834da7a472a
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
5 #include "line_buffer.h"
6 #include "obj_pool.h"
8 #define LINE_BUFFER_LEN 10000
9 #define COPY_BUFFER_LEN 4096
11 /* Create memory pool for char sequence of known length */
12 obj_pool_gen(blob, char, 4096);
14 static char line_buffer[LINE_BUFFER_LEN];
15 static char byte_buffer[COPY_BUFFER_LEN];
16 static uint32_t line_buffer_len = 0;
17 static uint32_t line_len = 0;
19 char *buffer_read_line(void)
21 char *end;
22 uint32_t n_read;
24 if (line_len) {
25 memmove(line_buffer, &line_buffer[line_len],
26 line_buffer_len - line_len);
27 line_buffer_len -= line_len;
28 line_len = 0;
31 end = memchr(line_buffer, '\n', line_buffer_len);
32 while (line_buffer_len < LINE_BUFFER_LEN - 1 &&
33 !feof(stdin) && NULL == end) {
34 n_read =
35 fread(&line_buffer[line_buffer_len], 1,
36 LINE_BUFFER_LEN - 1 - line_buffer_len,
37 stdin);
38 end = memchr(&line_buffer[line_buffer_len], '\n', n_read);
39 line_buffer_len += n_read;
42 if (ferror(stdin))
43 return NULL;
45 if (end != NULL) {
46 line_len = end - line_buffer;
47 line_buffer[line_len++] = '\0';
48 } else {
49 line_len = line_buffer_len;
50 line_buffer[line_buffer_len] = '\0';
53 if (line_len == 0)
54 return NULL;
56 return line_buffer;
59 char *buffer_read_string(uint32_t len)
61 char *s;
62 blob_free(blob_pool.size);
63 s = blob_pointer(blob_alloc(len + 1));
64 uint32_t offset = 0;
65 if (line_buffer_len > line_len) {
66 offset = line_buffer_len - line_len;
67 if (offset > len)
68 offset = len;
69 memcpy(s, &line_buffer[line_len], offset);
70 line_len += offset;
72 while (offset < len && !feof(stdin)) {
73 offset += fread(&s[offset], 1, len - offset, stdin);
75 s[offset] = '\0';
76 return s;
79 void buffer_copy_bytes(uint32_t len)
81 uint32_t in, out;
82 if (line_buffer_len > line_len) {
83 in = line_buffer_len - line_len;
84 if (in > len)
85 in = len;
86 out = 0;
87 while (out < in && !ferror(stdout)) {
88 out +=
89 fwrite(&line_buffer[line_len + out], 1, in - out, stdout);
91 len -= in;
92 line_len += in;
94 while (len > 0 && !feof(stdin)) {
95 in = len < COPY_BUFFER_LEN ? len : COPY_BUFFER_LEN;
96 in = fread(byte_buffer, 1, in, stdin);
97 len -= in;
98 out = 0;
99 while (out < in && !ferror(stdout)) {
100 out += fwrite(&byte_buffer[out], 1, in - out, stdout);
105 void buffer_skip_bytes(uint32_t len)
107 uint32_t in;
108 if (line_buffer_len > line_len) {
109 in = line_buffer_len - line_len;
110 if (in > len)
111 in = len;
112 line_len += in;
113 len -= in;
115 while (len > 0 && !feof(stdin)) {
116 in = len < COPY_BUFFER_LEN ? len : COPY_BUFFER_LEN;
117 in = fread(byte_buffer, 1, in, stdin);
118 len -= in;
122 void buffer_reset(void)
124 blob_reset();