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