summaryrefslogtreecommitdiff
path: root/src/io.cc
blob: 660c5f7b6d6433213991c7bb6f0df0ac381f777e (plain)
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
#include "io.hh"

#include "unique_fd.hh"

#include <algorithm>
#include <cerrno>
#include <cstdio>
#include <cstring>
#include <expected>
#include <fcntl.h>
#include <limits>
#include <memory>
#include <optional>
#include <string>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <utility>

namespace io {

namespace {

class BasicReader : public Reader {
 public:
  explicit BasicReader(unique_fd fd) : fd_(std::move(fd)) {}

  [[nodiscard]]
  std::expected<size_t, ReadError> read(void* dst, size_t max) override {
    ssize_t ret = ::read(
        fd_.get(), dst,
        std::min(static_cast<size_t>(std::numeric_limits<ssize_t>::max()),
                 max));
    if (ret < 0) {
      switch (errno) {
        case EINTR:
          return read(dst, max);
        default:
          return std::unexpected(ReadError::Error);
      }
    } else if (ret == 0 && max > 0) {
      return std::unexpected(ReadError::Eof);
    }
    offset_ += ret;
    return ret;
  }

  [[nodiscard]]
  std::expected<size_t, ReadError> skip(size_t max) override {
    off_t ret;
    if (sizeof(size_t) > sizeof(off_t)) {
      ret = lseek(
          fd_.get(),
          // NOLINTNEXTLINE(bugprone-narrowing-conversions)
          std::min(static_cast<size_t>(std::numeric_limits<off_t>::max()), max),
          SEEK_CUR);
    } else {
      ret = lseek(fd_.get(), static_cast<off_t>(max), SEEK_CUR);
    }
    if (ret < 0) {
      return std::unexpected(ReadError::Error);
    }
    // Don't want skip to go past (cached) file end.
    if (!size_.has_value() || ret >= size_.value()) {
      // When going past end, double check that it still is the end.
      off_t ret2 = lseek(fd_.get(), 0, SEEK_END);
      if (ret2 < 0) {
        // We're screwed, but try to go back to original position and then
        // return error.
        size_.reset();
        lseek(fd_.get(), offset_, SEEK_SET);
        return std::unexpected(ReadError::Error);
      }
      size_ = ret2;
      if (ret >= ret2) {
        auto distance = ret2 - offset_;
        offset_ = ret2;
        if (distance == 0 && max > 0)
          return std::unexpected(ReadError::Eof);
        return distance;
      }
      // Seek back to where we should be
      if (lseek(fd_.get(), ret, SEEK_SET) < 0) {
        return std::unexpected(ReadError::Error);
      }
    }
    auto distance = ret - offset_;
    offset_ = ret;
    return distance;
  }

  [[nodiscard]]
  int raw_fd() const override {
    return fd_.get();
  }

 private:
  unique_fd fd_;
  off_t offset_{0};
  std::optional<off_t> size_;
};

class MemoryReader : public Reader {
 public:
  MemoryReader(void* ptr, size_t size) : ptr_(ptr), size_(size) {}

  [[nodiscard]]
  std::expected<size_t, ReadError> read(void* dst, size_t max) override {
    size_t avail = size_ - offset_;
    if (avail == 0 && max > 0)
      return std::unexpected(io::ReadError::Eof);
    size_t ret = std::min(max, avail);
    memcpy(dst, reinterpret_cast<char*>(ptr_) + offset_, ret);
    offset_ += ret;
    return ret;
  }

  [[nodiscard]]
  std::expected<size_t, ReadError> skip(size_t max) override {
    size_t avail = size_ - offset_;
    size_t ret = std::min(max, avail);
    offset_ += ret;
    return ret;
  }

  [[nodiscard]]
  int raw_fd() const override {
    return -1;
  }

 protected:
  void* ptr_;
  size_t const size_;

 private:
  size_t offset_{0};
};

class MmapReader : public MemoryReader {
 public:
  MmapReader(unique_fd fd, void* ptr, size_t size)
      : MemoryReader(ptr, size), fd_(std::move(fd)) {}

  ~MmapReader() override { munmap(ptr_, size_); }

  [[nodiscard]]
  int raw_fd() const override {
    return fd_.get();
  }

 private:
  unique_fd fd_;
};

class StringReader : public MemoryReader {
 public:
  explicit StringReader(std::string data)
      : MemoryReader(nullptr, data.size()), data_(std::move(data)) {
    ptr_ = data_.data();
  }

 private:
  std::string data_;
};

class BasicWriter : public Writer {
 public:
  explicit BasicWriter(unique_fd fd) : fd_(std::move(fd)) {}

  [[nodiscard]]
  std::expected<size_t, WriteError> write(void const* dst,
                                          size_t size) override {
    ssize_t ret = ::write(
        fd_.get(), dst,
        std::min(static_cast<size_t>(std::numeric_limits<ssize_t>::max()),
                 size));
    if (ret < 0) {
      switch (errno) {
        case EINTR:
          return write(dst, size);
        default:
          return std::unexpected(WriteError::Error);
      }
    } else if (ret == 0 && size > 0) {
      return std::unexpected(WriteError::Error);
    }
    return ret;
  }

  [[nodiscard]]
  std::expected<void, WriteError> close() override {
    if (::close(fd_.release()) == 0)
      return {};
    return std::unexpected(WriteError::Error);
  }

  [[nodiscard]]
  int raw_fd() const override {
    return fd_.get();
  }

 private:
  unique_fd fd_;
};

}  // namespace

std::expected<size_t, ReadError> Reader::repeat_read(void* dst, size_t max) {
  auto ret = read(dst, max);
  if (!ret.has_value() || ret.value() == max)
    return ret;

  char* d = reinterpret_cast<char*>(dst);
  size_t offset = ret.value();
  while (true) {
    ret = read(d + offset, max - offset);
    if (!ret.has_value())
      break;
    offset += ret.value();
    if (offset == max)
      break;
  }
  return offset;
}

std::expected<size_t, ReadError> Reader::repeat_skip(size_t max) {
  auto ret = skip(max);
  if (!ret.has_value() || ret.value() == max)
    return ret;

  size_t offset = ret.value();
  while (true) {
    ret = skip(max - offset);
    if (!ret.has_value())
      break;
    offset += ret.value();
    if (offset == max)
      break;
  }
  return offset;
}

std::expected<size_t, WriteError> Writer::repeat_write(void const* dst,
                                                       size_t size) {
  auto ret = write(dst, size);
  if (!ret.has_value() || ret.value() == size)
    return ret;

  char const* d = reinterpret_cast<char const*>(dst);
  size_t offset = ret.value();
  while (true) {
    ret = write(d + offset, size - offset);
    if (!ret.has_value())
      break;
    offset += ret.value();
    if (offset == size)
      break;
  }
  return offset;
}

std::expected<std::unique_ptr<Reader>, OpenError> open(
    const std::string& file_path) {
  return openat(AT_FDCWD, file_path);
}

std::expected<std::unique_ptr<Reader>, OpenError> openat(
    int dirfd, const std::string& file_path) {
  unique_fd fd(::openat(dirfd, file_path.c_str(), O_RDONLY));
  if (fd) {
    struct stat buf;
    if (fstat(fd.get(), &buf) == 0) {
      if (std::cmp_less_equal(buf.st_size,
                              std::numeric_limits<size_t>::max())) {
        auto size = static_cast<size_t>(buf.st_size);
        void* ptr = mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd.get(), 0);
        if (ptr != MAP_FAILED) {
          return std::make_unique<MmapReader>(std::move(fd), ptr, size);
        }
      }
    }
    return std::make_unique<BasicReader>(std::move(fd));
  }
  OpenError err;
  switch (errno) {
    case EINTR:
      return openat(dirfd, file_path);
    case EACCES:
      err = OpenError::NoAccess;
      break;
    case ENOENT:
      err = OpenError::NoSuchFile;
      break;
    default:
      err = OpenError::Error;
      break;
  }
  return std::unexpected(err);
}

std::unique_ptr<Reader> memory(std::string data) {
  return std::make_unique<StringReader>(std::move(data));
}

std::expected<std::unique_ptr<Writer>, CreateError> create(
    const std::string& file_path, bool replace_existing) {
  return createat(AT_FDCWD, file_path, replace_existing);
}

std::expected<std::unique_ptr<Writer>, CreateError> createat(
    int dirfd, const std::string& file_path, bool replace_existing) {
  int flags = O_WRONLY | O_CREAT;
  if (replace_existing) {
    flags |= O_TRUNC;
  } else {
    flags |= O_EXCL;
  }
  unique_fd fd(::openat(dirfd, file_path.c_str(), flags, 0666));
  if (fd) {
    return std::make_unique<BasicWriter>(std::move(fd));
  }
  CreateError err;
  switch (errno) {
    case EINTR:
      return createat(dirfd, file_path, replace_existing);
    case EACCES:
      err = CreateError::NoAccess;
      break;
    case EEXIST:
      err = CreateError::Exists;
      break;
    default:
      err = CreateError::Error;
      break;
  }
  return std::unexpected(err);
}

std::expected<std::pair<std::unique_ptr<Reader>, std::unique_ptr<Writer>>,
              PipeError>
pipe() {
  int fds[2];
  if (::pipe(fds) == 0) {
    return std::make_pair(reader_from_raw(fds[0]), writer_from_raw(fds[1]));
  }
  return std::unexpected(PipeError::Error);
}

std::unique_ptr<Reader> reader_from_raw(int fd) {
  return std::make_unique<BasicReader>(unique_fd{fd});
}

std::unique_ptr<Writer> writer_from_raw(int fd) {
  return std::make_unique<BasicWriter>(unique_fd{fd});
}

}  // namespace io