1 /// \file Bailout.d
2 
3 module tagion.betterC.utils.Bailout;
4 
5 @nogc:
6 import tagion.betterC.utils.platform;
7 
8 // import core.stdc.string;
9 // import core.stdc.stdio;
10 import tagion.betterC.utils.Text;
11 
12 enum MESSAGE_BUFFER_SIZE = 0x80;
13 
14 protected __gshared const(char)[] _message;
15 protected __gshared char[MESSAGE_BUFFER_SIZE] _message_buffer;
16 protected __gshared size_t _line;
17 protected __gshared const(char)[] _file;
18 
19 /**
20  * @brief File created for providing base functionality for messages
21  */
22 
23 /**
24  * Function create buffer based on unout string with data and arguments
25  * @param text - input data
26  * @param args - arguments which can be set for every message
27  * @return buffer based on input data and arguments
28  */
29 
30 bool isEqual(immutable(char)[] input_arr, string word, size_t start_pos) {
31     bool res = true;
32     foreach (i, key; word) {
33         if (input_arr[start_pos + i] != key) {
34             res = false;
35             break;
36         }
37     }
38     return res;
39 }
40 
41 const(char[]) message(Args...)(string text, Args args) {
42     auto temp = Text(_message_buffer.length);
43     enum {
44         NUM = "%d",
45         TEXT = "%s"
46     }
47     size_t pos;
48     static foreach (arg; args) {
49         {
50             const start = pos;
51             while (pos + NUM.length < text.length) {
52                 if (isEqual(text, NUM, pos) || isEqual(text, TEXT, pos)) {
53                     temp(text[start .. pos])(arg);
54                     break;
55                 }
56                 pos++;
57             }
58         }
59     }
60     _message_buffer[0 .. temp.length] = temp.serialize;
61     _message_buffer[temp.length] = '\0';
62     //    _message=_message_buffer;
63     return _message_buffer;
64 }
65 
66 unittest {
67     auto test = message("text=%d", 10);
68 }
69 
70 void check(const bool flag, lazy const(char[]) msg, string file = __FILE__, size_t line = __LINE__) {
71     if ((!flag) && (_message is null)) {
72         _message = msg;
73         _file = file;
74         _line = line;
75     }
76 }
77 
78 void clear() {
79     _message = null;
80 }
81 
82 bool failed() {
83     return _message !is null;
84 }
85 
86 const(char[]) message() {
87     return _message;
88 }
89 
90 size_t line() {
91     return _line;
92 }
93 
94 const(char[]) file() {
95     return _file;
96 }
97 
98 version (WebAssembly) {
99     void dump() {
100         // empty
101     }
102 }
103 else {
104     void dump() {
105         if (message) {
106             printf("%s:%d:%s\n", file.ptr, cast(int) line, message.ptr);
107         }
108         else {
109             printf("No error\n");
110         }
111     }
112 }