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_deinit(struct line_buffer
*buf
)
23 if (buf
->infile
== stdin
)
24 return ferror(buf
->infile
);
25 err
= ferror(buf
->infile
);
26 err
|= fclose(buf
->infile
);
30 /* Read a line without trailing newline. */
31 char *buffer_read_line(struct line_buffer
*buf
)
34 if (!fgets(buf
->line_buffer
, sizeof(buf
->line_buffer
), buf
->infile
))
35 /* Error or data exhausted. */
37 end
= buf
->line_buffer
+ strlen(buf
->line_buffer
);
40 else if (feof(buf
->infile
))
41 ; /* No newline at end of file. That's fine. */
45 * There is probably a saner way to deal with this,
46 * but for now let's return an error.
49 return buf
->line_buffer
;
52 char *buffer_read_string(struct line_buffer
*buf
, uint32_t len
)
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
;
59 void buffer_read_binary(struct line_buffer
*buf
,
60 struct strbuf
*sb
, uint32_t size
)
62 strbuf_fread(sb
, size
, buf
->infile
);
65 void buffer_copy_bytes(struct line_buffer
*buf
, uint32_t len
)
67 char byte_buffer
[COPY_BUFFER_LEN
];
69 while (len
> 0 && !feof(buf
->infile
) && !ferror(buf
->infile
)) {
70 in
= len
< COPY_BUFFER_LEN
? len
: COPY_BUFFER_LEN
;
71 in
= fread(byte_buffer
, 1, in
, buf
->infile
);
73 fwrite(byte_buffer
, 1, in
, stdout
);
75 buffer_skip_bytes(buf
, len
);
81 void buffer_skip_bytes(struct line_buffer
*buf
, uint32_t len
)
83 char byte_buffer
[COPY_BUFFER_LEN
];
85 while (len
> 0 && !feof(buf
->infile
) && !ferror(buf
->infile
)) {
86 in
= len
< COPY_BUFFER_LEN
? len
: COPY_BUFFER_LEN
;
87 in
= fread(byte_buffer
, 1, in
, buf
->infile
);
92 void buffer_reset(struct line_buffer
*buf
)
94 strbuf_release(&buf
->blob_buffer
);