Coverage Report

Created: 2020-05-07 18:36

/proc/self/cwd/c/file.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
Copyright 2020 Google LLC
3
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
*/
8
9
#include "system.h"
10
11
#include "block.h"
12
#include "iter.h"
13
#include "record.h"
14
#include "reftable.h"
15
#include "tree.h"
16
17
struct file_block_source {
18
  int fd;
19
  uint64_t size;
20
};
21
22
static uint64_t file_size(void *b)
23
330
{
24
330
  return ((struct file_block_source *)b)->size;
25
330
}
26
27
static void file_return_block(void *b, struct reftable_block *dest)
28
1.58k
{
29
1.58k
  memset(dest->data, 0xff, dest->len);
30
1.58k
  reftable_free(dest->data);
31
1.58k
}
32
33
static void file_close(void *b)
34
330
{
35
330
  int fd = ((struct file_block_source *)b)->fd;
36
330
  if (fd > 0) {
37
330
    close(fd);
38
330
    ((struct file_block_source *)b)->fd = 0;
39
330
  }
40
330
41
330
  reftable_free(b);
42
330
}
43
44
static int file_read_block(void *v, struct reftable_block *dest, uint64_t off,
45
         uint32_t size)
46
1.58k
{
47
1.58k
  struct file_block_source *b = (struct file_block_source *)v;
48
1.58k
  assert(off + size <= b->size);
49
1.58k
  dest->data = reftable_malloc(size);
50
1.58k
  if (pread(b->fd, dest->data, size, off) != size) {
51
0
    return -1;
52
0
  }
53
1.58k
  dest->len = size;
54
1.58k
  return size;
55
1.58k
}
56
57
struct reftable_block_source_vtable file_vtable = {
58
  .size = &file_size,
59
  .read_block = &file_read_block,
60
  .return_block = &file_return_block,
61
  .close = &file_close,
62
};
63
64
int reftable_block_source_from_file(struct reftable_block_source *bs,
65
            const char *name)
66
330
{
67
330
  struct stat st = { 0 };
68
330
  int err = 0;
69
330
  int fd = open(name, O_RDONLY);
70
330
  if (fd < 0) {
71
0
    if (errno == ENOENT) {
72
0
      return REFTABLE_NOT_EXIST_ERROR;
73
0
    }
74
0
    return -1;
75
0
  }
76
330
77
330
  err = fstat(fd, &st);
78
330
  if (err < 0) {
79
0
    return -1;
80
0
  }
81
330
82
330
  {
83
330
    struct file_block_source *p =
84
330
      reftable_calloc(sizeof(struct file_block_source));
85
330
    p->size = st.st_size;
86
330
    p->fd = fd;
87
330
88
330
    assert(bs->ops == NULL);
89
330
    bs->ops = &file_vtable;
90
330
    bs->arg = p;
91
330
  }
92
330
  return 0;
93
330
}
94
95
int reftable_fd_write(void *arg, byte *data, size_t sz)
96
399
{
97
399
  int *fdp = (int *)arg;
98
399
  return write(*fdp, data, sz);
99
399
}