vcs-svn: replace buffer_read_string memory pool with a strbuf
[svn-fe.git] / line_buffer.c
blob6f32f28e5436f208a0a85bdcafe4d38a1f683631
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 LINE_BUFFER_LEN 10000
11 #define COPY_BUFFER_LEN 4096
13 static char line_buffer[LINE_BUFFER_LEN];
14 static struct strbuf blob_buffer = STRBUF_INIT;
15 static FILE *infile;
17 int buffer_init(const char *filename)
19 infile = filename ? fopen(filename, "r") : stdin;
20 if (!infile)
21 return -1;
22 return 0;
25 int buffer_deinit(void)
27 int err;
28 if (infile == stdin)
29 return ferror(infile);
30 err = ferror(infile);
31 err |= fclose(infile);
32 return err;
35 /* Read a line without trailing newline. */
36 char *buffer_read_line(void)
38 char *end;
39 if (!fgets(line_buffer, sizeof(line_buffer), infile))
40 /* Error or data exhausted. */
41 return NULL;
42 end = line_buffer + strlen(line_buffer);
43 if (end[-1] == '\n')
44 end[-1] = '\0';
45 else if (feof(infile))
46 ; /* No newline at end of file. That's fine. */
47 else
49 * Line was too long.
50 * There is probably a saner way to deal with this,
51 * but for now let's return an error.
53 return NULL;
54 return line_buffer;
57 char *buffer_read_string(uint32_t len)
59 strbuf_reset(&blob_buffer);
60 strbuf_fread(&blob_buffer, len, infile);
61 return ferror(infile) ? NULL : blob_buffer.buf;
64 void buffer_copy_bytes(uint32_t len)
66 char byte_buffer[COPY_BUFFER_LEN];
67 uint32_t in;
68 while (len > 0 && !feof(infile) && !ferror(infile)) {
69 in = len < COPY_BUFFER_LEN ? len : COPY_BUFFER_LEN;
70 in = fread(byte_buffer, 1, in, infile);
71 len -= in;
72 fwrite(byte_buffer, 1, in, stdout);
73 if (ferror(stdout)) {
74 buffer_skip_bytes(len);
75 return;
80 void buffer_skip_bytes(uint32_t len)
82 char byte_buffer[COPY_BUFFER_LEN];
83 uint32_t in;
84 while (len > 0 && !feof(infile) && !ferror(infile)) {
85 in = len < COPY_BUFFER_LEN ? len : COPY_BUFFER_LEN;
86 in = fread(byte_buffer, 1, in, infile);
87 len -= in;
91 void buffer_reset(void)
93 strbuf_release(&blob_buffer);