Home | History | Annotate | Download | only in common
      1 /*
      2  * Copyright (C) 2017 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 #pragma once
     17 
     18 #include <stdio.h>
     19 #include <stdarg.h>
     20 
     21 #include <string>
     22 
     23 class Result {
     24 public:
     25     static Result success() {
     26         return Result(true);
     27     }
     28     // Construct a result indicating an error.
     29     static Result error(std::string message) {
     30         return Result(message);
     31     }
     32     static Result error(const char* format, ...) {
     33         char buffer[1024];
     34         va_list args;
     35         va_start(args, format);
     36         vsnprintf(buffer, sizeof(buffer), format, args);
     37         va_end(args);
     38         buffer[sizeof(buffer) - 1] = '\0';
     39         return Result(std::string(buffer));
     40     }
     41 
     42     bool isSuccess() const { return mSuccess; }
     43     bool operator!() const { return !mSuccess; }
     44 
     45     const char* c_str() const { return mMessage.c_str(); }
     46 private:
     47     explicit Result(bool success) : mSuccess(success) { }
     48     explicit Result(std::string message)
     49         : mMessage(message), mSuccess(false) {
     50     }
     51     std::string mMessage;
     52     bool mSuccess;
     53 };
     54 
     55