-
Notifications
You must be signed in to change notification settings - Fork 115
/
file.hh
83 lines (76 loc) · 2.5 KB
/
file.hh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/* Masstree
* Eddie Kohler, Yandong Mao, Robert Morris
* Copyright (c) 2012-2014 President and Fellows of Harvard College
* Copyright (c) 2012-2014 Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, subject to the conditions
* listed in the Masstree LICENSE file. These conditions include: you must
* preserve this copyright notice, and you cannot mention the copyright
* holders in advertising related to the Software without their permission.
* The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
* notice is a summary of the Masstree LICENSE file; the license in that file
* is legally binding.
*/
#ifndef KVDB_FILE_HH
#define KVDB_FILE_HH 1
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include "string.hh"
inline ssize_t
safe_read(int fd, void *buf, size_t count)
{
size_t pos = 0;
while (pos != count) {
ssize_t x = ::read(fd, buf, count - pos);
if (x != -1 && x != 0) {
buf = reinterpret_cast<char *>(buf) + x;
pos += x;
} else if (x == 0)
break;
else if (errno != EINTR && pos == 0)
return -1;
else if (errno != EINTR)
break;
}
return pos;
}
inline ssize_t
safe_write(int fd, const void *buf, size_t count)
{
size_t pos = 0;
while (pos != count) {
ssize_t x = ::write(fd, buf, count - pos);
if (x != -1 && x != 0) {
buf = reinterpret_cast<const char *>(buf) + x;
pos += x;
} else if (x == 0)
break;
else if (errno != EINTR && pos == 0)
return -1;
else if (errno != EINTR)
break;
}
return pos;
}
inline void
checked_write(int fd, const void *buf, size_t count)
{
ssize_t x = safe_write(fd, buf, count);
always_assert(size_t(x) == count);
}
template <typename T> inline void
checked_write(int fd, const T *x)
{
checked_write(fd, reinterpret_cast<const void *>(x), sizeof(*x));
}
lcdf::String read_file_contents(int fd);
lcdf::String read_file_contents(const char *filename);
int sync_write_file_contents(const char *filename, const lcdf::String &contents,
mode_t mode = 0666);
int atomic_write_file_contents(const char *filename, const lcdf::String &contents,
mode_t mode = 0666);
#endif