utils: Improve option/result types

And add the beginnings of unit tests.
This commit is contained in:
Dirk-Jan C. Binnema 2020-11-26 09:26:28 +02:00
parent 4b6d9a0ce8
commit d0e357c150
5 changed files with 82 additions and 2 deletions

1
.gitignore vendored
View File

@ -122,3 +122,4 @@ mu-*-coverage
mu*tar.xz
compile_commands.json
/lib/utils/test-sexp
/lib/utils/test-option

View File

@ -116,6 +116,14 @@ test_command_parser_SOURCES= \
test_command_parser_LDADD= \
libmu-utils.la
TEST_PROGS+= \
test-option
test_option_SOURCES= \
test-option.cc
test_option_LDADD= \
libmu-utils.la
TESTS=$(TEST_PROGS)
include $(top_srcdir)/aminclude_static.am

View File

@ -19,8 +19,11 @@
namespace Mu {
/// Either a value of type T, or nothing.
/// Either a value of type T, or None
template <typename T> using Option=tl::optional<T>;
template <typename T> Option<T> Some(T&& t) { return t; }
constexpr auto Nothing = tl::nullopt; // 'None' is take already
}
#endif /*MU_OPTION__*/

View File

@ -29,10 +29,19 @@
namespace Mu {
/**
* A Result is _either_ some value of type T, _or_ an error.
*
*/
template <typename T> using Result = tl::expected<T, Error>;
template <typename T> typename Result<T>::expected_type
Ok(T&& t) {
return Result<T>::expected(std::move(t));
}
template <typename T> typename Result<T>::unexpected_type
Err(Error&& err) {
return Result<T>::unexpected(std::move(err));
}
} // namespace Mu

59
lib/utils/test-option.cc Normal file
View File

@ -0,0 +1,59 @@
/*
** Copyright (C) 2020 Dirk-Jan C. Binnema <djcb@djcbsoftware.nl>
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public License
** as published by the Free Software Foundation; either version 2.1
** of the License, or (at your option) any later version.
**
** This library 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
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free
** Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
** 02110-1301, USA.
*/
#include "mu-utils.hh"
#include "mu-option.hh"
using namespace Mu;
static Option<int>
get_opt_int (bool b)
{
if (b)
return Some(123);
else
return Nothing;
}
static void
test_option()
{
{
const auto oi{get_opt_int(true)};
g_assert_true(!!oi);
g_assert_cmpint(oi.value(),==,123);
}
{
const auto oi{get_opt_int(false)};
g_assert_false(!!oi);
g_assert_false(oi.has_value());
g_assert_cmpint(oi.value_or(456),==,456);
}
}
int
main (int argc, char *argv[])
{
g_test_init (&argc, &argv, NULL);
g_test_add_func ("/option/option", test_option);
return g_test_run ();
}