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 UNUSED
, struct reftable_block
*dest
)
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
,
31 assert(off
+ size
<= b
->len
);
32 REFTABLE_CALLOC_ARRAY(dest
->data
, size
);
35 memcpy(dest
->data
, b
->buf
+ off
, size
);
40 static uint64_t strbuf_size(void *b
)
42 return ((struct strbuf
*)b
)->len
;
45 static struct reftable_block_source_vtable strbuf_vtable
= {
47 .read_block
= &strbuf_read_block
,
48 .return_block
= &strbuf_return_block
,
49 .close
= &strbuf_close
,
52 void block_source_from_strbuf(struct reftable_block_source
*bs
,
56 bs
->ops
= &strbuf_vtable
;
60 struct file_block_source
{
65 static uint64_t file_size(void *b
)
67 return ((struct file_block_source
*)b
)->size
;
70 static void file_return_block(void *b UNUSED
, struct reftable_block
*dest UNUSED
)
74 static void file_close(void *v
)
76 struct file_block_source
*b
= v
;
77 munmap(b
->data
, b
->size
);
81 static int file_read_block(void *v
, struct reftable_block
*dest
, uint64_t off
,
84 struct file_block_source
*b
= v
;
85 assert(off
+ size
<= b
->size
);
86 dest
->data
= b
->data
+ off
;
91 static struct reftable_block_source_vtable file_vtable
= {
93 .read_block
= &file_read_block
,
94 .return_block
= &file_return_block
,
98 int reftable_block_source_from_file(struct reftable_block_source
*bs
,
101 struct file_block_source
*p
;
105 fd
= open(name
, O_RDONLY
);
108 return REFTABLE_NOT_EXIST_ERROR
;
113 if (fstat(fd
, &st
) < 0) {
114 err
= REFTABLE_IO_ERROR
;
118 REFTABLE_CALLOC_ARRAY(p
, 1);
120 err
= REFTABLE_OUT_OF_MEMORY_ERROR
;
124 p
->size
= st
.st_size
;
125 p
->data
= xmmap(NULL
, st
.st_size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
128 bs
->ops
= &file_vtable
;