| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | //====================================================================================================================== | ||
| 2 | //! @file | ||
| 3 | /* | ||
| 4 | TTS - Tiny Test System | ||
| 5 | Copyright : TTS Contributors & Maintainers | ||
| 6 | SPDX-License-Identifier: BSL-1.0 | ||
| 7 | */ | ||
| 8 | //====================================================================================================================== | ||
| 9 | #pragma once | ||
| 10 | |||
| 11 | #include <tts/tools/preprocessor.hpp> | ||
| 12 | #include <cstdio> | ||
| 13 | |||
| 14 | namespace tts::_ | ||
| 15 | { | ||
| 16 | // Not std::unique_ptr: avoids <memory> - see doc/compile_time.hpp. | ||
| 17 | TTS_DISABLE_WARNING_PUSH | ||
| 18 | TTS_DISABLE_WARNING_CRT_SECURE | ||
| 19 | class file_guard | ||
| 20 | { | ||
| 21 | public: | ||
| 22 | 2 | file_guard() = default; | |
| 23 | |||
| 24 | 2 | explicit file_guard(FILE* f) | |
| 25 | 2 | : file_(f) | |
| 26 | { | ||
| 27 | 2 | } | |
| 28 | |||
| 29 | file_guard(file_guard const&) = delete; | ||
| 30 | file_guard& operator=(file_guard const&) = delete; | ||
| 31 | |||
| 32 | 2 | file_guard(file_guard&& other) noexcept | |
| 33 | 2 | : file_guard() | |
| 34 | { | ||
| 35 | 2 | swap(other); | |
| 36 | 2 | } | |
| 37 | |||
| 38 | 2 | file_guard& operator=(file_guard&& other) noexcept | |
| 39 | { | ||
| 40 | 2 | file_guard {TTS_MOVE(other)}.swap(*this); | |
| 41 | 2 | return *this; | |
| 42 | } | ||
| 43 | |||
| 44 | 104 | ~file_guard() | |
| 45 | { | ||
| 46 | 104 | close(); | |
| 47 | 104 | } | |
| 48 | |||
| 49 | 4 | void swap(file_guard& other) noexcept | |
| 50 | { | ||
| 51 | 4 | FILE* tmp = file_; | |
| 52 | 4 | file_ = other.file_; | |
| 53 | 4 | other.file_ = tmp; | |
| 54 | 4 | } | |
| 55 | |||
| 56 | 1 | FILE* get() const | |
| 57 | { | ||
| 58 | 1 | return file_; | |
| 59 | } | ||
| 60 | 299 | explicit operator bool() const | |
| 61 | { | ||
| 62 | 299 | return file_ != nullptr; | |
| 63 | } | ||
| 64 | |||
| 65 | private: | ||
| 66 | 104 | void close() | |
| 67 | { | ||
| 68 |
2/2✓ Branch 0 taken 1 times.
✓ Branch 1 taken 103 times.
|
104 | if(file_) fclose(file_); |
| 69 | 104 | file_ = nullptr; | |
| 70 | 104 | } | |
| 71 | |||
| 72 | FILE* file_ = nullptr; | ||
| 73 | }; | ||
| 74 | TTS_DISABLE_WARNING_POP | ||
| 75 | } | ||
| 76 |