From 2b7f56003f27e04868bba2052e5395f68a5ad817 Mon Sep 17 00:00:00 2001 From: Ben Longbons Date: Tue, 30 Sep 2014 16:20:07 -0700 Subject: Implement Option and Borrowed --- src/compat/borrow.hpp | 101 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 src/compat/borrow.hpp (limited to 'src/compat/borrow.hpp') diff --git a/src/compat/borrow.hpp b/src/compat/borrow.hpp new file mode 100644 index 0000000..8b23d7f --- /dev/null +++ b/src/compat/borrow.hpp @@ -0,0 +1,101 @@ +#pragma once +// borrow.hpp - a non-null, unowned, pointer +// +// Copyright © 2014 Ben Longbons +// +// This file is part of The Mana World (Athena server) +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +#include "fwd.hpp" + +#include + +#include + +#include "option.hpp" + +// unit tests currention in option_test.cpp + +namespace tmwa +{ + // TODO see if const-by-default is a thing + template + class Borrowed + { + T *stupid; + public: + explicit + Borrowed(T *p) : stupid(p) + { + if (!p) abort(); + } + + T& operator *() const + { + return *stupid; + } + + T *operator ->() const + { + return stupid; + } + + template + Borrowed downcast_to() const + { + static_assert(std::is_base_of::value, "base check"); + static_assert(!std::is_same::value, "same check"); + return Borrowed(static_cast(stupid)); + } + + template + Borrowed upcast_to() const + { + static_assert(std::is_base_of::value, "base check"); + static_assert(!std::is_same::value, "same check"); + return Borrowed(stupid); + } + }; + + namespace option + { + template + class OptionRepr> + { + T *stupider; + public: + void set_none() { stupider = nullptr; } + void post_set_some() {} + bool is_some() const { return stupider != nullptr; } + Borrowed *ptr() { return reinterpret_cast *>(&stupider); } + const Borrowed *ptr() const { return reinterpret_cast *>(&stupider); } + }; + } + + template + using P = Borrowed; + + template + Borrowed borrow(T& ref) + { + return Borrowed(&ref); + } + + template + T *as_raw_pointer(Option> ptr) + { + return &*TRY_UNWRAP(ptr, return nullptr); + } +} // namespace tmwa -- cgit v1.2.3-60-g2f50