-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathutil.hh
64 lines (53 loc) · 1.51 KB
/
util.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
#ifndef UTIL_HH
#define UTIL_HH
#include <system_error>
#include <iostream>
#include <string>
#include <cstring>
/* tagged_error: system_error + name of what was being attempted */
class tagged_error : public std::system_error
{
private:
std::string attempt_and_error_;
public:
tagged_error( const std::error_category & category,
const std::string & s_attempt,
const int error_code )
: system_error( error_code, category ),
attempt_and_error_( s_attempt + ": " + std::system_error::what() )
{}
const char * what() const noexcept override
{
return attempt_and_error_.c_str();
}
};
/* unix_error: a tagged_error for syscalls */
class unix_error : public tagged_error
{
public:
unix_error( const std::string & s_attempt,
const int s_errno = errno )
: tagged_error( std::system_category(), s_attempt, s_errno )
{}
};
/* print the error to the terminal */
inline void print_exception( const std::exception & e )
{
std::cerr << e.what() << std::endl;
}
/* error-checking wrapper for most syscalls */
inline int SystemCall( const char * s_attempt, const int return_value )
{
if ( return_value >= 0 ) {
return return_value;
}
throw unix_error( s_attempt );
}
/* version of SystemCall that takes a C++ std::string */
inline int SystemCall( const std::string & s_attempt, const int return_value )
{
return SystemCall( s_attempt.c_str(), return_value );
}
/* zero out an arbitrary structure */
template <typename T> void zero( T & x ) { memset( &x, 0, sizeof( x ) ); }
#endif /* UTIL_HH */