2 * Licensed under a two-clause BSD-style license.
3 * See LICENSE for details.
6 #include "git-compat-util.h"
7 #include "line_buffer.h"
10 #define LINE_BUFFER_LEN 10000
11 #define COPY_BUFFER_LEN 4096
13 /* Create memory pool for char sequence of known length */
14 obj_pool_gen(blob, char, 4096)
16 static char line_buffer[LINE_BUFFER_LEN];
17 static char byte_buffer[COPY_BUFFER_LEN];
20 int buffer_init(const char *filename)
22 infile = filename ? fopen(filename, "r") : stdin;
28 int buffer_deinit(void)
32 return ferror(infile);
34 err |= fclose(infile);
38 /* Read a line without trailing newline. */
39 char *buffer_read_line(void)
42 if (!fgets(line_buffer, sizeof(line_buffer), infile))
43 /* Error or data exhausted. */
45 end = line_buffer + strlen(line_buffer);
48 else if (feof(infile))
49 ; /* No newline at end of file. That's fine. */
53 * There is probably a saner way to deal with this,
54 * but for now let's return an error.
60 char *buffer_read_string(uint32_t len)
63 blob_free(blob_pool.size);
64 s = blob_pointer(blob_alloc(len + 1));
65 s[fread(s, 1, len, infile)] = '\0';
66 return ferror(infile) ? NULL : s;
69 void buffer_copy_bytes(uint32_t len)
72 while (len > 0 && !feof(infile) && !ferror(infile)) {
73 in = len < COPY_BUFFER_LEN ? len : COPY_BUFFER_LEN;
74 in = fread(byte_buffer, 1, in, infile);
76 fwrite(byte_buffer, 1, in, stdout);
78 buffer_skip_bytes(len);
84 void buffer_skip_bytes(uint32_t len)
87 while (len > 0 && !feof(infile) && !ferror(infile)) {
88 in = len < COPY_BUFFER_LEN ? len : COPY_BUFFER_LEN;
89 in = fread(byte_buffer, 1, in, infile);
94 void buffer_reset(void)