From b4d8e166d854679941396f59e5b43ce4a21e697a Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Sun, 5 Sep 2021 13:32:15 +0200 Subject: AK: Add a TRY(expression) macro to simplify the unwrap-or-return pattern The way we use classes like Kernel::KResultOr and AK::Result makes checking for errors (and short-circuiting returns) quite verbose. This patch adds a new TRY(expression) macro that either evaluates to the released result of the expression if successful, or returns the error if not. Before: auto foo_or_error = get_foo(); if (foo_or_error.is_error()) return foo_or_error.release_error(); auto foo = foo_or_error.release_value(); After: auto foo = TRY(get_foo()); The macro uses a GNU C++ extension which is supported by GCC, Clang, Intel C++, and possibly others. It's not *ideal*, but since it makes our codebase considerably nicer, let's try(!) it out. :^) Co-authored-by: Ali Mohammad Pur --- AK/Try.h | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 AK/Try.h (limited to 'AK/Try.h') diff --git a/AK/Try.h b/AK/Try.h new file mode 100644 index 0000000000..862fc7dbc5 --- /dev/null +++ b/AK/Try.h @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2021, Andreas Kling + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +// NOTE: This macro works with any result type that has the expected APIs. +// It's designed with AK::Result and Kernel::KResult in mind. + +#define TRY(expression) \ + ({ \ + auto result = (expression); \ + if (result.is_error()) \ + return result.release_error(); \ + result.release_value(); \ + }) -- cgit v1.2.3