refspec: store raw refspecs inside refspec_item
[git/gitster.git] / reftable / blocksource.c
blobe93cac9bb6fbc12936f90b273f13dcea636c4dd7
1 /*
2 Copyright 2020 Google LLC
4 Use of this source code is governed by a BSD-style
5 license that can be found in the LICENSE file or at
6 https://developers.google.com/open-source/licenses/bsd
7 */
9 #include "system.h"
11 #include "basics.h"
12 #include "blocksource.h"
13 #include "reftable-blocksource.h"
14 #include "reftable-error.h"
16 static void strbuf_return_block(void *b UNUSED, struct reftable_block *dest)
18 if (dest->len)
19 memset(dest->data, 0xff, dest->len);
20 reftable_free(dest->data);
23 static void strbuf_close(void *b UNUSED)
27 static int strbuf_read_block(void *v, struct reftable_block *dest, uint64_t off,
28 uint32_t size)
30 struct strbuf *b = v;
31 assert(off + size <= b->len);
32 REFTABLE_CALLOC_ARRAY(dest->data, size);
33 memcpy(dest->data, b->buf + off, size);
34 dest->len = size;
35 return size;
38 static uint64_t strbuf_size(void *b)
40 return ((struct strbuf *)b)->len;
43 static struct reftable_block_source_vtable strbuf_vtable = {
44 .size = &strbuf_size,
45 .read_block = &strbuf_read_block,
46 .return_block = &strbuf_return_block,
47 .close = &strbuf_close,
50 void block_source_from_strbuf(struct reftable_block_source *bs,
51 struct strbuf *buf)
53 assert(!bs->ops);
54 bs->ops = &strbuf_vtable;
55 bs->arg = buf;
58 struct file_block_source {
59 uint64_t size;
60 unsigned char *data;
63 static uint64_t file_size(void *b)
65 return ((struct file_block_source *)b)->size;
68 static void file_return_block(void *b UNUSED, struct reftable_block *dest UNUSED)
72 static void file_close(void *v)
74 struct file_block_source *b = v;
75 munmap(b->data, b->size);
76 reftable_free(b);
79 static int file_read_block(void *v, struct reftable_block *dest, uint64_t off,
80 uint32_t size)
82 struct file_block_source *b = v;
83 assert(off + size <= b->size);
84 dest->data = b->data + off;
85 dest->len = size;
86 return size;
89 static struct reftable_block_source_vtable file_vtable = {
90 .size = &file_size,
91 .read_block = &file_read_block,
92 .return_block = &file_return_block,
93 .close = &file_close,
96 int reftable_block_source_from_file(struct reftable_block_source *bs,
97 const char *name)
99 struct file_block_source *p;
100 struct stat st;
101 int fd;
103 fd = open(name, O_RDONLY);
104 if (fd < 0) {
105 if (errno == ENOENT)
106 return REFTABLE_NOT_EXIST_ERROR;
107 return -1;
110 if (fstat(fd, &st) < 0) {
111 close(fd);
112 return REFTABLE_IO_ERROR;
115 REFTABLE_CALLOC_ARRAY(p, 1);
116 p->size = st.st_size;
117 p->data = xmmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
118 close(fd);
120 assert(!bs->ops);
121 bs->ops = &file_vtable;
122 bs->arg = p;
123 return 0;