Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of https://framagit.org/mwapl/simgrid
[simgrid.git] / include / xbt / system_error.hpp
1 /* Copyright (c) 2016-2023. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include <cerrno>
8
9 #include <system_error>
10
11 #ifndef SIMGRID_MC_SYSTEM_ERROR_HPP
12 #define SIMGRID_MC_SYSTEM_ERROR_HPP
13
14 namespace simgrid::xbt {
15
16 /** A `error_category` suitable to be used with `errno`
17  *
18  *  It is not clear which error we are supposed to generate
19  *  when getting an errno:
20  *
21  *  * `system_error` clearly cannot be used for this on Windows;
22  *
23  *  * `generic_error` might not be used for non-standard `errno`.
24  *
25  *  Let's just define a function which gives us the correct
26  *  category.
27  */
28 inline
29 const std::error_category& errno_category() noexcept
30 {
31   return std::generic_category();
32 }
33
34 /** Create a `error_code` from an `errno` value
35  *
36  *  This is expected to to whatever is right to create a
37  *  `error_code` from a given `errno` value.
38  */
39 inline
40 std::error_code errno_code(int errnum)
41 {
42   return std::error_code(errnum, errno_category());
43 }
44
45 /** Create an `error_code` from `errno` (and clear it) */
46 inline
47 std::error_code errno_code()
48 {
49   int errnum = errno;
50   errno = 0;
51   return errno_code(errnum);
52 }
53
54 /** Create a `system_error` from an `errno` value
55  *
56  *  This is expected to to whatever is right to create a
57  *  `system_error` from a given `errno` value.
58  */
59 inline
60 std::system_error errno_error(int errnum)
61 {
62   return std::system_error(errno_code(errnum));
63 }
64
65 inline
66 std::system_error errno_error(int errnum, const char* what)
67 {
68   return std::system_error(errno_code(errnum), what);
69 }
70
71 /** Create a `system_code` from `errno` (and clear it) */
72 inline
73 std::system_error errno_error()
74 {
75   return std::system_error(errno_code());
76 }
77
78 inline
79 std::system_error errno_error(const char* what)
80 {
81   return std::system_error(errno_code(), what);
82 }
83
84 } // namespace simgrid::xbt
85
86 #endif