1f653d428STrond Norbye/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2f653d428STrond Norbye/*
3f653d428STrond Norbye *     Copyright 2015 Couchbase, Inc.
4f653d428STrond Norbye *
5f653d428STrond Norbye *   Licensed under the Apache License, Version 2.0 (the "License");
6f653d428STrond Norbye *   you may not use this file except in compliance with the License.
7f653d428STrond Norbye *   You may obtain a copy of the License at
8f653d428STrond Norbye *
9f653d428STrond Norbye *       http://www.apache.org/licenses/LICENSE-2.0
10f653d428STrond Norbye *
11f653d428STrond Norbye *   Unless required by applicable law or agreed to in writing, software
12f653d428STrond Norbye *   distributed under the License is distributed on an "AS IS" BASIS,
13f653d428STrond Norbye *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14f653d428STrond Norbye *   See the License for the specific language governing permissions and
15f653d428STrond Norbye *   limitations under the License.
16f653d428STrond Norbye */
17f653d428STrond Norbye#include <platform/strerror.h>
18f653d428STrond Norbye
19f653d428STrond Norbye#ifdef WIN32
20f653d428STrond Norbye#include <windows.h>
21f653d428STrond Norbye#else
22f653d428STrond Norbye#include <string.h>
23f653d428STrond Norbye#include <errno.h>
24f653d428STrond Norbye#endif
25f653d428STrond Norbye
26f653d428STrond NorbyePLATFORM_PUBLIC_API
27f653d428STrond Norbyestd::string cb_strerror() {
282073a31aSTrond Norbye#ifdef WIN32
292073a31aSTrond Norbye    return cb_strerror(GetLastError());
302073a31aSTrond Norbye#else
312073a31aSTrond Norbye    return cb_strerror(errno);
322073a31aSTrond Norbye#endif
332073a31aSTrond Norbye}
342073a31aSTrond Norbye
352073a31aSTrond NorbyePLATFORM_PUBLIC_API
362073a31aSTrond Norbyestd::string cb_strerror(cb_os_error_t error)
372073a31aSTrond Norbye{
38f653d428STrond Norbye#ifdef WIN32
39f653d428STrond Norbye    std::string reason;
40f653d428STrond Norbye    char *win_msg = NULL;
41f653d428STrond Norbye    if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
42f653d428STrond Norbye                      FORMAT_MESSAGE_FROM_SYSTEM |
43f653d428STrond Norbye                      FORMAT_MESSAGE_IGNORE_INSERTS,
44f653d428STrond Norbye                      NULL, error,
45f653d428STrond Norbye                      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
46f653d428STrond Norbye                      (LPTSTR)&win_msg,
47f653d428STrond Norbye                      0, NULL) > 0) {
48f653d428STrond Norbye        reason.assign(win_msg);
49f653d428STrond Norbye        LocalFree(win_msg);
50f653d428STrond Norbye    } else {
51f653d428STrond Norbye        reason = std::string("Windows error: ") + std::to_string(error);
52f653d428STrond Norbye    }
53f653d428STrond Norbye    return reason;
54f653d428STrond Norbye#else
552073a31aSTrond Norbye    return std::string(strerror(error));
56f653d428STrond Norbye#endif
572073a31aSTrond Norbye}