aboutsummaryrefslogtreecommitdiff
path: root/include/cru/base/platform/unix/UnixFile.h
blob: 63545428810778ae1dc23f903b30cbdb14adc068 (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
#pragma once

#if !defined(__unix)
#error "This file can only be included on unix."
#endif

#include "../../Bitmask.h"

#include <functional>

namespace cru::platform::unix {
class UnixFileDescriptor {
 public:
  UnixFileDescriptor();
  /**
   * \param close Default to POSIX close function.
   */
  explicit UnixFileDescriptor(int descriptor, bool auto_close = true,
                              std::function<int(int)> close = {});
  ~UnixFileDescriptor();

  UnixFileDescriptor(const UnixFileDescriptor& other) = delete;
  UnixFileDescriptor& operator=(const UnixFileDescriptor& other) = delete;

  UnixFileDescriptor(UnixFileDescriptor&& other) noexcept;
  UnixFileDescriptor& operator=(UnixFileDescriptor&& other) noexcept;

  bool IsValid() const;
  int GetValue() const;
  void Close();

  bool IsAutoClose() const { return auto_close_; }
  void SetAutoClose(bool auto_close) { this->auto_close_ = auto_close; }

  explicit operator bool() const { return this->IsValid(); }
  operator int() const { return this->GetValue(); }

 private:
  bool DoClose();

 private:
  int descriptor_;
  bool auto_close_;
  std::function<int(int)> close_;
};

struct UniDirectionalUnixPipeResult {
  UnixFileDescriptor read;
  UnixFileDescriptor write;
};

namespace details {
struct UnixPipeFlagTag;
}
using UnixPipeFlag = Bitmask<details::UnixPipeFlagTag>;
struct UnixPipeFlags {
  constexpr static auto NonBlock = UnixPipeFlag::FromOffset(1);
};

UniDirectionalUnixPipeResult OpenUniDirectionalPipe(UnixPipeFlag flags = {});
}  // namespace cru::platform::unix