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_tmpfile_init(struct line_buffer
*buf
)
30 buf
->infile
= tmpfile();
36 int buffer_deinit(struct line_buffer
*buf
)
39 if (buf
->infile
== stdin
)
40 return ferror(buf
->infile
);
41 err
= ferror(buf
->infile
);
42 err
|= fclose(buf
->infile
);
46 FILE *buffer_tmpfile_rewind(struct line_buffer
*buf
)
52 long buffer_tmpfile_prepare_to_read(struct line_buffer
*buf
)
54 long pos
= ftell(buf
->infile
);
56 return error("ftell error: %s", strerror(errno
));
57 if (fseek(buf
->infile
, 0, SEEK_SET
))
58 return error("seek error: %s", strerror(errno
));
62 int buffer_read_char(struct line_buffer
*buf
)
64 return fgetc(buf
->infile
);
67 /* Read a line without trailing newline. */
68 char *buffer_read_line(struct line_buffer
*buf
)
71 if (!fgets(buf
->line_buffer
, sizeof(buf
->line_buffer
), buf
->infile
))
72 /* Error or data exhausted. */
74 end
= buf
->line_buffer
+ strlen(buf
->line_buffer
);
77 else if (feof(buf
->infile
))
78 ; /* No newline at end of file. That's fine. */
82 * There is probably a saner way to deal with this,
83 * but for now let's return an error.
86 return buf
->line_buffer
;
89 char *buffer_read_string(struct line_buffer
*buf
, uint32_t len
)
91 strbuf_reset(&buf
->blob_buffer
);
92 strbuf_fread(&buf
->blob_buffer
, len
, buf
->infile
);
93 return ferror(buf
->infile
) ? NULL
: buf
->blob_buffer
.buf
;
96 void buffer_read_binary(struct line_buffer
*buf
,
97 struct strbuf
*sb
, uint32_t size
)
99 strbuf_fread(sb
, size
, buf
->infile
);
102 void buffer_copy_bytes(struct line_buffer
*buf
, uint32_t len
)
104 char byte_buffer
[COPY_BUFFER_LEN
];
106 while (len
> 0 && !feof(buf
->infile
) && !ferror(buf
->infile
)) {
107 in
= len
< COPY_BUFFER_LEN
? len
: COPY_BUFFER_LEN
;
108 in
= fread(byte_buffer
, 1, in
, buf
->infile
);
110 fwrite(byte_buffer
, 1, in
, stdout
);
111 if (ferror(stdout
)) {
112 buffer_skip_bytes(buf
, len
);
118 void buffer_skip_bytes(struct line_buffer
*buf
, uint32_t len
)
120 char byte_buffer
[COPY_BUFFER_LEN
];
122 while (len
> 0 && !feof(buf
->infile
) && !ferror(buf
->infile
)) {
123 in
= len
< COPY_BUFFER_LEN
? len
: COPY_BUFFER_LEN
;
124 in
= fread(byte_buffer
, 1, in
, buf
->infile
);
129 void buffer_reset(struct line_buffer
*buf
)
131 strbuf_release(&buf
->blob_buffer
);