1 /*
2  * Hunt - A refined core library for D programming language.
3  *
4  * Copyright (C) 2018-2019 HuntLabs
5  *
6  * Website: https://www.huntlabs.net/
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11 
12 module hunt.system.Error;
13 
14 import core.stdc.string;
15 
16 version (Windows) {
17     import core.sys.windows.winnt;
18     /// https://docs.microsoft.com/zh-cn/windows/desktop/Intl/language-identifier-constants-and-strings
19     string getErrorMessage(bool useStdC = false)(int errno, int langId = LANG_ENGLISH) @trusted {
20 
21         static if (useStdC) {
22             auto s = strerror(errno);
23             return s[0 .. s.strlen].idup;
24         } else {
25             import std.windows.syserror;
26 
27             return sysErrorString(errno, langId);
28         }
29     }
30 } else {
31     string getErrorMessage(int errno) @trusted {
32         version (Posix) {
33             import core.stdc.errno;
34             import std.conv: to;
35 
36             char[80] buf;
37             const(char)* cs;
38             version (CRuntime_Glibc) {
39                 cs = strerror_r(errno, buf.ptr, buf.length);
40             } else {
41                 auto errs = strerror_r(errno, buf.ptr, buf.length);
42                 if (errs == 0)
43                     cs = buf.ptr;
44                 else
45                     return to!string(errno);
46             }
47 
48             auto len = strlen(cs);
49 
50             if (cs[len - 1] == '\n')
51                 len--;
52             if (cs[len - 1] == '\r')
53                 len--;
54             return cs[0 .. len].idup;
55         } else {
56             auto s = strerror(errno);
57             return s[0 .. s.strlen].idup;
58         }
59     }
60 }