Re-sync with internal repository
[hiphop-php.git] / third-party / folly / src / folly / detail / FileUtilDetail.h
blobd522110ad5242632c7455d1f05c2444ff83d140b
1 /*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #pragma once
19 #include <cerrno>
20 #include <cstddef>
21 #include <type_traits>
23 #include <folly/portability/SysTypes.h>
25 // Private functions for wrapping file-io against interrupt and partial op
26 // completions.
28 // This header is intended to be extremely lightweight. In particular, the
29 // parallel private functions for wrapping vector file-io are in a separate
30 // header.
32 namespace folly {
33 namespace fileutil_detail {
35 // Wrap call to f(args) in loop to retry on EINTR
36 template <class F, class... Args>
37 ssize_t wrapNoInt(F f, Args... args) {
38 ssize_t r;
39 do {
40 r = f(args...);
41 } while (r == -1 && errno == EINTR);
42 return r;
45 inline void incr(ssize_t) {}
46 template <typename Offset>
47 inline void incr(ssize_t n, Offset& offset) {
48 offset += static_cast<Offset>(n);
51 // Wrap call to read/pread/write/pwrite(fd, buf, count, offset?) to retry on
52 // incomplete reads / writes. The variadic argument magic is there to support
53 // an additional argument (offset) for pread / pwrite; see the incr() functions
54 // above which do nothing if the offset is not present and increment it if it
55 // is.
56 template <class F, class... Offset>
57 ssize_t wrapFull(F f, int fd, void* buf, size_t count, Offset... offset) {
58 char* b = static_cast<char*>(buf);
59 ssize_t totalBytes = 0;
60 ssize_t r;
61 do {
62 r = f(fd, b, count, offset...);
63 if (r == -1) {
64 if (errno == EINTR) {
65 continue;
67 return r;
70 totalBytes += r;
71 b += r;
72 count -= r;
73 incr(r, offset...);
74 } while (r != 0 && count); // 0 means EOF
76 return totalBytes;
79 } // namespace fileutil_detail
80 } // namespace folly