-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpointer.hh
149 lines (116 loc) · 3.16 KB
/
pointer.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
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
// Copyright (c) 2022 Mikael Simonsson <https://mikaelsimonsson.com>.
// SPDX-License-Identifier: BSL-1.0
// # File pointer wrapper
// The file pointer is implicitly closed on destruction but it is recommended to explicitly call
// `close()` and check the return value.
#pragma once
#include "snn-core/exception.hh"
#include "snn-core/optional.hh"
#include "snn-core/result.hh"
#include "snn-core/generic/error.hh"
#include "snn-core/system/error.hh"
#include <cerrno> // errno, E*
#include <cstdio> // fclose, fileno, FILE
namespace snn::file
{
// ## Classes
// ### pointer
class pointer final
{
public:
// #### Types
using trivially_relocatable_type = pointer;
// #### Constructors & assignment operators
pointer() noexcept
: fp_{nullptr}
{
}
explicit pointer(std::FILE* const fp) noexcept
: fp_{fp}
{
}
// #### Non-copyable
pointer(const pointer&) = delete;
pointer& operator=(const pointer&) = delete;
// #### Movable
pointer(pointer&& other) noexcept
: fp_{std::exchange(other.fp_, nullptr)}
{
}
pointer& operator=(pointer&& other) noexcept
{
swap(other);
return *this;
}
// #### Destructor
~pointer()
{
close().discard();
}
// #### Explicit conversion operators
explicit operator bool() const noexcept
{
return has_value();
}
// #### Close
[[nodiscard]] result<void> close() noexcept
{
if (has_value())
{
const int ret = std::fclose(std::exchange(fp_, nullptr));
if (ret == 0)
{
return {};
}
return error_code{errno, system::error_category};
}
return generic::error::no_value;
}
// #### Descriptor
[[nodiscard]] optional<int> integer_descriptor() const noexcept
{
if (has_value())
{
return ::fileno(fp_);
}
return nullopt;
}
// #### Swap
void swap(pointer& other) noexcept
{
std::swap(fp_, other.fp_);
}
// #### Value
[[nodiscard]] bool has_value() const noexcept
{
return fp_ != nullptr;
}
[[nodiscard]] std::FILE* value() const
{
if (has_value())
{
return fp_;
}
throw_or_abort(generic::error::no_value);
}
[[nodiscard]] std::FILE* value(promise::has_value_t) const noexcept
{
snn_should(has_value());
return fp_;
}
[[nodiscard]] std::FILE* value_or(std::FILE* const alt) const noexcept
{
if (has_value())
{
return fp_;
}
return alt;
}
private:
std::FILE* fp_;
};
inline void swap(pointer& a, pointer& b) noexcept
{
a.swap(b);
}
}