Code

vcs-svn: teach line_buffer to handle multiple input files
[git.git] / vcs-svn / line_buffer.c
1 /*
2  * Licensed under a two-clause BSD-style license.
3  * See LICENSE for details.
4  */
6 #include "git-compat-util.h"
7 #include "line_buffer.h"
8 #include "strbuf.h"
10 #define COPY_BUFFER_LEN 4096
12 int buffer_init(struct line_buffer *buf, const char *filename)
13 {
14         buf->infile = filename ? fopen(filename, "r") : stdin;
15         if (!buf->infile)
16                 return -1;
17         return 0;
18 }
20 int buffer_deinit(struct line_buffer *buf)
21 {
22         int err;
23         if (buf->infile == stdin)
24                 return ferror(buf->infile);
25         err = ferror(buf->infile);
26         err |= fclose(buf->infile);
27         return err;
28 }
30 /* Read a line without trailing newline. */
31 char *buffer_read_line(struct line_buffer *buf)
32 {
33         char *end;
34         if (!fgets(buf->line_buffer, sizeof(buf->line_buffer), buf->infile))
35                 /* Error or data exhausted. */
36                 return NULL;
37         end = buf->line_buffer + strlen(buf->line_buffer);
38         if (end[-1] == '\n')
39                 end[-1] = '\0';
40         else if (feof(buf->infile))
41                 ; /* No newline at end of file.  That's fine. */
42         else
43                 /*
44                  * Line was too long.
45                  * There is probably a saner way to deal with this,
46                  * but for now let's return an error.
47                  */
48                 return NULL;
49         return buf->line_buffer;
50 }
52 char *buffer_read_string(struct line_buffer *buf, uint32_t len)
53 {
54         strbuf_reset(&buf->blob_buffer);
55         strbuf_fread(&buf->blob_buffer, len, buf->infile);
56         return ferror(buf->infile) ? NULL : buf->blob_buffer.buf;
57 }
59 void buffer_copy_bytes(struct line_buffer *buf, uint32_t len)
60 {
61         char byte_buffer[COPY_BUFFER_LEN];
62         uint32_t in;
63         while (len > 0 && !feof(buf->infile) && !ferror(buf->infile)) {
64                 in = len < COPY_BUFFER_LEN ? len : COPY_BUFFER_LEN;
65                 in = fread(byte_buffer, 1, in, buf->infile);
66                 len -= in;
67                 fwrite(byte_buffer, 1, in, stdout);
68                 if (ferror(stdout)) {
69                         buffer_skip_bytes(buf, len);
70                         return;
71                 }
72         }
73 }
75 void buffer_skip_bytes(struct line_buffer *buf, uint32_t len)
76 {
77         char byte_buffer[COPY_BUFFER_LEN];
78         uint32_t in;
79         while (len > 0 && !feof(buf->infile) && !ferror(buf->infile)) {
80                 in = len < COPY_BUFFER_LEN ? len : COPY_BUFFER_LEN;
81                 in = fread(byte_buffer, 1, in, buf->infile);
82                 len -= in;
83         }
84 }
86 void buffer_reset(struct line_buffer *buf)
87 {
88         strbuf_release(&buf->blob_buffer);
89 }