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
12 int buffer_init(struct line_buffer *buf, const char *filename)
14 buf->infile = filename ? fopen(filename, "r") : stdin;
20 int buffer_fdinit(struct line_buffer *buf, int fd)
22 buf->infile = fdopen(fd, "r");
28 int buffer_deinit(struct line_buffer *buf)
31 if (buf->infile == stdin)
32 return ferror(buf->infile);
33 err = ferror(buf->infile);
34 err |= fclose(buf->infile);
38 int buffer_read_char(struct line_buffer *buf)
40 return fgetc(buf->infile);
43 /* Read a line without trailing newline. */
44 char *buffer_read_line(struct line_buffer *buf)
47 if (!fgets(buf->line_buffer, sizeof(buf->line_buffer), buf->infile))
48 /* Error or data exhausted. */
50 end = buf->line_buffer + strlen(buf->line_buffer);
53 else if (feof(buf->infile))
54 ; /* No newline at end of file. That's fine. */
58 * There is probably a saner way to deal with this,
59 * but for now let's return an error.
62 return buf->line_buffer;
65 char *buffer_read_string(struct line_buffer *buf, uint32_t len)
67 strbuf_reset(&buf->blob_buffer);
68 strbuf_fread(&buf->blob_buffer, len, buf->infile);
69 return ferror(buf->infile) ? NULL : buf->blob_buffer.buf;
72 void buffer_read_binary(struct line_buffer *buf,
73 struct strbuf *sb, uint32_t size)
75 strbuf_fread(sb, size, buf->infile);
78 void buffer_copy_bytes(struct line_buffer *buf, uint32_t len)
80 char byte_buffer[COPY_BUFFER_LEN];
82 while (len > 0 && !feof(buf->infile) && !ferror(buf->infile)) {
83 in = len < COPY_BUFFER_LEN ? len : COPY_BUFFER_LEN;
84 in = fread(byte_buffer, 1, in, buf->infile);
86 fwrite(byte_buffer, 1, in, stdout);
88 buffer_skip_bytes(buf, len);
94 void buffer_skip_bytes(struct line_buffer *buf, uint32_t len)
96 char byte_buffer[COPY_BUFFER_LEN];
98 while (len > 0 && !feof(buf->infile) && !ferror(buf->infile)) {
99 in = len < COPY_BUFFER_LEN ? len : COPY_BUFFER_LEN;
100 in = fread(byte_buffer, 1, in, buf->infile);
105 void buffer_reset(struct line_buffer *buf)
107 strbuf_release(&buf->blob_buffer);