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
12 #include "blocksource.h"
13 #include "reftable-blocksource.h"
14 #include "reftable-error.h"
16 static void strbuf_return_block(void *b
, struct reftable_block
*dest
)
19 memset(dest
->data
, 0xff, dest
->len
);
20 reftable_free(dest
->data
);
23 static void strbuf_close(void *b
)
27 static int strbuf_read_block(void *v
, struct reftable_block
*dest
, uint64_t off
,
31 assert(off
+ size
<= b
->len
);
32 REFTABLE_CALLOC_ARRAY(dest
->data
, size
);
33 memcpy(dest
->data
, b
->buf
+ off
, size
);
38 static uint64_t strbuf_size(void *b
)
40 return ((struct strbuf
*)b
)->len
;
43 static struct reftable_block_source_vtable strbuf_vtable
= {
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
,
54 bs
->ops
= &strbuf_vtable
;
58 static void malloc_return_block(void *b
, struct reftable_block
*dest
)
61 memset(dest
->data
, 0xff, dest
->len
);
62 reftable_free(dest
->data
);
65 static struct reftable_block_source_vtable malloc_vtable
= {
66 .return_block
= &malloc_return_block
,
69 static struct reftable_block_source malloc_block_source_instance
= {
70 .ops
= &malloc_vtable
,
73 struct reftable_block_source
malloc_block_source(void)
75 return malloc_block_source_instance
;
78 struct file_block_source
{
83 static uint64_t file_size(void *b
)
85 return ((struct file_block_source
*)b
)->size
;
88 static void file_return_block(void *b
, struct reftable_block
*dest
)
92 static void file_close(void *v
)
94 struct file_block_source
*b
= v
;
95 munmap(b
->data
, b
->size
);
99 static int file_read_block(void *v
, struct reftable_block
*dest
, uint64_t off
,
102 struct file_block_source
*b
= v
;
103 assert(off
+ size
<= b
->size
);
104 dest
->data
= b
->data
+ off
;
109 static struct reftable_block_source_vtable file_vtable
= {
111 .read_block
= &file_read_block
,
112 .return_block
= &file_return_block
,
113 .close
= &file_close
,
116 int reftable_block_source_from_file(struct reftable_block_source
*bs
,
119 struct file_block_source
*p
;
123 fd
= open(name
, O_RDONLY
);
126 return REFTABLE_NOT_EXIST_ERROR
;
130 if (fstat(fd
, &st
) < 0) {
132 return REFTABLE_IO_ERROR
;
135 REFTABLE_CALLOC_ARRAY(p
, 1);
136 p
->size
= st
.st_size
;
137 p
->data
= xmmap(NULL
, st
.st_size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
141 bs
->ops
= &file_vtable
;