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
)
18 memset(dest
->data
, 0xff, dest
->len
);
19 reftable_free(dest
->data
);
22 static void strbuf_close(void *b
)
26 static int strbuf_read_block(void *v
, struct reftable_block
*dest
, uint64_t off
,
30 assert(off
+ size
<= b
->len
);
31 dest
->data
= reftable_calloc(size
);
32 memcpy(dest
->data
, b
->buf
+ off
, size
);
37 static uint64_t strbuf_size(void *b
)
39 return ((struct strbuf
*)b
)->len
;
42 static struct reftable_block_source_vtable strbuf_vtable
= {
44 .read_block
= &strbuf_read_block
,
45 .return_block
= &strbuf_return_block
,
46 .close
= &strbuf_close
,
49 void block_source_from_strbuf(struct reftable_block_source
*bs
,
53 bs
->ops
= &strbuf_vtable
;
57 static void malloc_return_block(void *b
, struct reftable_block
*dest
)
59 memset(dest
->data
, 0xff, dest
->len
);
60 reftable_free(dest
->data
);
63 static struct reftable_block_source_vtable malloc_vtable
= {
64 .return_block
= &malloc_return_block
,
67 static struct reftable_block_source malloc_block_source_instance
= {
68 .ops
= &malloc_vtable
,
71 struct reftable_block_source
malloc_block_source(void)
73 return malloc_block_source_instance
;
76 struct file_block_source
{
81 static uint64_t file_size(void *b
)
83 return ((struct file_block_source
*)b
)->size
;
86 static void file_return_block(void *b
, struct reftable_block
*dest
)
88 memset(dest
->data
, 0xff, dest
->len
);
89 reftable_free(dest
->data
);
92 static void file_close(void *b
)
94 int fd
= ((struct file_block_source
*)b
)->fd
;
97 ((struct file_block_source
*)b
)->fd
= 0;
103 static int file_read_block(void *v
, struct reftable_block
*dest
, uint64_t off
,
106 struct file_block_source
*b
= v
;
107 assert(off
+ size
<= b
->size
);
108 dest
->data
= reftable_malloc(size
);
109 if (pread(b
->fd
, dest
->data
, size
, off
) != size
)
115 static struct reftable_block_source_vtable file_vtable
= {
117 .read_block
= &file_read_block
,
118 .return_block
= &file_return_block
,
119 .close
= &file_close
,
122 int reftable_block_source_from_file(struct reftable_block_source
*bs
,
125 struct stat st
= { 0 };
127 int fd
= open(name
, O_RDONLY
);
128 struct file_block_source
*p
= NULL
;
130 if (errno
== ENOENT
) {
131 return REFTABLE_NOT_EXIST_ERROR
;
136 err
= fstat(fd
, &st
);
140 p
= reftable_calloc(sizeof(struct file_block_source
));
141 p
->size
= st
.st_size
;
145 bs
->ops
= &file_vtable
;