From a7495db03f42661b05ca5341ef042f154df0bd1a Mon Sep 17 00:00:00 2001 From: erki Date: Wed, 25 Oct 2023 11:39:55 +0300 Subject: [PATCH] Utility: add notnull --- Tests/CMakeLists.txt | 1 + Tests/notnull.cpp | 59 +++++++++++++++++++++++++++++++++ Utility/Inc/utility_notnull.hpp | 51 ++++++++++++++++++++++++++++ 3 files changed, 111 insertions(+) create mode 100644 Tests/notnull.cpp create mode 100644 Utility/Inc/utility_notnull.hpp diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt index 69185ad..66073d1 100644 --- a/Tests/CMakeLists.txt +++ b/Tests/CMakeLists.txt @@ -32,6 +32,7 @@ add_executable(tests bytes.cpp filters.cpp cpptick.cpp + notnull.cpp ) target_link_libraries(tests diff --git a/Tests/notnull.cpp b/Tests/notnull.cpp new file mode 100644 index 0000000..6157cc6 --- /dev/null +++ b/Tests/notnull.cpp @@ -0,0 +1,59 @@ +// +// Created by erki on 25/10/23. +// + +#include + +#include + +#ifdef NDEBUG +#undef NDEBUG +#define NDEBUG_WAS_DEFINED +#endif + +#include "utility_assert.hpp" +#include "utility_notnull.hpp" + +#ifdef NDEBUG_WAS_DEFINED +#define NDEBUG +#endif + +namespace +{ + +std::atomic assert_flag = false; + +void assertCallback(const char*, const char*, const int) +{ + assert_flag = true; +} + +}// namespace + +TEST_CASE("Assert is tripped if nullptr passed.", "[utility],[notnull]") +{ + assert_flag = false; + Utility::Assert::setHandler(assertCallback); + REQUIRE(assert_flag == false); + + auto call = [](Utility::NotNull i) -> void {}; + + call(nullptr); + CHECK(assert_flag == true); +} + +TEST_CASE("Assert is not tripped if valid pointer is passed.", "[utility],[notnull]") +{ + assert_flag = false; + Utility::Assert::setHandler(assertCallback); + REQUIRE(assert_flag == false); + + auto call = [](Utility::NotNull i) -> int { + return *i; + }; + + int a = 5; + const int test = call(&a); + CHECK(assert_flag == false); + CHECK(a == test); +} diff --git a/Utility/Inc/utility_notnull.hpp b/Utility/Inc/utility_notnull.hpp new file mode 100644 index 0000000..9ee984e --- /dev/null +++ b/Utility/Inc/utility_notnull.hpp @@ -0,0 +1,51 @@ +// +// Created by erki on 25/10/23. +// + +#pragma once + +#include "utility_assert.hpp" + +namespace Utility +{ + +template +struct NotNull +{ + NotNull(T* ptr) + : ptr_(ptr) + { + SKULLC_ASSERT_DEBUG(ptr_ != nullptr); + } + + NotNull() = delete; + NotNull(const NotNull&) = delete; + NotNull(NotNull&&) = delete; + NotNull& operator=(const NotNull&) = delete; + NotNull& operator=(NotNull&&) = delete; + + const T& operator*() const + { + return *ptr_; + } + + T& operator*() + { + return *ptr_; + } + + const T* operator->() const noexcept + { + return ptr_; + } + + T* operator->() noexcept + { + return ptr_; + } + +private: + T* ptr_; +}; + +}// namespace Utility