Add a file reading routine along with an io buffer type In particular, the gitfo_read_file() routine can be used to slurp the complete file contents into an gitfo_buf structure. The buffer content will be allocated by malloc() and may be released by the gitfo_free_buf() routine. The io buffer type can be initialised on the stack with the GITFO_BUF_INIT macro. Signed-off-by: Ramsay Jones <ramsay@ramsay1.demon.co.uk> Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
diff --git a/src/common.h b/src/common.h
index f5be02b..bdf2334 100644
--- a/src/common.h
+++ b/src/common.h
@@ -4,6 +4,7 @@
#include "cc-compat.h"
#include "util.h"
#include "errors.h"
+#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
diff --git a/src/fileops.c b/src/fileops.c
index e5f6ef8..caa7d9e 100644
--- a/src/fileops.c
+++ b/src/fileops.c
@@ -49,6 +49,43 @@ off_t gitfo_size(git_file fd)
return sb.st_size;
}
+int gitfo_read_file(gitfo_buf *obj, const char *path)
+{
+ git_file fd;
+ off_t len;
+ void *buff;
+
+ assert(obj && path && *path);
+
+ if ((fd = gitfo_open(path, O_RDONLY)) < 0)
+ return GIT_ERROR; /* TODO: error handling */
+
+ if (((len = gitfo_size(fd)) < 0) || ((buff = malloc(len)) == NULL)) {
+ gitfo_close(fd);
+ return GIT_ERROR; /* TODO: error handling */
+ }
+
+ if (gitfo_read(fd, buff, len) < 0) {
+ gitfo_close(fd);
+ free(buff);
+ return GIT_ERROR; /* TODO: error handling */
+ }
+
+ gitfo_close(fd);
+
+ obj->data = buff;
+ obj->len = len;
+
+ return GIT_SUCCESS;
+}
+
+void gitfo_free_buf(gitfo_buf *obj)
+{
+ assert(obj);
+ free(obj->data);
+ obj->data = NULL;
+}
+
/* cached diskio */
struct gitfo_cache {
git_file fd;
diff --git a/src/fileops.h b/src/fileops.h
index 2683a6b..d25d5d3 100644
--- a/src/fileops.h
+++ b/src/fileops.h
@@ -21,10 +21,18 @@
#include "errors.h"
#include "git/fileops.h"
+#define GITFO_BUF_INIT {NULL, 0}
+
typedef int git_file;
typedef struct stat gitfo_statbuf;
typedef struct gitfo_cache gitfo_cache;
+typedef struct { /* file io buffer */
+ void *data; /* data bytes */
+ size_t len; /* data length */
+} gitfo_buf;
+
+
#define gitfo_open(path, flags) open(path, flags)
#define gitfo_close(fd) close(fd)
@@ -37,6 +45,9 @@ extern off_t gitfo_size(git_file fd);
#define gitfo_stat(path, buf) stat(path, buf)
#define gitfo_fsync(fd) fsync(fd)
+extern int gitfo_read_file(gitfo_buf *obj, const char *path);
+extern void gitfo_free_buf(gitfo_buf *obj);
+
extern gitfo_cache *gitfo_enable_caching(git_file fd, size_t cache_size);
extern int gitfo_write_cached(gitfo_cache *ioc, void *buf, size_t len);
extern int gitfo_flush_cached(gitfo_cache *ioc);