status.h 4.34 KB
Newer Older
gejun's avatar
gejun committed
1
// Copyright (c) 2015 Baidu, Inc.
gejun's avatar
gejun committed
2

gejun's avatar
gejun committed
3 4
#ifndef BAIDU_BASE_STATUS_H
#define BAIDU_BASE_STATUS_H
gejun's avatar
gejun committed
5 6 7 8 9

#include <stdarg.h>                       // va_list
#include <stdlib.h>                       // free
#include <string>                         // std::string
#include <ostream>                        // std::ostream
10
#include "butil/strings/string_piece.h"
gejun's avatar
gejun committed
11

12
namespace butil {
gejun's avatar
gejun committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

// A Status encapsulates the result of an operation. It may indicate success,
// or it may indicate an error with an associated error message. It's suitable
// for passing status of functions with richer information than just error_code
// in exception-forbidden code. This utility is inspired by leveldb::Status.
//
// Multiple threads can invoke const methods on a Status without
// external synchronization, but if any of the threads may call a
// non-const method, all threads accessing the same Status must use
// external synchronization.
//
// Since failed status needs to allocate memory, you should be careful when
// failed status is frequent.

class Status {
public:
    struct State {
        int code;
        unsigned size;  // length of message string
        unsigned state_size;
        char message[0];
    };

    // Create a success status.
    Status() : _state(NULL) { }
    // Return a success status.
    static Status OK() { return Status(); }

    ~Status() { reset(); }

    // Create a failed status.
    // error_text is formatted from `fmt' and following arguments.
    Status(int code, const char* fmt, ...) 
        __attribute__ ((__format__ (__printf__, 3, 4)))
        : _state(NULL) {
        va_list ap;
        va_start(ap, fmt);
        set_errorv(code, fmt, ap);
        va_end(ap);
    }
53
    Status(int code, const butil::StringPiece& error_msg) : _state(NULL) {
gejun's avatar
gejun committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67
        set_error(code, error_msg);
    }

    // Copy the specified status. Internal fields are deeply copied.
    Status(const Status& s);
    void operator=(const Status& s);

    // Reset this status to be OK.
    void reset();
    
    // Reset this status to be failed.
    // Returns 0 on success, -1 otherwise and internal fields are not changed.
    int set_error(int code, const char* error_format, ...)
        __attribute__ ((__format__ (__printf__, 3, 4)));
68
    int set_error(int code, const butil::StringPiece& error_msg);
gejun's avatar
gejun committed
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    int set_errorv(int code, const char* error_format, va_list args);

    // Returns true iff the status indicates success.
    bool ok() const { return (_state == NULL); }

    // Get the error code
    int error_code() const {
        return (_state == NULL) ? 0 : _state->code;
    }

    // Return a string representation of the status.
    // Returns "OK" for success.
    // NOTICE:
    //   * You can print a Status to std::ostream directly
    //   * if message contains '\0', error_cstr() will not be shown fully.
    const char* error_cstr() const {
        return (_state == NULL ? "OK" : _state->message);
    }
87 88 89
    butil::StringPiece error_data() const {
        return (_state == NULL ? butil::StringPiece("OK", 2) 
                : butil::StringPiece(_state->message, _state->size));
gejun's avatar
gejun committed
90 91 92
    }
    std::string error_str() const;

93
    void swap(butil::Status& other) { std::swap(_state, other._state); }
gejun's avatar
gejun committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130

private:    
    // OK status has a NULL _state.  Otherwise, _state is a State object
    // converted from malloc().
    State* _state;

    static State* copy_state(const State* s);
};

inline Status::Status(const Status& s) {
    _state = (s._state == NULL) ? NULL : copy_state(s._state);
}

inline int Status::set_error(int code, const char* msg, ...) {
    va_list ap;
    va_start(ap, msg);
    const int rc = set_errorv(code, msg, ap);
    va_end(ap);
    return rc;
}

inline void Status::reset() {
    free(_state);
    _state = NULL;
}

inline void Status::operator=(const Status& s) {
    // The following condition catches both aliasing (when this == &s),
    // and the common case where both s and *this are ok.
    if (_state == s._state) {
        return;
    }
    if (s._state == NULL) {
        free(_state);
        _state = NULL;
    } else {
        set_error(s._state->code,
131
                  butil::StringPiece(s._state->message, s._state->size));
gejun's avatar
gejun committed
132 133 134 135 136 137 138 139
    }
}

inline std::ostream& operator<<(std::ostream& os, const Status& st) {
    // NOTE: don't use st.error_text() which is inaccurate if message has '\0'
    return os << st.error_data();
}

140
}  // namespace butil
gejun's avatar
gejun committed
141

gejun's avatar
gejun committed
142
#endif  // BAIDU_BASE_STATUS_H