GCC Code Coverage Report


Directory: cvmfs/
File: cvmfs/util/file_guard.h
Date: 2024-04-28 02:33:07
Exec Total Coverage
Lines: 14 14 100.0%
Branches: 4 6 66.7%

Line Branch Exec Source
1 /**
2 * This file is part of the CernVM File System.
3 */
4
5 #ifndef CVMFS_UTIL_FILE_GUARD_H_
6 #define CVMFS_UTIL_FILE_GUARD_H_
7
8 #include <unistd.h>
9
10 #include <cstdio>
11 #include <string>
12
13 #include "util/single_copy.h"
14
15 #ifdef CVMFS_NAMESPACE_GUARD
16 namespace CVMFS_NAMESPACE_GUARD {
17 #endif
18
19
20 /**
21 * RAII object to call `unlink()` on a containing file when it gets out of scope
22 */
23 class UnlinkGuard : SingleCopy {
24 public:
25 enum InitialState { kEnabled, kDisabled };
26
27 25 inline UnlinkGuard() : enabled_(false) {}
28 472 inline explicit UnlinkGuard(const std::string &path,
29 const InitialState state = kEnabled)
30 472 : path_(path)
31 472 , enabled_(state == kEnabled) {}
32
2/2
✓ Branch 1 taken 154 times.
✓ Branch 2 taken 340 times.
494 inline ~UnlinkGuard() { if (IsEnabled()) unlink(path_.c_str()); }
33
34 25 inline void Set(const std::string &path) { path_ = path; Enable(); }
35
36 974 inline bool IsEnabled() const { return enabled_; }
37 133 inline void Enable() { enabled_ = true; }
38 7 inline void Disable() { enabled_ = false; }
39
40 2146 const std::string& path() const { return path_; }
41
42 private:
43 std::string path_;
44 bool enabled_;
45 };
46
47
48 /**
49 * RAII object to close a file descriptor when it gets out of scope
50 */
51 class FdGuard : SingleCopy {
52 public:
53 inline FdGuard() : fd_(-1) { }
54 10 explicit inline FdGuard(const int fd) : fd_(fd) { }
55
1/2
✓ Branch 0 taken 10 times.
✗ Branch 1 not taken.
10 inline ~FdGuard() { if (fd_ >= 0) close(fd_); }
56 int fd() const { return fd_; }
57
58 private:
59 int fd_;
60 };
61
62
63 /**
64 * RAII object to close a FILE stream when it gets out of scope
65 */
66 class FileGuard : SingleCopy {
67 public:
68 inline FileGuard() : file_(NULL) { }
69 608 explicit inline FileGuard(FILE *file) : file_(file) { }
70
1/2
✓ Branch 0 taken 608 times.
✗ Branch 1 not taken.
608 inline ~FileGuard() { if (file_ != NULL) fclose(file_); }
71 const FILE *file() const { return file_; }
72
73 private:
74 FILE *file_;
75 };
76
77
78 #ifdef CVMFS_NAMESPACE_GUARD
79 } // namespace CVMFS_NAMESPACE_GUARD
80 #endif
81
82 #endif // CVMFS_UTIL_FILE_GUARD_H_
83