From 8f8d738e0eb9c863b266a84bb72d136f22f315b3 Mon Sep 17 00:00:00 2001 From: Avril Date: Thu, 10 Jun 2021 15:49:15 +0100 Subject: [PATCH] c++: CowException for handling errors/poisoned cows --- Makefile | 2 +- include/cow.hpp | 11 +++++++++++ src/cow.cpp | 10 ++++++++-- src/test/main.cpp | 9 ++++++--- 4 files changed, 26 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index d2f627e..fc142e2 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ PROJECT=cow AUTHOR=Avril (Flanchan) VERSION_MAJOR=0 -VERSION_MINOR=2.0r0 +VERSION_MINOR=2.0r1 VERSION=$(VERSION_MAJOR).$(VERSION_MINOR) ifeq ($(PREFIX),) diff --git a/include/cow.hpp b/include/cow.hpp index 19b1651..b11dcb1 100644 --- a/include/cow.hpp +++ b/include/cow.hpp @@ -3,9 +3,20 @@ #include "cow.h" #include +#include #include "cow/slice.hpp" +struct CowException : public std::exception +{ + inline CowException(cow_err_kind k) : kind(k){} + + const char* what() const noexcept override; + inline ~CowException(){} + + const cow_err_kind kind; +}; + struct Cow : public _cow_util::Span { struct Fake; Cow() = delete; diff --git a/src/cow.cpp b/src/cow.cpp index 2f9fa56..a8cb14f 100644 --- a/src/cow.cpp +++ b/src/cow.cpp @@ -29,11 +29,11 @@ Cow::_inner::~_inner() { } Cow::_inner::_inner(size_t sz) : cow(_cow_create_unboxed(sz)){ //TODO: Real exception type? - if(UNLIKELY(cow.poisoned)) throw "POISONED"; + if(UNLIKELY(cow.poisoned)) throw CowException(cow_err()); } Cow::_inner::_inner(cow_t* ptr) : cow(*ptr) { - if(UNLIKELY(cow.poisoned)) throw "POISONED"; + if(UNLIKELY(cow.poisoned)) throw CowException(cow_err()); free(ptr); } @@ -66,4 +66,10 @@ Cow::Fake Cow::Fake::Fake::from_real(const Cow& real) { return Fake(real); } Cow::Fake Cow::Fake::clone() const { return Fake(*static_cast(this)); } cow_t* Cow::Fake::get_raw() const { return fake; } +// Error +const char* CowException::what() const noexcept { + auto str = cow_err_msg(kind); + if(str && *str) return *str; + else return "Unknown error"; +} diff --git a/src/test/main.cpp b/src/test/main.cpp index 7292050..ee1420f 100644 --- a/src/test/main.cpp +++ b/src/test/main.cpp @@ -217,9 +217,12 @@ int main() read_fake(clone); //clone still functions because of refcount on origin. printf("Last error: %d, %s\n", cow_err(), *cow_err_msg(cow_err())); - Cow should_fail(SIZE_MAX); - printf("Last error: %d, %s\n", cow_err(), *cow_err_msg(cow_err())); - Cow::Fake should_fail_clone = should_fail; + try { + Cow should_fail(SIZE_MAX); + Cow::Fake should_fail_clone = should_fail; + } catch (CowException& cw) { + printf("Error! (%d) %s\n", cw.kind, cw.what()); + } printf("Last error: %d, %s\n", cow_err(), *cow_err_msg(cow_err())); return 0; }