deadcef4c1
obj_pool is inherently global and does not use the standard growing factor alloc_nr, which makes it feel out of place in the git codebase. Plus it is overkill for this application: all that is needed is a buffer that can grow between requests to accomodate larger strings. Use a strbuf instead. As a side effect, this improves the error handling: allocation failures will result in a clean exit instead of segfaults. It would be nice to add a test case (using ulimit or failmalloc) but that can wait for another day. Signed-off-by: Jonathan Nieder <jrnieder@gmail.com>
95 lines
1.9 KiB
C
95 lines
1.9 KiB
C
/*
|
|
* Licensed under a two-clause BSD-style license.
|
|
* See LICENSE for details.
|
|
*/
|
|
|
|
#include "git-compat-util.h"
|
|
#include "line_buffer.h"
|
|
#include "strbuf.h"
|
|
|
|
#define LINE_BUFFER_LEN 10000
|
|
#define COPY_BUFFER_LEN 4096
|
|
|
|
static char line_buffer[LINE_BUFFER_LEN];
|
|
static struct strbuf blob_buffer = STRBUF_INIT;
|
|
static FILE *infile;
|
|
|
|
int buffer_init(const char *filename)
|
|
{
|
|
infile = filename ? fopen(filename, "r") : stdin;
|
|
if (!infile)
|
|
return -1;
|
|
return 0;
|
|
}
|
|
|
|
int buffer_deinit(void)
|
|
{
|
|
int err;
|
|
if (infile == stdin)
|
|
return ferror(infile);
|
|
err = ferror(infile);
|
|
err |= fclose(infile);
|
|
return err;
|
|
}
|
|
|
|
/* Read a line without trailing newline. */
|
|
char *buffer_read_line(void)
|
|
{
|
|
char *end;
|
|
if (!fgets(line_buffer, sizeof(line_buffer), infile))
|
|
/* Error or data exhausted. */
|
|
return NULL;
|
|
end = line_buffer + strlen(line_buffer);
|
|
if (end[-1] == '\n')
|
|
end[-1] = '\0';
|
|
else if (feof(infile))
|
|
; /* No newline at end of file. That's fine. */
|
|
else
|
|
/*
|
|
* Line was too long.
|
|
* There is probably a saner way to deal with this,
|
|
* but for now let's return an error.
|
|
*/
|
|
return NULL;
|
|
return line_buffer;
|
|
}
|
|
|
|
char *buffer_read_string(uint32_t len)
|
|
{
|
|
strbuf_reset(&blob_buffer);
|
|
strbuf_fread(&blob_buffer, len, infile);
|
|
return ferror(infile) ? NULL : blob_buffer.buf;
|
|
}
|
|
|
|
void buffer_copy_bytes(uint32_t len)
|
|
{
|
|
char byte_buffer[COPY_BUFFER_LEN];
|
|
uint32_t in;
|
|
while (len > 0 && !feof(infile) && !ferror(infile)) {
|
|
in = len < COPY_BUFFER_LEN ? len : COPY_BUFFER_LEN;
|
|
in = fread(byte_buffer, 1, in, infile);
|
|
len -= in;
|
|
fwrite(byte_buffer, 1, in, stdout);
|
|
if (ferror(stdout)) {
|
|
buffer_skip_bytes(len);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
void buffer_skip_bytes(uint32_t len)
|
|
{
|
|
char byte_buffer[COPY_BUFFER_LEN];
|
|
uint32_t in;
|
|
while (len > 0 && !feof(infile) && !ferror(infile)) {
|
|
in = len < COPY_BUFFER_LEN ? len : COPY_BUFFER_LEN;
|
|
in = fread(byte_buffer, 1, in, infile);
|
|
len -= in;
|
|
}
|
|
}
|
|
|
|
void buffer_reset(void)
|
|
{
|
|
strbuf_release(&blob_buffer);
|
|
}
|