2020-11-09 08:20:54 +01:00
|
|
|
/*
|
2023-07-05 22:10:13 +02:00
|
|
|
** Copyright (C) 2023 Dirk-Jan C. Binnema <djcb@djcbsoftware.nl>
|
|
|
|
**
|
|
|
|
** 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, 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, write to the Free Software Foundation,
|
|
|
|
** Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
|
|
|
**
|
|
|
|
*/
|
2020-11-09 08:20:54 +01:00
|
|
|
|
|
|
|
#ifndef MU_OPTION__
|
|
|
|
#define MU_OPTION__
|
|
|
|
|
2023-07-03 21:45:01 +02:00
|
|
|
#include <tl/optional.hpp>
|
2023-08-09 19:13:12 +02:00
|
|
|
#include <stdexcept>
|
2022-04-16 12:16:29 +02:00
|
|
|
#include <string>
|
2020-11-09 08:20:54 +01:00
|
|
|
|
|
|
|
namespace Mu {
|
|
|
|
|
2020-11-26 08:26:28 +01:00
|
|
|
/// Either a value of type T, or None
|
2021-10-20 11:18:15 +02:00
|
|
|
template <typename T> using Option = tl::optional<T>;
|
2020-11-09 08:20:54 +01:00
|
|
|
|
2021-10-20 11:18:15 +02:00
|
|
|
template <typename T>
|
|
|
|
Option<T>
|
|
|
|
Some(T&& t)
|
|
|
|
{
|
|
|
|
return std::move(t);
|
|
|
|
}
|
2023-07-05 22:10:13 +02:00
|
|
|
constexpr auto Nothing = tl::nullopt; // 'None' is already taken.
|
2020-11-26 08:26:28 +01:00
|
|
|
|
2023-08-09 19:13:12 +02:00
|
|
|
template<typename T> T
|
|
|
|
unwrap(Option<T>&& res)
|
|
|
|
{
|
|
|
|
if (!!res)
|
|
|
|
return std::move(res.value());
|
|
|
|
else
|
|
|
|
throw std::runtime_error("failure is not an option");
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2022-04-16 12:16:29 +02:00
|
|
|
/**
|
|
|
|
* Maybe create a string from a const char pointer.
|
|
|
|
*
|
|
|
|
* @param str a char pointer or NULL
|
|
|
|
*
|
|
|
|
* @return option with either the string or nothing if str was NULL.
|
|
|
|
*/
|
|
|
|
Option<std::string>
|
|
|
|
static inline to_string_opt(const char* str) {
|
|
|
|
if (str)
|
|
|
|
return std::string{str};
|
|
|
|
else
|
|
|
|
return Nothing;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Like maybe_string that takes a const char*, but additionally,
|
|
|
|
* g_free() the string.
|
|
|
|
*
|
|
|
|
* @param str char pointer or NULL (consumed)
|
|
|
|
*
|
|
|
|
* @return option with either the string or nothing if str was NULL.
|
|
|
|
*/
|
|
|
|
Option<std::string> to_string_opt_gchar(char*&& str);
|
|
|
|
|
|
|
|
|
2021-10-20 11:18:15 +02:00
|
|
|
} // namespace Mu
|
2020-11-09 08:20:54 +01:00
|
|
|
#endif /*MU_OPTION__*/
|