1 //===-- A simple classes to manage error return vals ----------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #ifndef LLVM_LIBC_SRC_SUPPORT_CPP_ERROR_H 10 #define LLVM_LIBC_SRC_SUPPORT_CPP_ERROR_H 11 12 namespace __llvm_libc { 13 namespace cpp { 14 // Many C functions return an error val and/or the actual result of the 15 // evaluation/operation performed by the function. This file defines a simple 16 // convenience data structure to encapsulate the error and the actual val in 17 // a single place. 18 19 struct Error { 20 int error_code; 21 }; 22 23 // This class is implemented in a simple fashion as the intention is it add 24 // more generality as required. Currently, it only supports simple copyable 25 // types for T. 26 template <typename T> class ErrorOr { 27 bool is_error; 28 29 union { 30 T val; 31 Error error; 32 }; 33 34 public: ErrorOr(const T & value)35 ErrorOr(const T &value) : is_error(false), val(value) {} 36 ErrorOr(const Error & error)37 ErrorOr(const Error &error) : is_error(true), error(error) {} 38 39 operator bool() { return !is_error; } 40 41 operator T &() { return val; } 42 value()43 T &value() { return val; } 44 error_code()45 int error_code() { return is_error ? error.error_code : 0; } 46 }; 47 48 } // namespace cpp 49 } // namespace __llvm_libc 50 51 #endif // LLVM_LIBC_SRC_SUPPORT_CPP_ERROR_H 52