Utility: add notnull
All checks were successful
CI & Unit Tests / Unit-Tests (push) Successful in 1m34s

This commit is contained in:
erki 2023-10-25 11:39:55 +03:00
parent 0271b0d0de
commit a7495db03f
3 changed files with 111 additions and 0 deletions

View File

@ -32,6 +32,7 @@ add_executable(tests
bytes.cpp bytes.cpp
filters.cpp filters.cpp
cpptick.cpp cpptick.cpp
notnull.cpp
) )
target_link_libraries(tests target_link_libraries(tests

59
Tests/notnull.cpp Normal file
View File

@ -0,0 +1,59 @@
//
// Created by erki on 25/10/23.
//
#include <catch2/catch.hpp>
#include <atomic>
#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<bool> 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<int> 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<int> i) -> int {
return *i;
};
int a = 5;
const int test = call(&a);
CHECK(assert_flag == false);
CHECK(a == test);
}

View File

@ -0,0 +1,51 @@
//
// Created by erki on 25/10/23.
//
#pragma once
#include "utility_assert.hpp"
namespace Utility
{
template<typename T>
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