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 COPY_BUFFER_LEN 4096
11 static struct line_buffer buf_ = LINE_BUFFER_INIT;
12 static struct line_buffer *buf;
14 int buffer_init(const char *filename)
18 buf->infile = filename ? fopen(filename, "r") : stdin;
24 int buffer_deinit(void)
27 if (buf->infile == stdin)
28 return ferror(buf->infile);
29 err = ferror(buf->infile);
30 err |= fclose(buf->infile);
34 /* Read a line without trailing newline. */
35 char *buffer_read_line(void)
38 if (!fgets(buf->line_buffer, sizeof(buf->line_buffer), buf->infile))
39 /* Error or data exhausted. */
41 end = buf->line_buffer + strlen(buf->line_buffer);
44 else if (feof(buf->infile))
45 ; /* No newline at end of file. That's fine. */
49 * There is probably a saner way to deal with this,
50 * but for now let's return an error.
53 return buf->line_buffer;
56 char *buffer_read_string(uint32_t len)
58 strbuf_reset(&buf->blob_buffer);
59 strbuf_fread(&buf->blob_buffer, len, buf->infile);
60 return ferror(buf->infile) ? NULL : buf->blob_buffer.buf;
63 void buffer_copy_bytes(uint32_t len)
65 char byte_buffer[COPY_BUFFER_LEN];
67 while (len > 0 && !feof(buf->infile) && !ferror(buf->infile)) {
68 in = len < COPY_BUFFER_LEN ? len : COPY_BUFFER_LEN;
69 in = fread(byte_buffer, 1, in, buf->infile);
71 fwrite(byte_buffer, 1, in, stdout);
73 buffer_skip_bytes(len);
79 void buffer_skip_bytes(uint32_t len)
81 char byte_buffer[COPY_BUFFER_LEN];
83 while (len > 0 && !feof(buf->infile) && !ferror(buf->infile)) {
84 in = len < COPY_BUFFER_LEN ? len : COPY_BUFFER_LEN;
85 in = fread(byte_buffer, 1, in, buf->infile);
90 void buffer_reset(void)
92 strbuf_release(&buf->blob_buffer);