Home | History | Annotate | Download | only in utils
      1 /*
      2  * Copyright (C) 2018 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #pragma once
     18 
     19 #include <variant>
     20 #include <log/log.h>
     21 
     22 namespace android::uirenderer {
     23 
     24 template <typename E>
     25 struct Error {
     26     E error;
     27 };
     28 
     29 template <typename R, typename E>
     30 class Result {
     31 public:
     32     Result(const R& r) : result(std::forward<R>(r)) {}
     33     Result(R&& r) : result(std::forward<R>(r)) {}
     34     Result(Error<E>&& error) : result(std::forward<Error<E>>(error)) {}
     35 
     36     operator bool() const {
     37         return result.index() == 0;
     38     }
     39 
     40     R unwrap() const {
     41         LOG_ALWAYS_FATAL_IF(result.index() == 1, "unwrap called on error value!");
     42         return std::get<R>(result);
     43     }
     44 
     45     E error() const {
     46         LOG_ALWAYS_FATAL_IF(result.index() == 0, "No error to get from Result");
     47         return std::get<Error<E>>(result).error;
     48     }
     49 
     50 private:
     51     std::variant<R, Error<E>> result;
     52 };
     53 
     54 } // namespace android::uirenderer
     55