// Copyright (c) 2010 Baidu.com, Inc. All Rights Reserved
//
// Add customized errno.
// 
// Author: Ge,Jun (gejun@baidu.com)
// Date: Fri Sep 10 13:34:25 CST 2010

#ifndef BRPC_BASE_BAIDU_ERRNO_H
#define BRPC_BASE_BAIDU_ERRNO_H

#define __const__
#include <errno.h>                           // errno
#include "base/macros.h"                     // BAIDU_CONCAT

//-----------------------------------------
// Use system errno before defining yours !
//-----------------------------------------
//
// To add new errno, you shall define the errno in header first, either by
// macro or constant, or even in protobuf.
//
//     #define ESTOP -114                // C/C++
//     static const int EMYERROR = 30;   // C/C++
//     const int EMYERROR2 = -31;        // C++ only
//
// Then you can register description of the error by calling
// BAIDU_REGISTER_ERRNO(the_error_number, its_description) in global scope of
// a .cpp or .cc files which will be linked.
// 
//     BAIDU_REGISTER_ERRNO(ESTOP, "the thread is stopping")
//     BAIDU_REGISTER_ERRNO(EMYERROR, "my error")
//
// Once the error is successfully defined:
//     berror(error_code) returns the description.
//     berror() returns description of last system error code.
//
// %m in printf-alike functions does NOT recognize errors defined by
// BAIDU_REGISTER_ERRNO, you have to explicitly print them by %s.
//
//     errno = ESTOP;
//     printf("Something got wrong, %m\n");            // NO
//     printf("Something got wrong, %s\n", berror());  // YES
//
// When the error number is re-defined, a linking error will be reported:
// 
//     "redefinition of `class BaiduErrnoHelper<30>'"
//
// Or the program aborts at runtime before entering main():
// 
//     "Fail to define EMYERROR(30) which is already defined as `Read-only file system', abort"
//

namespace base {
// You should not call this function, use BAIDU_REGISTER_ERRNO instead.
extern int DescribeCustomizedErrno(int, const char*, const char*);
}

template <int error_code> class BaiduErrnoHelper {};

#define BAIDU_REGISTER_ERRNO(error_code, description)                   \
    const int ALLOW_UNUSED BAIDU_CONCAT(baidu_errno_dummy_, __LINE__) =              \
        ::base::DescribeCustomizedErrno((error_code), #error_code, (description)); \
    template <> class BaiduErrnoHelper<(int)(error_code)> {};

const char* berror(int error_code);
const char* berror();

#endif  //BRPC_BASE_BAIDU_ERRNO_H