New upstream version 2.6.0
Markus Koschany
3 years ago
2 | 2 | set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${blockattack_SOURCE_DIR}/source/misc/cmake") |
3 | 3 | set(BIN_DIR ${blockattack_SOURCE_DIR}/Game) |
4 | 4 | |
5 | SET(CPACK_PACKAGE_VERSION "2.5.0") | |
5 | SET(CPACK_PACKAGE_VERSION "2.6.0") | |
6 | 6 | SET(CPACK_PACKAGE_VERSION_MAJOR "2") |
7 | SET(CPACK_PACKAGE_VERSION_MINOR "5") | |
7 | SET(CPACK_PACKAGE_VERSION_MINOR "6") | |
8 | 8 | SET(CPACK_PACKAGE_VERSION_PATCH "0") |
9 | 9 | SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Block Attack - Rise of the Blocks ${CPACK_PACKAGE_VERSION}") |
10 | 10 | SET(CPACK_PACKAGE_VENDOR "Poul Sander") |
39 | 39 | endif() |
40 | 40 | |
41 | 41 | if (NOT WIN32 AND NOT STANDALONE) |
42 | #The path to the data dir must be compiled into the binary | |
43 | add_definitions(-DSHAREDIR=\"${CMAKE_INSTALL_PREFIX}/${INSTALL_DATA_DIR}\") | |
44 | add_definitions(-DLOCALEDIR=\"${CMAKE_INSTALL_PREFIX}/${INSTALL_LOCALE_DIR}\") | |
42 | #The path to the data dir must be compiled into the binary | |
43 | if (IS_ABSOLUTE ${INSTALL_DATA_DIR}) | |
44 | add_definitions(-DSHAREDIR=\"${INSTALL_DATA_DIR}\") | |
45 | else() | |
46 | add_definitions(-DSHAREDIR=\"${CMAKE_INSTALL_PREFIX}/${INSTALL_DATA_DIR}\") | |
47 | endif() | |
48 | if (IS_ABSOLUTE ${INSTALL_DATA_DIR}) | |
49 | add_definitions(-DLOCALEDIR=\"${INSTALL_LOCALE_DIR}\") | |
50 | else() | |
51 | add_definitions(-DLOCALEDIR=\"${CMAKE_INSTALL_PREFIX}/${INSTALL_LOCALE_DIR}\") | |
52 | endif() | |
45 | 53 | endif() |
46 | 54 | |
47 | 55 | #Compiler options |
61 | 69 | pkg_search_module(SDL2MIXER REQUIRED SDL2_mixer) |
62 | 70 | pkg_search_module(SDL2IMAGE REQUIRED SDL2_image) |
63 | 71 | pkg_search_module(SDL2TTF REQUIRED SDL2_ttf) |
72 | ||
73 | include_directories(${SDL2MIXER_INCLUDE_DIRS}) | |
74 | include_directories(${SDL2IMAGE_INCLUDE_DIRS}) | |
75 | include_directories(${SDL2TTF_INCLUDE_DIRS}) | |
64 | 76 | |
65 | 77 | find_package(Boost COMPONENTS program_options REQUIRED) |
66 | 78 |
0 | This is Block Attack - Rise of the Blocks - version 2.5.0 | |
1 | ||
2 | Changes since 2.4.0: | |
3 | Added option to always use the software renderer | |
4 | Automatically start in software render the first time after a crash | |
5 | Fixed the search order in archives | |
6 | Added widescreen support. Only used in fullscreen by default. | |
7 | Added appstream metadata | |
8 | Screenshot feature no longer crashes in hardware acceleration. Still only works in software mode | |
9 | ||
10 | Feedback can be given on https://blockattack.net or https://github.com/blockattack/blockattack-game |
0 | This is Block Attack - Rise of the Blocks - version 2.6.0 | |
1 | ||
2 | The main focus of this release is improved controller support. | |
3 | ||
4 | Changes since 2.5.0: | |
5 | ||
6 | Modified the controller keybind. "B" is now Cancel instead of "Y" | |
7 | There is a virtual keyboard on the enter name screen allowing using a mouse or a gamepad to type. | |
8 | Added patch by bmwiedemann for sorting in the data file | |
9 | Update embedded Cerial from 1.2.2 to 1.3.0 | |
10 | Update library versions for the compiled Linux version: | |
11 | * SDL2: 2.0.9 to 2.0.12 | |
12 | * SDL2_image: 2.0.4 to 2.0.5 | |
13 | * SDL2_ttf: 2.0.14 to 2.0.15 | |
14 | * physfs: 2.0.3 to 3.0.2 | |
15 |
0 | .\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.10. | |
1 | .TH BLOCKATTACK "6" "May 2019" "blockattack 2.5.0" "Games" | |
0 | .\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.13. | |
1 | .TH BLOCKATTACK "6" "September 2020" "blockattack 2.6.0" "Games" | |
2 | 2 | .SH NAME |
3 | 3 | blockattack \- a puzzle game inspired by Tetris Attack |
4 | 4 | .SH SYNOPSIS |
5 | 5 | .B blockattack |
6 | 6 | [\fI\,OPTION\/\fR]... |
7 | 7 | .SH DESCRIPTION |
8 | Block Attack \- Rise of the blocks 2.5.0 | |
8 | Block Attack \- Rise of the blocks 2.6.0 | |
9 | 9 | .PP |
10 | 10 | Block Attack \- Rise of the Blocks is a puzzle/blockfall game inspired by Tetris Attack for the SNES. |
11 | 11 | .PP |
0 | 0 | #!/bin/bash |
1 | 1 | set -e |
2 | zip -9rjX Game/blockattack.data source/AUTH | |
2 | zip -9jX Game/blockattack.data source/AUTH | |
3 | 3 | cd Game/data |
4 | zip -9rX ../blockattack.data * -x \*svn* | |
4 | zip -9X $(find ../blockattack.data * | sort) -x \*svn* | |
5 | 5 | cd ../../man |
6 | gzip -9 -c blockattack.man > blockattack.6.gz | |
6 | gzip -9n -c blockattack.man > blockattack.6.gz | |
7 | 7 | cd ../source/misc/translation/ |
8 | 8 | ./build_mo_all.sh |
9 | 9 |
64 | 64 | #include <sstream> |
65 | 65 | #include <deque> |
66 | 66 | |
67 | using std::string; | |
68 | using std::stringstream; | |
69 | using std::cerr; | |
70 | using std::vector; | |
71 | 67 | |
72 | 68 | //Function to convert numbers to string (2 diget) |
73 | static string itoa2(int num) { | |
69 | static std::string itoa2(int num) { | |
74 | 70 | char buffer[20]; |
75 | 71 | snprintf(buffer, sizeof(buffer), "%02i", num); |
76 | 72 | return buffer; |
1055 | 1051 | LongChainDoneEvent(); |
1056 | 1052 | } |
1057 | 1053 | if (chainSize[i]>1 && !puzzleMode && recordStats) { |
1058 | Stats::getInstance()->addOne((string)"chainX"+std::to_string(chainSize[i])); | |
1054 | Stats::getInstance()->addOne((std::string)"chainX"+std::to_string(chainSize[i])); | |
1059 | 1055 | } |
1060 | 1056 | chainUsed[i]=false; |
1061 | 1057 | } |
1392 | 1388 | |
1393 | 1389 | double BlockGame::firstInLine1(int line) { |
1394 | 1390 | if (line > 20 || line < 0) { |
1395 | cerr << "Warning: first in Line1: " << line << "\n"; | |
1391 | std::cerr << "Warning: first in Line1: " << line << "\n"; | |
1396 | 1392 | return 3.0; |
1397 | 1393 | } |
1398 | 1394 | for (int i=0; i<6; i++) { |
1406 | 1402 | //returns the first coordinate of the block of type |
1407 | 1403 | double BlockGame::firstInLine(int line, int type) { |
1408 | 1404 | if (line > 20 || line < 0) { |
1409 | cerr << "Warning: first in Line: " << line << "\n"; | |
1405 | std::cerr << "Warning: first in Line: " << line << "\n"; | |
1410 | 1406 | return 3.0; |
1411 | 1407 | } |
1412 | 1408 | for (int i=0; i<6; i++) { |
1567 | 1563 | int placeToCenter = (int)(firstInLine(AIlineToClear, AIcolorToClear)/3.0+firstInLine(AIlineToClear+1, AIcolorToClear)/3.0+firstInLine(AIlineToClear+2, AIcolorToClear)/3.0); |
1568 | 1564 | int unlimitedLoop=0; |
1569 | 1565 | if (AIlineToClear < 0 || AIlineToClear > 20) { |
1570 | cerr << "AIlineToClear out of range: " << AIlineToClear << "\n"; | |
1566 | std::cerr << "AIlineToClear out of range: " << AIlineToClear << "\n"; | |
1571 | 1567 | return; |
1572 | 1568 | } |
1573 | 1569 | if (placeToCenter<0 || placeToCenter > 5) { |
1574 | cerr << "placeToCenter out of range: " << placeToCenter << "\n"; | |
1570 | std::cerr << "placeToCenter out of range: " << placeToCenter << "\n"; | |
1575 | 1571 | return; |
1576 | 1572 | } |
1577 | 1573 | while (((board[placeToCenter][AIlineToClear]>1000000)||(board[placeToCenter][AIlineToClear+1]>1000000)||(board[placeToCenter][AIlineToClear+2]>1000000))&&(unlimitedLoop<10)) { |
167 | 167 | private: |
168 | 168 | //Draws all the bricks to the board (including garbage) |
169 | 169 | void PaintBricks() const { |
170 | for (int i=0; ((i<13)&&(i<30)); i++) { | |
171 | for (int j=0; j<6; j++) { | |
170 | for (int i=0; i<13; ++i) { | |
171 | for (int j=0; j<6; ++j) { | |
172 | 172 | int basicBrick = board[j][i]%10; //The basic brick, stored on the least significant digit |
173 | 173 | if ((basicBrick > -1) && (basicBrick < 7) && ((board[j][i]/1000000)%10==0)) { |
174 | 174 | DrawImgBoardBounded(bricks[basicBrick], j*bsize, bsize*12-i*bsize-pixels); |
264 | 264 | if ((board[j][i]/1000000)%10==1) { |
265 | 265 | int left, right, over, under; |
266 | 266 | int number = board[j][i]; |
267 | if (j<1) { | |
268 | left = -1; | |
269 | } | |
270 | else { | |
271 | left = board[j-1][i]; | |
272 | } | |
273 | if (j>5) { | |
274 | right = -1; | |
275 | } | |
276 | else { | |
277 | right = board[j+1][i]; | |
278 | } | |
267 | left = -1; | |
268 | right = board[j+1][i]; | |
279 | 269 | if (i>28) { |
280 | 270 | over = -1; |
281 | 271 | } |
24 | 24 | #include "global.hpp" |
25 | 25 | #include "common.h" |
26 | 26 | #include "ReadKeyboard.h" |
27 | #include "utf8.h" | |
28 | #include "MenuSystem.h" | |
27 | 29 | |
28 | 30 | static void setButtonFont(const sago::SagoDataHolder* holder, sago::SagoTextField& field, const char* text) { |
29 | 31 | field.SetHolder(holder); |
93 | 95 | sagoTextSetBlueFont(textField); |
94 | 96 | sagoTextSetBlueFont(cursorLabel); |
95 | 97 | cursorLabel.SetText("|"); |
98 | for (auto position = virtualKeyboard.alphabet.begin(); position != virtualKeyboard.alphabet.end() ; utf8::advance(position, 1, virtualKeyboard.alphabet.end())) { | |
99 | auto endPosition = position; | |
100 | utf8::advance(endPosition, 1, virtualKeyboard.alphabet.end()); | |
101 | std::string theChar(position, endPosition); | |
102 | virtualKeyboard.gamePadChars.push_back(theChar); | |
103 | virtualKeyboard.gamePadCharFields.emplace_back(); | |
104 | sago::SagoTextField& tf = virtualKeyboard.gamePadCharFields.back(); | |
105 | setButtonFont(&globalData.spriteHolder->GetDataHolder(), tf, theChar.c_str()); | |
106 | if (globalData.verboseLevel) { | |
107 | std::cout << *position; | |
108 | } | |
109 | } | |
110 | if (globalData.verboseLevel) { | |
111 | std::cout << "\n"; | |
112 | } | |
96 | 113 | } |
97 | 114 | |
98 | 115 | |
103 | 120 | return isActive; |
104 | 121 | } |
105 | 122 | |
123 | static bool insideRect (int x, int y, int height, int width) { | |
124 | if (globalData.mousex < x) { | |
125 | return false; | |
126 | } | |
127 | if (globalData.mousex > x+width) { | |
128 | return false; | |
129 | } | |
130 | if (globalData.mousey < y) { | |
131 | return false; | |
132 | } | |
133 | if (globalData.mousey > y+height) { | |
134 | return false; | |
135 | } | |
136 | return true; | |
137 | } | |
138 | ||
139 | // For use with the mouse/gamepad keyboard | |
140 | int keyboardRowLimit = 20; | |
106 | 141 | |
107 | 142 | void DialogBox::Draw(SDL_Renderer* target) { |
108 | 143 | DrawBackground(globalData.screen); |
110 | 145 | this->y = globalData.ysize/2-100; |
111 | 146 | DrawRectYellow(target, x, y, 200, 600); |
112 | 147 | headerLabel.Draw(target, x+300, y+20, sago::SagoTextField::Alignment::center); |
148 | DrawRectYellow(target, x+25, y+128, 50, 250); | |
113 | 149 | enterLabel.Draw(target, x+150, y+140, sago::SagoTextField::Alignment::center); |
150 | DrawRectYellow(target, x+325, y+128, 50, 250); | |
114 | 151 | cancelLabel.Draw(target, x+450, y+140, sago::SagoTextField::Alignment::center); |
115 | 152 | DrawRectWhite(target, x+26, y+64, 54, 600-2*26); |
116 | 153 | textField.SetText(rk->GetString()); |
124 | 161 | width -= 2; |
125 | 162 | cursorLabel.Draw(target, x+40+width,y+76); |
126 | 163 | } |
127 | } | |
164 | const sago::SagoSprite& marked = globalData.spriteHolder->GetSprite("i_level_check_box_marked"); | |
165 | for (size_t i = 0; i<virtualKeyboard.gamePadCharFields.size(); ++i) { | |
166 | if (virtualKeyboard.selectedChar == static_cast<int>(i)) { | |
167 | marked.Draw(target, SDL_GetTicks(), globalData.xsize/2-400+(i%keyboardRowLimit)*40-5, globalData.ysize/2+150+(i/keyboardRowLimit)*40-5); | |
168 | } | |
169 | sago::SagoTextField& f = virtualKeyboard.gamePadCharFields.at(i); | |
170 | f.Draw(target, globalData.xsize/2-400+(i%keyboardRowLimit)*40, globalData.ysize/2+150+(i/keyboardRowLimit)*40); | |
171 | } | |
172 | } | |
173 | ||
174 | ||
175 | static bool isGamePadStartEvent(const SDL_Event& event) { | |
176 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
177 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_START ) { | |
178 | return true; | |
179 | } | |
180 | } | |
181 | return false; | |
182 | } | |
183 | ||
184 | static bool isGamePadLEvent(const SDL_Event& event) { | |
185 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
186 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_LEFTSHOULDER ) { | |
187 | return true; | |
188 | } | |
189 | } | |
190 | return false; | |
191 | } | |
192 | ||
193 | static bool isGamePadREvent(const SDL_Event& event) { | |
194 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
195 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_RIGHTSHOULDER ) { | |
196 | return true; | |
197 | } | |
198 | } | |
199 | return false; | |
200 | } | |
201 | ||
202 | ||
203 | void DialogBox::virtualKeyboardWriteSelectedChar(ReadKeyboard* rk, const std::string& insertChar) const { | |
204 | if (insertChar == virtualKeyboard.backspace) { | |
205 | rk->emulateBackspace(); | |
206 | } | |
207 | else if (insertChar == virtualKeyboard.leftChar) { | |
208 | rk->cursorLeft(); | |
209 | } | |
210 | else if (insertChar == virtualKeyboard.rightChar) { | |
211 | rk->cursorRight(); | |
212 | } | |
213 | else { | |
214 | rk->putchar(insertChar); | |
215 | } | |
216 | } | |
217 | ||
128 | 218 | |
129 | 219 | void DialogBox::ProcessInput(const SDL_Event& event, bool& processed) { |
130 | 220 | if (event.type == SDL_TEXTINPUT) { |
148 | 238 | } |
149 | 239 | } |
150 | 240 | } |
241 | else { | |
242 | if (isGamePadStartEvent(event)) { | |
243 | name = rk->GetString(); | |
244 | updated = true; | |
245 | isActive = false; | |
246 | } | |
247 | if (isEscapeEvent(event)) { | |
248 | isActive = false; | |
249 | } | |
250 | if (isConfirmEvent(event)) { | |
251 | const sago::SagoTextField& f = virtualKeyboard.gamePadCharFields.at(virtualKeyboard.selectedChar); | |
252 | const std::string& insertChar = f.GetText(); | |
253 | virtualKeyboardWriteSelectedChar(rk.get(), insertChar); | |
254 | } | |
255 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
256 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_X ) { | |
257 | rk->emulateBackspace(); | |
258 | } | |
259 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_Y ) { | |
260 | rk->putchar(" "); | |
261 | } | |
262 | } | |
263 | if (isGamePadLEvent(event)) { | |
264 | rk->cursorLeft(); | |
265 | } | |
266 | if (isGamePadREvent(event)) { | |
267 | rk->cursorRight(); | |
268 | } | |
269 | if (isRightEvent(event)) { | |
270 | if ( (virtualKeyboard.selectedChar+1)/keyboardRowLimit != virtualKeyboard.selectedChar/keyboardRowLimit ) { | |
271 | virtualKeyboard.selectedChar -= keyboardRowLimit; | |
272 | } | |
273 | ++virtualKeyboard.selectedChar; | |
274 | if (virtualKeyboard.selectedChar >= static_cast<int>(virtualKeyboard.gamePadCharFields.size())) { | |
275 | virtualKeyboard.selectedChar -= virtualKeyboard.selectedChar%keyboardRowLimit; | |
276 | } | |
277 | } | |
278 | if (isLeftEvent(event)) { | |
279 | if ( (virtualKeyboard.selectedChar-1)/keyboardRowLimit != virtualKeyboard.selectedChar/keyboardRowLimit || virtualKeyboard.selectedChar == 0 ) { | |
280 | virtualKeyboard.selectedChar += keyboardRowLimit; | |
281 | } | |
282 | --virtualKeyboard.selectedChar; | |
283 | } | |
284 | if (isDownEvent(event)) { | |
285 | virtualKeyboard.selectedChar+= keyboardRowLimit; | |
286 | } | |
287 | if (isUpEvent(event)) { | |
288 | virtualKeyboard.selectedChar -= keyboardRowLimit; | |
289 | } | |
290 | if (virtualKeyboard.selectedChar < 0) { | |
291 | virtualKeyboard.selectedChar = 0; | |
292 | } | |
293 | if (virtualKeyboard.selectedChar >= static_cast<int>(virtualKeyboard.gamePadCharFields.size())) { | |
294 | virtualKeyboard.selectedChar = virtualKeyboard.gamePadCharFields.size()-1; | |
295 | } | |
296 | } | |
151 | 297 | processed = true; |
298 | if ( !(SDL_GetMouseState(nullptr, nullptr)&SDL_BUTTON(1)) ) { | |
299 | bMouseUp=true; | |
300 | } | |
301 | ||
302 | if (SDL_GetMouseState(nullptr,nullptr)&SDL_BUTTON(1) && bMouseUp) { | |
303 | bMouseUp = false; | |
304 | if (insideRect(x+25, y+128, 50, 250)) { | |
305 | name = rk->GetString(); | |
306 | updated = true; | |
307 | isActive = false; | |
308 | } | |
309 | if (insideRect(x+325, y+128, 50, 250)) { | |
310 | isActive = false; | |
311 | } | |
312 | for (size_t i = 0; i<virtualKeyboard.gamePadCharFields.size(); ++i) { | |
313 | sago::SagoTextField& f = virtualKeyboard.gamePadCharFields.at(i); | |
314 | auto topx = globalData.xsize/2-400+(i%keyboardRowLimit)*40-5; | |
315 | auto topy = globalData.ysize/2+150+(i/keyboardRowLimit)*40-5; | |
316 | if (insideRect(topx, topy, 30, 30)) { | |
317 | std::string insertChar = f.GetText(); | |
318 | virtualKeyboardWriteSelectedChar(rk.get(), insertChar); | |
319 | } | |
320 | } | |
321 | } | |
322 | ||
323 | if (globalData.mousex != oldmousex || globalData.mousey != oldmousey) { | |
324 | for (size_t i = 0; i<virtualKeyboard.gamePadCharFields.size(); ++i) { | |
325 | auto topx = globalData.xsize/2-400+(i%keyboardRowLimit)*40-5; | |
326 | auto topy = globalData.ysize/2+150+(i/keyboardRowLimit)*40-5; | |
327 | if (insideRect(topx, topy, 30, 30)) { | |
328 | virtualKeyboard.selectedChar = i; | |
329 | } | |
330 | } | |
331 | oldmousex = globalData.mousex; | |
332 | oldmousey = globalData.mousey; | |
333 | } | |
152 | 334 | } |
153 | 335 | |
154 | 336 | void DialogBox::SetName(const std::string& name) { |
30 | 30 | #include "scopeHelpers.hpp" |
31 | 31 | #include "global.hpp" |
32 | 32 | |
33 | struct VirtualKeyboard { | |
34 | const std::string leftChar = "‹"; | |
35 | const std::string rightChar = "›"; | |
36 | const std::string backspace = "«"; | |
37 | std::string alphabet = std::string(_("ABCDEFGHIJKLMNOPQRSTUVWXYZ" | |
38 | "abcdefghijklmnopqrstuvwxyz" | |
39 | ".,:!?+_^@#%&=*")) + leftChar + rightChar + backspace; | |
40 | std::vector<std::string> gamePadChars; | |
41 | std::vector<sago::SagoTextField> gamePadCharFields; | |
42 | int selectedChar = 0; | |
43 | }; | |
44 | ||
33 | 45 | class DialogBox : public sago::GameStateInterface { |
34 | 46 | public: |
35 | 47 | DialogBox(int x, int y, const std::string& name, const std::string& header); |
44 | 56 | std::string GetName() const; |
45 | 57 | bool IsUpdated() const; |
46 | 58 | private: |
59 | void virtualKeyboardWriteSelectedChar(ReadKeyboard *rk, const std::string& insertChar) const; | |
47 | 60 | bool isActive = true; |
61 | bool bMouseUp = false; | |
48 | 62 | std::shared_ptr<ReadKeyboard> rk; |
49 | 63 | int x; |
50 | 64 | int y; |
57 | 71 | sago::SagoTextField cancelLabel; |
58 | 72 | sago::SagoTextField textField; |
59 | 73 | sago::SagoTextField cursorLabel; |
74 | VirtualKeyboard virtualKeyboard; | |
75 | int oldmousex = 0; | |
76 | int oldmousey = 0; | |
60 | 77 | }; |
78 | ||
79 | void DrawRectYellow(SDL_Renderer* target, int topx, int topy, int height, int width); | |
61 | 80 | |
62 | 81 | #endif /* DIALOGBOX_HPP */ |
63 | 82 |
20 | 20 | =========================================================================== |
21 | 21 | */ |
22 | 22 | |
23 | #include "DialogBox.hpp" | |
24 | #include "HelpCommon.hpp" | |
23 | 25 | #include "HelpAboutState.hpp" |
24 | 26 | #include "global.hpp" |
25 | 27 | #include "common.h" |
42 | 44 | field.SetText(text); |
43 | 45 | } |
44 | 46 | |
45 | static void setHelpGamepadFont(const sago::SagoDataHolder* holder, sago::SagoTextBox& field, const char* text) { | |
46 | field.SetHolder(holder); | |
47 | field.SetFont("freeserif"); | |
48 | field.SetColor({255,255,255,255}); | |
49 | field.SetColor({0,0,0,255}); | |
50 | field.SetFontSize(20); | |
51 | field.SetOutline(0, {0,0,0,255}); | |
52 | field.SetText(text); | |
53 | } | |
47 | ||
54 | 48 | |
55 | 49 | |
56 | 50 | |
79 | 73 | infoStream << _("Save folder:") << " " << PHYSFS_getWriteDir() << "\n"; |
80 | 74 | infoStream << _("Locale:") << " " << setlocale( LC_CTYPE, nullptr ) << "\n"; |
81 | 75 | setHelpGamepadFont(&globalData.spriteHolder->GetDataHolder(), titleField, _("About")); |
82 | setHelpGamepadFont(&globalData.spriteHolder->GetDataHolder(), infoBox, infoStream.str().c_str()); | |
76 | setHelpBoxFont(&globalData.spriteHolder->GetDataHolder(), infoBox, infoStream.str().c_str()); | |
83 | 77 | sago::WriteFileContent("about.txt", infoStream.str()); |
84 | 78 | } |
85 | 79 | |
99 | 93 | processed = true; |
100 | 94 | } |
101 | 95 | } |
102 | ||
103 | extern void DrawRectYellow(SDL_Renderer* target, int topx, int topy, int height, int width); | |
104 | 96 | |
105 | 97 | void HelpAboutState::Draw(SDL_Renderer* target) { |
106 | 98 | DrawBackground(target); |
135 | 127 | } |
136 | 128 | |
137 | 129 | } |
138 | }⏎ | |
130 | } |
0 | /* | |
1 | =========================================================================== | |
2 | blockattack - Block Attack - Rise of the Blocks | |
3 | Copyright (C) 2005-2020 Poul Sander | |
4 | ||
5 | This program is free software: you can redistribute it and/or modify | |
6 | it under the terms of the GNU General Public License as published by | |
7 | the Free Software Foundation, either version 2 of the License, or | |
8 | (at your option) any later version. | |
9 | ||
10 | This program is distributed in the hope that it will be useful, | |
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of | |
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
13 | GNU General Public License for more details. | |
14 | ||
15 | You should have received a copy of the GNU General Public License | |
16 | along with this program. If not, see http://www.gnu.org/licenses/ | |
17 | ||
18 | Source information and contacts persons can be found at | |
19 | https://blockattack.net | |
20 | =========================================================================== | |
21 | */ | |
22 | ||
23 | #include "HelpCommon.hpp" | |
24 | ||
25 | ||
26 | ||
27 | template<typename T> void setHelp30FontTemplate(const sago::SagoDataHolder* holder, T& field, const char* text) { | |
28 | field.SetHolder(holder); | |
29 | field.SetFont("freeserif"); | |
30 | field.SetColor({255,255,255,255}); | |
31 | field.SetFontSize(30); | |
32 | field.SetOutline(2, {0,0,0,255}); | |
33 | field.SetText(text); | |
34 | } | |
35 | ||
36 | void setHelp30Font(const sago::SagoDataHolder* holder, sago::SagoTextField& field, const char* text) { | |
37 | setHelp30FontTemplate(holder, field, text); | |
38 | } | |
39 | ||
40 | void setHelp30Font(const sago::SagoDataHolder* holder, sago::SagoTextBox& field, const char* text) { | |
41 | setHelp30FontTemplate(holder, field, text); | |
42 | } | |
43 | ||
44 | void setHelpBoxFont(const sago::SagoDataHolder* holder, sago::SagoTextBox& field, const char* text) { | |
45 | field.SetHolder(holder); | |
46 | field.SetFont("freeserif"); | |
47 | field.SetColor({255,255,255,255}); | |
48 | field.SetColor({0,0,0,255}); | |
49 | field.SetFontSize(20); | |
50 | field.SetOutline(0, {0,0,0,255}); | |
51 | field.SetText(text); | |
52 | } |
0 | /* | |
1 | =========================================================================== | |
2 | blockattack - Block Attack - Rise of the Blocks | |
3 | Copyright (C) 2005-2020 Poul Sander | |
4 | ||
5 | This program is free software: you can redistribute it and/or modify | |
6 | it under the terms of the GNU General Public License as published by | |
7 | the Free Software Foundation, either version 2 of the License, or | |
8 | (at your option) any later version. | |
9 | ||
10 | This program is distributed in the hope that it will be useful, | |
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of | |
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
13 | GNU General Public License for more details. | |
14 | ||
15 | You should have received a copy of the GNU General Public License | |
16 | along with this program. If not, see http://www.gnu.org/licenses/ | |
17 | ||
18 | Source information and contacts persons can be found at | |
19 | https://blockattack.net | |
20 | =========================================================================== | |
21 | */ | |
22 | ||
23 | ||
24 | #ifndef _HELP_COMMON_HPP | |
25 | #define _HELP_COMMON_HPP | |
26 | ||
27 | #include "sago/SagoTextBox.hpp" | |
28 | #include "sago/SagoTextField.hpp" | |
29 | ||
30 | ||
31 | void setHelp30Font(const sago::SagoDataHolder* holder, sago::SagoTextField& field, const char* text); | |
32 | void setHelp30Font(const sago::SagoDataHolder* holder, sago::SagoTextBox& field, const char* text); | |
33 | ||
34 | void setHelpBoxFont(const sago::SagoDataHolder* holder, sago::SagoTextBox& field, const char* text); | |
35 | ||
36 | #endif //_HELP_COMMON_HPP |
20 | 20 | =========================================================================== |
21 | 21 | */ |
22 | 22 | |
23 | #include "HelpCommon.hpp" | |
23 | 24 | #include "HelpGamepadState.hpp" |
24 | 25 | #include "global.hpp" |
25 | 26 | #include "common.h" |
28 | 29 | |
29 | 30 | const int buttonOffset = 160; |
30 | 31 | |
31 | static void setHelpGamepadFont(const sago::SagoDataHolder* holder, sago::SagoTextField& field, const char* text) { | |
32 | field.SetHolder(holder); | |
33 | field.SetFont("freeserif"); | |
34 | field.SetColor({255,255,255,255}); | |
35 | field.SetFontSize(30); | |
36 | field.SetOutline(2, {0,0,0,255}); | |
37 | field.SetText(text); | |
38 | } | |
39 | 32 | |
40 | static void setHelpGamepadFont(const sago::SagoDataHolder* holder, sago::SagoTextBox& field, const char* text) { | |
41 | field.SetHolder(holder); | |
42 | field.SetFont("freeserif"); | |
43 | field.SetColor({255,255,255,255}); | |
44 | field.SetFontSize(30); | |
45 | field.SetOutline(2, {0,0,0,255}); | |
46 | field.SetText(text); | |
47 | } | |
48 | ||
49 | ||
50 | HelpGamepadState::HelpGamepadState() { | |
51 | setHelpGamepadFont(&globalData.spriteHolder->GetDataHolder(), moveLabel, _("Move cursor")); | |
52 | setHelpGamepadFont(&globalData.spriteHolder->GetDataHolder(), pushLabel, _("Push line")); | |
53 | setHelpGamepadFont(&globalData.spriteHolder->GetDataHolder(), backLabel, _("Back (Menu)")); | |
54 | setHelpGamepadFont(&globalData.spriteHolder->GetDataHolder(), switchLabel, _("Switch")); | |
55 | setHelpGamepadFont(&globalData.spriteHolder->GetDataHolder(), confirmLabel, _("Confirm")); | |
33 | static std::string getLabelForSupportedControllerNames() { | |
56 | 34 | std::string s = _("Only SDL2 compatible controllers are supported!\nSupported controllers: "); |
57 | 35 | for (size_t i = 0 ; i<GetSupportedControllerNames().size(); ++i ) { |
58 | 36 | if (i != 0) { |
60 | 38 | } |
61 | 39 | s+= GetSupportedControllerNames().at(i); |
62 | 40 | } |
63 | setHelpGamepadFont(&globalData.spriteHolder->GetDataHolder(), supportedControllers, s.c_str()); | |
41 | return s; | |
42 | } | |
43 | ||
44 | ||
45 | HelpGamepadState::HelpGamepadState() { | |
46 | setHelp30Font(&globalData.spriteHolder->GetDataHolder(), moveLabel, _("Move cursor")); | |
47 | setHelp30Font(&globalData.spriteHolder->GetDataHolder(), pushLabel, _("Push line")); | |
48 | setHelp30Font(&globalData.spriteHolder->GetDataHolder(), backLabel, _("Back (Menu)")); | |
49 | setHelp30Font(&globalData.spriteHolder->GetDataHolder(), switchLabel, _("Switch")); | |
50 | setHelp30Font(&globalData.spriteHolder->GetDataHolder(), confirmLabel, _("Confirm")); | |
51 | std::string s = getLabelForSupportedControllerNames(); | |
52 | setHelp30Font(&globalData.spriteHolder->GetDataHolder(), supportedControllers, s.c_str()); | |
64 | 53 | supportedControllers.SetMaxWidth(740); |
65 | 54 | } |
66 | 55 | |
73 | 62 | |
74 | 63 | void HelpGamepadState::ProcessInput(const SDL_Event& event, bool& processed) { |
75 | 64 | UpdateMouseCoordinates(event, globalData.mousex, globalData.mousey); |
65 | ||
66 | if (isGameControllerConnectionEvent(event)) { | |
67 | UnInitGameControllers(); | |
68 | InitGameControllers(); | |
69 | std::string s = getLabelForSupportedControllerNames(); | |
70 | setHelp30Font(&globalData.spriteHolder->GetDataHolder(), supportedControllers, s.c_str()); | |
71 | processed = true; | |
72 | } | |
76 | 73 | |
77 | 74 | if (isConfirmEvent(event) || isEscapeEvent(event)) { |
78 | 75 | isActive = false; |
101 | 98 | SDL_RenderDrawLine(target, globalData.xsize/2, 80, globalData.xsize/2, 90); |
102 | 99 | pushLabel.Draw(target, globalData.xsize/2, 80, sago::SagoTextField::Alignment::center, sago::SagoTextField::VerticalAlignment::bottom); |
103 | 100 | //Back lines |
104 | SDL_RenderDrawLine(target, 625+OFFSETX, 168, 800+OFFSETX, 168); | |
105 | SDL_RenderDrawLine(target, 800+OFFSETX, 158, 800+OFFSETX, 195); | |
106 | SDL_RenderDrawLine(target, 490+OFFSETX, 195, 800+OFFSETX, 195); | |
101 | SDL_RenderDrawLine(target, 800+OFFSETX, 158, 800+OFFSETX, 207); | |
102 | SDL_RenderDrawLine(target, 490+OFFSETX, 180, 800+OFFSETX, 180); | |
103 | SDL_RenderDrawLine(target, 490+OFFSETX, 180, 490+OFFSETX, 195); | |
104 | SDL_RenderDrawLine(target, 663+OFFSETX, 207, 800+OFFSETX, 207); | |
107 | 105 | backLabel.Draw(target, 800+OFFSETX, 156, sago::SagoTextField::Alignment::center, sago::SagoTextField::VerticalAlignment::bottom); |
108 | 106 | SDL_RenderDrawLine(target, 625+OFFSETX, 241, 900+OFFSETX, 241); |
109 | SDL_RenderDrawLine(target, 663+OFFSETX, 207, 900+OFFSETX, 207); | |
110 | SDL_RenderDrawLine(target, 900+OFFSETX, 207, 900+OFFSETX, 400); | |
107 | SDL_RenderDrawLine(target, 900+OFFSETX, 241, 900+OFFSETX, 400); | |
111 | 108 | switchLabel.Draw(target, 900+OFFSETX, 404, sago::SagoTextField::Alignment::center); |
112 | 109 | confirmLabel.Draw(target, 900+OFFSETX, 404+30, sago::SagoTextField::Alignment::center); |
113 | 110 | bExit.Draw(globalData.screen, SDL_GetTicks(), globalData.xsize-buttonOffset, globalData.ysize-buttonOffset); |
139 | 136 | } |
140 | 137 | |
141 | 138 | } |
142 | }⏎ | |
139 | } |
0 | 0 | /*! \file access.hpp |
1 | \brief Access control, default construction, and serialization disambiguation */ | |
1 | \brief Access control and default construction */ | |
2 | 2 | /* |
3 | 3 | Copyright (c) 2014, Randolph Voorhies, Shane Grant |
4 | 4 | All rights reserved. |
34 | 34 | #include <functional> |
35 | 35 | |
36 | 36 | #include "cereal/macros.hpp" |
37 | #include "cereal/specialize.hpp" | |
37 | 38 | #include "cereal/details/helpers.hpp" |
38 | 39 | |
39 | 40 | namespace cereal |
109 | 110 | // forward decl for construct |
110 | 111 | //! @cond PRIVATE_NEVERDEFINED |
111 | 112 | namespace memory_detail{ template <class Ar, class T> struct LoadAndConstructLoadWrapper; } |
113 | namespace boost_variant_detail{ template <class Ar, class T> struct LoadAndConstructLoadWrapper; } | |
112 | 114 | //! @endcond |
113 | 115 | |
114 | 116 | //! Used to construct types with no default constructor |
201 | 203 | } |
202 | 204 | |
203 | 205 | private: |
204 | template <class A, class B> friend struct ::cereal::memory_detail::LoadAndConstructLoadWrapper; | |
206 | template <class Ar, class TT> friend struct ::cereal::memory_detail::LoadAndConstructLoadWrapper; | |
207 | template <class Ar, class TT> friend struct ::cereal::boost_variant_detail::LoadAndConstructLoadWrapper; | |
205 | 208 | |
206 | 209 | construct( T * p ) : itsPtr( p ), itsEnableSharedRestoreFunction( [](){} ), itsValid( false ) {} |
207 | 210 | construct( T * p, std::function<void()> enableSharedFunc ) : // g++4.7 ice with default lambda to std func |
331 | 334 | }; // end class access |
332 | 335 | |
333 | 336 | // ###################################################################### |
334 | //! A specifier used in conjunction with cereal::specialize to disambiguate | |
335 | //! serialization in special cases | |
336 | /*! @relates specialize | |
337 | @ingroup Access */ | |
338 | enum class specialization | |
339 | { | |
340 | member_serialize, //!< Force the use of a member serialize function | |
341 | member_load_save, //!< Force the use of a member load/save pair | |
342 | member_load_save_minimal, //!< Force the use of a member minimal load/save pair | |
343 | non_member_serialize, //!< Force the use of a non-member serialize function | |
344 | non_member_load_save, //!< Force the use of a non-member load/save pair | |
345 | non_member_load_save_minimal //!< Force the use of a non-member minimal load/save pair | |
346 | }; | |
347 | ||
348 | //! A class used to disambiguate cases where cereal cannot detect a unique way of serializing a class | |
349 | /*! cereal attempts to figure out which method of serialization (member vs. non-member serialize | |
350 | or load/save pair) at compile time. If for some reason cereal cannot find a non-ambiguous way | |
351 | of serializing a type, it will produce a static assertion complaining about this. | |
352 | ||
353 | This can happen because you have both a serialize and load/save pair, or even because a base | |
354 | class has a serialize (public or private with friend access) and a derived class does not | |
355 | overwrite this due to choosing some other serialization type. | |
356 | ||
357 | Specializing this class will tell cereal to explicitly use the serialization type you specify | |
358 | and it will not complain about ambiguity in its compile time selection. However, if cereal detects | |
359 | an ambiguity in specializations, it will continue to issue a static assertion. | |
360 | ||
361 | @code{.cpp} | |
362 | class MyParent | |
363 | { | |
364 | friend class cereal::access; | |
365 | template <class Archive> | |
366 | void serialize( Archive & ar ) {} | |
367 | }; | |
368 | ||
369 | // Although serialize is private in MyParent, to cereal::access it will look public, | |
370 | // even through MyDerived | |
371 | class MyDerived : public MyParent | |
372 | { | |
373 | public: | |
374 | template <class Archive> | |
375 | void load( Archive & ar ) {} | |
376 | ||
377 | template <class Archive> | |
378 | void save( Archive & ar ) {} | |
379 | }; | |
380 | ||
381 | // The load/save pair in MyDerived is ambiguous because serialize in MyParent can | |
382 | // be accessed from cereal::access. This looks the same as making serialize public | |
383 | // in MyParent, making it seem as though MyDerived has both a serialize and a load/save pair. | |
384 | // cereal will complain about this at compile time unless we disambiguate: | |
385 | ||
386 | namespace cereal | |
387 | { | |
388 | // This struct specialization will tell cereal which is the right way to serialize the ambiguity | |
389 | template <class Archive> struct specialize<Archive, MyDerived, cereal::specialization::member_load_save> {}; | |
390 | ||
391 | // If we only had a disambiguation for a specific archive type, it would look something like this | |
392 | template <> struct specialize<cereal::BinaryOutputArchive, MyDerived, cereal::specialization::member_load_save> {}; | |
393 | } | |
394 | @endcode | |
395 | ||
396 | You can also choose to use the macros CEREAL_SPECIALIZE_FOR_ALL_ARCHIVES or | |
397 | CEREAL_SPECIALIZE_FOR_ARCHIVE if you want to type a little bit less. | |
398 | ||
399 | @tparam T The type to specialize the serialization for | |
400 | @tparam S The specialization type to use for T | |
401 | @ingroup Access */ | |
402 | template <class Archive, class T, specialization S> | |
403 | struct specialize : public std::false_type {}; | |
404 | ||
405 | //! Convenient macro for performing specialization for all archive types | |
406 | /*! This performs specialization for the specific type for all types of archives. | |
407 | This macro should be placed at the global namespace. | |
408 | ||
409 | @code{cpp} | |
410 | struct MyType {}; | |
411 | CEREAL_SPECIALIZE_FOR_ALL_ARCHIVES( MyType, cereal::specialization::member_load_save ); | |
412 | @endcode | |
413 | ||
414 | @relates specialize | |
415 | @ingroup Access */ | |
416 | #define CEREAL_SPECIALIZE_FOR_ALL_ARCHIVES( Type, Specialization ) \ | |
417 | namespace cereal { template <class Archive> struct specialize<Archive, Type, Specialization> {}; } | |
418 | ||
419 | //! Convenient macro for performing specialization for a single archive type | |
420 | /*! This performs specialization for the specific type for a single type of archive. | |
421 | This macro should be placed at the global namespace. | |
422 | ||
423 | @code{cpp} | |
424 | struct MyType {}; | |
425 | CEREAL_SPECIALIZE_FOR_ARCHIVE( cereal::XMLInputArchive, MyType, cereal::specialization::member_load_save ); | |
426 | @endcode | |
427 | ||
428 | @relates specialize | |
429 | @ingroup Access */ | |
430 | #define CEREAL_SPECIALIZE_FOR_ARCHIVE( Archive, Type, Specialization ) \ | |
431 | namespace cereal { template <> struct specialize<Archive, Type, Specialization> {}; } | |
432 | ||
433 | // ###################################################################### | |
434 | 337 | // Deferred Implementation, see construct for more information |
435 | 338 | template <class T> template <class ... Args> inline |
436 | 339 | void construct<T>::operator()( Args && ... args ) |
61 | 61 | ~BinaryOutputArchive() CEREAL_NOEXCEPT = default; |
62 | 62 | |
63 | 63 | //! Writes size bytes of data to the output stream |
64 | void saveBinary( const void * data, std::size_t size ) | |
64 | void saveBinary( const void * data, std::streamsize size ) | |
65 | 65 | { |
66 | auto const writtenSize = static_cast<std::size_t>( itsStream.rdbuf()->sputn( reinterpret_cast<const char*>( data ), size ) ); | |
66 | auto const writtenSize = itsStream.rdbuf()->sputn( reinterpret_cast<const char*>( data ), size ); | |
67 | 67 | |
68 | 68 | if(writtenSize != size) |
69 | 69 | throw Exception("Failed to write " + std::to_string(size) + " bytes to output stream! Wrote " + std::to_string(writtenSize)); |
96 | 96 | ~BinaryInputArchive() CEREAL_NOEXCEPT = default; |
97 | 97 | |
98 | 98 | //! Reads size bytes of data from the input stream |
99 | void loadBinary( void * const data, std::size_t size ) | |
99 | void loadBinary( void * const data, std::streamsize size ) | |
100 | 100 | { |
101 | auto const readSize = static_cast<std::size_t>( itsStream.rdbuf()->sgetn( reinterpret_cast<char*>( data ), size ) ); | |
101 | auto const readSize = itsStream.rdbuf()->sgetn( reinterpret_cast<char*>( data ), size ); | |
102 | 102 | |
103 | 103 | if(readSize != size) |
104 | 104 | throw Exception("Failed to read " + std::to_string(size) + " bytes from input stream! Read " + std::to_string(readSize)); |
147 | 147 | template <class T> inline |
148 | 148 | void CEREAL_SAVE_FUNCTION_NAME(BinaryOutputArchive & ar, BinaryData<T> const & bd) |
149 | 149 | { |
150 | ar.saveBinary( bd.data, static_cast<std::size_t>( bd.size ) ); | |
150 | ar.saveBinary( bd.data, static_cast<std::streamsize>( bd.size ) ); | |
151 | 151 | } |
152 | 152 | |
153 | 153 | //! Loading binary data |
154 | 154 | template <class T> inline |
155 | 155 | void CEREAL_LOAD_FUNCTION_NAME(BinaryInputArchive & ar, BinaryData<T> & bd) |
156 | 156 | { |
157 | ar.loadBinary(bd.data, static_cast<std::size_t>(bd.size)); | |
157 | ar.loadBinary(bd.data, static_cast<std::streamsize>( bd.size ) ); | |
158 | 158 | } |
159 | 159 | } // namespace cereal |
160 | 160 |
39 | 39 | { RapidJSONException( const char * what_ ) : Exception( what_ ) {} }; |
40 | 40 | } |
41 | 41 | |
42 | // Inform rapidjson that assert will throw | |
43 | #ifndef CEREAL_RAPIDJSON_ASSERT_THROWS | |
44 | #define CEREAL_RAPIDJSON_ASSERT_THROWS | |
45 | #endif // CEREAL_RAPIDJSON_ASSERT_THROWS | |
46 | ||
42 | 47 | // Override rapidjson assertions to throw exceptions by default |
43 | 48 | #ifndef CEREAL_RAPIDJSON_ASSERT |
44 | 49 | #define CEREAL_RAPIDJSON_ASSERT(x) if(!(x)){ \ |
46 | 51 | #endif // RAPIDJSON_ASSERT |
47 | 52 | |
48 | 53 | // Enable support for parsing of nan, inf, -inf |
54 | #ifndef CEREAL_RAPIDJSON_WRITE_DEFAULT_FLAGS | |
49 | 55 | #define CEREAL_RAPIDJSON_WRITE_DEFAULT_FLAGS kWriteNanAndInfFlag |
56 | #endif | |
57 | ||
58 | // Enable support for parsing of nan, inf, -inf | |
59 | #ifndef CEREAL_RAPIDJSON_PARSE_DEFAULT_FLAGS | |
50 | 60 | #define CEREAL_RAPIDJSON_PARSE_DEFAULT_FLAGS kParseFullPrecisionFlag | kParseNanAndInfFlag |
61 | #endif | |
51 | 62 | |
52 | 63 | #include "cereal/external/rapidjson/prettywriter.h" |
53 | 64 | #include "cereal/external/rapidjson/ostreamwrapper.h" |
208 | 219 | { |
209 | 220 | case NodeType::StartArray: |
210 | 221 | itsWriter.StartArray(); |
222 | // fall through | |
211 | 223 | case NodeType::InArray: |
212 | 224 | itsWriter.EndArray(); |
213 | 225 | break; |
214 | 226 | case NodeType::StartObject: |
215 | 227 | itsWriter.StartObject(); |
228 | // fall through | |
216 | 229 | case NodeType::InObject: |
217 | 230 | itsWriter.EndObject(); |
218 | 231 | break; |
476 | 489 | } |
477 | 490 | |
478 | 491 | Iterator(ValueIterator begin, ValueIterator end) : |
479 | itsValueItBegin(begin), itsValueItEnd(end), itsIndex(0), itsType(Value) | |
492 | itsValueItBegin(begin), itsIndex(0), itsType(Value) | |
480 | 493 | { |
481 | 494 | if( std::distance( begin, end ) == 0 ) |
482 | 495 | itsType = Null_; |
531 | 544 | |
532 | 545 | private: |
533 | 546 | MemberIterator itsMemberItBegin, itsMemberItEnd; //!< The member iterator (object) |
534 | ValueIterator itsValueItBegin, itsValueItEnd; //!< The value iterator (array) | |
547 | ValueIterator itsValueItBegin; //!< The value iterator (array) | |
535 | 548 | size_t itsIndex; //!< The current index of this iterator |
536 | 549 | enum Type {Value, Member, Null_} itsType; //!< Whether this holds values (array) or members (objects) or nothing |
537 | 550 | }; |
751 | 764 | { } |
752 | 765 | |
753 | 766 | // ###################################################################### |
767 | //! Prologue for deferred data for JSON archives | |
768 | /*! Do nothing for the defer wrapper */ | |
769 | template <class T> inline | |
770 | void prologue( JSONOutputArchive &, DeferredData<T> const & ) | |
771 | { } | |
772 | ||
773 | //! Prologue for deferred data for JSON archives | |
774 | template <class T> inline | |
775 | void prologue( JSONInputArchive &, DeferredData<T> const & ) | |
776 | { } | |
777 | ||
778 | // ###################################################################### | |
779 | //! Epilogue for deferred for JSON archives | |
780 | /*! NVPs do not start or finish nodes - they just set up the names */ | |
781 | template <class T> inline | |
782 | void epilogue( JSONOutputArchive &, DeferredData<T> const & ) | |
783 | { } | |
784 | ||
785 | //! Epilogue for deferred for JSON archives | |
786 | /*! Do nothing for the defer wrapper */ | |
787 | template <class T> inline | |
788 | void epilogue( JSONInputArchive &, DeferredData<T> const & ) | |
789 | { } | |
790 | ||
791 | // ###################################################################### | |
754 | 792 | //! Prologue for SizeTags for JSON archives |
755 | 793 | /*! SizeTags are strictly ignored for JSON, they just indicate |
756 | 794 | that the current node should be made into an array */ |
127 | 127 | ~PortableBinaryOutputArchive() CEREAL_NOEXCEPT = default; |
128 | 128 | |
129 | 129 | //! Writes size bytes of data to the output stream |
130 | template <std::size_t DataSize> inline | |
131 | void saveBinary( const void * data, std::size_t size ) | |
132 | { | |
133 | std::size_t writtenSize = 0; | |
130 | template <std::streamsize DataSize> inline | |
131 | void saveBinary( const void * data, std::streamsize size ) | |
132 | { | |
133 | std::streamsize writtenSize = 0; | |
134 | 134 | |
135 | 135 | if( itsConvertEndianness ) |
136 | 136 | { |
137 | for( std::size_t i = 0; i < size; i += DataSize ) | |
138 | for( std::size_t j = 0; j < DataSize; ++j ) | |
139 | writtenSize += static_cast<std::size_t>( itsStream.rdbuf()->sputn( reinterpret_cast<const char*>( data ) + DataSize - j - 1 + i, 1 ) ); | |
137 | for( std::streamsize i = 0; i < size; i += DataSize ) | |
138 | for( std::streamsize j = 0; j < DataSize; ++j ) | |
139 | writtenSize += itsStream.rdbuf()->sputn( reinterpret_cast<const char*>( data ) + DataSize - j - 1 + i, 1 ); | |
140 | 140 | } |
141 | 141 | else |
142 | writtenSize = static_cast<std::size_t>( itsStream.rdbuf()->sputn( reinterpret_cast<const char*>( data ), size ) ); | |
142 | writtenSize = itsStream.rdbuf()->sputn( reinterpret_cast<const char*>( data ), size ); | |
143 | 143 | |
144 | 144 | if(writtenSize != size) |
145 | 145 | throw Exception("Failed to write " + std::to_string(size) + " bytes to output stream! Wrote " + std::to_string(writtenSize)); |
234 | 234 | /*! @param data The data to save |
235 | 235 | @param size The number of bytes in the data |
236 | 236 | @tparam DataSize T The size of the actual type of the data elements being loaded */ |
237 | template <std::size_t DataSize> inline | |
238 | void loadBinary( void * const data, std::size_t size ) | |
237 | template <std::streamsize DataSize> inline | |
238 | void loadBinary( void * const data, std::streamsize size ) | |
239 | 239 | { |
240 | 240 | // load data |
241 | auto const readSize = static_cast<std::size_t>( itsStream.rdbuf()->sgetn( reinterpret_cast<char*>( data ), size ) ); | |
241 | auto const readSize = itsStream.rdbuf()->sgetn( reinterpret_cast<char*>( data ), size ); | |
242 | 242 | |
243 | 243 | if(readSize != size) |
244 | 244 | throw Exception("Failed to read " + std::to_string(size) + " bytes from input stream! Read " + std::to_string(readSize)); |
247 | 247 | if( itsConvertEndianness ) |
248 | 248 | { |
249 | 249 | std::uint8_t * ptr = reinterpret_cast<std::uint8_t*>( data ); |
250 | for( std::size_t i = 0; i < size; i += DataSize ) | |
250 | for( std::streamsize i = 0; i < size; i += DataSize ) | |
251 | 251 | portable_binary_detail::swap_bytes<DataSize>( ptr + i ); |
252 | 252 | } |
253 | 253 | } |
307 | 307 | (std::is_floating_point<TT>::value && std::numeric_limits<TT>::is_iec559), |
308 | 308 | "Portable binary only supports IEEE 754 standardized floating point" ); |
309 | 309 | |
310 | ar.template saveBinary<sizeof(TT)>( bd.data, static_cast<std::size_t>( bd.size ) ); | |
310 | ar.template saveBinary<sizeof(TT)>( bd.data, static_cast<std::streamsize>( bd.size ) ); | |
311 | 311 | } |
312 | 312 | |
313 | 313 | //! Loading binary data from portable binary |
319 | 319 | (std::is_floating_point<TT>::value && std::numeric_limits<TT>::is_iec559), |
320 | 320 | "Portable binary only supports IEEE 754 standardized floating point" ); |
321 | 321 | |
322 | ar.template loadBinary<sizeof(TT)>( bd.data, static_cast<std::size_t>( bd.size ) ); | |
322 | ar.template loadBinary<sizeof(TT)>( bd.data, static_cast<std::streamsize>( bd.size ) ); | |
323 | 323 | } |
324 | 324 | } // namespace cereal |
325 | 325 |
100 | 100 | //! @{ |
101 | 101 | |
102 | 102 | //! A class containing various advanced options for the XML archive |
103 | /*! Options can either be directly passed to the constructor, or chained using the | |
104 | modifier functions for an interface analogous to named parameters */ | |
103 | 105 | class Options |
104 | 106 | { |
105 | 107 | public: |
106 | 108 | //! Default options |
107 | 109 | static Options Default(){ return Options(); } |
108 | 110 | |
109 | //! Default options with no indentation | |
110 | static Options NoIndent(){ return Options( std::numeric_limits<double>::max_digits10, false ); } | |
111 | ||
112 | 111 | //! Specify specific options for the XMLOutputArchive |
113 | /*! @param precision The precision used for floating point numbers | |
114 | @param indent Whether to indent each line of XML | |
115 | @param outputType Whether to output the type of each serialized object as an attribute */ | |
116 | explicit Options( int precision = std::numeric_limits<double>::max_digits10, | |
117 | bool indent = true, | |
118 | bool outputType = false ) : | |
119 | itsPrecision( precision ), | |
120 | itsIndent( indent ), | |
121 | itsOutputType( outputType ) { } | |
112 | /*! @param precision_ The precision used for floating point numbers | |
113 | @param indent_ Whether to indent each line of XML | |
114 | @param outputType_ Whether to output the type of each serialized object as an attribute | |
115 | @param sizeAttributes_ Whether dynamically sized containers output the size=dynamic attribute */ | |
116 | explicit Options( int precision_ = std::numeric_limits<double>::max_digits10, | |
117 | bool indent_ = true, | |
118 | bool outputType_ = false, | |
119 | bool sizeAttributes_ = true ) : | |
120 | itsPrecision( precision_ ), | |
121 | itsIndent( indent_ ), | |
122 | itsOutputType( outputType_ ), | |
123 | itsSizeAttributes( sizeAttributes_ ) | |
124 | { } | |
125 | ||
126 | /*! @name Option Modifiers | |
127 | An interface for setting option settings analogous to named parameters. | |
128 | ||
129 | @code{cpp} | |
130 | cereal::XMLOutputArchive ar( myStream, | |
131 | cereal::XMLOutputArchive::Options() | |
132 | .indent(true) | |
133 | .sizeAttributes(false) ); | |
134 | @endcode | |
135 | */ | |
136 | //! @{ | |
137 | ||
138 | //! Sets the precision used for floaing point numbers | |
139 | Options & precision( int value ){ itsPrecision = value; return * this; } | |
140 | //! Whether to indent each line of XML | |
141 | Options & indent( bool enable ){ itsIndent = enable; return *this; } | |
142 | //! Whether to output the type of each serialized object as an attribute | |
143 | Options & outputType( bool enable ){ itsOutputType = enable; return *this; } | |
144 | //! Whether dynamically sized containers (e.g. vector) output the size=dynamic attribute | |
145 | Options & sizeAttributes( bool enable ){ itsSizeAttributes = enable; return *this; } | |
146 | ||
147 | //! @} | |
122 | 148 | |
123 | 149 | private: |
124 | 150 | friend class XMLOutputArchive; |
125 | 151 | int itsPrecision; |
126 | 152 | bool itsIndent; |
127 | 153 | bool itsOutputType; |
154 | bool itsSizeAttributes; | |
128 | 155 | }; |
129 | 156 | |
130 | 157 | //! Construct, outputting to the provided stream upon destruction |
136 | 163 | OutputArchive<XMLOutputArchive>(this), |
137 | 164 | itsStream(stream), |
138 | 165 | itsOutputType( options.itsOutputType ), |
139 | itsIndent( options.itsIndent ) | |
166 | itsIndent( options.itsIndent ), | |
167 | itsSizeAttributes(options.itsSizeAttributes) | |
140 | 168 | { |
141 | 169 | // rapidxml will delete all allocations when xml_document is cleared |
142 | 170 | auto node = itsXML.allocate_node( rapidxml::node_declaration ); |
181 | 209 | itsNodes.top().node->append_attribute( itsXML.allocate_attribute( "type", "cereal binary data" ) ); |
182 | 210 | |
183 | 211 | finishNode(); |
184 | }; | |
212 | } | |
185 | 213 | |
186 | 214 | //! @} |
187 | 215 | /*! @name Internal Functionality |
287 | 315 | auto valuePtr = itsXML.allocate_string( value ); |
288 | 316 | itsNodes.top().node->append_attribute( itsXML.allocate_attribute( namePtr, valuePtr ) ); |
289 | 317 | } |
318 | ||
319 | bool hasSizeAttributes() const { return itsSizeAttributes; } | |
290 | 320 | |
291 | 321 | protected: |
292 | 322 | //! A struct that contains metadata about a node |
329 | 359 | std::ostringstream itsOS; //!< Used to format strings internally |
330 | 360 | bool itsOutputType; //!< Controls whether type information is printed |
331 | 361 | bool itsIndent; //!< Controls whether indenting is used |
362 | bool itsSizeAttributes; //!< Controls whether lists have a size attribute | |
332 | 363 | }; // XMLOutputArchive |
333 | 364 | |
334 | 365 | // ###################################################################### |
435 | 466 | std::memcpy( data, decoded.data(), decoded.size() ); |
436 | 467 | |
437 | 468 | finishNode(); |
438 | }; | |
469 | } | |
439 | 470 | |
440 | 471 | //! @} |
441 | 472 | /*! @name Internal Functionality |
758 | 789 | { } |
759 | 790 | |
760 | 791 | // ###################################################################### |
792 | //! Prologue for deferred data for XML archives | |
793 | /*! Do nothing for the defer wrapper */ | |
794 | template <class T> inline | |
795 | void prologue( XMLOutputArchive &, DeferredData<T> const & ) | |
796 | { } | |
797 | ||
798 | //! Prologue for deferred data for XML archives | |
799 | template <class T> inline | |
800 | void prologue( XMLInputArchive &, DeferredData<T> const & ) | |
801 | { } | |
802 | ||
803 | // ###################################################################### | |
804 | //! Epilogue for deferred for XML archives | |
805 | /*! NVPs do not start or finish nodes - they just set up the names */ | |
806 | template <class T> inline | |
807 | void epilogue( XMLOutputArchive &, DeferredData<T> const & ) | |
808 | { } | |
809 | ||
810 | //! Epilogue for deferred for XML archives | |
811 | /*! Do nothing for the defer wrapper */ | |
812 | template <class T> inline | |
813 | void epilogue( XMLInputArchive &, DeferredData<T> const & ) | |
814 | { } | |
815 | ||
816 | // ###################################################################### | |
761 | 817 | //! Prologue for SizeTags for XML output archives |
762 | 818 | /*! SizeTags do not start or finish nodes */ |
763 | 819 | template <class T> inline |
764 | 820 | void prologue( XMLOutputArchive & ar, SizeTag<T> const & ) |
765 | 821 | { |
766 | ar.appendAttribute( "size", "dynamic" ); | |
822 | if (ar.hasSizeAttributes()) | |
823 | { | |
824 | ar.appendAttribute("size", "dynamic"); | |
825 | } | |
767 | 826 | } |
768 | 827 | |
769 | 828 | template <class T> inline |
31 | 31 | #include <type_traits> |
32 | 32 | #include <string> |
33 | 33 | #include <memory> |
34 | #include <functional> | |
34 | 35 | #include <unordered_map> |
35 | 36 | #include <unordered_set> |
36 | 37 | #include <vector> |
94 | 95 | SizeTag<T> make_size_tag( T && sz ) |
95 | 96 | { |
96 | 97 | return {std::forward<T>(sz)}; |
98 | } | |
99 | ||
100 | // ###################################################################### | |
101 | //! Marks data for deferred serialization | |
102 | /*! cereal performs a recursive depth-first traversal of data it serializes. When | |
103 | serializing smart pointers to large, nested, or cyclical data structures, it | |
104 | is possible to encounter a stack overflow from excessive recursion when following | |
105 | a chain of pointers. | |
106 | ||
107 | Deferment can help in these situations if the data can be serialized separately from | |
108 | the pointers used to traverse the structure. For example, a graph structure can have its | |
109 | nodes serialized before its edges: | |
110 | ||
111 | @code{.cpp} | |
112 | struct MyEdge | |
113 | { | |
114 | std::shared_ptr<MyNode> connection; | |
115 | int some_value; | |
116 | ||
117 | template<class Archive> | |
118 | void serialize(Archive & archive) | |
119 | { | |
120 | // when we serialize an edge, we'll defer serializing the associated node | |
121 | archive( cereal::defer( connection ), | |
122 | some_value ); | |
123 | } | |
124 | }; | |
125 | ||
126 | struct MyGraphStructure | |
127 | { | |
128 | std::vector<MyEdge> edges; | |
129 | std::vector<MyNodes> nodes; | |
130 | ||
131 | template<class Archive> | |
132 | void serialize(Archive & archive) | |
133 | { | |
134 | // because of the deferment, we ensure all nodes are fully serialized | |
135 | // before any connection pointers to those nodes are serialized | |
136 | archive( edges, nodes ); | |
137 | ||
138 | // we have to explicitly inform the archive when it is safe to serialize | |
139 | // the deferred data | |
140 | archive.serializeDeferments(); | |
141 | } | |
142 | }; | |
143 | @endcode | |
144 | ||
145 | @relates DeferredData | |
146 | @ingroup Utility */ | |
147 | template <class T> inline | |
148 | DeferredData<T> defer( T && value ) | |
149 | { | |
150 | return {std::forward<T>(value)}; | |
97 | 151 | } |
98 | 152 | |
99 | 153 | // ###################################################################### |
144 | 198 | instantiate_polymorphic_binding( T*, Archive*, BindingTag, adl_tag ); \ |
145 | 199 | } } /* end namespaces */ |
146 | 200 | |
201 | //! Helper macro to omit unused warning | |
202 | #if defined(__GNUC__) | |
203 | // GCC / clang don't want the function | |
204 | #define CEREAL_UNUSED_FUNCTION | |
205 | #else | |
206 | #define CEREAL_UNUSED_FUNCTION static void unused() { (void)version; } | |
207 | #endif | |
208 | ||
147 | 209 | // ###################################################################### |
148 | 210 | //! Defines a class version for some type |
149 | 211 | /*! Versioning information is optional and adds some small amount of |
206 | 268 | std::type_index(typeid(TYPE)).hash_code(), VERSION_NUMBER ); \ |
207 | 269 | return VERSION_NUMBER; \ |
208 | 270 | } \ |
209 | static void unused() { (void)version; } \ | |
271 | CEREAL_UNUSED_FUNCTION \ | |
210 | 272 | }; /* end Version */ \ |
211 | 273 | const std::uint32_t Version<TYPE>::version = \ |
212 | 274 | Version<TYPE>::registerVersion(); \ |
249 | 311 | return *self; |
250 | 312 | } |
251 | 313 | |
314 | //! Serializes any data marked for deferment using defer | |
315 | /*! This will cause any data wrapped in DeferredData to be immediately serialized */ | |
316 | void serializeDeferments() | |
317 | { | |
318 | for( auto & deferment : itsDeferments ) | |
319 | deferment(); | |
320 | } | |
321 | ||
252 | 322 | /*! @name Boost Transition Layer |
253 | 323 | Functionality that mirrors the syntax for Boost. This is useful if you are transitioning |
254 | 324 | a large project from Boost to cereal. The preferred interface for cereal is using operator(). */ |
257 | 327 | //! Indicates this archive is not intended for loading |
258 | 328 | /*! This ensures compatibility with boost archive types. If you are transitioning |
259 | 329 | from boost, you can check this value within a member or external serialize function |
260 | (i.e., Archive::is_loading::value) to disable behavior specific to loading, until | |
330 | (i.e., Archive::is_loading::value) to disable behavior specific to loading, until | |
261 | 331 | you can transition to split save/load or save_minimal/load_minimal functions */ |
262 | 332 | using is_loading = std::false_type; |
263 | 333 | |
264 | 334 | //! Indicates this archive is intended for saving |
265 | 335 | /*! This ensures compatibility with boost archive types. If you are transitioning |
266 | 336 | from boost, you can check this value within a member or external serialize function |
267 | (i.e., Archive::is_saving::value) to enable behavior specific to loading, until | |
337 | (i.e., Archive::is_saving::value) to enable behavior specific to loading, until | |
268 | 338 | you can transition to split save/load or save_minimal/load_minimal functions */ |
269 | 339 | using is_saving = std::true_type; |
270 | 340 | |
375 | 445 | ArchiveType & processImpl(base_class<T> const & b) |
376 | 446 | { |
377 | 447 | self->processImpl( *b.base_ptr ); |
448 | return *self; | |
449 | } | |
450 | ||
451 | std::vector<std::function<void(void)>> itsDeferments; | |
452 | ||
453 | template <class T> inline | |
454 | ArchiveType & processImpl(DeferredData<T> const & d) | |
455 | { | |
456 | std::function<void(void)> deferment( [=](){ self->process( d.value ); } ); | |
457 | itsDeferments.emplace_back( std::move(deferment) ); | |
458 | ||
378 | 459 | return *self; |
379 | 460 | } |
380 | 461 | |
482 | 563 | /*! If this is the first time this class has been serialized, we will record its |
483 | 564 | version number and serialize that. |
484 | 565 | |
485 | @tparam T The type of the class being serialized | |
486 | @param version The version number associated with it */ | |
566 | @tparam T The type of the class being serialized */ | |
487 | 567 | template <class T> inline |
488 | 568 | std::uint32_t registerClassVersion() |
489 | 569 | { |
619 | 699 | return *self; |
620 | 700 | } |
621 | 701 | |
702 | //! Serializes any data marked for deferment using defer | |
703 | /*! This will cause any data wrapped in DeferredData to be immediately serialized */ | |
704 | void serializeDeferments() | |
705 | { | |
706 | for( auto & deferment : itsDeferments ) | |
707 | deferment(); | |
708 | } | |
709 | ||
622 | 710 | /*! @name Boost Transition Layer |
623 | 711 | Functionality that mirrors the syntax for Boost. This is useful if you are transitioning |
624 | 712 | a large project from Boost to cereal. The preferred interface for cereal is using operator(). */ |
627 | 715 | //! Indicates this archive is intended for loading |
628 | 716 | /*! This ensures compatibility with boost archive types. If you are transitioning |
629 | 717 | from boost, you can check this value within a member or external serialize function |
630 | (i.e., Archive::is_loading::value) to enable behavior specific to loading, until | |
718 | (i.e., Archive::is_loading::value) to enable behavior specific to loading, until | |
631 | 719 | you can transition to split save/load or save_minimal/load_minimal functions */ |
632 | 720 | using is_loading = std::true_type; |
633 | 721 | |
634 | 722 | //! Indicates this archive is not intended for saving |
635 | 723 | /*! This ensures compatibility with boost archive types. If you are transitioning |
636 | 724 | from boost, you can check this value within a member or external serialize function |
637 | (i.e., Archive::is_saving::value) to disable behavior specific to loading, until | |
725 | (i.e., Archive::is_saving::value) to disable behavior specific to loading, until | |
638 | 726 | you can transition to split save/load or save_minimal/load_minimal functions */ |
639 | 727 | using is_saving = std::false_type; |
640 | 728 | |
666 | 754 | /*! This is used to retrieve a previously registered shared_ptr |
667 | 755 | which has already been loaded. |
668 | 756 | |
757 | @internal | |
669 | 758 | @param id The unique id that was serialized for the pointer |
670 | 759 | @return A shared pointer to the data |
671 | 760 | @throw Exception if the id does not exist */ |
684 | 773 | /*! After a shared pointer has been allocated for the first time, it should |
685 | 774 | be registered with its loaded id for future references to it. |
686 | 775 | |
776 | @internal | |
687 | 777 | @param id The unique identifier for the shared pointer |
688 | 778 | @param ptr The actual shared pointer */ |
689 | 779 | inline void registerSharedPointer(std::uint32_t const id, std::shared_ptr<void> ptr) |
696 | 786 | /*! This is used to retrieve a string previously registered during |
697 | 787 | a polymorphic load. |
698 | 788 | |
789 | @internal | |
699 | 790 | @param id The unique id that was serialized for the polymorphic type |
700 | 791 | @return The string identifier for the tyep */ |
701 | 792 | inline std::string getPolymorphicName(std::uint32_t const id) |
712 | 803 | /*! After a polymorphic type has been loaded for the first time, it should |
713 | 804 | be registered with its loaded id for future references to it. |
714 | 805 | |
806 | @internal | |
715 | 807 | @param id The unique identifier for the polymorphic type |
716 | 808 | @param name The name associated with the tyep */ |
717 | 809 | inline void registerPolymorphicName(std::uint32_t const id, std::string const & name) |
758 | 850 | ArchiveType & processImpl(base_class<T> & b) |
759 | 851 | { |
760 | 852 | self->processImpl( *b.base_ptr ); |
853 | return *self; | |
854 | } | |
855 | ||
856 | std::vector<std::function<void(void)>> itsDeferments; | |
857 | ||
858 | template <class T> inline | |
859 | ArchiveType & processImpl(DeferredData<T> const & d) | |
860 | { | |
861 | std::function<void(void)> deferment( [=](){ self->process( d.value ); } ); | |
862 | itsDeferments.emplace_back( std::move(deferment) ); | |
863 | ||
761 | 864 | return *self; |
762 | 865 | } |
763 | 866 | |
874 | 977 | /*! If this is the first time this class has been serialized, we will record its |
875 | 978 | version number and serialize that. |
876 | 979 | |
877 | @tparam T The type of the class being serialized | |
878 | @param version The version number associated with it */ | |
980 | @tparam T The type of the class being serialized */ | |
879 | 981 | template <class T> inline |
880 | 982 | std::uint32_t loadClassVersion() |
881 | 983 | { |
67 | 67 | namespace detail |
68 | 68 | { |
69 | 69 | struct NameValuePairCore {}; //!< Traits struct for NVPs |
70 | struct DeferredDataCore {}; //!< Traits struct for DeferredData | |
70 | 71 | } |
71 | 72 | |
73 | // ###################################################################### | |
72 | 74 | //! For holding name value pairs |
73 | 75 | /*! This pairs a name (some string) with some value such that an archive |
74 | 76 | can potentially take advantage of the pairing. |
209 | 211 | { |
210 | 212 | //! Internally store the pointer as a void *, keeping const if created with |
211 | 213 | //! a const pointer |
212 | using PT = typename std::conditional<std::is_const<typename std::remove_pointer<T>::type>::value, | |
214 | using PT = typename std::conditional<std::is_const<typename std::remove_pointer<typename std::remove_reference<T>::type>::type>::value, | |
213 | 215 | const void *, |
214 | 216 | void *>::type; |
215 | 217 | |
217 | 219 | |
218 | 220 | PT data; //!< pointer to beginning of data |
219 | 221 | uint64_t size; //!< size in bytes |
222 | }; | |
223 | ||
224 | // ###################################################################### | |
225 | //! A wrapper around data that should be serialized after all non-deferred data | |
226 | /*! This class is used to demarcate data that can only be safely serialized after | |
227 | any data not wrapped in this class. | |
228 | ||
229 | @internal */ | |
230 | template <class T> | |
231 | class DeferredData : detail::DeferredDataCore | |
232 | { | |
233 | private: | |
234 | // If we get passed an array, keep the type as is, otherwise store | |
235 | // a reference if we were passed an l value reference, else copy the value | |
236 | using Type = typename std::conditional<std::is_array<typename std::remove_reference<T>::type>::value, | |
237 | typename std::remove_cv<T>::type, | |
238 | typename std::conditional<std::is_lvalue_reference<T>::value, | |
239 | T, | |
240 | typename std::decay<T>::type>::type>::type; | |
241 | ||
242 | // prevent nested nvps | |
243 | static_assert( !std::is_base_of<detail::DeferredDataCore, T>::value, | |
244 | "Cannot defer DeferredData" ); | |
245 | ||
246 | DeferredData & operator=( DeferredData const & ) = delete; | |
247 | ||
248 | public: | |
249 | //! Constructs a new NameValuePair | |
250 | /*! @param v The value to defer. Ideally this should be an l-value reference so that | |
251 | the value can be both loaded and saved to. If you pass an r-value reference, | |
252 | the DeferredData will store a copy of it instead of a reference. Thus you should | |
253 | only pass r-values in cases where this makes sense, such as the result of some | |
254 | size() call. | |
255 | @internal */ | |
256 | DeferredData( T && v ) : value(std::forward<T>(v)) {} | |
257 | ||
258 | Type value; | |
220 | 259 | }; |
221 | 260 | |
222 | 261 | // ###################################################################### |
255 | 294 | struct adl_tag; |
256 | 295 | |
257 | 296 | // used during saving pointers |
258 | static const int32_t msb_32bit = 0x80000000; | |
297 | static const uint32_t msb_32bit = 0x80000000; | |
259 | 298 | static const int32_t msb2_32bit = 0x40000000; |
260 | 299 | } |
261 | 300 |
55 | 55 | #include <set> |
56 | 56 | #include <stack> |
57 | 57 | |
58 | //! Helper macro to omit unused warning | |
59 | #if defined(__GNUC__) | |
60 | // GCC / clang don't want the function | |
61 | #define CEREAL_BIND_TO_ARCHIVES_UNUSED_FUNCTION | |
62 | #else | |
63 | #define CEREAL_BIND_TO_ARCHIVES_UNUSED_FUNCTION static void unused() { (void)b; } | |
64 | #endif | |
65 | ||
58 | 66 | //! Binds a polymorhic type to all registered archives |
59 | 67 | /*! This binds a polymorphic type to all compatible registered archives that |
60 | 68 | have been registered with CEREAL_REGISTER_ARCHIVE. This must be called |
66 | 74 | template<> \ |
67 | 75 | struct init_binding<__VA_ARGS__> { \ |
68 | 76 | static bind_to_archives<__VA_ARGS__> const & b; \ |
69 | static void unused() { (void)b; } \ | |
77 | CEREAL_BIND_TO_ARCHIVES_UNUSED_FUNCTION \ | |
70 | 78 | }; \ |
71 | 79 | bind_to_archives<__VA_ARGS__> const & init_binding<__VA_ARGS__>::b = \ |
72 | 80 | ::cereal::detail::StaticObject< \ |
114 | 122 | all registered mappings between base and derived types. */ |
115 | 123 | struct PolymorphicCasters |
116 | 124 | { |
125 | //! Maps from a derived type index to a set of chainable casters | |
126 | using DerivedCasterMap = std::unordered_map<std::type_index, std::vector<PolymorphicCaster const *>>; | |
117 | 127 | //! Maps from base type index to a map from derived type index to caster |
118 | std::map<std::type_index, std::map<std::type_index, std::vector<PolymorphicCaster const*>>> map; | |
128 | std::unordered_map<std::type_index, DerivedCasterMap> map; | |
119 | 129 | |
120 | 130 | std::multimap<std::type_index, std::type_index> reverseMap; |
121 | 131 | |
126 | 136 | "Make sure you either serialize the base class at some point via cereal::base_class or cereal::virtual_base_class.\n" \ |
127 | 137 | "Alternatively, manually register the association with CEREAL_REGISTER_POLYMORPHIC_RELATION."); |
128 | 138 | |
129 | //! Checks if the mapping object that can perform the upcast or downcast | |
139 | //! Checks if the mapping object that can perform the upcast or downcast exists, and returns it if so | |
130 | 140 | /*! Uses the type index from the base and derived class to find the matching |
131 | registered caster. If no matching caster exists, returns false. */ | |
132 | static bool exists( std::type_index const & baseIndex, std::type_index const & derivedIndex ) | |
141 | registered caster. If no matching caster exists, the bool in the pair will be false and the vector | |
142 | reference should not be used. */ | |
143 | static std::pair<bool, std::vector<PolymorphicCaster const *> const &> | |
144 | lookup_if_exists( std::type_index const & baseIndex, std::type_index const & derivedIndex ) | |
133 | 145 | { |
134 | 146 | // First phase of lookup - match base type index |
135 | 147 | auto const & baseMap = StaticObject<PolymorphicCasters>::getInstance().map; |
136 | 148 | auto baseIter = baseMap.find( baseIndex ); |
137 | 149 | if (baseIter == baseMap.end()) |
138 | return false; | |
150 | return {false, {}}; | |
139 | 151 | |
140 | 152 | // Second phase - find a match from base to derived |
141 | auto & derivedMap = baseIter->second; | |
153 | auto const & derivedMap = baseIter->second; | |
142 | 154 | auto derivedIter = derivedMap.find( derivedIndex ); |
143 | 155 | if (derivedIter == derivedMap.end()) |
144 | return false; | |
145 | ||
146 | return true; | |
156 | return {false, {}}; | |
157 | ||
158 | return {true, derivedIter->second}; | |
147 | 159 | } |
148 | 160 | |
149 | 161 | //! Gets the mapping object that can perform the upcast or downcast |
161 | 173 | exceptionFunc(); |
162 | 174 | |
163 | 175 | // Second phase - find a match from base to derived |
164 | auto & derivedMap = baseIter->second; | |
176 | auto const & derivedMap = baseIter->second; | |
165 | 177 | auto derivedIter = derivedMap.find( derivedIndex ); |
166 | 178 | if( derivedIter == derivedMap.end() ) |
167 | 179 | exceptionFunc(); |
175 | 187 | { |
176 | 188 | auto const & mapping = lookup( baseInfo, typeid(Derived), [&](){ UNREGISTERED_POLYMORPHIC_CAST_EXCEPTION(save) } ); |
177 | 189 | |
178 | for( auto const * map : mapping ) | |
179 | dptr = map->downcast( dptr ); | |
190 | for( auto const * dmap : mapping ) | |
191 | dptr = dmap->downcast( dptr ); | |
180 | 192 | |
181 | 193 | return static_cast<Derived const *>( dptr ); |
182 | 194 | } |
212 | 224 | #undef UNREGISTERED_POLYMORPHIC_CAST_EXCEPTION |
213 | 225 | }; |
214 | 226 | |
227 | #ifdef CEREAL_OLDER_GCC | |
228 | #define CEREAL_EMPLACE_MAP(map, key, value) \ | |
229 | map.insert( std::make_pair(std::move(key), std::move(value)) ); | |
230 | #else // NOT CEREAL_OLDER_GCC | |
231 | #define CEREAL_EMPLACE_MAP(map, key, value) \ | |
232 | map.emplace( key, value ); | |
233 | #endif // NOT_CEREAL_OLDER_GCC | |
234 | ||
215 | 235 | //! Strongly typed derivation of PolymorphicCaster |
216 | 236 | template <class Base, class Derived> |
217 | 237 | struct PolymorphicVirtualCaster : PolymorphicCaster |
228 | 248 | // First insert the relation Base->Derived |
229 | 249 | const auto lock = StaticObject<PolymorphicCasters>::lock(); |
230 | 250 | auto & baseMap = StaticObject<PolymorphicCasters>::getInstance().map; |
231 | auto lb = baseMap.lower_bound(baseKey); | |
232 | 251 | |
233 | 252 | { |
234 | auto & derivedMap = baseMap.insert( lb, {baseKey, {}} )->second; | |
235 | auto lbd = derivedMap.lower_bound(derivedKey); | |
236 | auto & derivedVec = derivedMap.insert( lbd, { std::move(derivedKey), {}} )->second; | |
253 | auto & derivedMap = baseMap.insert( {baseKey, PolymorphicCasters::DerivedCasterMap{}} ).first->second; | |
254 | auto & derivedVec = derivedMap.insert( {derivedKey, {}} ).first->second; | |
237 | 255 | derivedVec.push_back( this ); |
238 | 256 | } |
239 | 257 | |
240 | 258 | // Insert reverse relation Derived->Base |
241 | 259 | auto & reverseMap = StaticObject<PolymorphicCasters>::getInstance().reverseMap; |
242 | reverseMap.insert( {derivedKey, baseKey} ); | |
260 | CEREAL_EMPLACE_MAP(reverseMap, derivedKey, baseKey); | |
243 | 261 | |
244 | 262 | // Find all chainable unregistered relations |
245 | 263 | /* The strategy here is to process only the nodes in the class hierarchy graph that have been |
253 | 271 | // Checks whether there is a path from parent->child and returns a <dist, path> pair |
254 | 272 | // dist is set to MAX if the path does not exist |
255 | 273 | auto checkRelation = [](std::type_index const & parentInfo, std::type_index const & childInfo) -> |
256 | std::pair<size_t, std::vector<PolymorphicCaster const *>> | |
274 | std::pair<size_t, std::vector<PolymorphicCaster const *> const &> | |
257 | 275 | { |
258 | if( PolymorphicCasters::exists( parentInfo, childInfo ) ) | |
276 | auto result = PolymorphicCasters::lookup_if_exists( parentInfo, childInfo ); | |
277 | if( result.first ) | |
259 | 278 | { |
260 | auto const & path = PolymorphicCasters::lookup( parentInfo, childInfo, [](){} ); | |
279 | auto const & path = result.second; | |
261 | 280 | return {path.size(), path}; |
262 | 281 | } |
263 | 282 | else |
264 | return {std::numeric_limits<size_t>::max(), {}}; | |
283 | return {(std::numeric_limits<size_t>::max)(), {}}; | |
265 | 284 | }; |
266 | 285 | |
267 | std::stack<std::type_index> parentStack; // Holds the parent nodes to be processed | |
268 | std::set<std::type_index> dirtySet; // Marks child nodes that have been changed | |
269 | std::set<std::type_index> processedParents; // Marks parent nodes that have been processed | |
286 | std::stack<std::type_index> parentStack; // Holds the parent nodes to be processed | |
287 | std::vector<std::type_index> dirtySet; // Marks child nodes that have been changed | |
288 | std::unordered_set<std::type_index> processedParents; // Marks parent nodes that have been processed | |
289 | ||
290 | // Checks if a child has been marked dirty | |
291 | auto isDirty = [&](std::type_index const & c) | |
292 | { | |
293 | auto const dirtySetSize = dirtySet.size(); | |
294 | for( size_t i = 0; i < dirtySetSize; ++i ) | |
295 | if( dirtySet[i] == c ) | |
296 | return true; | |
297 | ||
298 | return false; | |
299 | }; | |
270 | 300 | |
271 | 301 | // Begin processing the base key and mark derived as dirty |
272 | 302 | parentStack.push( baseKey ); |
273 | dirtySet.insert( derivedKey ); | |
303 | dirtySet.emplace_back( derivedKey ); | |
274 | 304 | |
275 | 305 | while( !parentStack.empty() ) |
276 | 306 | { |
277 | using Relations = std::multimap<std::type_index, std::pair<std::type_index, std::vector<PolymorphicCaster const *>>>; | |
307 | using Relations = std::unordered_multimap<std::type_index, std::pair<std::type_index, std::vector<PolymorphicCaster const *>>>; | |
278 | 308 | Relations unregisteredRelations; // Defer insertions until after main loop to prevent iterator invalidation |
279 | 309 | |
280 | 310 | const auto parent = parentStack.top(); |
284 | 314 | for( auto const & childPair : baseMap[parent] ) |
285 | 315 | { |
286 | 316 | const auto child = childPair.first; |
287 | if( dirtySet.count( child ) && baseMap.count( child ) ) | |
317 | if( isDirty( child ) && baseMap.count( child ) ) | |
288 | 318 | { |
289 | 319 | auto parentChildPath = checkRelation( parent, child ); |
290 | 320 | |
339 | 369 | { |
340 | 370 | auto & derivedMap = baseMap.find( it.first )->second; |
341 | 371 | derivedMap[it.second.first] = it.second.second; |
342 | reverseMap.insert( {it.second.first, it.first} ); | |
372 | CEREAL_EMPLACE_MAP(reverseMap, it.second.first, it.first ); | |
343 | 373 | } |
344 | 374 | |
345 | 375 | // Mark current parent as modified |
346 | dirtySet.insert( parent ); | |
376 | dirtySet.emplace_back( parent ); | |
347 | 377 | |
348 | 378 | // Insert all parents of the current parent node that haven't yet been processed |
349 | 379 | auto parentRange = reverseMap.equal_range( parent ); |
360 | 390 | } // end chainable relations |
361 | 391 | } // end PolymorphicVirtualCaster() |
362 | 392 | |
393 | #undef CEREAL_EMPLACE_MAP | |
394 | ||
363 | 395 | //! Performs the proper downcast with the templated types |
364 | 396 | void const * downcast( void const * const ptr ) const override |
365 | 397 | { |
47 | 47 | # define CEREAL_DLL_EXPORT __declspec(dllexport) |
48 | 48 | # define CEREAL_USED |
49 | 49 | #else // clang or gcc |
50 | # define CEREAL_DLL_EXPORT | |
50 | # define CEREAL_DLL_EXPORT __attribute__ ((visibility("default"))) | |
51 | 51 | # define CEREAL_USED __attribute__ ((__used__)) |
52 | 52 | #endif |
53 | 53 | |
66 | 66 | class CEREAL_DLL_EXPORT StaticObject |
67 | 67 | { |
68 | 68 | private: |
69 | //! Forces instantiation at pre-execution time | |
70 | static void instantiate( T const & ) {} | |
71 | 69 | |
72 | 70 | static T & create() |
73 | 71 | { |
74 | 72 | static T t; |
75 | instantiate(instance); | |
73 | //! Forces instantiation at pre-execution time | |
74 | (void)instance; | |
76 | 75 | return t; |
77 | 76 | } |
78 | 77 | |
94 | 93 | std::unique_lock<std::mutex> lock; |
95 | 94 | #else |
96 | 95 | public: |
96 | LockGuard(LockGuard const &) = default; // prevents implicit copy ctor warning | |
97 | 97 | ~LockGuard() CEREAL_NOEXCEPT {} // prevents variable not used |
98 | 98 | #endif |
99 | 99 | }; |
799 | 799 | |
800 | 800 | See notes from member load_minimal implementation. |
801 | 801 | |
802 | Note that there should be an additional const check on load_minimal after the valid check, | |
803 | but this currently interferes with many valid uses of minimal serialization. It has been | |
804 | removed (see #565 on github) and previously was: | |
805 | ||
806 | @code | |
807 | static_assert( check::const_valid || !check::exists, | |
808 | "cereal detected an invalid serialization type parameter in non-member " #test_name ". " | |
809 | #test_name " non-member functions must accept their serialization type by non-const reference" ); | |
810 | @endcode | |
811 | ||
812 | See #132, #436, #263, and #565 on https://github.com/USCiLab/cereal for more details. | |
813 | ||
802 | 814 | @param test_name The name to give the test (e.g. load_minimal or versioned_load_minimal) |
803 | 815 | @param save_name The corresponding name the save test would have (e.g. save_minimal or versioned_save_minimal) |
804 | 816 | @param versioned Either blank or the macro CEREAL_MAKE_VERSIONED_TEST */ |
846 | 858 | static_assert( check::valid || !check::exists, "cereal detected different types in corresponding non-member " \ |
847 | 859 | #test_name " and " #save_name " functions. \n " \ |
848 | 860 | "the paramater to " #test_name " must be a constant reference to the type that " #save_name " returns." ); \ |
849 | static_assert( check::const_valid || !check::exists, \ | |
850 | "cereal detected an invalid serialization type parameter in non-member " #test_name ". " \ | |
851 | #test_name " non-member functions must accept their serialization type by non-const reference" ); \ | |
852 | 861 | }; \ |
853 | 862 | } /* namespace detail */ \ |
854 | 863 | \ |
868 | 877 | #undef CEREAL_MAKE_HAS_NON_MEMBER_LOAD_MINIMAL_TEST |
869 | 878 | |
870 | 879 | // ###################################################################### |
880 | namespace detail | |
881 | { | |
882 | // const stripped away before reaching here, prevents errors on conversion from | |
883 | // construct<const T> to construct<T> | |
884 | template<typename T, typename A> | |
885 | struct has_member_load_and_construct_impl : std::integral_constant<bool, | |
886 | std::is_same<decltype( access::load_and_construct<T>( std::declval<A&>(), std::declval< ::cereal::construct<T>&>() ) ), void>::value> | |
887 | { }; | |
888 | ||
889 | template<typename T, typename A> | |
890 | struct has_member_versioned_load_and_construct_impl : std::integral_constant<bool, | |
891 | std::is_same<decltype( access::load_and_construct<T>( std::declval<A&>(), std::declval< ::cereal::construct<T>&>(), 0 ) ), void>::value> | |
892 | { }; | |
893 | } // namespace detail | |
894 | ||
871 | 895 | //! Member load and construct check |
872 | 896 | template<typename T, typename A> |
873 | struct has_member_load_and_construct : std::integral_constant<bool, | |
874 | std::is_same<decltype( access::load_and_construct<T>( std::declval<A&>(), std::declval< ::cereal::construct<T>&>() ) ), void>::value> | |
897 | struct has_member_load_and_construct : detail::has_member_load_and_construct_impl<typename std::remove_const<T>::type, A> | |
875 | 898 | { }; |
876 | 899 | |
877 | // ###################################################################### | |
878 | 900 | //! Member load and construct check (versioned) |
879 | 901 | template<typename T, typename A> |
880 | struct has_member_versioned_load_and_construct : std::integral_constant<bool, | |
881 | std::is_same<decltype( access::load_and_construct<T>( std::declval<A&>(), std::declval< ::cereal::construct<T>&>(), 0 ) ), void>::value> | |
902 | struct has_member_versioned_load_and_construct : detail::has_member_versioned_load_and_construct_impl<typename std::remove_const<T>::type, A> | |
882 | 903 | { }; |
883 | 904 | |
884 | 905 | // ###################################################################### |
900 | 921 | }; \ |
901 | 922 | } /* end namespace detail */ \ |
902 | 923 | template <class T, class A> \ |
903 | struct has_non_member_##test_name : std::integral_constant<bool, detail::has_non_member_##test_name##_impl<T, A>::value> {}; | |
924 | struct has_non_member_##test_name : \ | |
925 | std::integral_constant<bool, detail::has_non_member_##test_name##_impl<typename std::remove_const<T>::type, A>::value> {}; | |
904 | 926 | |
905 | 927 | // ###################################################################### |
906 | 928 | //! Non member load and construct check |
23 | 23 | |
24 | 24 | #ifndef CEREAL_EXTERNAL_BASE64_HPP_ |
25 | 25 | #define CEREAL_EXTERNAL_BASE64_HPP_ |
26 | ||
27 | #ifdef __GNUC__ | |
28 | #pragma GCC diagnostic push | |
29 | #pragma GCC diagnostic ignored "-Wconversion" | |
30 | #endif | |
26 | 31 | |
27 | 32 | #include <string> |
28 | 33 | |
122 | 127 | } |
123 | 128 | } // namespace base64 |
124 | 129 | } // namespace cereal |
125 | ||
130 | #ifdef __GNUC__ | |
131 | #pragma GCC diagnostic pop | |
132 | #endif | |
126 | 133 | #endif // CEREAL_EXTERNAL_BASE64_HPP_ |
51 | 51 | \endcode |
52 | 52 | */ |
53 | 53 | |
54 | ||
55 | /*! \def CEREAL_RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY | |
56 | \ingroup CEREAL_RAPIDJSON_CONFIG | |
57 | \brief User-defined kDefaultChunkCapacity definition. | |
58 | ||
59 | User can define this as any \c size that is a power of 2. | |
60 | */ | |
61 | ||
62 | #ifndef CEREAL_RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY | |
63 | #define CEREAL_RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY (64 * 1024) | |
64 | #endif | |
65 | ||
66 | ||
54 | 67 | /////////////////////////////////////////////////////////////////////////////// |
55 | 68 | // CrtAllocator |
56 | 69 | |
235 | 248 | */ |
236 | 249 | bool AddChunk(size_t capacity) { |
237 | 250 | if (!baseAllocator_) |
238 | ownBaseAllocator_ = baseAllocator_ = CEREAL_RAPIDJSON_NEW(BaseAllocator()); | |
251 | ownBaseAllocator_ = baseAllocator_ = CEREAL_RAPIDJSON_NEW(BaseAllocator)(); | |
239 | 252 | if (ChunkHeader* chunk = reinterpret_cast<ChunkHeader*>(baseAllocator_->Malloc(CEREAL_RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + capacity))) { |
240 | 253 | chunk->capacity = capacity; |
241 | 254 | chunk->size = 0; |
247 | 260 | return false; |
248 | 261 | } |
249 | 262 | |
250 | static const int kDefaultChunkCapacity = 64 * 1024; //!< Default chunk capacity. | |
263 | static const int kDefaultChunkCapacity = CEREAL_RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY; //!< Default chunk capacity. | |
251 | 264 | |
252 | 265 | //! Chunk header for perpending to each chunk. |
253 | 266 | /*! Chunks are stored as a singly linked list. |
0 | // Tencent is pleased to support the open source community by making RapidJSON available. | |
1 | // | |
2 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. | |
3 | // | |
4 | // Licensed under the MIT License (the "License"); you may not use this file except | |
5 | // in compliance with the License. You may obtain a copy of the License at | |
6 | // | |
7 | // http://opensource.org/licenses/MIT | |
8 | // | |
9 | // Unless required by applicable law or agreed to in writing, software distributed | |
10 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR | |
11 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the | |
12 | // specific language governing permissions and limitations under the License. | |
13 | ||
14 | #ifndef CEREAL_RAPIDJSON_CURSORSTREAMWRAPPER_H_ | |
15 | #define CEREAL_RAPIDJSON_CURSORSTREAMWRAPPER_H_ | |
16 | ||
17 | #include "stream.h" | |
18 | ||
19 | #if defined(__GNUC__) | |
20 | CEREAL_RAPIDJSON_DIAG_PUSH | |
21 | CEREAL_RAPIDJSON_DIAG_OFF(effc++) | |
22 | #endif | |
23 | ||
24 | #if defined(_MSC_VER) && _MSC_VER <= 1800 | |
25 | CEREAL_RAPIDJSON_DIAG_PUSH | |
26 | CEREAL_RAPIDJSON_DIAG_OFF(4702) // unreachable code | |
27 | CEREAL_RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated | |
28 | #endif | |
29 | ||
30 | CEREAL_RAPIDJSON_NAMESPACE_BEGIN | |
31 | ||
32 | ||
33 | //! Cursor stream wrapper for counting line and column number if error exists. | |
34 | /*! | |
35 | \tparam InputStream Any stream that implements Stream Concept | |
36 | */ | |
37 | template <typename InputStream, typename Encoding = UTF8<> > | |
38 | class CursorStreamWrapper : public GenericStreamWrapper<InputStream, Encoding> { | |
39 | public: | |
40 | typedef typename Encoding::Ch Ch; | |
41 | ||
42 | CursorStreamWrapper(InputStream& is): | |
43 | GenericStreamWrapper<InputStream, Encoding>(is), line_(1), col_(0) {} | |
44 | ||
45 | // counting line and column number | |
46 | Ch Take() { | |
47 | Ch ch = this->is_.Take(); | |
48 | if(ch == '\n') { | |
49 | line_ ++; | |
50 | col_ = 0; | |
51 | } else { | |
52 | col_ ++; | |
53 | } | |
54 | return ch; | |
55 | } | |
56 | ||
57 | //! Get the error line number, if error exists. | |
58 | size_t GetLine() const { return line_; } | |
59 | //! Get the error column number, if error exists. | |
60 | size_t GetColumn() const { return col_; } | |
61 | ||
62 | private: | |
63 | size_t line_; //!< Current Line | |
64 | size_t col_; //!< Current Column | |
65 | }; | |
66 | ||
67 | #if defined(_MSC_VER) && _MSC_VER <= 1800 | |
68 | CEREAL_RAPIDJSON_DIAG_POP | |
69 | #endif | |
70 | ||
71 | #if defined(__GNUC__) | |
72 | CEREAL_RAPIDJSON_DIAG_POP | |
73 | #endif | |
74 | ||
75 | CEREAL_RAPIDJSON_NAMESPACE_END | |
76 | ||
77 | #endif // CEREAL_RAPIDJSON_CURSORSTREAMWRAPPER_H_ |
0 | 0 | // Tencent is pleased to support the open source community by making RapidJSON available. |
1 | // | |
1 | // | |
2 | 2 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. |
3 | 3 | // |
4 | 4 | // Licensed under the MIT License (the "License"); you may not use this file except |
6 | 6 | // |
7 | 7 | // http://opensource.org/licenses/MIT |
8 | 8 | // |
9 | // Unless required by applicable law or agreed to in writing, software distributed | |
10 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR | |
11 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the | |
9 | // Unless required by applicable law or agreed to in writing, software distributed | |
10 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR | |
11 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the | |
12 | 12 | // specific language governing permissions and limitations under the License. |
13 | 13 | |
14 | 14 | #ifndef CEREAL_RAPIDJSON_DOCUMENT_H_ |
25 | 25 | #include <limits> |
26 | 26 | |
27 | 27 | CEREAL_RAPIDJSON_DIAG_PUSH |
28 | #ifdef _MSC_VER | |
29 | CEREAL_RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant | |
30 | CEREAL_RAPIDJSON_DIAG_OFF(4244) // conversion from kXxxFlags to 'uint16_t', possible loss of data | |
31 | #endif | |
32 | ||
33 | 28 | #ifdef __clang__ |
34 | 29 | CEREAL_RAPIDJSON_DIAG_OFF(padded) |
35 | 30 | CEREAL_RAPIDJSON_DIAG_OFF(switch-enum) |
36 | 31 | CEREAL_RAPIDJSON_DIAG_OFF(c++98-compat) |
32 | #elif defined(_MSC_VER) | |
33 | CEREAL_RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant | |
34 | CEREAL_RAPIDJSON_DIAG_OFF(4244) // conversion from kXxxFlags to 'uint16_t', possible loss of data | |
37 | 35 | #endif |
38 | 36 | |
39 | 37 | #ifdef __GNUC__ |
40 | 38 | CEREAL_RAPIDJSON_DIAG_OFF(effc++) |
41 | #if __GNUC__ >= 6 | |
42 | CEREAL_RAPIDJSON_DIAG_OFF(terminate) // ignore throwing CEREAL_RAPIDJSON_ASSERT in CEREAL_RAPIDJSON_NOEXCEPT functions | |
43 | #endif | |
44 | 39 | #endif // __GNUC__ |
45 | 40 | |
46 | 41 | #ifndef CEREAL_RAPIDJSON_NOMEMBERITERATORCLASS |
47 | #include <iterator> // std::iterator, std::random_access_iterator_tag | |
42 | #include <iterator> // std::random_access_iterator_tag | |
48 | 43 | #endif |
49 | 44 | |
50 | 45 | #if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS |
66 | 61 | But a compiler (IBM XL C/C++ for AIX) have reported to have problem with that so it moved as a namespace scope struct. |
67 | 62 | https://code.google.com/p/rapidjson/issues/detail?id=64 |
68 | 63 | */ |
69 | template <typename Encoding, typename Allocator> | |
70 | struct GenericMember { | |
64 | template <typename Encoding, typename Allocator> | |
65 | struct GenericMember { | |
71 | 66 | GenericValue<Encoding, Allocator> name; //!< name of member (must be a string) |
72 | 67 | GenericValue<Encoding, Allocator> value; //!< value of member. |
68 | ||
69 | // swap() for std::sort() and other potential use in STL. | |
70 | friend inline void swap(GenericMember& a, GenericMember& b) CEREAL_RAPIDJSON_NOEXCEPT { | |
71 | a.name.Swap(b.name); | |
72 | a.value.Swap(b.value); | |
73 | } | |
73 | 74 | }; |
74 | 75 | |
75 | 76 | /////////////////////////////////////////////////////////////////////////////// |
97 | 98 | \see GenericMember, GenericValue::MemberIterator, GenericValue::ConstMemberIterator |
98 | 99 | */ |
99 | 100 | template <bool Const, typename Encoding, typename Allocator> |
100 | class GenericMemberIterator | |
101 | : public std::iterator<std::random_access_iterator_tag | |
102 | , typename internal::MaybeAddConst<Const,GenericMember<Encoding,Allocator> >::Type> { | |
101 | class GenericMemberIterator { | |
103 | 102 | |
104 | 103 | friend class GenericValue<Encoding,Allocator>; |
105 | 104 | template <bool, typename, typename> friend class GenericMemberIterator; |
106 | 105 | |
107 | 106 | typedef GenericMember<Encoding,Allocator> PlainType; |
108 | 107 | typedef typename internal::MaybeAddConst<Const,PlainType>::Type ValueType; |
109 | typedef std::iterator<std::random_access_iterator_tag,ValueType> BaseType; | |
110 | 108 | |
111 | 109 | public: |
112 | 110 | //! Iterator type itself |
116 | 114 | //! Non-constant iterator type |
117 | 115 | typedef GenericMemberIterator<false,Encoding,Allocator> NonConstIterator; |
118 | 116 | |
117 | /** \name std::iterator_traits support */ | |
118 | //@{ | |
119 | typedef ValueType value_type; | |
120 | typedef ValueType * pointer; | |
121 | typedef ValueType & reference; | |
122 | typedef std::ptrdiff_t difference_type; | |
123 | typedef std::random_access_iterator_tag iterator_category; | |
124 | //@} | |
125 | ||
119 | 126 | //! Pointer to (const) GenericMember |
120 | typedef typename BaseType::pointer Pointer; | |
127 | typedef pointer Pointer; | |
121 | 128 | //! Reference to (const) GenericMember |
122 | typedef typename BaseType::reference Reference; | |
129 | typedef reference Reference; | |
123 | 130 | //! Signed integer type (e.g. \c ptrdiff_t) |
124 | typedef typename BaseType::difference_type DifferenceType; | |
131 | typedef difference_type DifferenceType; | |
125 | 132 | |
126 | 133 | //! Default constructor (singular value) |
127 | 134 | /*! Creates an iterator pointing to no element. |
197 | 204 | // class-based member iterator implementation disabled, use plain pointers |
198 | 205 | |
199 | 206 | template <bool Const, typename Encoding, typename Allocator> |
200 | struct GenericMemberIterator; | |
207 | class GenericMemberIterator; | |
201 | 208 | |
202 | 209 | //! non-const GenericMemberIterator |
203 | 210 | template <typename Encoding, typename Allocator> |
204 | struct GenericMemberIterator<false,Encoding,Allocator> { | |
211 | class GenericMemberIterator<false,Encoding,Allocator> { | |
205 | 212 | //! use plain pointer as iterator type |
206 | 213 | typedef GenericMember<Encoding,Allocator>* Iterator; |
207 | 214 | }; |
208 | 215 | //! const GenericMemberIterator |
209 | 216 | template <typename Encoding, typename Allocator> |
210 | struct GenericMemberIterator<true,Encoding,Allocator> { | |
217 | class GenericMemberIterator<true,Encoding,Allocator> { | |
211 | 218 | //! use plain const pointer as iterator type |
212 | 219 | typedef const GenericMember<Encoding,Allocator>* Iterator; |
213 | 220 | }; |
299 | 306 | */ |
300 | 307 | #endif |
301 | 308 | explicit GenericStringRef(const CharType* str) |
302 | : s(str), length(internal::StrLen(str)){ CEREAL_RAPIDJSON_ASSERT(s != 0); } | |
309 | : s(str), length(NotNullStrLen(str)) {} | |
303 | 310 | |
304 | 311 | //! Create constant string reference from pointer and length |
305 | 312 | #ifndef __clang__ // -Wdocumentation |
311 | 318 | */ |
312 | 319 | #endif |
313 | 320 | GenericStringRef(const CharType* str, SizeType len) |
314 | : s(str), length(len) { CEREAL_RAPIDJSON_ASSERT(s != 0); } | |
321 | : s(CEREAL_RAPIDJSON_LIKELY(str) ? str : emptyString), length(len) { CEREAL_RAPIDJSON_ASSERT(str != 0 || len == 0u); } | |
315 | 322 | |
316 | 323 | GenericStringRef(const GenericStringRef& rhs) : s(rhs.s), length(rhs.length) {} |
317 | ||
318 | GenericStringRef& operator=(const GenericStringRef& rhs) { s = rhs.s; length = rhs.length; } | |
319 | 324 | |
320 | 325 | //! implicit conversion to plain CharType pointer |
321 | 326 | operator const Ch *() const { return s; } |
324 | 329 | const SizeType length; //!< length of the string (excluding the trailing NULL terminator) |
325 | 330 | |
326 | 331 | private: |
332 | SizeType NotNullStrLen(const CharType* str) { | |
333 | CEREAL_RAPIDJSON_ASSERT(str != 0); | |
334 | return internal::StrLen(str); | |
335 | } | |
336 | ||
337 | /// Empty string - used when passing in a NULL pointer | |
338 | static const Ch emptyString[]; | |
339 | ||
327 | 340 | //! Disallow construction from non-const array |
328 | 341 | template<SizeType N> |
329 | 342 | GenericStringRef(CharType (&str)[N]) /* = delete */; |
343 | //! Copy assignment operator not permitted - immutable type | |
344 | GenericStringRef& operator=(const GenericStringRef& rhs) /* = delete */; | |
330 | 345 | }; |
346 | ||
347 | template<typename CharType> | |
348 | const CharType GenericStringRef<CharType>::emptyString[] = { CharType() }; | |
331 | 349 | |
332 | 350 | //! Mark a character pointer as constant string |
333 | 351 | /*! Mark a plain character pointer as a "string literal". This function |
343 | 361 | */ |
344 | 362 | template<typename CharType> |
345 | 363 | inline GenericStringRef<CharType> StringRef(const CharType* str) { |
346 | return GenericStringRef<CharType>(str, internal::StrLen(str)); | |
364 | return GenericStringRef<CharType>(str); | |
347 | 365 | } |
348 | 366 | |
349 | 367 | //! Mark a character pointer as constant string |
409 | 427 | template <typename ValueType, typename T> |
410 | 428 | struct TypeHelper {}; |
411 | 429 | |
412 | template<typename ValueType> | |
430 | template<typename ValueType> | |
413 | 431 | struct TypeHelper<ValueType, bool> { |
414 | 432 | static bool Is(const ValueType& v) { return v.IsBool(); } |
415 | 433 | static bool Get(const ValueType& v) { return v.GetBool(); } |
417 | 435 | static ValueType& Set(ValueType& v, bool data, typename ValueType::AllocatorType&) { return v.SetBool(data); } |
418 | 436 | }; |
419 | 437 | |
420 | template<typename ValueType> | |
438 | template<typename ValueType> | |
421 | 439 | struct TypeHelper<ValueType, int> { |
422 | 440 | static bool Is(const ValueType& v) { return v.IsInt(); } |
423 | 441 | static int Get(const ValueType& v) { return v.GetInt(); } |
425 | 443 | static ValueType& Set(ValueType& v, int data, typename ValueType::AllocatorType&) { return v.SetInt(data); } |
426 | 444 | }; |
427 | 445 | |
428 | template<typename ValueType> | |
446 | template<typename ValueType> | |
429 | 447 | struct TypeHelper<ValueType, unsigned> { |
430 | 448 | static bool Is(const ValueType& v) { return v.IsUint(); } |
431 | 449 | static unsigned Get(const ValueType& v) { return v.GetUint(); } |
433 | 451 | static ValueType& Set(ValueType& v, unsigned data, typename ValueType::AllocatorType&) { return v.SetUint(data); } |
434 | 452 | }; |
435 | 453 | |
436 | template<typename ValueType> | |
454 | #ifdef _MSC_VER | |
455 | CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(long) == sizeof(int)); | |
456 | template<typename ValueType> | |
457 | struct TypeHelper<ValueType, long> { | |
458 | static bool Is(const ValueType& v) { return v.IsInt(); } | |
459 | static long Get(const ValueType& v) { return v.GetInt(); } | |
460 | static ValueType& Set(ValueType& v, long data) { return v.SetInt(data); } | |
461 | static ValueType& Set(ValueType& v, long data, typename ValueType::AllocatorType&) { return v.SetInt(data); } | |
462 | }; | |
463 | ||
464 | CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(unsigned long) == sizeof(unsigned)); | |
465 | template<typename ValueType> | |
466 | struct TypeHelper<ValueType, unsigned long> { | |
467 | static bool Is(const ValueType& v) { return v.IsUint(); } | |
468 | static unsigned long Get(const ValueType& v) { return v.GetUint(); } | |
469 | static ValueType& Set(ValueType& v, unsigned long data) { return v.SetUint(data); } | |
470 | static ValueType& Set(ValueType& v, unsigned long data, typename ValueType::AllocatorType&) { return v.SetUint(data); } | |
471 | }; | |
472 | #endif | |
473 | ||
474 | template<typename ValueType> | |
437 | 475 | struct TypeHelper<ValueType, int64_t> { |
438 | 476 | static bool Is(const ValueType& v) { return v.IsInt64(); } |
439 | 477 | static int64_t Get(const ValueType& v) { return v.GetInt64(); } |
441 | 479 | static ValueType& Set(ValueType& v, int64_t data, typename ValueType::AllocatorType&) { return v.SetInt64(data); } |
442 | 480 | }; |
443 | 481 | |
444 | template<typename ValueType> | |
482 | template<typename ValueType> | |
445 | 483 | struct TypeHelper<ValueType, uint64_t> { |
446 | 484 | static bool Is(const ValueType& v) { return v.IsUint64(); } |
447 | 485 | static uint64_t Get(const ValueType& v) { return v.GetUint64(); } |
449 | 487 | static ValueType& Set(ValueType& v, uint64_t data, typename ValueType::AllocatorType&) { return v.SetUint64(data); } |
450 | 488 | }; |
451 | 489 | |
452 | template<typename ValueType> | |
490 | template<typename ValueType> | |
453 | 491 | struct TypeHelper<ValueType, double> { |
454 | 492 | static bool Is(const ValueType& v) { return v.IsDouble(); } |
455 | 493 | static double Get(const ValueType& v) { return v.GetDouble(); } |
457 | 495 | static ValueType& Set(ValueType& v, double data, typename ValueType::AllocatorType&) { return v.SetDouble(data); } |
458 | 496 | }; |
459 | 497 | |
460 | template<typename ValueType> | |
498 | template<typename ValueType> | |
461 | 499 | struct TypeHelper<ValueType, float> { |
462 | 500 | static bool Is(const ValueType& v) { return v.IsFloat(); } |
463 | 501 | static float Get(const ValueType& v) { return v.GetFloat(); } |
465 | 503 | static ValueType& Set(ValueType& v, float data, typename ValueType::AllocatorType&) { return v.SetFloat(data); } |
466 | 504 | }; |
467 | 505 | |
468 | template<typename ValueType> | |
506 | template<typename ValueType> | |
469 | 507 | struct TypeHelper<ValueType, const typename ValueType::Ch*> { |
470 | 508 | typedef const typename ValueType::Ch* StringType; |
471 | 509 | static bool Is(const ValueType& v) { return v.IsString(); } |
475 | 513 | }; |
476 | 514 | |
477 | 515 | #if CEREAL_RAPIDJSON_HAS_STDSTRING |
478 | template<typename ValueType> | |
516 | template<typename ValueType> | |
479 | 517 | struct TypeHelper<ValueType, std::basic_string<typename ValueType::Ch> > { |
480 | 518 | typedef std::basic_string<typename ValueType::Ch> StringType; |
481 | 519 | static bool Is(const ValueType& v) { return v.IsString(); } |
484 | 522 | }; |
485 | 523 | #endif |
486 | 524 | |
487 | template<typename ValueType> | |
525 | template<typename ValueType> | |
488 | 526 | struct TypeHelper<ValueType, typename ValueType::Array> { |
489 | 527 | typedef typename ValueType::Array ArrayType; |
490 | 528 | static bool Is(const ValueType& v) { return v.IsArray(); } |
493 | 531 | static ValueType& Set(ValueType& v, ArrayType data, typename ValueType::AllocatorType&) { return v = data; } |
494 | 532 | }; |
495 | 533 | |
496 | template<typename ValueType> | |
534 | template<typename ValueType> | |
497 | 535 | struct TypeHelper<ValueType, typename ValueType::ConstArray> { |
498 | 536 | typedef typename ValueType::ConstArray ArrayType; |
499 | 537 | static bool Is(const ValueType& v) { return v.IsArray(); } |
500 | 538 | static ArrayType Get(const ValueType& v) { return v.GetArray(); } |
501 | 539 | }; |
502 | 540 | |
503 | template<typename ValueType> | |
541 | template<typename ValueType> | |
504 | 542 | struct TypeHelper<ValueType, typename ValueType::Object> { |
505 | 543 | typedef typename ValueType::Object ObjectType; |
506 | 544 | static bool Is(const ValueType& v) { return v.IsObject(); } |
507 | 545 | static ObjectType Get(ValueType& v) { return v.GetObject(); } |
508 | 546 | static ValueType& Set(ValueType& v, ObjectType data) { return v = data; } |
509 | static ValueType& Set(ValueType& v, ObjectType data, typename ValueType::AllocatorType&) { v = data; } | |
547 | static ValueType& Set(ValueType& v, ObjectType data, typename ValueType::AllocatorType&) { return v = data; } | |
510 | 548 | }; |
511 | 549 | |
512 | template<typename ValueType> | |
550 | template<typename ValueType> | |
513 | 551 | struct TypeHelper<ValueType, typename ValueType::ConstObject> { |
514 | 552 | typedef typename ValueType::ConstObject ObjectType; |
515 | 553 | static bool Is(const ValueType& v) { return v.IsObject(); } |
535 | 573 | \tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document) |
536 | 574 | \tparam Allocator Allocator type for allocating memory of object, array and string. |
537 | 575 | */ |
538 | template <typename Encoding, typename Allocator = MemoryPoolAllocator<> > | |
576 | template <typename Encoding, typename Allocator = MemoryPoolAllocator<> > | |
539 | 577 | class GenericValue { |
540 | 578 | public: |
541 | 579 | //! Name-value pair in an object. |
589 | 627 | \note Default content for number is zero. |
590 | 628 | */ |
591 | 629 | explicit GenericValue(Type type) CEREAL_RAPIDJSON_NOEXCEPT : data_() { |
592 | static const uint16_t defaultFlags[7] = { | |
630 | static const uint16_t defaultFlags[] = { | |
593 | 631 | kNullFlag, kFalseFlag, kTrueFlag, kObjectFlag, kArrayFlag, kShortStringFlag, |
594 | 632 | kNumberAnyFlag |
595 | 633 | }; |
596 | CEREAL_RAPIDJSON_ASSERT(type <= kNumberType); | |
634 | CEREAL_RAPIDJSON_NOEXCEPT_ASSERT(type >= kNullType && type <= kNumberType); | |
597 | 635 | data_.f.flags = defaultFlags[type]; |
598 | 636 | |
599 | 637 | // Use ShortString to store empty string. |
606 | 644 | \tparam SourceAllocator allocator of \c rhs |
607 | 645 | \param rhs Value to copy from (read-only) |
608 | 646 | \param allocator Allocator for allocating copied elements and buffers. Commonly use GenericDocument::GetAllocator(). |
647 | \param copyConstStrings Force copying of constant strings (e.g. referencing an in-situ buffer) | |
609 | 648 | \see CopyFrom() |
610 | 649 | */ |
611 | template< typename SourceAllocator > | |
612 | GenericValue(const GenericValue<Encoding, SourceAllocator>& rhs, Allocator & allocator); | |
650 | template <typename SourceAllocator> | |
651 | GenericValue(const GenericValue<Encoding,SourceAllocator>& rhs, Allocator& allocator, bool copyConstStrings = false) { | |
652 | switch (rhs.GetType()) { | |
653 | case kObjectType: { | |
654 | SizeType count = rhs.data_.o.size; | |
655 | Member* lm = reinterpret_cast<Member*>(allocator.Malloc(count * sizeof(Member))); | |
656 | const typename GenericValue<Encoding,SourceAllocator>::Member* rm = rhs.GetMembersPointer(); | |
657 | for (SizeType i = 0; i < count; i++) { | |
658 | new (&lm[i].name) GenericValue(rm[i].name, allocator, copyConstStrings); | |
659 | new (&lm[i].value) GenericValue(rm[i].value, allocator, copyConstStrings); | |
660 | } | |
661 | data_.f.flags = kObjectFlag; | |
662 | data_.o.size = data_.o.capacity = count; | |
663 | SetMembersPointer(lm); | |
664 | } | |
665 | break; | |
666 | case kArrayType: { | |
667 | SizeType count = rhs.data_.a.size; | |
668 | GenericValue* le = reinterpret_cast<GenericValue*>(allocator.Malloc(count * sizeof(GenericValue))); | |
669 | const GenericValue<Encoding,SourceAllocator>* re = rhs.GetElementsPointer(); | |
670 | for (SizeType i = 0; i < count; i++) | |
671 | new (&le[i]) GenericValue(re[i], allocator, copyConstStrings); | |
672 | data_.f.flags = kArrayFlag; | |
673 | data_.a.size = data_.a.capacity = count; | |
674 | SetElementsPointer(le); | |
675 | } | |
676 | break; | |
677 | case kStringType: | |
678 | if (rhs.data_.f.flags == kConstStringFlag && !copyConstStrings) { | |
679 | data_.f.flags = rhs.data_.f.flags; | |
680 | data_ = *reinterpret_cast<const Data*>(&rhs.data_); | |
681 | } | |
682 | else | |
683 | SetStringRaw(StringRef(rhs.GetString(), rhs.GetStringLength()), allocator); | |
684 | break; | |
685 | default: | |
686 | data_.f.flags = rhs.data_.f.flags; | |
687 | data_ = *reinterpret_cast<const Data*>(&rhs.data_); | |
688 | break; | |
689 | } | |
690 | } | |
613 | 691 | |
614 | 692 | //! Constructor for boolean value. |
615 | 693 | /*! \param b Boolean value |
637 | 715 | |
638 | 716 | //! Constructor for unsigned value. |
639 | 717 | explicit GenericValue(unsigned u) CEREAL_RAPIDJSON_NOEXCEPT : data_() { |
640 | data_.n.u64 = u; | |
718 | data_.n.u64 = u; | |
641 | 719 | data_.f.flags = (u & 0x80000000) ? kNumberUintFlag : (kNumberUintFlag | kIntFlag | kInt64Flag); |
642 | 720 | } |
643 | 721 | |
671 | 749 | //! Constructor for double value. |
672 | 750 | explicit GenericValue(double d) CEREAL_RAPIDJSON_NOEXCEPT : data_() { data_.n.d = d; data_.f.flags = kNumberDoubleFlag; } |
673 | 751 | |
752 | //! Constructor for float value. | |
753 | explicit GenericValue(float f) CEREAL_RAPIDJSON_NOEXCEPT : data_() { data_.n.d = static_cast<double>(f); data_.f.flags = kNumberDoubleFlag; } | |
754 | ||
674 | 755 | //! Constructor for constant string (i.e. do not make a copy of string) |
675 | 756 | GenericValue(const Ch* s, SizeType length) CEREAL_RAPIDJSON_NOEXCEPT : data_() { SetStringRaw(StringRef(s, length)); } |
676 | 757 | |
752 | 833 | /*! \param rhs Source of the assignment. It will become a null value after assignment. |
753 | 834 | */ |
754 | 835 | GenericValue& operator=(GenericValue& rhs) CEREAL_RAPIDJSON_NOEXCEPT { |
755 | CEREAL_RAPIDJSON_ASSERT(this != &rhs); | |
756 | this->~GenericValue(); | |
757 | RawAssign(rhs); | |
836 | if (CEREAL_RAPIDJSON_LIKELY(this != &rhs)) { | |
837 | this->~GenericValue(); | |
838 | RawAssign(rhs); | |
839 | } | |
758 | 840 | return *this; |
759 | 841 | } |
760 | 842 | |
799 | 881 | \tparam SourceAllocator Allocator type of \c rhs |
800 | 882 | \param rhs Value to copy from (read-only) |
801 | 883 | \param allocator Allocator to use for copying |
884 | \param copyConstStrings Force copying of constant strings (e.g. referencing an in-situ buffer) | |
802 | 885 | */ |
803 | 886 | template <typename SourceAllocator> |
804 | GenericValue& CopyFrom(const GenericValue<Encoding, SourceAllocator>& rhs, Allocator& allocator) { | |
887 | GenericValue& CopyFrom(const GenericValue<Encoding, SourceAllocator>& rhs, Allocator& allocator, bool copyConstStrings = false) { | |
805 | 888 | CEREAL_RAPIDJSON_ASSERT(static_cast<void*>(this) != static_cast<void const*>(&rhs)); |
806 | 889 | this->~GenericValue(); |
807 | new (this) GenericValue(rhs, allocator); | |
890 | new (this) GenericValue(rhs, allocator, copyConstStrings); | |
808 | 891 | return *this; |
809 | 892 | } |
810 | 893 | |
845 | 928 | //! Equal-to operator |
846 | 929 | /*! |
847 | 930 | \note If an object contains duplicated named member, comparing equality with any object is always \c false. |
848 | \note Linear time complexity (number of all values in the subtree and total lengths of all strings). | |
931 | \note Complexity is quadratic in Object's member number and linear for the rest (number of all values in the subtree and total lengths of all strings). | |
849 | 932 | */ |
850 | 933 | template <typename SourceAllocator> |
851 | 934 | bool operator==(const GenericValue<Encoding, SourceAllocator>& rhs) const { |
856 | 939 | switch (GetType()) { |
857 | 940 | case kObjectType: // Warning: O(n^2) inner-loop |
858 | 941 | if (data_.o.size != rhs.data_.o.size) |
859 | return false; | |
942 | return false; | |
860 | 943 | for (ConstMemberIterator lhsMemberItr = MemberBegin(); lhsMemberItr != MemberEnd(); ++lhsMemberItr) { |
861 | 944 | typename RhsType::ConstMemberIterator rhsMemberItr = rhs.FindMember(lhsMemberItr->name); |
862 | 945 | if (rhsMemberItr == rhs.MemberEnd() || lhsMemberItr->value != rhsMemberItr->value) |
863 | 946 | return false; |
864 | 947 | } |
865 | 948 | return true; |
866 | ||
949 | ||
867 | 950 | case kArrayType: |
868 | 951 | if (data_.a.size != rhs.data_.a.size) |
869 | 952 | return false; |
954 | 1037 | uint64_t u = GetUint64(); |
955 | 1038 | volatile double d = static_cast<double>(u); |
956 | 1039 | return (d >= 0.0) |
957 | && (d < static_cast<double>(std::numeric_limits<uint64_t>::max())) | |
1040 | && (d < static_cast<double>((std::numeric_limits<uint64_t>::max)())) | |
958 | 1041 | && (u == static_cast<uint64_t>(d)); |
959 | 1042 | } |
960 | 1043 | if (IsInt64()) { |
961 | 1044 | int64_t i = GetInt64(); |
962 | 1045 | volatile double d = static_cast<double>(i); |
963 | return (d >= static_cast<double>(std::numeric_limits<int64_t>::min())) | |
964 | && (d < static_cast<double>(std::numeric_limits<int64_t>::max())) | |
1046 | return (d >= static_cast<double>((std::numeric_limits<int64_t>::min)())) | |
1047 | && (d < static_cast<double>((std::numeric_limits<int64_t>::max)())) | |
965 | 1048 | && (i == static_cast<int64_t>(d)); |
966 | 1049 | } |
967 | 1050 | return true; // double, int, uint are always lossless |
978 | 1061 | bool IsLosslessFloat() const { |
979 | 1062 | if (!IsNumber()) return false; |
980 | 1063 | double a = GetDouble(); |
981 | if (a < static_cast<double>(-std::numeric_limits<float>::max()) | |
982 | || a > static_cast<double>(std::numeric_limits<float>::max())) | |
1064 | if (a < static_cast<double>(-(std::numeric_limits<float>::max)()) | |
1065 | || a > static_cast<double>((std::numeric_limits<float>::max)())) | |
983 | 1066 | return false; |
984 | 1067 | double b = static_cast<double>(static_cast<float>(a)); |
985 | 1068 | return a >= b && a <= b; // Prevent -Wfloat-equal |
1013 | 1096 | |
1014 | 1097 | //! Get the number of members in the object. |
1015 | 1098 | SizeType MemberCount() const { CEREAL_RAPIDJSON_ASSERT(IsObject()); return data_.o.size; } |
1099 | ||
1100 | //! Get the capacity of object. | |
1101 | SizeType MemberCapacity() const { CEREAL_RAPIDJSON_ASSERT(IsObject()); return data_.o.capacity; } | |
1016 | 1102 | |
1017 | 1103 | //! Check whether the object is empty. |
1018 | 1104 | bool ObjectEmpty() const { CEREAL_RAPIDJSON_ASSERT(IsObject()); return data_.o.size == 0; } |
1082 | 1168 | /*! \pre IsObject() == true */ |
1083 | 1169 | MemberIterator MemberEnd() { CEREAL_RAPIDJSON_ASSERT(IsObject()); return MemberIterator(GetMembersPointer() + data_.o.size); } |
1084 | 1170 | |
1171 | //! Request the object to have enough capacity to store members. | |
1172 | /*! \param newCapacity The capacity that the object at least need to have. | |
1173 | \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). | |
1174 | \return The value itself for fluent API. | |
1175 | \note Linear time complexity. | |
1176 | */ | |
1177 | GenericValue& MemberReserve(SizeType newCapacity, Allocator &allocator) { | |
1178 | CEREAL_RAPIDJSON_ASSERT(IsObject()); | |
1179 | if (newCapacity > data_.o.capacity) { | |
1180 | SetMembersPointer(reinterpret_cast<Member*>(allocator.Realloc(GetMembersPointer(), data_.o.capacity * sizeof(Member), newCapacity * sizeof(Member)))); | |
1181 | data_.o.capacity = newCapacity; | |
1182 | } | |
1183 | return *this; | |
1184 | } | |
1185 | ||
1085 | 1186 | //! Check whether a member exists in the object. |
1086 | 1187 | /*! |
1087 | 1188 | \param name Member name to be searched. |
1187 | 1288 | CEREAL_RAPIDJSON_ASSERT(name.IsString()); |
1188 | 1289 | |
1189 | 1290 | ObjectData& o = data_.o; |
1190 | if (o.size >= o.capacity) { | |
1191 | if (o.capacity == 0) { | |
1192 | o.capacity = kDefaultObjectCapacity; | |
1193 | SetMembersPointer(reinterpret_cast<Member*>(allocator.Malloc(o.capacity * sizeof(Member)))); | |
1194 | } | |
1195 | else { | |
1196 | SizeType oldCapacity = o.capacity; | |
1197 | o.capacity += (oldCapacity + 1) / 2; // grow by factor 1.5 | |
1198 | SetMembersPointer(reinterpret_cast<Member*>(allocator.Realloc(GetMembersPointer(), oldCapacity * sizeof(Member), o.capacity * sizeof(Member)))); | |
1199 | } | |
1200 | } | |
1291 | if (o.size >= o.capacity) | |
1292 | MemberReserve(o.capacity == 0 ? kDefaultObjectCapacity : (o.capacity + (o.capacity + 1) / 2), allocator); | |
1201 | 1293 | Member* members = GetMembersPointer(); |
1202 | 1294 | members[o.size].name.RawAssign(name); |
1203 | 1295 | members[o.size].value.RawAssign(value); |
1334 | 1426 | \note Linear time complexity. |
1335 | 1427 | */ |
1336 | 1428 | void RemoveAllMembers() { |
1337 | CEREAL_RAPIDJSON_ASSERT(IsObject()); | |
1429 | CEREAL_RAPIDJSON_ASSERT(IsObject()); | |
1338 | 1430 | for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m) |
1339 | 1431 | m->~Member(); |
1340 | 1432 | data_.o.size = 0; |
1424 | 1516 | MemberIterator pos = MemberBegin() + (first - MemberBegin()); |
1425 | 1517 | for (MemberIterator itr = pos; itr != last; ++itr) |
1426 | 1518 | itr->~Member(); |
1427 | std::memmove(&*pos, &*last, static_cast<size_t>(MemberEnd() - last) * sizeof(Member)); | |
1519 | std::memmove(static_cast<void*>(&*pos), &*last, static_cast<size_t>(MemberEnd() - last) * sizeof(Member)); | |
1428 | 1520 | data_.o.size -= static_cast<SizeType>(last - first); |
1429 | 1521 | return pos; |
1430 | 1522 | } |
1480 | 1572 | \note Linear time complexity. |
1481 | 1573 | */ |
1482 | 1574 | void Clear() { |
1483 | CEREAL_RAPIDJSON_ASSERT(IsArray()); | |
1575 | CEREAL_RAPIDJSON_ASSERT(IsArray()); | |
1484 | 1576 | GenericValue* e = GetElementsPointer(); |
1485 | 1577 | for (GenericValue* v = e; v != e + data_.a.size; ++v) |
1486 | 1578 | v->~GenericValue(); |
1627 | 1719 | CEREAL_RAPIDJSON_ASSERT(last <= End()); |
1628 | 1720 | ValueIterator pos = Begin() + (first - Begin()); |
1629 | 1721 | for (ValueIterator itr = pos; itr != last; ++itr) |
1630 | itr->~GenericValue(); | |
1631 | std::memmove(pos, last, static_cast<size_t>(End() - last) * sizeof(GenericValue)); | |
1722 | itr->~GenericValue(); | |
1723 | std::memmove(static_cast<void*>(pos), last, static_cast<size_t>(End() - last) * sizeof(GenericValue)); | |
1632 | 1724 | data_.a.size -= static_cast<SizeType>(last - first); |
1633 | 1725 | return pos; |
1634 | 1726 | } |
1670 | 1762 | GenericValue& SetInt64(int64_t i64) { this->~GenericValue(); new (this) GenericValue(i64); return *this; } |
1671 | 1763 | GenericValue& SetUint64(uint64_t u64) { this->~GenericValue(); new (this) GenericValue(u64); return *this; } |
1672 | 1764 | GenericValue& SetDouble(double d) { this->~GenericValue(); new (this) GenericValue(d); return *this; } |
1673 | GenericValue& SetFloat(float f) { this->~GenericValue(); new (this) GenericValue(f); return *this; } | |
1765 | GenericValue& SetFloat(float f) { this->~GenericValue(); new (this) GenericValue(static_cast<double>(f)); return *this; } | |
1674 | 1766 | |
1675 | 1767 | //@} |
1676 | 1768 | |
1686 | 1778 | |
1687 | 1779 | //! Set this value as a string without copying source string. |
1688 | 1780 | /*! This version has better performance with supplied length, and also support string containing null character. |
1689 | \param s source string pointer. | |
1781 | \param s source string pointer. | |
1690 | 1782 | \param length The length of source string, excluding the trailing null terminator. |
1691 | 1783 | \return The value itself for fluent API. |
1692 | 1784 | \post IsString() == true && GetString() == s && GetStringLength() == length |
1703 | 1795 | |
1704 | 1796 | //! Set this value as a string by copying from source string. |
1705 | 1797 | /*! This version has better performance with supplied length, and also support string containing null character. |
1706 | \param s source string. | |
1798 | \param s source string. | |
1707 | 1799 | \param length The length of source string, excluding the trailing null terminator. |
1708 | 1800 | \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator(). |
1709 | 1801 | \return The value itself for fluent API. |
1710 | 1802 | \post IsString() == true && GetString() != s && strcmp(GetString(),s) == 0 && GetStringLength() == length |
1711 | 1803 | */ |
1712 | GenericValue& SetString(const Ch* s, SizeType length, Allocator& allocator) { this->~GenericValue(); SetStringRaw(StringRef(s, length), allocator); return *this; } | |
1804 | GenericValue& SetString(const Ch* s, SizeType length, Allocator& allocator) { return SetString(StringRef(s, length), allocator); } | |
1713 | 1805 | |
1714 | 1806 | //! Set this value as a string by copying from source string. |
1715 | /*! \param s source string. | |
1807 | /*! \param s source string. | |
1716 | 1808 | \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator(). |
1717 | 1809 | \return The value itself for fluent API. |
1718 | 1810 | \post IsString() == true && GetString() != s && strcmp(GetString(),s) == 0 && GetStringLength() == length |
1719 | 1811 | */ |
1720 | GenericValue& SetString(const Ch* s, Allocator& allocator) { return SetString(s, internal::StrLen(s), allocator); } | |
1812 | GenericValue& SetString(const Ch* s, Allocator& allocator) { return SetString(StringRef(s), allocator); } | |
1813 | ||
1814 | //! Set this value as a string by copying from source string. | |
1815 | /*! \param s source string reference | |
1816 | \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator(). | |
1817 | \return The value itself for fluent API. | |
1818 | \post IsString() == true && GetString() != s.s && strcmp(GetString(),s) == 0 && GetStringLength() == length | |
1819 | */ | |
1820 | GenericValue& SetString(StringRefType s, Allocator& allocator) { this->~GenericValue(); SetStringRaw(s, allocator); return *this; } | |
1721 | 1821 | |
1722 | 1822 | #if CEREAL_RAPIDJSON_HAS_STDSTRING |
1723 | 1823 | //! Set this value as a string by copying from source string. |
1727 | 1827 | \post IsString() == true && GetString() != s.data() && strcmp(GetString(),s.data() == 0 && GetStringLength() == s.size() |
1728 | 1828 | \note Requires the definition of the preprocessor symbol \ref CEREAL_RAPIDJSON_HAS_STDSTRING. |
1729 | 1829 | */ |
1730 | GenericValue& SetString(const std::basic_string<Ch>& s, Allocator& allocator) { return SetString(s.data(), SizeType(s.size()), allocator); } | |
1830 | GenericValue& SetString(const std::basic_string<Ch>& s, Allocator& allocator) { return SetString(StringRef(s), allocator); } | |
1731 | 1831 | #endif |
1732 | 1832 | |
1733 | 1833 | //@} |
1789 | 1889 | if (CEREAL_RAPIDJSON_UNLIKELY(!v->Accept(handler))) |
1790 | 1890 | return false; |
1791 | 1891 | return handler.EndArray(data_.a.size); |
1792 | ||
1892 | ||
1793 | 1893 | case kStringType: |
1794 | 1894 | return handler.String(GetString(), GetStringLength(), (data_.f.flags & kCopyFlag) != 0); |
1795 | ||
1895 | ||
1796 | 1896 | default: |
1797 | 1897 | CEREAL_RAPIDJSON_ASSERT(GetType() == kNumberType); |
1798 | 1898 | if (IsDouble()) return handler.Double(data_.n.d); |
1935 | 2035 | if (count) { |
1936 | 2036 | GenericValue* e = static_cast<GenericValue*>(allocator.Malloc(count * sizeof(GenericValue))); |
1937 | 2037 | SetElementsPointer(e); |
1938 | std::memcpy(e, values, count * sizeof(GenericValue)); | |
2038 | std::memcpy(static_cast<void*>(e), values, count * sizeof(GenericValue)); | |
1939 | 2039 | } |
1940 | 2040 | else |
1941 | 2041 | SetElementsPointer(0); |
1948 | 2048 | if (count) { |
1949 | 2049 | Member* m = static_cast<Member*>(allocator.Malloc(count * sizeof(Member))); |
1950 | 2050 | SetMembersPointer(m); |
1951 | std::memcpy(m, members, count * sizeof(Member)); | |
2051 | std::memcpy(static_cast<void*>(m), members, count * sizeof(Member)); | |
1952 | 2052 | } |
1953 | 2053 | else |
1954 | 2054 | SetMembersPointer(0); |
2009 | 2109 | typedef GenericValue<UTF8<> > Value; |
2010 | 2110 | |
2011 | 2111 | /////////////////////////////////////////////////////////////////////////////// |
2012 | // GenericDocument | |
2112 | // GenericDocument | |
2013 | 2113 | |
2014 | 2114 | //! A document for parsing JSON text as DOM. |
2015 | 2115 | /*! |
2037 | 2137 | GenericValue<Encoding, Allocator>(type), allocator_(allocator), ownAllocator_(0), stack_(stackAllocator, stackCapacity), parseResult_() |
2038 | 2138 | { |
2039 | 2139 | if (!allocator_) |
2040 | ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator()); | |
2140 | ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator)(); | |
2041 | 2141 | } |
2042 | 2142 | |
2043 | 2143 | //! Constructor |
2044 | /*! Creates an empty document which type is Null. | |
2144 | /*! Creates an empty document which type is Null. | |
2045 | 2145 | \param allocator Optional allocator for allocating memory. |
2046 | 2146 | \param stackCapacity Optional initial capacity of stack in bytes. |
2047 | 2147 | \param stackAllocator Optional allocator for allocating memory for stack. |
2048 | 2148 | */ |
2049 | GenericDocument(Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity, StackAllocator* stackAllocator = 0) : | |
2149 | GenericDocument(Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity, StackAllocator* stackAllocator = 0) : | |
2050 | 2150 | allocator_(allocator), ownAllocator_(0), stack_(stackAllocator, stackCapacity), parseResult_() |
2051 | 2151 | { |
2052 | 2152 | if (!allocator_) |
2053 | ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator()); | |
2153 | ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator)(); | |
2054 | 2154 | } |
2055 | 2155 | |
2056 | 2156 | #if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS |
2110 | 2210 | internal::Swap(parseResult_, rhs.parseResult_); |
2111 | 2211 | return *this; |
2112 | 2212 | } |
2213 | ||
2214 | // Allow Swap with ValueType. | |
2215 | // Refer to Effective C++ 3rd Edition/Item 33: Avoid hiding inherited names. | |
2216 | using ValueType::Swap; | |
2113 | 2217 | |
2114 | 2218 | //! free-standing swap function helper |
2115 | 2219 | /*! |
2242 | 2346 | template <unsigned parseFlags, typename SourceEncoding> |
2243 | 2347 | GenericDocument& Parse(const typename SourceEncoding::Ch* str, size_t length) { |
2244 | 2348 | CEREAL_RAPIDJSON_ASSERT(!(parseFlags & kParseInsituFlag)); |
2245 | MemoryStream ms(static_cast<const char*>(str), length * sizeof(typename SourceEncoding::Ch)); | |
2349 | MemoryStream ms(reinterpret_cast<const char*>(str), length * sizeof(typename SourceEncoding::Ch)); | |
2246 | 2350 | EncodedInputStream<SourceEncoding, MemoryStream> is(ms); |
2247 | 2351 | ParseStream<parseFlags, SourceEncoding>(is); |
2248 | 2352 | return *this; |
2252 | 2356 | GenericDocument& Parse(const Ch* str, size_t length) { |
2253 | 2357 | return Parse<parseFlags, Encoding>(str, length); |
2254 | 2358 | } |
2255 | ||
2359 | ||
2256 | 2360 | GenericDocument& Parse(const Ch* str, size_t length) { |
2257 | 2361 | return Parse<kParseDefaultFlags>(str, length); |
2258 | 2362 | } |
2272 | 2376 | GenericDocument& Parse(const std::basic_string<Ch>& str) { |
2273 | 2377 | return Parse<kParseDefaultFlags>(str); |
2274 | 2378 | } |
2275 | #endif // CEREAL_RAPIDJSON_HAS_STDSTRING | |
2379 | #endif // CEREAL_RAPIDJSON_HAS_STDSTRING | |
2276 | 2380 | |
2277 | 2381 | //!@} |
2278 | 2382 | |
2279 | 2383 | //!@name Handling parse errors |
2280 | 2384 | //!@{ |
2281 | 2385 | |
2282 | //! Whether a parse error has occured in the last parsing. | |
2386 | //! Whether a parse error has occurred in the last parsing. | |
2283 | 2387 | bool HasParseError() const { return parseResult_.IsError(); } |
2284 | 2388 | |
2285 | 2389 | //! Get the \ref ParseErrorCode of last parsing. |
2337 | 2441 | bool Uint64(uint64_t i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; } |
2338 | 2442 | bool Double(double d) { new (stack_.template Push<ValueType>()) ValueType(d); return true; } |
2339 | 2443 | |
2340 | bool RawNumber(const Ch* str, SizeType length, bool copy) { | |
2341 | if (copy) | |
2444 | bool RawNumber(const Ch* str, SizeType length, bool copy) { | |
2445 | if (copy) | |
2342 | 2446 | new (stack_.template Push<ValueType>()) ValueType(str, length, GetAllocator()); |
2343 | 2447 | else |
2344 | 2448 | new (stack_.template Push<ValueType>()) ValueType(str, length); |
2345 | 2449 | return true; |
2346 | 2450 | } |
2347 | 2451 | |
2348 | bool String(const Ch* str, SizeType length, bool copy) { | |
2349 | if (copy) | |
2452 | bool String(const Ch* str, SizeType length, bool copy) { | |
2453 | if (copy) | |
2350 | 2454 | new (stack_.template Push<ValueType>()) ValueType(str, length, GetAllocator()); |
2351 | 2455 | else |
2352 | 2456 | new (stack_.template Push<ValueType>()) ValueType(str, length); |
2354 | 2458 | } |
2355 | 2459 | |
2356 | 2460 | bool StartObject() { new (stack_.template Push<ValueType>()) ValueType(kObjectType); return true; } |
2357 | ||
2461 | ||
2358 | 2462 | bool Key(const Ch* str, SizeType length, bool copy) { return String(str, length, copy); } |
2359 | 2463 | |
2360 | 2464 | bool EndObject(SizeType memberCount) { |
2364 | 2468 | } |
2365 | 2469 | |
2366 | 2470 | bool StartArray() { new (stack_.template Push<ValueType>()) ValueType(kArrayType); return true; } |
2367 | ||
2471 | ||
2368 | 2472 | bool EndArray(SizeType elementCount) { |
2369 | 2473 | ValueType* elements = stack_.template Pop<ValueType>(elementCount); |
2370 | 2474 | stack_.template Top<ValueType>()->SetArrayRaw(elements, elementCount, GetAllocator()); |
2399 | 2503 | |
2400 | 2504 | //! GenericDocument with UTF8 encoding |
2401 | 2505 | typedef GenericDocument<UTF8<> > Document; |
2402 | ||
2403 | // defined here due to the dependency on GenericDocument | |
2404 | template <typename Encoding, typename Allocator> | |
2405 | template <typename SourceAllocator> | |
2406 | inline | |
2407 | GenericValue<Encoding,Allocator>::GenericValue(const GenericValue<Encoding,SourceAllocator>& rhs, Allocator& allocator) | |
2408 | { | |
2409 | switch (rhs.GetType()) { | |
2410 | case kObjectType: | |
2411 | case kArrayType: { // perform deep copy via SAX Handler | |
2412 | GenericDocument<Encoding,Allocator> d(&allocator); | |
2413 | rhs.Accept(d); | |
2414 | RawAssign(*d.stack_.template Pop<GenericValue>(1)); | |
2415 | } | |
2416 | break; | |
2417 | case kStringType: | |
2418 | if (rhs.data_.f.flags == kConstStringFlag) { | |
2419 | data_.f.flags = rhs.data_.f.flags; | |
2420 | data_ = *reinterpret_cast<const Data*>(&rhs.data_); | |
2421 | } else { | |
2422 | SetStringRaw(StringRef(rhs.GetString(), rhs.GetStringLength()), allocator); | |
2423 | } | |
2424 | break; | |
2425 | default: | |
2426 | data_.f.flags = rhs.data_.f.flags; | |
2427 | data_ = *reinterpret_cast<const Data*>(&rhs.data_); | |
2428 | break; | |
2429 | } | |
2430 | } | |
2431 | 2506 | |
2432 | 2507 | //! Helper class for accessing Value of array type. |
2433 | 2508 | /*! |
2509 | 2584 | ~GenericObject() {} |
2510 | 2585 | |
2511 | 2586 | SizeType MemberCount() const { return value_.MemberCount(); } |
2587 | SizeType MemberCapacity() const { return value_.MemberCapacity(); } | |
2512 | 2588 | bool ObjectEmpty() const { return value_.ObjectEmpty(); } |
2513 | 2589 | template <typename T> ValueType& operator[](T* name) const { return value_[name]; } |
2514 | 2590 | template <typename SourceAllocator> ValueType& operator[](const GenericValue<EncodingType, SourceAllocator>& name) const { return value_[name]; } |
2517 | 2593 | #endif |
2518 | 2594 | MemberIterator MemberBegin() const { return value_.MemberBegin(); } |
2519 | 2595 | MemberIterator MemberEnd() const { return value_.MemberEnd(); } |
2596 | GenericObject MemberReserve(SizeType newCapacity, AllocatorType &allocator) const { value_.MemberReserve(newCapacity, allocator); return *this; } | |
2520 | 2597 | bool HasMember(const Ch* name) const { return value_.HasMember(name); } |
2521 | 2598 | #if CEREAL_RAPIDJSON_HAS_STDSTRING |
2522 | 2599 | bool HasMember(const std::basic_string<Ch>& name) const { return value_.HasMember(name); } |
2542 | 2619 | GenericObject AddMember(StringRefType name, ValueType& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } |
2543 | 2620 | GenericObject AddMember(StringRefType name, StringRefType value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } |
2544 | 2621 | template <typename T> CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (GenericObject)) AddMember(StringRefType name, T value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } |
2545 | void RemoveAllMembers() { return value_.RemoveAllMembers(); } | |
2622 | void RemoveAllMembers() { value_.RemoveAllMembers(); } | |
2546 | 2623 | bool RemoveMember(const Ch* name) const { return value_.RemoveMember(name); } |
2547 | 2624 | #if CEREAL_RAPIDJSON_HAS_STDSTRING |
2548 | 2625 | bool RemoveMember(const std::basic_string<Ch>& name) const { return value_.RemoveMember(name); } |
199 | 199 | // xx xx xx xx UTF-8 |
200 | 200 | |
201 | 201 | if (!hasBOM_) { |
202 | unsigned pattern = (c[0] ? 1 : 0) | (c[1] ? 2 : 0) | (c[2] ? 4 : 0) | (c[3] ? 8 : 0); | |
202 | int pattern = (c[0] ? 1 : 0) | (c[1] ? 2 : 0) | (c[2] ? 4 : 0) | (c[3] ? 8 : 0); | |
203 | 203 | switch (pattern) { |
204 | 204 | case 0x08: type_ = kUTF32BE; break; |
205 | 205 | case 0x0A: type_ = kUTF16BE; break; |
16 | 16 | |
17 | 17 | #include "rapidjson.h" |
18 | 18 | |
19 | #ifdef _MSC_VER | |
19 | #if defined(_MSC_VER) && !defined(__clang__) | |
20 | 20 | CEREAL_RAPIDJSON_DIAG_PUSH |
21 | 21 | CEREAL_RAPIDJSON_DIAG_OFF(4244) // conversion from 'type1' to 'type2', possible loss of data |
22 | 22 | CEREAL_RAPIDJSON_DIAG_OFF(4702) // unreachable code |
143 | 143 | |
144 | 144 | template <typename InputStream> |
145 | 145 | static bool Decode(InputStream& is, unsigned* codepoint) { |
146 | #define COPY() c = is.Take(); *codepoint = (*codepoint << 6) | (static_cast<unsigned char>(c) & 0x3Fu) | |
147 | #define TRANS(mask) result &= ((GetRange(static_cast<unsigned char>(c)) & mask) != 0) | |
148 | #define TAIL() COPY(); TRANS(0x70) | |
146 | #define CEREAL_RAPIDJSON_COPY() c = is.Take(); *codepoint = (*codepoint << 6) | (static_cast<unsigned char>(c) & 0x3Fu) | |
147 | #define CEREAL_RAPIDJSON_TRANS(mask) result &= ((GetRange(static_cast<unsigned char>(c)) & mask) != 0) | |
148 | #define CEREAL_RAPIDJSON_TAIL() CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x70) | |
149 | 149 | typename InputStream::Ch c = is.Take(); |
150 | 150 | if (!(c & 0x80)) { |
151 | 151 | *codepoint = static_cast<unsigned char>(c); |
156 | 156 | if (type >= 32) { |
157 | 157 | *codepoint = 0; |
158 | 158 | } else { |
159 | *codepoint = (0xFF >> type) & static_cast<unsigned char>(c); | |
159 | *codepoint = (0xFFu >> type) & static_cast<unsigned char>(c); | |
160 | 160 | } |
161 | 161 | bool result = true; |
162 | 162 | switch (type) { |
163 | case 2: TAIL(); return result; | |
164 | case 3: TAIL(); TAIL(); return result; | |
165 | case 4: COPY(); TRANS(0x50); TAIL(); return result; | |
166 | case 5: COPY(); TRANS(0x10); TAIL(); TAIL(); return result; | |
167 | case 6: TAIL(); TAIL(); TAIL(); return result; | |
168 | case 10: COPY(); TRANS(0x20); TAIL(); return result; | |
169 | case 11: COPY(); TRANS(0x60); TAIL(); TAIL(); return result; | |
163 | case 2: CEREAL_RAPIDJSON_TAIL(); return result; | |
164 | case 3: CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); return result; | |
165 | case 4: CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x50); CEREAL_RAPIDJSON_TAIL(); return result; | |
166 | case 5: CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x10); CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); return result; | |
167 | case 6: CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); return result; | |
168 | case 10: CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x20); CEREAL_RAPIDJSON_TAIL(); return result; | |
169 | case 11: CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x60); CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); return result; | |
170 | 170 | default: return false; |
171 | 171 | } |
172 | #undef COPY | |
173 | #undef TRANS | |
174 | #undef TAIL | |
172 | #undef CEREAL_RAPIDJSON_COPY | |
173 | #undef CEREAL_RAPIDJSON_TRANS | |
174 | #undef CEREAL_RAPIDJSON_TAIL | |
175 | 175 | } |
176 | 176 | |
177 | 177 | template <typename InputStream, typename OutputStream> |
178 | 178 | static bool Validate(InputStream& is, OutputStream& os) { |
179 | #define COPY() os.Put(c = is.Take()) | |
180 | #define TRANS(mask) result &= ((GetRange(static_cast<unsigned char>(c)) & mask) != 0) | |
181 | #define TAIL() COPY(); TRANS(0x70) | |
179 | #define CEREAL_RAPIDJSON_COPY() os.Put(c = is.Take()) | |
180 | #define CEREAL_RAPIDJSON_TRANS(mask) result &= ((GetRange(static_cast<unsigned char>(c)) & mask) != 0) | |
181 | #define CEREAL_RAPIDJSON_TAIL() CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x70) | |
182 | 182 | Ch c; |
183 | COPY(); | |
183 | CEREAL_RAPIDJSON_COPY(); | |
184 | 184 | if (!(c & 0x80)) |
185 | 185 | return true; |
186 | 186 | |
187 | 187 | bool result = true; |
188 | 188 | switch (GetRange(static_cast<unsigned char>(c))) { |
189 | case 2: TAIL(); return result; | |
190 | case 3: TAIL(); TAIL(); return result; | |
191 | case 4: COPY(); TRANS(0x50); TAIL(); return result; | |
192 | case 5: COPY(); TRANS(0x10); TAIL(); TAIL(); return result; | |
193 | case 6: TAIL(); TAIL(); TAIL(); return result; | |
194 | case 10: COPY(); TRANS(0x20); TAIL(); return result; | |
195 | case 11: COPY(); TRANS(0x60); TAIL(); TAIL(); return result; | |
189 | case 2: CEREAL_RAPIDJSON_TAIL(); return result; | |
190 | case 3: CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); return result; | |
191 | case 4: CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x50); CEREAL_RAPIDJSON_TAIL(); return result; | |
192 | case 5: CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x10); CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); return result; | |
193 | case 6: CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); return result; | |
194 | case 10: CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x20); CEREAL_RAPIDJSON_TAIL(); return result; | |
195 | case 11: CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x60); CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); return result; | |
196 | 196 | default: return false; |
197 | 197 | } |
198 | #undef COPY | |
199 | #undef TRANS | |
200 | #undef TAIL | |
198 | #undef CEREAL_RAPIDJSON_COPY | |
199 | #undef CEREAL_RAPIDJSON_TRANS | |
200 | #undef CEREAL_RAPIDJSON_TAIL | |
201 | 201 | } |
202 | 202 | |
203 | 203 | static unsigned char GetRange(unsigned char c) { |
282 | 282 | CEREAL_RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); |
283 | 283 | unsigned v = codepoint - 0x10000; |
284 | 284 | os.Put(static_cast<typename OutputStream::Ch>((v >> 10) | 0xD800)); |
285 | os.Put((v & 0x3FF) | 0xDC00); | |
285 | os.Put(static_cast<typename OutputStream::Ch>((v & 0x3FF) | 0xDC00)); | |
286 | 286 | } |
287 | 287 | } |
288 | 288 | |
298 | 298 | CEREAL_RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); |
299 | 299 | unsigned v = codepoint - 0x10000; |
300 | 300 | PutUnsafe(os, static_cast<typename OutputStream::Ch>((v >> 10) | 0xD800)); |
301 | PutUnsafe(os, (v & 0x3FF) | 0xDC00); | |
301 | PutUnsafe(os, static_cast<typename OutputStream::Ch>((v & 0x3FF) | 0xDC00)); | |
302 | 302 | } |
303 | 303 | } |
304 | 304 | |
383 | 383 | static CharType Take(InputByteStream& is) { |
384 | 384 | CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); |
385 | 385 | unsigned c = static_cast<unsigned>(static_cast<uint8_t>(is.Take())) << 8; |
386 | c |= static_cast<uint8_t>(is.Take()); | |
386 | c |= static_cast<unsigned>(static_cast<uint8_t>(is.Take())); | |
387 | 387 | return static_cast<CharType>(c); |
388 | 388 | } |
389 | 389 | |
619 | 619 | #define CEREAL_RAPIDJSON_ENCODINGS_FUNC(x) UTF8<Ch>::x, UTF16LE<Ch>::x, UTF16BE<Ch>::x, UTF32LE<Ch>::x, UTF32BE<Ch>::x |
620 | 620 | |
621 | 621 | template<typename OutputStream> |
622 | CEREAL_RAPIDJSON_FORCEINLINE static void Encode(OutputStream& os, unsigned codepoint) { | |
622 | static CEREAL_RAPIDJSON_FORCEINLINE void Encode(OutputStream& os, unsigned codepoint) { | |
623 | 623 | typedef void (*EncodeFunc)(OutputStream&, unsigned); |
624 | 624 | static const EncodeFunc f[] = { CEREAL_RAPIDJSON_ENCODINGS_FUNC(Encode) }; |
625 | 625 | (*f[os.GetType()])(os, codepoint); |
626 | 626 | } |
627 | 627 | |
628 | 628 | template<typename OutputStream> |
629 | CEREAL_RAPIDJSON_FORCEINLINE static void EncodeUnsafe(OutputStream& os, unsigned codepoint) { | |
629 | static CEREAL_RAPIDJSON_FORCEINLINE void EncodeUnsafe(OutputStream& os, unsigned codepoint) { | |
630 | 630 | typedef void (*EncodeFunc)(OutputStream&, unsigned); |
631 | 631 | static const EncodeFunc f[] = { CEREAL_RAPIDJSON_ENCODINGS_FUNC(EncodeUnsafe) }; |
632 | 632 | (*f[os.GetType()])(os, codepoint); |
633 | 633 | } |
634 | 634 | |
635 | 635 | template <typename InputStream> |
636 | CEREAL_RAPIDJSON_FORCEINLINE static bool Decode(InputStream& is, unsigned* codepoint) { | |
636 | static CEREAL_RAPIDJSON_FORCEINLINE bool Decode(InputStream& is, unsigned* codepoint) { | |
637 | 637 | typedef bool (*DecodeFunc)(InputStream&, unsigned*); |
638 | 638 | static const DecodeFunc f[] = { CEREAL_RAPIDJSON_ENCODINGS_FUNC(Decode) }; |
639 | 639 | return (*f[is.GetType()])(is, codepoint); |
640 | 640 | } |
641 | 641 | |
642 | 642 | template <typename InputStream, typename OutputStream> |
643 | CEREAL_RAPIDJSON_FORCEINLINE static bool Validate(InputStream& is, OutputStream& os) { | |
643 | static CEREAL_RAPIDJSON_FORCEINLINE bool Validate(InputStream& is, OutputStream& os) { | |
644 | 644 | typedef bool (*ValidateFunc)(InputStream&, OutputStream&); |
645 | 645 | static const ValidateFunc f[] = { CEREAL_RAPIDJSON_ENCODINGS_FUNC(Validate) }; |
646 | 646 | return (*f[is.GetType()])(is, os); |
657 | 657 | struct Transcoder { |
658 | 658 | //! Take one Unicode codepoint from source encoding, convert it to target encoding and put it to the output stream. |
659 | 659 | template<typename InputStream, typename OutputStream> |
660 | CEREAL_RAPIDJSON_FORCEINLINE static bool Transcode(InputStream& is, OutputStream& os) { | |
660 | static CEREAL_RAPIDJSON_FORCEINLINE bool Transcode(InputStream& is, OutputStream& os) { | |
661 | 661 | unsigned codepoint; |
662 | 662 | if (!SourceEncoding::Decode(is, &codepoint)) |
663 | 663 | return false; |
666 | 666 | } |
667 | 667 | |
668 | 668 | template<typename InputStream, typename OutputStream> |
669 | CEREAL_RAPIDJSON_FORCEINLINE static bool TranscodeUnsafe(InputStream& is, OutputStream& os) { | |
669 | static CEREAL_RAPIDJSON_FORCEINLINE bool TranscodeUnsafe(InputStream& is, OutputStream& os) { | |
670 | 670 | unsigned codepoint; |
671 | 671 | if (!SourceEncoding::Decode(is, &codepoint)) |
672 | 672 | return false; |
676 | 676 | |
677 | 677 | //! Validate one Unicode codepoint from an encoded stream. |
678 | 678 | template<typename InputStream, typename OutputStream> |
679 | CEREAL_RAPIDJSON_FORCEINLINE static bool Validate(InputStream& is, OutputStream& os) { | |
679 | static CEREAL_RAPIDJSON_FORCEINLINE bool Validate(InputStream& is, OutputStream& os) { | |
680 | 680 | return Transcode(is, os); // Since source/target encoding is different, must transcode. |
681 | 681 | } |
682 | 682 | }; |
689 | 689 | template<typename Encoding> |
690 | 690 | struct Transcoder<Encoding, Encoding> { |
691 | 691 | template<typename InputStream, typename OutputStream> |
692 | CEREAL_RAPIDJSON_FORCEINLINE static bool Transcode(InputStream& is, OutputStream& os) { | |
692 | static CEREAL_RAPIDJSON_FORCEINLINE bool Transcode(InputStream& is, OutputStream& os) { | |
693 | 693 | os.Put(is.Take()); // Just copy one code unit. This semantic is different from primary template class. |
694 | 694 | return true; |
695 | 695 | } |
696 | 696 | |
697 | 697 | template<typename InputStream, typename OutputStream> |
698 | CEREAL_RAPIDJSON_FORCEINLINE static bool TranscodeUnsafe(InputStream& is, OutputStream& os) { | |
698 | static CEREAL_RAPIDJSON_FORCEINLINE bool TranscodeUnsafe(InputStream& is, OutputStream& os) { | |
699 | 699 | PutUnsafe(os, is.Take()); // Just copy one code unit. This semantic is different from primary template class. |
700 | 700 | return true; |
701 | 701 | } |
702 | 702 | |
703 | 703 | template<typename InputStream, typename OutputStream> |
704 | CEREAL_RAPIDJSON_FORCEINLINE static bool Validate(InputStream& is, OutputStream& os) { | |
704 | static CEREAL_RAPIDJSON_FORCEINLINE bool Validate(InputStream& is, OutputStream& os) { | |
705 | 705 | return Encoding::Validate(is, os); // source/target encoding are the same |
706 | 706 | } |
707 | 707 | }; |
708 | 708 | |
709 | 709 | CEREAL_RAPIDJSON_NAMESPACE_END |
710 | 710 | |
711 | #if defined(__GNUC__) || defined(_MSC_VER) | |
711 | #if defined(__GNUC__) || (defined(_MSC_VER) && !defined(__clang__)) | |
712 | 712 | CEREAL_RAPIDJSON_DIAG_POP |
713 | 713 | #endif |
714 | 714 |
103 | 103 | \see GenericReader::Parse, GenericDocument::Parse |
104 | 104 | */ |
105 | 105 | struct ParseResult { |
106 | //!! Unspecified boolean type | |
107 | typedef bool (ParseResult::*BooleanType)() const; | |
106 | 108 | public: |
107 | 109 | //! Default constructor, no error. |
108 | 110 | ParseResult() : code_(kParseErrorNone), offset_(0) {} |
114 | 116 | //! Get the error offset, if \ref IsError(), 0 otherwise. |
115 | 117 | size_t Offset() const { return offset_; } |
116 | 118 | |
117 | //! Conversion to \c bool, returns \c true, iff !\ref IsError(). | |
118 | operator bool() const { return !IsError(); } | |
119 | //! Explicit conversion to \c bool, returns \c true, iff !\ref IsError(). | |
120 | operator BooleanType() const { return !IsError() ? &ParseResult::IsError : NULL; } | |
119 | 121 | //! Whether the result is an error. |
120 | 122 | bool IsError() const { return code_ != kParseErrorNone; } |
121 | 123 | |
122 | 124 | bool operator==(const ParseResult& that) const { return code_ == that.code_; } |
123 | 125 | bool operator==(ParseErrorCode code) const { return code_ == code; } |
124 | 126 | friend bool operator==(ParseErrorCode code, const ParseResult & err) { return code == err.code_; } |
127 | ||
128 | bool operator!=(const ParseResult& that) const { return !(*this == that); } | |
129 | bool operator!=(ParseErrorCode code) const { return !(*this == code); } | |
130 | friend bool operator!=(ParseErrorCode code, const ParseResult & err) { return err != code; } | |
125 | 131 | |
126 | 132 | //! Reset error code. |
127 | 133 | void Clear() { Set(kParseErrorNone); } |
58 | 58 | |
59 | 59 | // For encoding detection only. |
60 | 60 | const Ch* Peek4() const { |
61 | return (current_ + 4 <= bufferLast_) ? current_ : 0; | |
61 | return (current_ + 4 - !eof_ <= bufferLast_) ? current_ : 0; | |
62 | 62 | } |
63 | 63 | |
64 | 64 | private: |
67 | 67 | ++current_; |
68 | 68 | else if (!eof_) { |
69 | 69 | count_ += readCount_; |
70 | readCount_ = fread(buffer_, 1, bufferSize_, fp_); | |
70 | readCount_ = std::fread(buffer_, 1, bufferSize_, fp_); | |
71 | 71 | bufferLast_ = buffer_ + readCount_ - 1; |
72 | 72 | current_ = buffer_; |
73 | 73 |
24 | 24 | |
25 | 25 | CEREAL_RAPIDJSON_NAMESPACE_BEGIN |
26 | 26 | |
27 | //! Wrapper of C file stream for input using fread(). | |
27 | //! Wrapper of C file stream for output using fwrite(). | |
28 | 28 | /*! |
29 | 29 | \note implements Stream concept |
30 | 30 | */ |
61 | 61 | |
62 | 62 | void Flush() { |
63 | 63 | if (current_ != buffer_) { |
64 | size_t result = fwrite(buffer_, 1, static_cast<size_t>(current_ - buffer_), fp_); | |
64 | size_t result = std::fwrite(buffer_, 1, static_cast<size_t>(current_ - buffer_), fp_); | |
65 | 65 | if (result < static_cast<size_t>(current_ - buffer_)) { |
66 | 66 | // failure deliberately ignored at this time |
67 | 67 | // added to avoid warn_unused_result build errors |
16 | 16 | |
17 | 17 | #include "../rapidjson.h" |
18 | 18 | |
19 | #if defined(_MSC_VER) && defined(_M_AMD64) | |
19 | #if defined(_MSC_VER) && !__INTEL_COMPILER && defined(_M_AMD64) | |
20 | 20 | #include <intrin.h> // for _umul128 |
21 | 21 | #pragma intrinsic(_umul128) |
22 | 22 | #endif |
132 | 132 | CEREAL_RAPIDJSON_ASSERT(count_ + offset <= kCapacity); |
133 | 133 | |
134 | 134 | if (interShift == 0) { |
135 | std::memmove(&digits_[count_ - 1 + offset], &digits_[count_ - 1], count_ * sizeof(Type)); | |
135 | std::memmove(digits_ + offset, digits_, count_ * sizeof(Type)); | |
136 | 136 | count_ += offset; |
137 | 137 | } |
138 | 138 | else { |
0 | 0 | // Tencent is pleased to support the open source community by making RapidJSON available. |
1 | // | |
1 | // | |
2 | 2 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. |
3 | 3 | // |
4 | 4 | // Licensed under the MIT License (the "License"); you may not use this file except |
6 | 6 | // |
7 | 7 | // http://opensource.org/licenses/MIT |
8 | 8 | // |
9 | // Unless required by applicable law or agreed to in writing, software distributed | |
10 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR | |
11 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the | |
9 | // Unless required by applicable law or agreed to in writing, software distributed | |
10 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR | |
11 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the | |
12 | 12 | // specific language governing permissions and limitations under the License. |
13 | 13 | |
14 | 14 | // This is a C++ header-only implementation of Grisu2 algorithm from the publication: |
19 | 19 | #define CEREAL_RAPIDJSON_DIYFP_H_ |
20 | 20 | |
21 | 21 | #include "../rapidjson.h" |
22 | ||
23 | #if defined(_MSC_VER) && defined(_M_AMD64) | |
22 | #include <limits> | |
23 | ||
24 | #if defined(_MSC_VER) && defined(_M_AMD64) && !defined(__INTEL_COMPILER) | |
24 | 25 | #include <intrin.h> |
25 | 26 | #pragma intrinsic(_BitScanReverse64) |
26 | 27 | #pragma intrinsic(_umul128) |
55 | 56 | if (biased_e != 0) { |
56 | 57 | f = significand + kDpHiddenBit; |
57 | 58 | e = biased_e - kDpExponentBias; |
58 | } | |
59 | } | |
59 | 60 | else { |
60 | 61 | f = significand; |
61 | 62 | e = kDpMinExponent + 1; |
98 | 99 | } |
99 | 100 | |
100 | 101 | DiyFp Normalize() const { |
102 | CEREAL_RAPIDJSON_ASSERT(f != 0); // https://stackoverflow.com/a/26809183/291737 | |
101 | 103 | #if defined(_MSC_VER) && defined(_M_AMD64) |
102 | 104 | unsigned long index; |
103 | 105 | _BitScanReverse64(&index, f); |
140 | 142 | double d; |
141 | 143 | uint64_t u64; |
142 | 144 | }u; |
143 | const uint64_t be = (e == kDpDenormalExponent && (f & kDpHiddenBit) == 0) ? 0 : | |
145 | CEREAL_RAPIDJSON_ASSERT(f <= kDpHiddenBit + kDpSignificandMask); | |
146 | if (e < kDpDenormalExponent) { | |
147 | // Underflow. | |
148 | return 0.0; | |
149 | } | |
150 | if (e >= kDpMaxExponent) { | |
151 | // Overflow. | |
152 | return std::numeric_limits<double>::infinity(); | |
153 | } | |
154 | const uint64_t be = (e == kDpDenormalExponent && (f & kDpHiddenBit) == 0) ? 0 : | |
144 | 155 | static_cast<uint64_t>(e + kDpExponentBias); |
145 | 156 | u.u64 = (f & kDpSignificandMask) | (be << kDpSignificandSize); |
146 | 157 | return u.d; |
219 | 230 | 641, 667, 694, 720, 747, 774, 800, 827, 853, 880, |
220 | 231 | 907, 933, 960, 986, 1013, 1039, 1066 |
221 | 232 | }; |
233 | CEREAL_RAPIDJSON_ASSERT(index < 87); | |
222 | 234 | return DiyFp(kCachedPowers_F[index], kCachedPowers_E[index]); |
223 | 235 | } |
224 | ||
236 | ||
225 | 237 | inline DiyFp GetCachedPower(int e, int* K) { |
226 | 238 | |
227 | 239 | //int k = static_cast<int>(ceil((-61 - e) * 0.30102999566398114)) + 374; |
237 | 249 | } |
238 | 250 | |
239 | 251 | inline DiyFp GetCachedPower10(int exp, int *outExp) { |
240 | unsigned index = (static_cast<unsigned>(exp) + 348u) / 8u; | |
241 | *outExp = -348 + static_cast<int>(index) * 8; | |
242 | return GetCachedPowerByIndex(index); | |
243 | } | |
252 | CEREAL_RAPIDJSON_ASSERT(exp >= -348); | |
253 | unsigned index = static_cast<unsigned>(exp + 348) / 8u; | |
254 | *outExp = -348 + static_cast<int>(index) * 8; | |
255 | return GetCachedPowerByIndex(index); | |
256 | } | |
244 | 257 | |
245 | 258 | #ifdef __GNUC__ |
246 | 259 | CEREAL_RAPIDJSON_DIAG_POP |
40 | 40 | } |
41 | 41 | } |
42 | 42 | |
43 | inline unsigned CountDecimalDigit32(uint32_t n) { | |
43 | inline int CountDecimalDigit32(uint32_t n) { | |
44 | 44 | // Simple pure C++ implementation was faster than __builtin_clz version in this situation. |
45 | 45 | if (n < 10) return 1; |
46 | 46 | if (n < 100) return 2; |
62 | 62 | const DiyFp wp_w = Mp - W; |
63 | 63 | uint32_t p1 = static_cast<uint32_t>(Mp.f >> -one.e); |
64 | 64 | uint64_t p2 = Mp.f & (one.f - 1); |
65 | unsigned kappa = CountDecimalDigit32(p1); // kappa in [0, 9] | |
65 | int kappa = CountDecimalDigit32(p1); // kappa in [0, 9] | |
66 | 66 | *len = 0; |
67 | 67 | |
68 | 68 | while (kappa > 0) { |
101 | 101 | kappa--; |
102 | 102 | if (p2 < delta) { |
103 | 103 | *K += kappa; |
104 | int index = -static_cast<int>(kappa); | |
105 | GrisuRound(buffer, *len, delta, p2, one.f, wp_w.f * (index < 9 ? kPow10[-static_cast<int>(kappa)] : 0)); | |
104 | int index = -kappa; | |
105 | GrisuRound(buffer, *len, delta, p2, one.f, wp_w.f * (index < 9 ? kPow10[index] : 0)); | |
106 | 106 | return; |
107 | 107 | } |
108 | 108 | } |
47 | 47 | int IntegerExponent() const { return (IsNormal() ? Exponent() : kDenormalExponent) - kSignificandSize; } |
48 | 48 | uint64_t ToBias() const { return (u_ & kSignMask) ? ~u_ + 1 : u_ | kSignMask; } |
49 | 49 | |
50 | static unsigned EffectiveSignificandSize(int order) { | |
50 | static int EffectiveSignificandSize(int order) { | |
51 | 51 | if (order >= -1021) |
52 | 52 | return 53; |
53 | 53 | else if (order <= -1074) |
54 | 54 | return 0; |
55 | 55 | else |
56 | return static_cast<unsigned>(order) + 1074; | |
56 | return order + 1074; | |
57 | 57 | } |
58 | 58 | |
59 | 59 | private: |
0 | 0 | // Tencent is pleased to support the open source community by making RapidJSON available. |
1 | // | |
1 | // | |
2 | 2 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. |
3 | 3 | // |
4 | 4 | // Licensed under the MIT License (the "License"); you may not use this file except |
6 | 6 | // |
7 | 7 | // http://opensource.org/licenses/MIT |
8 | 8 | // |
9 | // Unless required by applicable law or agreed to in writing, software distributed | |
10 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR | |
11 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the | |
9 | // Unless required by applicable law or agreed to in writing, software distributed | |
10 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR | |
11 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the | |
12 | 12 | // specific language governing permissions and limitations under the License. |
13 | 13 | |
14 | 14 | #ifndef CEREAL_RAPIDJSON_ITOA_ |
36 | 36 | } |
37 | 37 | |
38 | 38 | inline char* u32toa(uint32_t value, char* buffer) { |
39 | CEREAL_RAPIDJSON_ASSERT(buffer != 0); | |
40 | ||
39 | 41 | const char* cDigitsLut = GetDigitsLut(); |
40 | 42 | |
41 | 43 | if (value < 10000) { |
42 | 44 | const uint32_t d1 = (value / 100) << 1; |
43 | 45 | const uint32_t d2 = (value % 100) << 1; |
44 | ||
46 | ||
45 | 47 | if (value >= 1000) |
46 | 48 | *buffer++ = cDigitsLut[d1]; |
47 | 49 | if (value >= 100) |
54 | 56 | // value = bbbbcccc |
55 | 57 | const uint32_t b = value / 10000; |
56 | 58 | const uint32_t c = value % 10000; |
57 | ||
59 | ||
58 | 60 | const uint32_t d1 = (b / 100) << 1; |
59 | 61 | const uint32_t d2 = (b % 100) << 1; |
60 | ||
62 | ||
61 | 63 | const uint32_t d3 = (c / 100) << 1; |
62 | 64 | const uint32_t d4 = (c % 100) << 1; |
63 | ||
65 | ||
64 | 66 | if (value >= 10000000) |
65 | 67 | *buffer++ = cDigitsLut[d1]; |
66 | 68 | if (value >= 1000000) |
68 | 70 | if (value >= 100000) |
69 | 71 | *buffer++ = cDigitsLut[d2]; |
70 | 72 | *buffer++ = cDigitsLut[d2 + 1]; |
71 | ||
73 | ||
72 | 74 | *buffer++ = cDigitsLut[d3]; |
73 | 75 | *buffer++ = cDigitsLut[d3 + 1]; |
74 | 76 | *buffer++ = cDigitsLut[d4]; |
76 | 78 | } |
77 | 79 | else { |
78 | 80 | // value = aabbbbcccc in decimal |
79 | ||
81 | ||
80 | 82 | const uint32_t a = value / 100000000; // 1 to 42 |
81 | 83 | value %= 100000000; |
82 | ||
84 | ||
83 | 85 | if (a >= 10) { |
84 | 86 | const unsigned i = a << 1; |
85 | 87 | *buffer++ = cDigitsLut[i]; |
90 | 92 | |
91 | 93 | const uint32_t b = value / 10000; // 0 to 9999 |
92 | 94 | const uint32_t c = value % 10000; // 0 to 9999 |
93 | ||
95 | ||
94 | 96 | const uint32_t d1 = (b / 100) << 1; |
95 | 97 | const uint32_t d2 = (b % 100) << 1; |
96 | ||
98 | ||
97 | 99 | const uint32_t d3 = (c / 100) << 1; |
98 | 100 | const uint32_t d4 = (c % 100) << 1; |
99 | ||
101 | ||
100 | 102 | *buffer++ = cDigitsLut[d1]; |
101 | 103 | *buffer++ = cDigitsLut[d1 + 1]; |
102 | 104 | *buffer++ = cDigitsLut[d2]; |
110 | 112 | } |
111 | 113 | |
112 | 114 | inline char* i32toa(int32_t value, char* buffer) { |
115 | CEREAL_RAPIDJSON_ASSERT(buffer != 0); | |
113 | 116 | uint32_t u = static_cast<uint32_t>(value); |
114 | 117 | if (value < 0) { |
115 | 118 | *buffer++ = '-'; |
120 | 123 | } |
121 | 124 | |
122 | 125 | inline char* u64toa(uint64_t value, char* buffer) { |
126 | CEREAL_RAPIDJSON_ASSERT(buffer != 0); | |
123 | 127 | const char* cDigitsLut = GetDigitsLut(); |
124 | 128 | const uint64_t kTen8 = 100000000; |
125 | 129 | const uint64_t kTen9 = kTen8 * 10; |
130 | 134 | const uint64_t kTen14 = kTen8 * 1000000; |
131 | 135 | const uint64_t kTen15 = kTen8 * 10000000; |
132 | 136 | const uint64_t kTen16 = kTen8 * kTen8; |
133 | ||
137 | ||
134 | 138 | if (value < kTen8) { |
135 | 139 | uint32_t v = static_cast<uint32_t>(value); |
136 | 140 | if (v < 10000) { |
137 | 141 | const uint32_t d1 = (v / 100) << 1; |
138 | 142 | const uint32_t d2 = (v % 100) << 1; |
139 | ||
143 | ||
140 | 144 | if (v >= 1000) |
141 | 145 | *buffer++ = cDigitsLut[d1]; |
142 | 146 | if (v >= 100) |
149 | 153 | // value = bbbbcccc |
150 | 154 | const uint32_t b = v / 10000; |
151 | 155 | const uint32_t c = v % 10000; |
152 | ||
156 | ||
153 | 157 | const uint32_t d1 = (b / 100) << 1; |
154 | 158 | const uint32_t d2 = (b % 100) << 1; |
155 | ||
159 | ||
156 | 160 | const uint32_t d3 = (c / 100) << 1; |
157 | 161 | const uint32_t d4 = (c % 100) << 1; |
158 | ||
162 | ||
159 | 163 | if (value >= 10000000) |
160 | 164 | *buffer++ = cDigitsLut[d1]; |
161 | 165 | if (value >= 1000000) |
163 | 167 | if (value >= 100000) |
164 | 168 | *buffer++ = cDigitsLut[d2]; |
165 | 169 | *buffer++ = cDigitsLut[d2 + 1]; |
166 | ||
170 | ||
167 | 171 | *buffer++ = cDigitsLut[d3]; |
168 | 172 | *buffer++ = cDigitsLut[d3 + 1]; |
169 | 173 | *buffer++ = cDigitsLut[d4]; |
173 | 177 | else if (value < kTen16) { |
174 | 178 | const uint32_t v0 = static_cast<uint32_t>(value / kTen8); |
175 | 179 | const uint32_t v1 = static_cast<uint32_t>(value % kTen8); |
176 | ||
180 | ||
177 | 181 | const uint32_t b0 = v0 / 10000; |
178 | 182 | const uint32_t c0 = v0 % 10000; |
179 | ||
183 | ||
180 | 184 | const uint32_t d1 = (b0 / 100) << 1; |
181 | 185 | const uint32_t d2 = (b0 % 100) << 1; |
182 | ||
186 | ||
183 | 187 | const uint32_t d3 = (c0 / 100) << 1; |
184 | 188 | const uint32_t d4 = (c0 % 100) << 1; |
185 | 189 | |
186 | 190 | const uint32_t b1 = v1 / 10000; |
187 | 191 | const uint32_t c1 = v1 % 10000; |
188 | ||
192 | ||
189 | 193 | const uint32_t d5 = (b1 / 100) << 1; |
190 | 194 | const uint32_t d6 = (b1 % 100) << 1; |
191 | ||
195 | ||
192 | 196 | const uint32_t d7 = (c1 / 100) << 1; |
193 | 197 | const uint32_t d8 = (c1 % 100) << 1; |
194 | 198 | |
206 | 210 | *buffer++ = cDigitsLut[d3 + 1]; |
207 | 211 | if (value >= kTen9) |
208 | 212 | *buffer++ = cDigitsLut[d4]; |
209 | if (value >= kTen8) | |
210 | *buffer++ = cDigitsLut[d4 + 1]; | |
211 | ||
213 | ||
214 | *buffer++ = cDigitsLut[d4 + 1]; | |
212 | 215 | *buffer++ = cDigitsLut[d5]; |
213 | 216 | *buffer++ = cDigitsLut[d5 + 1]; |
214 | 217 | *buffer++ = cDigitsLut[d6]; |
221 | 224 | else { |
222 | 225 | const uint32_t a = static_cast<uint32_t>(value / kTen16); // 1 to 1844 |
223 | 226 | value %= kTen16; |
224 | ||
227 | ||
225 | 228 | if (a < 10) |
226 | 229 | *buffer++ = static_cast<char>('0' + static_cast<char>(a)); |
227 | 230 | else if (a < 100) { |
231 | 234 | } |
232 | 235 | else if (a < 1000) { |
233 | 236 | *buffer++ = static_cast<char>('0' + static_cast<char>(a / 100)); |
234 | ||
237 | ||
235 | 238 | const uint32_t i = (a % 100) << 1; |
236 | 239 | *buffer++ = cDigitsLut[i]; |
237 | 240 | *buffer++ = cDigitsLut[i + 1]; |
244 | 247 | *buffer++ = cDigitsLut[j]; |
245 | 248 | *buffer++ = cDigitsLut[j + 1]; |
246 | 249 | } |
247 | ||
250 | ||
248 | 251 | const uint32_t v0 = static_cast<uint32_t>(value / kTen8); |
249 | 252 | const uint32_t v1 = static_cast<uint32_t>(value % kTen8); |
250 | ||
253 | ||
251 | 254 | const uint32_t b0 = v0 / 10000; |
252 | 255 | const uint32_t c0 = v0 % 10000; |
253 | ||
256 | ||
254 | 257 | const uint32_t d1 = (b0 / 100) << 1; |
255 | 258 | const uint32_t d2 = (b0 % 100) << 1; |
256 | ||
259 | ||
257 | 260 | const uint32_t d3 = (c0 / 100) << 1; |
258 | 261 | const uint32_t d4 = (c0 % 100) << 1; |
259 | ||
262 | ||
260 | 263 | const uint32_t b1 = v1 / 10000; |
261 | 264 | const uint32_t c1 = v1 % 10000; |
262 | ||
265 | ||
263 | 266 | const uint32_t d5 = (b1 / 100) << 1; |
264 | 267 | const uint32_t d6 = (b1 % 100) << 1; |
265 | ||
268 | ||
266 | 269 | const uint32_t d7 = (c1 / 100) << 1; |
267 | 270 | const uint32_t d8 = (c1 % 100) << 1; |
268 | ||
271 | ||
269 | 272 | *buffer++ = cDigitsLut[d1]; |
270 | 273 | *buffer++ = cDigitsLut[d1 + 1]; |
271 | 274 | *buffer++ = cDigitsLut[d2]; |
283 | 286 | *buffer++ = cDigitsLut[d8]; |
284 | 287 | *buffer++ = cDigitsLut[d8 + 1]; |
285 | 288 | } |
286 | ||
289 | ||
287 | 290 | return buffer; |
288 | 291 | } |
289 | 292 | |
290 | 293 | inline char* i64toa(int64_t value, char* buffer) { |
294 | CEREAL_RAPIDJSON_ASSERT(buffer != 0); | |
291 | 295 | uint64_t u = static_cast<uint64_t>(value); |
292 | 296 | if (value < 0) { |
293 | 297 | *buffer++ = '-'; |
20 | 20 | CEREAL_RAPIDJSON_DIAG_PUSH |
21 | 21 | CEREAL_RAPIDJSON_DIAG_OFF(effc++) |
22 | 22 | #endif |
23 | #if defined(_MSC_VER) | |
23 | ||
24 | #if defined(_MSC_VER) && !defined(__clang__) | |
24 | 25 | CEREAL_RAPIDJSON_DIAG_PUSH |
25 | 26 | CEREAL_RAPIDJSON_DIAG_OFF(6334) |
26 | 27 | #endif |
173 | 174 | CEREAL_RAPIDJSON_NAMESPACE_END |
174 | 175 | //@endcond |
175 | 176 | |
176 | #if defined(__GNUC__) || defined(_MSC_VER) | |
177 | #if defined(_MSC_VER) && !defined(__clang__) | |
178 | CEREAL_RAPIDJSON_DIAG_POP | |
179 | #endif | |
180 | ||
181 | #ifdef __GNUC__ | |
177 | 182 | CEREAL_RAPIDJSON_DIAG_POP |
178 | 183 | #endif |
179 | 184 |
23 | 23 | CEREAL_RAPIDJSON_DIAG_OFF(padded) |
24 | 24 | CEREAL_RAPIDJSON_DIAG_OFF(switch-enum) |
25 | 25 | CEREAL_RAPIDJSON_DIAG_OFF(implicit-fallthrough) |
26 | #elif defined(_MSC_VER) | |
27 | CEREAL_RAPIDJSON_DIAG_PUSH | |
28 | CEREAL_RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated | |
26 | 29 | #endif |
27 | 30 | |
28 | 31 | #ifdef __GNUC__ |
29 | 32 | CEREAL_RAPIDJSON_DIAG_PUSH |
30 | 33 | CEREAL_RAPIDJSON_DIAG_OFF(effc++) |
34 | #if __GNUC__ >= 7 | |
35 | CEREAL_RAPIDJSON_DIAG_OFF(implicit-fallthrough) | |
31 | 36 | #endif |
32 | ||
33 | #ifdef _MSC_VER | |
34 | CEREAL_RAPIDJSON_DIAG_PUSH | |
35 | CEREAL_RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated | |
36 | 37 | #endif |
37 | 38 | |
38 | 39 | #ifndef CEREAL_RAPIDJSON_REGEX_VERBOSE |
43 | 44 | namespace internal { |
44 | 45 | |
45 | 46 | /////////////////////////////////////////////////////////////////////////////// |
47 | // DecodedStream | |
48 | ||
49 | template <typename SourceStream, typename Encoding> | |
50 | class DecodedStream { | |
51 | public: | |
52 | DecodedStream(SourceStream& ss) : ss_(ss), codepoint_() { Decode(); } | |
53 | unsigned Peek() { return codepoint_; } | |
54 | unsigned Take() { | |
55 | unsigned c = codepoint_; | |
56 | if (c) // No further decoding when '\0' | |
57 | Decode(); | |
58 | return c; | |
59 | } | |
60 | ||
61 | private: | |
62 | void Decode() { | |
63 | if (!Encoding::Decode(ss_, &codepoint_)) | |
64 | codepoint_ = 0; | |
65 | } | |
66 | ||
67 | SourceStream& ss_; | |
68 | unsigned codepoint_; | |
69 | }; | |
70 | ||
71 | /////////////////////////////////////////////////////////////////////////////// | |
46 | 72 | // GenericRegex |
47 | 73 | |
48 | 74 | static const SizeType kRegexInvalidState = ~SizeType(0); //!< Represents an invalid index in GenericRegex::State::out, out1 |
49 | 75 | static const SizeType kRegexInvalidRange = ~SizeType(0); |
76 | ||
77 | template <typename Encoding, typename Allocator> | |
78 | class GenericRegexSearch; | |
50 | 79 | |
51 | 80 | //! Regular expression engine with subset of ECMAscript grammar. |
52 | 81 | /*! |
83 | 112 | template <typename Encoding, typename Allocator = CrtAllocator> |
84 | 113 | class GenericRegex { |
85 | 114 | public: |
115 | typedef Encoding EncodingType; | |
86 | 116 | typedef typename Encoding::Ch Ch; |
117 | template <typename, typename> friend class GenericRegexSearch; | |
87 | 118 | |
88 | 119 | GenericRegex(const Ch* source, Allocator* allocator = 0) : |
89 | states_(allocator, 256), ranges_(allocator, 256), root_(kRegexInvalidState), stateCount_(), rangeCount_(), | |
90 | stateSet_(), state0_(allocator, 0), state1_(allocator, 0), anchorBegin_(), anchorEnd_() | |
120 | ownAllocator_(allocator ? 0 : CEREAL_RAPIDJSON_NEW(Allocator)()), allocator_(allocator ? allocator : ownAllocator_), | |
121 | states_(allocator_, 256), ranges_(allocator_, 256), root_(kRegexInvalidState), stateCount_(), rangeCount_(), | |
122 | anchorBegin_(), anchorEnd_() | |
91 | 123 | { |
92 | 124 | GenericStringStream<Encoding> ss(source); |
93 | DecodedStream<GenericStringStream<Encoding> > ds(ss); | |
125 | DecodedStream<GenericStringStream<Encoding>, Encoding> ds(ss); | |
94 | 126 | Parse(ds); |
95 | 127 | } |
96 | 128 | |
97 | ~GenericRegex() { | |
98 | Allocator::Free(stateSet_); | |
129 | ~GenericRegex() | |
130 | { | |
131 | CEREAL_RAPIDJSON_DELETE(ownAllocator_); | |
99 | 132 | } |
100 | 133 | |
101 | 134 | bool IsValid() const { |
102 | 135 | return root_ != kRegexInvalidState; |
103 | } | |
104 | ||
105 | template <typename InputStream> | |
106 | bool Match(InputStream& is) const { | |
107 | return SearchWithAnchoring(is, true, true); | |
108 | } | |
109 | ||
110 | bool Match(const Ch* s) const { | |
111 | GenericStringStream<Encoding> is(s); | |
112 | return Match(is); | |
113 | } | |
114 | ||
115 | template <typename InputStream> | |
116 | bool Search(InputStream& is) const { | |
117 | return SearchWithAnchoring(is, anchorBegin_, anchorEnd_); | |
118 | } | |
119 | ||
120 | bool Search(const Ch* s) const { | |
121 | GenericStringStream<Encoding> is(s); | |
122 | return Search(is); | |
123 | 136 | } |
124 | 137 | |
125 | 138 | private: |
156 | 169 | SizeType minIndex; |
157 | 170 | }; |
158 | 171 | |
159 | template <typename SourceStream> | |
160 | class DecodedStream { | |
161 | public: | |
162 | DecodedStream(SourceStream& ss) : ss_(ss), codepoint_() { Decode(); } | |
163 | unsigned Peek() { return codepoint_; } | |
164 | unsigned Take() { | |
165 | unsigned c = codepoint_; | |
166 | if (c) // No further decoding when '\0' | |
167 | Decode(); | |
168 | return c; | |
169 | } | |
170 | ||
171 | private: | |
172 | void Decode() { | |
173 | if (!Encoding::Decode(ss_, &codepoint_)) | |
174 | codepoint_ = 0; | |
175 | } | |
176 | ||
177 | SourceStream& ss_; | |
178 | unsigned codepoint_; | |
179 | }; | |
180 | ||
181 | 172 | State& GetState(SizeType index) { |
182 | 173 | CEREAL_RAPIDJSON_ASSERT(index < stateCount_); |
183 | 174 | return states_.template Bottom<State>()[index]; |
199 | 190 | } |
200 | 191 | |
201 | 192 | template <typename InputStream> |
202 | void Parse(DecodedStream<InputStream>& ds) { | |
203 | Allocator allocator; | |
204 | Stack<Allocator> operandStack(&allocator, 256); // Frag | |
205 | Stack<Allocator> operatorStack(&allocator, 256); // Operator | |
206 | Stack<Allocator> atomCountStack(&allocator, 256); // unsigned (Atom per parenthesis) | |
193 | void Parse(DecodedStream<InputStream, Encoding>& ds) { | |
194 | Stack<Allocator> operandStack(allocator_, 256); // Frag | |
195 | Stack<Allocator> operatorStack(allocator_, 256); // Operator | |
196 | Stack<Allocator> atomCountStack(allocator_, 256); // unsigned (Atom per parenthesis) | |
207 | 197 | |
208 | 198 | *atomCountStack.template Push<unsigned>() = 0; |
209 | 199 | |
326 | 316 | printf("\n"); |
327 | 317 | #endif |
328 | 318 | } |
329 | ||
330 | // Preallocate buffer for SearchWithAnchoring() | |
331 | CEREAL_RAPIDJSON_ASSERT(stateSet_ == 0); | |
332 | if (stateCount_ > 0) { | |
333 | stateSet_ = static_cast<unsigned*>(states_.GetAllocator().Malloc(GetStateSetSize())); | |
334 | state0_.template Reserve<SizeType>(stateCount_); | |
335 | state1_.template Reserve<SizeType>(stateCount_); | |
336 | } | |
337 | 319 | } |
338 | 320 | |
339 | 321 | SizeType NewState(SizeType out, SizeType out1, unsigned codepoint) { |
412 | 394 | } |
413 | 395 | return false; |
414 | 396 | |
415 | default: | |
416 | CEREAL_RAPIDJSON_ASSERT(op == kOneOrMore); | |
397 | case kOneOrMore: | |
417 | 398 | if (operandStack.GetSize() >= sizeof(Frag)) { |
418 | 399 | Frag e = *operandStack.template Pop<Frag>(1); |
419 | 400 | SizeType s = NewState(kRegexInvalidState, e.start, 0); |
421 | 402 | *operandStack.template Push<Frag>() = Frag(e.start, s, e.minIndex); |
422 | 403 | return true; |
423 | 404 | } |
405 | return false; | |
406 | ||
407 | default: | |
408 | // syntax error (e.g. unclosed kLeftParenthesis) | |
424 | 409 | return false; |
425 | 410 | } |
426 | 411 | } |
482 | 467 | } |
483 | 468 | |
484 | 469 | template <typename InputStream> |
485 | bool ParseUnsigned(DecodedStream<InputStream>& ds, unsigned* u) { | |
470 | bool ParseUnsigned(DecodedStream<InputStream, Encoding>& ds, unsigned* u) { | |
486 | 471 | unsigned r = 0; |
487 | 472 | if (ds.Peek() < '0' || ds.Peek() > '9') |
488 | 473 | return false; |
496 | 481 | } |
497 | 482 | |
498 | 483 | template <typename InputStream> |
499 | bool ParseRange(DecodedStream<InputStream>& ds, SizeType* range) { | |
484 | bool ParseRange(DecodedStream<InputStream, Encoding>& ds, SizeType* range) { | |
500 | 485 | bool isBegin = true; |
501 | 486 | bool negate = false; |
502 | 487 | int step = 0; |
574 | 559 | } |
575 | 560 | |
576 | 561 | template <typename InputStream> |
577 | bool CharacterEscape(DecodedStream<InputStream>& ds, unsigned* escapedCodepoint) { | |
562 | bool CharacterEscape(DecodedStream<InputStream, Encoding>& ds, unsigned* escapedCodepoint) { | |
578 | 563 | unsigned codepoint; |
579 | 564 | switch (codepoint = ds.Take()) { |
580 | 565 | case '^': |
602 | 587 | } |
603 | 588 | } |
604 | 589 | |
590 | Allocator* ownAllocator_; | |
591 | Allocator* allocator_; | |
592 | Stack<Allocator> states_; | |
593 | Stack<Allocator> ranges_; | |
594 | SizeType root_; | |
595 | SizeType stateCount_; | |
596 | SizeType rangeCount_; | |
597 | ||
598 | static const unsigned kInfinityQuantifier = ~0u; | |
599 | ||
600 | // For SearchWithAnchoring() | |
601 | bool anchorBegin_; | |
602 | bool anchorEnd_; | |
603 | }; | |
604 | ||
605 | template <typename RegexType, typename Allocator = CrtAllocator> | |
606 | class GenericRegexSearch { | |
607 | public: | |
608 | typedef typename RegexType::EncodingType Encoding; | |
609 | typedef typename Encoding::Ch Ch; | |
610 | ||
611 | GenericRegexSearch(const RegexType& regex, Allocator* allocator = 0) : | |
612 | regex_(regex), allocator_(allocator), ownAllocator_(0), | |
613 | state0_(allocator, 0), state1_(allocator, 0), stateSet_() | |
614 | { | |
615 | CEREAL_RAPIDJSON_ASSERT(regex_.IsValid()); | |
616 | if (!allocator_) | |
617 | ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator)(); | |
618 | stateSet_ = static_cast<unsigned*>(allocator_->Malloc(GetStateSetSize())); | |
619 | state0_.template Reserve<SizeType>(regex_.stateCount_); | |
620 | state1_.template Reserve<SizeType>(regex_.stateCount_); | |
621 | } | |
622 | ||
623 | ~GenericRegexSearch() { | |
624 | Allocator::Free(stateSet_); | |
625 | CEREAL_RAPIDJSON_DELETE(ownAllocator_); | |
626 | } | |
627 | ||
605 | 628 | template <typename InputStream> |
606 | bool SearchWithAnchoring(InputStream& is, bool anchorBegin, bool anchorEnd) const { | |
607 | CEREAL_RAPIDJSON_ASSERT(IsValid()); | |
608 | DecodedStream<InputStream> ds(is); | |
629 | bool Match(InputStream& is) { | |
630 | return SearchWithAnchoring(is, true, true); | |
631 | } | |
632 | ||
633 | bool Match(const Ch* s) { | |
634 | GenericStringStream<Encoding> is(s); | |
635 | return Match(is); | |
636 | } | |
637 | ||
638 | template <typename InputStream> | |
639 | bool Search(InputStream& is) { | |
640 | return SearchWithAnchoring(is, regex_.anchorBegin_, regex_.anchorEnd_); | |
641 | } | |
642 | ||
643 | bool Search(const Ch* s) { | |
644 | GenericStringStream<Encoding> is(s); | |
645 | return Search(is); | |
646 | } | |
647 | ||
648 | private: | |
649 | typedef typename RegexType::State State; | |
650 | typedef typename RegexType::Range Range; | |
651 | ||
652 | template <typename InputStream> | |
653 | bool SearchWithAnchoring(InputStream& is, bool anchorBegin, bool anchorEnd) { | |
654 | DecodedStream<InputStream, Encoding> ds(is); | |
609 | 655 | |
610 | 656 | state0_.Clear(); |
611 | 657 | Stack<Allocator> *current = &state0_, *next = &state1_; |
612 | 658 | const size_t stateSetSize = GetStateSetSize(); |
613 | 659 | std::memset(stateSet_, 0, stateSetSize); |
614 | 660 | |
615 | bool matched = AddState(*current, root_); | |
661 | bool matched = AddState(*current, regex_.root_); | |
616 | 662 | unsigned codepoint; |
617 | 663 | while (!current->Empty() && (codepoint = ds.Take()) != 0) { |
618 | 664 | std::memset(stateSet_, 0, stateSetSize); |
619 | 665 | next->Clear(); |
620 | 666 | matched = false; |
621 | 667 | for (const SizeType* s = current->template Bottom<SizeType>(); s != current->template End<SizeType>(); ++s) { |
622 | const State& sr = GetState(*s); | |
668 | const State& sr = regex_.GetState(*s); | |
623 | 669 | if (sr.codepoint == codepoint || |
624 | sr.codepoint == kAnyCharacterClass || | |
625 | (sr.codepoint == kRangeCharacterClass && MatchRange(sr.rangeStart, codepoint))) | |
670 | sr.codepoint == RegexType::kAnyCharacterClass || | |
671 | (sr.codepoint == RegexType::kRangeCharacterClass && MatchRange(sr.rangeStart, codepoint))) | |
626 | 672 | { |
627 | 673 | matched = AddState(*next, sr.out) || matched; |
628 | 674 | if (!anchorEnd && matched) |
629 | 675 | return true; |
630 | 676 | } |
631 | 677 | if (!anchorBegin) |
632 | AddState(*next, root_); | |
678 | AddState(*next, regex_.root_); | |
633 | 679 | } |
634 | 680 | internal::Swap(current, next); |
635 | 681 | } |
638 | 684 | } |
639 | 685 | |
640 | 686 | size_t GetStateSetSize() const { |
641 | return (stateCount_ + 31) / 32 * 4; | |
687 | return (regex_.stateCount_ + 31) / 32 * 4; | |
642 | 688 | } |
643 | 689 | |
644 | 690 | // Return whether the added states is a match state |
645 | bool AddState(Stack<Allocator>& l, SizeType index) const { | |
691 | bool AddState(Stack<Allocator>& l, SizeType index) { | |
646 | 692 | CEREAL_RAPIDJSON_ASSERT(index != kRegexInvalidState); |
647 | 693 | |
648 | const State& s = GetState(index); | |
694 | const State& s = regex_.GetState(index); | |
649 | 695 | if (s.out1 != kRegexInvalidState) { // Split |
650 | 696 | bool matched = AddState(l, s.out); |
651 | 697 | return AddState(l, s.out1) || matched; |
652 | 698 | } |
653 | else if (!(stateSet_[index >> 5] & (1 << (index & 31)))) { | |
654 | stateSet_[index >> 5] |= (1 << (index & 31)); | |
699 | else if (!(stateSet_[index >> 5] & (1u << (index & 31)))) { | |
700 | stateSet_[index >> 5] |= (1u << (index & 31)); | |
655 | 701 | *l.template PushUnsafe<SizeType>() = index; |
656 | 702 | } |
657 | 703 | return s.out == kRegexInvalidState; // by using PushUnsafe() above, we can ensure s is not validated due to reallocation. |
658 | 704 | } |
659 | 705 | |
660 | 706 | bool MatchRange(SizeType rangeIndex, unsigned codepoint) const { |
661 | bool yes = (GetRange(rangeIndex).start & kRangeNegationFlag) == 0; | |
707 | bool yes = (regex_.GetRange(rangeIndex).start & RegexType::kRangeNegationFlag) == 0; | |
662 | 708 | while (rangeIndex != kRegexInvalidRange) { |
663 | const Range& r = GetRange(rangeIndex); | |
664 | if (codepoint >= (r.start & ~kRangeNegationFlag) && codepoint <= r.end) | |
709 | const Range& r = regex_.GetRange(rangeIndex); | |
710 | if (codepoint >= (r.start & ~RegexType::kRangeNegationFlag) && codepoint <= r.end) | |
665 | 711 | return yes; |
666 | 712 | rangeIndex = r.next; |
667 | 713 | } |
668 | 714 | return !yes; |
669 | 715 | } |
670 | 716 | |
671 | Stack<Allocator> states_; | |
672 | Stack<Allocator> ranges_; | |
673 | SizeType root_; | |
674 | SizeType stateCount_; | |
675 | SizeType rangeCount_; | |
676 | ||
677 | static const unsigned kInfinityQuantifier = ~0u; | |
678 | ||
679 | // For SearchWithAnchoring() | |
680 | uint32_t* stateSet_; // allocated by states_.GetAllocator() | |
681 | mutable Stack<Allocator> state0_; | |
682 | mutable Stack<Allocator> state1_; | |
683 | bool anchorBegin_; | |
684 | bool anchorEnd_; | |
717 | const RegexType& regex_; | |
718 | Allocator* allocator_; | |
719 | Allocator* ownAllocator_; | |
720 | Stack<Allocator> state0_; | |
721 | Stack<Allocator> state1_; | |
722 | uint32_t* stateSet_; | |
685 | 723 | }; |
686 | 724 | |
687 | 725 | typedef GenericRegex<UTF8<> > Regex; |
726 | typedef GenericRegexSearch<Regex> RegexSearch; | |
688 | 727 | |
689 | 728 | } // namespace internal |
690 | 729 | CEREAL_RAPIDJSON_NAMESPACE_END |
691 | 730 | |
692 | #ifdef __clang__ | |
731 | #ifdef __GNUC__ | |
693 | 732 | CEREAL_RAPIDJSON_DIAG_POP |
694 | 733 | #endif |
695 | 734 | |
696 | #ifdef _MSC_VER | |
735 | #if defined(__clang__) || defined(_MSC_VER) | |
697 | 736 | CEREAL_RAPIDJSON_DIAG_POP |
698 | 737 | #endif |
699 | 738 |
16 | 16 | |
17 | 17 | #include "../allocators.h" |
18 | 18 | #include "swap.h" |
19 | #include <cstddef> | |
19 | 20 | |
20 | 21 | #if defined(__clang__) |
21 | 22 | CEREAL_RAPIDJSON_DIAG_PUSH |
99 | 100 | void ShrinkToFit() { |
100 | 101 | if (Empty()) { |
101 | 102 | // If the stack is empty, completely deallocate the memory. |
102 | Allocator::Free(stack_); | |
103 | Allocator::Free(stack_); // NOLINT (+clang-analyzer-unix.Malloc) | |
103 | 104 | stack_ = 0; |
104 | 105 | stackTop_ = 0; |
105 | 106 | stackEnd_ = 0; |
113 | 114 | template<typename T> |
114 | 115 | CEREAL_RAPIDJSON_FORCEINLINE void Reserve(size_t count = 1) { |
115 | 116 | // Expand the stack if needed |
116 | if (CEREAL_RAPIDJSON_UNLIKELY(stackTop_ + sizeof(T) * count > stackEnd_)) | |
117 | if (CEREAL_RAPIDJSON_UNLIKELY(static_cast<std::ptrdiff_t>(sizeof(T) * count) > (stackEnd_ - stackTop_))) | |
117 | 118 | Expand<T>(count); |
118 | 119 | } |
119 | 120 | |
125 | 126 | |
126 | 127 | template<typename T> |
127 | 128 | CEREAL_RAPIDJSON_FORCEINLINE T* PushUnsafe(size_t count = 1) { |
128 | CEREAL_RAPIDJSON_ASSERT(stackTop_ + sizeof(T) * count <= stackEnd_); | |
129 | CEREAL_RAPIDJSON_ASSERT(stackTop_); | |
130 | CEREAL_RAPIDJSON_ASSERT(static_cast<std::ptrdiff_t>(sizeof(T) * count) <= (stackEnd_ - stackTop_)); | |
129 | 131 | T* ret = reinterpret_cast<T*>(stackTop_); |
130 | 132 | stackTop_ += sizeof(T) * count; |
131 | 133 | return ret; |
182 | 184 | size_t newCapacity; |
183 | 185 | if (stack_ == 0) { |
184 | 186 | if (!allocator_) |
185 | ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator()); | |
187 | ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator)(); | |
186 | 188 | newCapacity = initialCapacity_; |
187 | 189 | } else { |
188 | 190 | newCapacity = GetCapacity(); |
15 | 15 | #define CEREAL_RAPIDJSON_INTERNAL_STRFUNC_H_ |
16 | 16 | |
17 | 17 | #include "../stream.h" |
18 | #include <cwchar> | |
18 | 19 | |
19 | 20 | CEREAL_RAPIDJSON_NAMESPACE_BEGIN |
20 | 21 | namespace internal { |
27 | 28 | */ |
28 | 29 | template <typename Ch> |
29 | 30 | inline SizeType StrLen(const Ch* s) { |
31 | CEREAL_RAPIDJSON_ASSERT(s != 0); | |
30 | 32 | const Ch* p = s; |
31 | 33 | while (*p) ++p; |
32 | 34 | return SizeType(p - s); |
33 | 35 | } |
34 | 36 | |
37 | template <> | |
38 | inline SizeType StrLen(const char* s) { | |
39 | return SizeType(std::strlen(s)); | |
40 | } | |
41 | ||
42 | template <> | |
43 | inline SizeType StrLen(const wchar_t* s) { | |
44 | return SizeType(std::wcslen(s)); | |
45 | } | |
46 | ||
35 | 47 | //! Returns number of code points in a encoded string. |
36 | 48 | template<typename Encoding> |
37 | 49 | bool CountStringCodePoint(const typename Encoding::Ch* s, SizeType length, SizeType* outCount) { |
50 | CEREAL_RAPIDJSON_ASSERT(s != 0); | |
51 | CEREAL_RAPIDJSON_ASSERT(outCount != 0); | |
38 | 52 | GenericStringStream<Encoding> is(s); |
39 | 53 | const typename Encoding::Ch* end = s + length; |
40 | 54 | SizeType count = 0; |
18 | 18 | #include "biginteger.h" |
19 | 19 | #include "diyfp.h" |
20 | 20 | #include "pow10.h" |
21 | #include <climits> | |
22 | #include <limits> | |
21 | 23 | |
22 | 24 | CEREAL_RAPIDJSON_NAMESPACE_BEGIN |
23 | 25 | namespace internal { |
125 | 127 | } |
126 | 128 | |
127 | 129 | // Compute an approximation and see if it is within 1/2 ULP |
128 | inline bool StrtodDiyFp(const char* decimals, size_t length, size_t decimalPosition, int exp, double* result) { | |
130 | inline bool StrtodDiyFp(const char* decimals, int dLen, int dExp, double* result) { | |
129 | 131 | uint64_t significand = 0; |
130 | size_t i = 0; // 2^64 - 1 = 18446744073709551615, 1844674407370955161 = 0x1999999999999999 | |
131 | for (; i < length; i++) { | |
132 | int i = 0; // 2^64 - 1 = 18446744073709551615, 1844674407370955161 = 0x1999999999999999 | |
133 | for (; i < dLen; i++) { | |
132 | 134 | if (significand > CEREAL_RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) || |
133 | 135 | (significand == CEREAL_RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) && decimals[i] > '5')) |
134 | 136 | break; |
135 | 137 | significand = significand * 10u + static_cast<unsigned>(decimals[i] - '0'); |
136 | 138 | } |
137 | 139 | |
138 | if (i < length && decimals[i] >= '5') // Rounding | |
140 | if (i < dLen && decimals[i] >= '5') // Rounding | |
139 | 141 | significand++; |
140 | 142 | |
141 | size_t remaining = length - i; | |
142 | const unsigned kUlpShift = 3; | |
143 | const unsigned kUlp = 1 << kUlpShift; | |
143 | int remaining = dLen - i; | |
144 | const int kUlpShift = 3; | |
145 | const int kUlp = 1 << kUlpShift; | |
144 | 146 | int64_t error = (remaining == 0) ? 0 : kUlp / 2; |
145 | 147 | |
146 | 148 | DiyFp v(significand, 0); |
147 | 149 | v = v.Normalize(); |
148 | 150 | error <<= -v.e; |
149 | 151 | |
150 | const int dExp = static_cast<int>(decimalPosition) - static_cast<int>(i) + exp; | |
152 | dExp += remaining; | |
151 | 153 | |
152 | 154 | int actualExp; |
153 | 155 | DiyFp cachedPower = GetCachedPower10(dExp, &actualExp); |
154 | 156 | if (actualExp != dExp) { |
155 | 157 | static const DiyFp kPow10[] = { |
156 | DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0xa0000000, 00000000), -60), // 10^1 | |
157 | DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0xc8000000, 00000000), -57), // 10^2 | |
158 | DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0xfa000000, 00000000), -54), // 10^3 | |
159 | DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0x9c400000, 00000000), -50), // 10^4 | |
160 | DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0xc3500000, 00000000), -47), // 10^5 | |
161 | DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0xf4240000, 00000000), -44), // 10^6 | |
162 | DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0x98968000, 00000000), -40) // 10^7 | |
158 | DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0xa0000000, 0x00000000), -60), // 10^1 | |
159 | DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0xc8000000, 0x00000000), -57), // 10^2 | |
160 | DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0xfa000000, 0x00000000), -54), // 10^3 | |
161 | DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0x9c400000, 0x00000000), -50), // 10^4 | |
162 | DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0xc3500000, 0x00000000), -47), // 10^5 | |
163 | DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0xf4240000, 0x00000000), -44), // 10^6 | |
164 | DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0x98968000, 0x00000000), -40) // 10^7 | |
163 | 165 | }; |
164 | int adjustment = dExp - actualExp - 1; | |
165 | CEREAL_RAPIDJSON_ASSERT(adjustment >= 0 && adjustment < 7); | |
166 | v = v * kPow10[adjustment]; | |
167 | if (length + static_cast<unsigned>(adjustment)> 19u) // has more digits than decimal digits in 64-bit | |
166 | int adjustment = dExp - actualExp; | |
167 | CEREAL_RAPIDJSON_ASSERT(adjustment >= 1 && adjustment < 8); | |
168 | v = v * kPow10[adjustment - 1]; | |
169 | if (dLen + adjustment > 19) // has more digits than decimal digits in 64-bit | |
168 | 170 | error += kUlp / 2; |
169 | 171 | } |
170 | 172 | |
176 | 178 | v = v.Normalize(); |
177 | 179 | error <<= oldExp - v.e; |
178 | 180 | |
179 | const unsigned effectiveSignificandSize = Double::EffectiveSignificandSize(64 + v.e); | |
180 | unsigned precisionSize = 64 - effectiveSignificandSize; | |
181 | const int effectiveSignificandSize = Double::EffectiveSignificandSize(64 + v.e); | |
182 | int precisionSize = 64 - effectiveSignificandSize; | |
181 | 183 | if (precisionSize + kUlpShift >= 64) { |
182 | unsigned scaleExp = (precisionSize + kUlpShift) - 63; | |
184 | int scaleExp = (precisionSize + kUlpShift) - 63; | |
183 | 185 | v.f >>= scaleExp; |
184 | 186 | v.e += scaleExp; |
185 | error = (error >> scaleExp) + 1 + static_cast<int>(kUlp); | |
187 | error = (error >> scaleExp) + 1 + kUlp; | |
186 | 188 | precisionSize -= scaleExp; |
187 | 189 | } |
188 | 190 | |
189 | DiyFp rounded(v.f >> precisionSize, v.e + static_cast<int>(precisionSize)); | |
191 | DiyFp rounded(v.f >> precisionSize, v.e + precisionSize); | |
190 | 192 | const uint64_t precisionBits = (v.f & ((uint64_t(1) << precisionSize) - 1)) * kUlp; |
191 | 193 | const uint64_t halfWay = (uint64_t(1) << (precisionSize - 1)) * kUlp; |
192 | 194 | if (precisionBits >= halfWay + static_cast<unsigned>(error)) { |
202 | 204 | return halfWay - static_cast<unsigned>(error) >= precisionBits || precisionBits >= halfWay + static_cast<unsigned>(error); |
203 | 205 | } |
204 | 206 | |
205 | inline double StrtodBigInteger(double approx, const char* decimals, size_t length, size_t decimalPosition, int exp) { | |
206 | const BigInteger dInt(decimals, length); | |
207 | const int dExp = static_cast<int>(decimalPosition) - static_cast<int>(length) + exp; | |
207 | inline double StrtodBigInteger(double approx, const char* decimals, int dLen, int dExp) { | |
208 | CEREAL_RAPIDJSON_ASSERT(dLen >= 0); | |
209 | const BigInteger dInt(decimals, static_cast<unsigned>(dLen)); | |
208 | 210 | Double a(approx); |
209 | 211 | int cmp = CheckWithinHalfULP(a.Value(), dInt, dExp); |
210 | 212 | if (cmp < 0) |
224 | 226 | CEREAL_RAPIDJSON_ASSERT(d >= 0.0); |
225 | 227 | CEREAL_RAPIDJSON_ASSERT(length >= 1); |
226 | 228 | |
227 | double result; | |
229 | double result = 0.0; | |
228 | 230 | if (StrtodFast(d, p, &result)) |
229 | 231 | return result; |
230 | 232 | |
233 | CEREAL_RAPIDJSON_ASSERT(length <= INT_MAX); | |
234 | int dLen = static_cast<int>(length); | |
235 | ||
236 | CEREAL_RAPIDJSON_ASSERT(length >= decimalPosition); | |
237 | CEREAL_RAPIDJSON_ASSERT(length - decimalPosition <= INT_MAX); | |
238 | int dExpAdjust = static_cast<int>(length - decimalPosition); | |
239 | ||
240 | CEREAL_RAPIDJSON_ASSERT(exp >= INT_MIN + dExpAdjust); | |
241 | int dExp = exp - dExpAdjust; | |
242 | ||
243 | // Make sure length+dExp does not overflow | |
244 | CEREAL_RAPIDJSON_ASSERT(dExp <= INT_MAX - dLen); | |
245 | ||
231 | 246 | // Trim leading zeros |
232 | while (*decimals == '0' && length > 1) { | |
233 | length--; | |
247 | while (dLen > 0 && *decimals == '0') { | |
248 | dLen--; | |
234 | 249 | decimals++; |
235 | decimalPosition--; | |
236 | 250 | } |
237 | 251 | |
238 | 252 | // Trim trailing zeros |
239 | while (decimals[length - 1] == '0' && length > 1) { | |
240 | length--; | |
241 | decimalPosition--; | |
242 | exp++; | |
253 | while (dLen > 0 && decimals[dLen - 1] == '0') { | |
254 | dLen--; | |
255 | dExp++; | |
256 | } | |
257 | ||
258 | if (dLen == 0) { // Buffer only contains zeros. | |
259 | return 0.0; | |
243 | 260 | } |
244 | 261 | |
245 | 262 | // Trim right-most digits |
246 | const int kMaxDecimalDigit = 780; | |
247 | if (static_cast<int>(length) > kMaxDecimalDigit) { | |
248 | int delta = (static_cast<int>(length) - kMaxDecimalDigit); | |
249 | exp += delta; | |
250 | decimalPosition -= static_cast<unsigned>(delta); | |
251 | length = kMaxDecimalDigit; | |
252 | } | |
253 | ||
254 | // If too small, underflow to zero | |
255 | if (int(length) + exp < -324) | |
263 | const int kMaxDecimalDigit = 767 + 1; | |
264 | if (dLen > kMaxDecimalDigit) { | |
265 | dExp += dLen - kMaxDecimalDigit; | |
266 | dLen = kMaxDecimalDigit; | |
267 | } | |
268 | ||
269 | // If too small, underflow to zero. | |
270 | // Any x <= 10^-324 is interpreted as zero. | |
271 | if (dLen + dExp <= -324) | |
256 | 272 | return 0.0; |
257 | 273 | |
258 | if (StrtodDiyFp(decimals, length, decimalPosition, exp, &result)) | |
274 | // If too large, overflow to infinity. | |
275 | // Any x >= 10^309 is interpreted as +infinity. | |
276 | if (dLen + dExp > 309) | |
277 | return std::numeric_limits<double>::infinity(); | |
278 | ||
279 | if (StrtodDiyFp(decimals, dLen, dExp, &result)) | |
259 | 280 | return result; |
260 | 281 | |
261 | 282 | // Use approximation from StrtodDiyFp and make adjustment with BigInteger comparison |
262 | return StrtodBigInteger(result, decimals, length, decimalPosition, exp); | |
283 | return StrtodBigInteger(result, decimals, dLen, dExp); | |
263 | 284 | } |
264 | 285 | |
265 | 286 | } // namespace internal |
0 | 0 | // Tencent is pleased to support the open source community by making RapidJSON available. |
1 | // | |
1 | // | |
2 | 2 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. |
3 | 3 | // |
4 | 4 | // Licensed under the MIT License (the "License"); you may not use this file except |
6 | 6 | // |
7 | 7 | // http://opensource.org/licenses/MIT |
8 | 8 | // |
9 | // Unless required by applicable law or agreed to in writing, software distributed | |
10 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR | |
11 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the | |
9 | // Unless required by applicable law or agreed to in writing, software distributed | |
10 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR | |
11 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the | |
12 | 12 | // specific language governing permissions and limitations under the License. |
13 | 13 | |
14 | 14 | #ifndef CEREAL_RAPIDJSON_ISTREAMWRAPPER_H_ |
16 | 16 | |
17 | 17 | #include "stream.h" |
18 | 18 | #include <iosfwd> |
19 | #include <ios> | |
19 | 20 | |
20 | 21 | #ifdef __clang__ |
21 | 22 | CEREAL_RAPIDJSON_DIAG_PUSH |
22 | 23 | CEREAL_RAPIDJSON_DIAG_OFF(padded) |
23 | #endif | |
24 | ||
25 | #ifdef _MSC_VER | |
24 | #elif defined(_MSC_VER) | |
26 | 25 | CEREAL_RAPIDJSON_DIAG_PUSH |
27 | 26 | CEREAL_RAPIDJSON_DIAG_OFF(4351) // new behavior: elements of array 'array' will be default initialized |
28 | CEREAL_RAPIDJSON_DIAG_OFF(4127) // ignore assert(false) for triggering exception | |
29 | 27 | #endif |
30 | 28 | |
31 | 29 | CEREAL_RAPIDJSON_NAMESPACE_BEGIN |
45 | 43 | |
46 | 44 | \tparam StreamType Class derived from \c std::basic_istream. |
47 | 45 | */ |
48 | ||
46 | ||
49 | 47 | template <typename StreamType> |
50 | 48 | class BasicIStreamWrapper { |
51 | 49 | public: |
52 | 50 | typedef typename StreamType::char_type Ch; |
53 | BasicIStreamWrapper(StreamType& stream) : stream_(stream), count_(), peekBuffer_() {} | |
54 | 51 | |
55 | Ch Peek() const { | |
56 | typename StreamType::int_type c = stream_.peek(); | |
57 | return CEREAL_RAPIDJSON_LIKELY(c != StreamType::traits_type::eof()) ? static_cast<Ch>(c) : '\0'; | |
52 | //! Constructor. | |
53 | /*! | |
54 | \param stream stream opened for read. | |
55 | */ | |
56 | BasicIStreamWrapper(StreamType &stream) : stream_(stream), buffer_(peekBuffer_), bufferSize_(4), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) { | |
57 | Read(); | |
58 | 58 | } |
59 | 59 | |
60 | Ch Take() { | |
61 | typename StreamType::int_type c = stream_.get(); | |
62 | if (CEREAL_RAPIDJSON_LIKELY(c != StreamType::traits_type::eof())) { | |
63 | count_++; | |
64 | return static_cast<Ch>(c); | |
65 | } | |
66 | else | |
67 | return '\0'; | |
60 | //! Constructor. | |
61 | /*! | |
62 | \param stream stream opened for read. | |
63 | \param buffer user-supplied buffer. | |
64 | \param bufferSize size of buffer in bytes. Must >=4 bytes. | |
65 | */ | |
66 | BasicIStreamWrapper(StreamType &stream, char* buffer, size_t bufferSize) : stream_(stream), buffer_(buffer), bufferSize_(bufferSize), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) { | |
67 | CEREAL_RAPIDJSON_ASSERT(bufferSize >= 4); | |
68 | Read(); | |
68 | 69 | } |
69 | 70 | |
70 | // tellg() may return -1 when failed. So we count by ourself. | |
71 | size_t Tell() const { return count_; } | |
71 | Ch Peek() const { return *current_; } | |
72 | Ch Take() { Ch c = *current_; Read(); return c; } | |
73 | size_t Tell() const { return count_ + static_cast<size_t>(current_ - buffer_); } | |
72 | 74 | |
75 | // Not implemented | |
76 | void Put(Ch) { CEREAL_RAPIDJSON_ASSERT(false); } | |
77 | void Flush() { CEREAL_RAPIDJSON_ASSERT(false); } | |
73 | 78 | Ch* PutBegin() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } |
74 | void Put(Ch) { CEREAL_RAPIDJSON_ASSERT(false); } | |
75 | void Flush() { CEREAL_RAPIDJSON_ASSERT(false); } | |
76 | 79 | size_t PutEnd(Ch*) { CEREAL_RAPIDJSON_ASSERT(false); return 0; } |
77 | 80 | |
78 | 81 | // For encoding detection only. |
79 | 82 | const Ch* Peek4() const { |
80 | CEREAL_RAPIDJSON_ASSERT(sizeof(Ch) == 1); // Only usable for byte stream. | |
81 | int i; | |
82 | bool hasError = false; | |
83 | for (i = 0; i < 4; ++i) { | |
84 | typename StreamType::int_type c = stream_.get(); | |
85 | if (c == StreamType::traits_type::eof()) { | |
86 | hasError = true; | |
87 | stream_.clear(); | |
88 | break; | |
89 | } | |
90 | peekBuffer_[i] = static_cast<Ch>(c); | |
91 | } | |
92 | for (--i; i >= 0; --i) | |
93 | stream_.putback(peekBuffer_[i]); | |
94 | return !hasError ? peekBuffer_ : 0; | |
83 | return (current_ + 4 - !eof_ <= bufferLast_) ? current_ : 0; | |
95 | 84 | } |
96 | 85 | |
97 | 86 | private: |
87 | BasicIStreamWrapper(); | |
98 | 88 | BasicIStreamWrapper(const BasicIStreamWrapper&); |
99 | 89 | BasicIStreamWrapper& operator=(const BasicIStreamWrapper&); |
100 | 90 | |
101 | StreamType& stream_; | |
102 | size_t count_; //!< Number of characters read. Note: | |
103 | mutable Ch peekBuffer_[4]; | |
91 | void Read() { | |
92 | if (current_ < bufferLast_) | |
93 | ++current_; | |
94 | else if (!eof_) { | |
95 | count_ += readCount_; | |
96 | readCount_ = bufferSize_; | |
97 | bufferLast_ = buffer_ + readCount_ - 1; | |
98 | current_ = buffer_; | |
99 | ||
100 | if (!stream_.read(buffer_, static_cast<std::streamsize>(bufferSize_))) { | |
101 | readCount_ = static_cast<size_t>(stream_.gcount()); | |
102 | *(bufferLast_ = buffer_ + readCount_) = '\0'; | |
103 | eof_ = true; | |
104 | } | |
105 | } | |
106 | } | |
107 | ||
108 | StreamType &stream_; | |
109 | Ch peekBuffer_[4], *buffer_; | |
110 | size_t bufferSize_; | |
111 | Ch *bufferLast_; | |
112 | Ch *current_; | |
113 | size_t readCount_; | |
114 | size_t count_; //!< Number of characters read | |
115 | bool eof_; | |
104 | 116 | }; |
105 | 117 | |
106 | 118 | typedef BasicIStreamWrapper<std::istream> IStreamWrapper; |
0 | 0 | // Tencent is pleased to support the open source community by making RapidJSON available. |
1 | // | |
1 | // | |
2 | 2 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. |
3 | 3 | // |
4 | 4 | // Licensed under the MIT License (the "License"); you may not use this file except |
6 | 6 | // |
7 | 7 | // http://opensource.org/licenses/MIT |
8 | 8 | // |
9 | // Unless required by applicable law or agreed to in writing, software distributed | |
10 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR | |
11 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the | |
9 | // Unless required by applicable law or agreed to in writing, software distributed | |
10 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR | |
11 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the | |
12 | 12 | // specific language governing permissions and limitations under the License. |
13 | 13 | |
14 | 14 | #ifndef CEREAL_RAPIDJSON_MEMORYSTREAM_H_ |
20 | 20 | CEREAL_RAPIDJSON_DIAG_PUSH |
21 | 21 | CEREAL_RAPIDJSON_DIAG_OFF(unreachable-code) |
22 | 22 | CEREAL_RAPIDJSON_DIAG_OFF(missing-noreturn) |
23 | #endif | |
24 | ||
25 | #ifdef _MSC_VER | |
26 | CEREAL_RAPIDJSON_DIAG_PUSH | |
27 | CEREAL_RAPIDJSON_DIAG_OFF( 4127 ) // ignore assert(false) for triggering exception | |
28 | 23 | #endif |
29 | 24 | |
30 | 25 | CEREAL_RAPIDJSON_NAMESPACE_BEGIN |
68 | 63 | |
69 | 64 | CEREAL_RAPIDJSON_NAMESPACE_END |
70 | 65 | |
71 | #if defined(__clang__) || defined(_MSC_VER) | |
66 | #ifdef __clang__ | |
72 | 67 | CEREAL_RAPIDJSON_DIAG_POP |
73 | 68 | #endif |
74 | 69 |
20 | 20 | #ifdef __clang__ |
21 | 21 | CEREAL_RAPIDJSON_DIAG_PUSH |
22 | 22 | CEREAL_RAPIDJSON_DIAG_OFF(switch-enum) |
23 | #endif | |
24 | ||
25 | #ifdef _MSC_VER | |
23 | #elif defined(_MSC_VER) | |
26 | 24 | CEREAL_RAPIDJSON_DIAG_PUSH |
27 | 25 | CEREAL_RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated |
28 | 26 | #endif |
164 | 162 | GenericPointer(const Token* tokens, size_t tokenCount) : allocator_(), ownAllocator_(), nameBuffer_(), tokens_(const_cast<Token*>(tokens)), tokenCount_(tokenCount), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {} |
165 | 163 | |
166 | 164 | //! Copy constructor. |
167 | GenericPointer(const GenericPointer& rhs, Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { | |
165 | GenericPointer(const GenericPointer& rhs) : allocator_(rhs.allocator_), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { | |
166 | *this = rhs; | |
167 | } | |
168 | ||
169 | //! Copy constructor. | |
170 | GenericPointer(const GenericPointer& rhs, Allocator* allocator) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { | |
168 | 171 | *this = rhs; |
169 | 172 | } |
170 | 173 | |
195 | 198 | } |
196 | 199 | return *this; |
197 | 200 | } |
201 | ||
202 | //! Swap the content of this pointer with an other. | |
203 | /*! | |
204 | \param other The pointer to swap with. | |
205 | \note Constant complexity. | |
206 | */ | |
207 | GenericPointer& Swap(GenericPointer& other) CEREAL_RAPIDJSON_NOEXCEPT { | |
208 | internal::Swap(allocator_, other.allocator_); | |
209 | internal::Swap(ownAllocator_, other.ownAllocator_); | |
210 | internal::Swap(nameBuffer_, other.nameBuffer_); | |
211 | internal::Swap(tokens_, other.tokens_); | |
212 | internal::Swap(tokenCount_, other.tokenCount_); | |
213 | internal::Swap(parseErrorOffset_, other.parseErrorOffset_); | |
214 | internal::Swap(parseErrorCode_, other.parseErrorCode_); | |
215 | return *this; | |
216 | } | |
217 | ||
218 | //! free-standing swap function helper | |
219 | /*! | |
220 | Helper function to enable support for common swap implementation pattern based on \c std::swap: | |
221 | \code | |
222 | void swap(MyClass& a, MyClass& b) { | |
223 | using std::swap; | |
224 | swap(a.pointer, b.pointer); | |
225 | // ... | |
226 | } | |
227 | \endcode | |
228 | \see Swap() | |
229 | */ | |
230 | friend inline void swap(GenericPointer& a, GenericPointer& b) CEREAL_RAPIDJSON_NOEXCEPT { a.Swap(b); } | |
198 | 231 | |
199 | 232 | //@} |
200 | 233 | |
239 | 272 | template <typename T> |
240 | 273 | CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr<internal::IsSame<typename internal::RemoveConst<T>::Type, Ch> >), (GenericPointer)) |
241 | 274 | Append(T* name, Allocator* allocator = 0) const { |
242 | return Append(name, StrLen(name), allocator); | |
275 | return Append(name, internal::StrLen(name), allocator); | |
243 | 276 | } |
244 | 277 | |
245 | 278 | #if CEREAL_RAPIDJSON_HAS_STDSTRING |
273 | 306 | else { |
274 | 307 | Ch name[21]; |
275 | 308 | for (size_t i = 0; i <= length; i++) |
276 | name[i] = buffer[i]; | |
309 | name[i] = static_cast<Ch>(buffer[i]); | |
277 | 310 | Token token = { name, length, index }; |
278 | 311 | return Append(token, allocator); |
279 | 312 | } |
351 | 384 | \note When any pointers are invalid, always returns true. |
352 | 385 | */ |
353 | 386 | bool operator!=(const GenericPointer& rhs) const { return !(*this == rhs); } |
387 | ||
388 | //! Less than operator. | |
389 | /*! | |
390 | \note Invalid pointers are always greater than valid ones. | |
391 | */ | |
392 | bool operator<(const GenericPointer& rhs) const { | |
393 | if (!IsValid()) | |
394 | return false; | |
395 | if (!rhs.IsValid()) | |
396 | return true; | |
397 | ||
398 | if (tokenCount_ != rhs.tokenCount_) | |
399 | return tokenCount_ < rhs.tokenCount_; | |
400 | ||
401 | for (size_t i = 0; i < tokenCount_; i++) { | |
402 | if (tokens_[i].index != rhs.tokens_[i].index) | |
403 | return tokens_[i].index < rhs.tokens_[i].index; | |
404 | ||
405 | if (tokens_[i].length != rhs.tokens_[i].length) | |
406 | return tokens_[i].length < rhs.tokens_[i].length; | |
407 | ||
408 | if (int cmp = std::memcmp(tokens_[i].name, rhs.tokens_[i].name, sizeof(Ch) * tokens_[i].length)) | |
409 | return cmp < 0; | |
410 | } | |
411 | ||
412 | return false; | |
413 | } | |
354 | 414 | |
355 | 415 | //@} |
356 | 416 | |
531 | 591 | */ |
532 | 592 | ValueType& GetWithDefault(ValueType& root, const ValueType& defaultValue, typename ValueType::AllocatorType& allocator) const { |
533 | 593 | bool alreadyExist; |
534 | Value& v = Create(root, allocator, &alreadyExist); | |
594 | ValueType& v = Create(root, allocator, &alreadyExist); | |
535 | 595 | return alreadyExist ? v : v.CopyFrom(defaultValue, allocator); |
536 | 596 | } |
537 | 597 | |
538 | 598 | //! Query a value in a subtree with default null-terminated string. |
539 | 599 | ValueType& GetWithDefault(ValueType& root, const Ch* defaultValue, typename ValueType::AllocatorType& allocator) const { |
540 | 600 | bool alreadyExist; |
541 | Value& v = Create(root, allocator, &alreadyExist); | |
601 | ValueType& v = Create(root, allocator, &alreadyExist); | |
542 | 602 | return alreadyExist ? v : v.SetString(defaultValue, allocator); |
543 | 603 | } |
544 | 604 | |
546 | 606 | //! Query a value in a subtree with default std::basic_string. |
547 | 607 | ValueType& GetWithDefault(ValueType& root, const std::basic_string<Ch>& defaultValue, typename ValueType::AllocatorType& allocator) const { |
548 | 608 | bool alreadyExist; |
549 | Value& v = Create(root, allocator, &alreadyExist); | |
609 | ValueType& v = Create(root, allocator, &alreadyExist); | |
550 | 610 | return alreadyExist ? v : v.SetString(defaultValue, allocator); |
551 | 611 | } |
552 | 612 | #endif |
757 | 817 | */ |
758 | 818 | Ch* CopyFromRaw(const GenericPointer& rhs, size_t extraToken = 0, size_t extraNameBufferSize = 0) { |
759 | 819 | if (!allocator_) // allocator is independently owned. |
760 | ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator()); | |
820 | ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator)(); | |
761 | 821 | |
762 | 822 | size_t nameBufferSize = rhs.tokenCount_; // null terminators for tokens |
763 | 823 | for (Token *t = rhs.tokens_; t != rhs.tokens_ + rhs.tokenCount_; ++t) |
805 | 865 | |
806 | 866 | // Create own allocator if user did not supply. |
807 | 867 | if (!allocator_) |
808 | ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator()); | |
868 | ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator)(); | |
809 | 869 | |
810 | 870 | // Count number of '/' as tokenCount |
811 | 871 | tokenCount_ = 0; |
1028 | 1088 | unsigned char u = static_cast<unsigned char>(c); |
1029 | 1089 | static const char hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; |
1030 | 1090 | os_.Put('%'); |
1031 | os_.Put(hexDigits[u >> 4]); | |
1032 | os_.Put(hexDigits[u & 15]); | |
1091 | os_.Put(static_cast<typename OutputStream::Ch>(hexDigits[u >> 4])); | |
1092 | os_.Put(static_cast<typename OutputStream::Ch>(hexDigits[u & 15])); | |
1033 | 1093 | } |
1034 | 1094 | private: |
1035 | 1095 | OutputStream& os_; |
1346 | 1406 | |
1347 | 1407 | CEREAL_RAPIDJSON_NAMESPACE_END |
1348 | 1408 | |
1349 | #ifdef __clang__ | |
1409 | #if defined(__clang__) || defined(_MSC_VER) | |
1350 | 1410 | CEREAL_RAPIDJSON_DIAG_POP |
1351 | 1411 | #endif |
1352 | 1412 | |
1353 | #ifdef _MSC_VER | |
1354 | CEREAL_RAPIDJSON_DIAG_POP | |
1355 | #endif | |
1356 | ||
1357 | 1413 | #endif // CEREAL_RAPIDJSON_POINTER_H_ |
21 | 21 | CEREAL_RAPIDJSON_DIAG_OFF(effc++) |
22 | 22 | #endif |
23 | 23 | |
24 | #if defined(__clang__) | |
25 | CEREAL_RAPIDJSON_DIAG_PUSH | |
26 | CEREAL_RAPIDJSON_DIAG_OFF(c++98-compat) | |
27 | #endif | |
28 | ||
24 | 29 | CEREAL_RAPIDJSON_NAMESPACE_BEGIN |
25 | 30 | |
26 | 31 | //! Combination of PrettyWriter format flags. |
33 | 38 | |
34 | 39 | //! Writer with indentation and spacing. |
35 | 40 | /*! |
36 | \tparam OutputStream Type of ouptut os. | |
41 | \tparam OutputStream Type of output os. | |
37 | 42 | \tparam SourceEncoding Encoding of source string. |
38 | 43 | \tparam TargetEncoding Encoding of output stream. |
39 | 44 | \tparam StackAllocator Type of allocator for allocating memory of stack. |
41 | 46 | template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename StackAllocator = CrtAllocator, unsigned writeFlags = kWriteDefaultFlags> |
42 | 47 | class PrettyWriter : public Writer<OutputStream, SourceEncoding, TargetEncoding, StackAllocator, writeFlags> { |
43 | 48 | public: |
44 | typedef Writer<OutputStream, SourceEncoding, TargetEncoding, StackAllocator> Base; | |
49 | typedef Writer<OutputStream, SourceEncoding, TargetEncoding, StackAllocator, writeFlags> Base; | |
45 | 50 | typedef typename Base::Ch Ch; |
46 | 51 | |
47 | 52 | //! Constructor |
55 | 60 | |
56 | 61 | explicit PrettyWriter(StackAllocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) : |
57 | 62 | Base(allocator, levelDepth), indentChar_(' '), indentCharCount_(4) {} |
63 | ||
64 | #if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS | |
65 | PrettyWriter(PrettyWriter&& rhs) : | |
66 | Base(std::forward<PrettyWriter>(rhs)), indentChar_(rhs.indentChar_), indentCharCount_(rhs.indentCharCount_), formatOptions_(rhs.formatOptions_) {} | |
67 | #endif | |
58 | 68 | |
59 | 69 | //! Set custom indentation. |
60 | 70 | /*! \param indentChar Character for indentation. Must be whitespace character (' ', '\\t', '\\n', '\\r'). |
81 | 91 | */ |
82 | 92 | //@{ |
83 | 93 | |
84 | bool Null() { PrettyPrefix(kNullType); return Base::WriteNull(); } | |
85 | bool Bool(bool b) { PrettyPrefix(b ? kTrueType : kFalseType); return Base::WriteBool(b); } | |
86 | bool Int(int i) { PrettyPrefix(kNumberType); return Base::WriteInt(i); } | |
87 | bool Uint(unsigned u) { PrettyPrefix(kNumberType); return Base::WriteUint(u); } | |
88 | bool Int64(int64_t i64) { PrettyPrefix(kNumberType); return Base::WriteInt64(i64); } | |
89 | bool Uint64(uint64_t u64) { PrettyPrefix(kNumberType); return Base::WriteUint64(u64); } | |
90 | bool Double(double d) { PrettyPrefix(kNumberType); return Base::WriteDouble(d); } | |
94 | bool Null() { PrettyPrefix(kNullType); return Base::EndValue(Base::WriteNull()); } | |
95 | bool Bool(bool b) { PrettyPrefix(b ? kTrueType : kFalseType); return Base::EndValue(Base::WriteBool(b)); } | |
96 | bool Int(int i) { PrettyPrefix(kNumberType); return Base::EndValue(Base::WriteInt(i)); } | |
97 | bool Uint(unsigned u) { PrettyPrefix(kNumberType); return Base::EndValue(Base::WriteUint(u)); } | |
98 | bool Int64(int64_t i64) { PrettyPrefix(kNumberType); return Base::EndValue(Base::WriteInt64(i64)); } | |
99 | bool Uint64(uint64_t u64) { PrettyPrefix(kNumberType); return Base::EndValue(Base::WriteUint64(u64)); } | |
100 | bool Double(double d) { PrettyPrefix(kNumberType); return Base::EndValue(Base::WriteDouble(d)); } | |
91 | 101 | |
92 | 102 | bool RawNumber(const Ch* str, SizeType length, bool copy = false) { |
103 | CEREAL_RAPIDJSON_ASSERT(str != 0); | |
93 | 104 | (void)copy; |
94 | 105 | PrettyPrefix(kNumberType); |
95 | return Base::WriteString(str, length); | |
106 | return Base::EndValue(Base::WriteString(str, length)); | |
96 | 107 | } |
97 | 108 | |
98 | 109 | bool String(const Ch* str, SizeType length, bool copy = false) { |
110 | CEREAL_RAPIDJSON_ASSERT(str != 0); | |
99 | 111 | (void)copy; |
100 | 112 | PrettyPrefix(kStringType); |
101 | return Base::WriteString(str, length); | |
113 | return Base::EndValue(Base::WriteString(str, length)); | |
102 | 114 | } |
103 | 115 | |
104 | 116 | #if CEREAL_RAPIDJSON_HAS_STDSTRING |
123 | 135 | |
124 | 136 | bool EndObject(SizeType memberCount = 0) { |
125 | 137 | (void)memberCount; |
126 | CEREAL_RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level)); | |
127 | CEREAL_RAPIDJSON_ASSERT(!Base::level_stack_.template Top<typename Base::Level>()->inArray); | |
138 | CEREAL_RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level)); // not inside an Object | |
139 | CEREAL_RAPIDJSON_ASSERT(!Base::level_stack_.template Top<typename Base::Level>()->inArray); // currently inside an Array, not Object | |
140 | CEREAL_RAPIDJSON_ASSERT(0 == Base::level_stack_.template Top<typename Base::Level>()->valueCount % 2); // Object has a Key without a Value | |
141 | ||
128 | 142 | bool empty = Base::level_stack_.template Pop<typename Base::Level>(1)->valueCount == 0; |
129 | 143 | |
130 | 144 | if (!empty) { |
131 | 145 | Base::os_->Put('\n'); |
132 | 146 | WriteIndent(); |
133 | 147 | } |
134 | bool ret = Base::WriteEndObject(); | |
148 | bool ret = Base::EndValue(Base::WriteEndObject()); | |
135 | 149 | (void)ret; |
136 | 150 | CEREAL_RAPIDJSON_ASSERT(ret == true); |
137 | 151 | if (Base::level_stack_.Empty()) // end of json text |
138 | Base::os_->Flush(); | |
152 | Base::Flush(); | |
139 | 153 | return true; |
140 | 154 | } |
141 | 155 | |
155 | 169 | Base::os_->Put('\n'); |
156 | 170 | WriteIndent(); |
157 | 171 | } |
158 | bool ret = Base::WriteEndArray(); | |
172 | bool ret = Base::EndValue(Base::WriteEndArray()); | |
159 | 173 | (void)ret; |
160 | 174 | CEREAL_RAPIDJSON_ASSERT(ret == true); |
161 | 175 | if (Base::level_stack_.Empty()) // end of json text |
162 | Base::os_->Flush(); | |
176 | Base::Flush(); | |
163 | 177 | return true; |
164 | 178 | } |
165 | 179 | |
183 | 197 | \param type Type of the root of json. |
184 | 198 | \note When using PrettyWriter::RawValue(), the result json may not be indented correctly. |
185 | 199 | */ |
186 | bool RawValue(const Ch* json, size_t length, Type type) { PrettyPrefix(type); return Base::WriteRawValue(json, length); } | |
200 | bool RawValue(const Ch* json, size_t length, Type type) { | |
201 | CEREAL_RAPIDJSON_ASSERT(json != 0); | |
202 | PrettyPrefix(type); | |
203 | return Base::EndValue(Base::WriteRawValue(json, length)); | |
204 | } | |
187 | 205 | |
188 | 206 | protected: |
189 | 207 | void PrettyPrefix(Type type) { |
232 | 250 | |
233 | 251 | void WriteIndent() { |
234 | 252 | size_t count = (Base::level_stack_.GetSize() / sizeof(typename Base::Level)) * indentCharCount_; |
235 | PutN(*Base::os_, static_cast<typename TargetEncoding::Ch>(indentChar_), count); | |
253 | PutN(*Base::os_, static_cast<typename OutputStream::Ch>(indentChar_), count); | |
236 | 254 | } |
237 | 255 | |
238 | 256 | Ch indentChar_; |
247 | 265 | |
248 | 266 | CEREAL_RAPIDJSON_NAMESPACE_END |
249 | 267 | |
268 | #if defined(__clang__) | |
269 | CEREAL_RAPIDJSON_DIAG_POP | |
270 | #endif | |
271 | ||
250 | 272 | #ifdef __GNUC__ |
251 | 273 | CEREAL_RAPIDJSON_DIAG_POP |
252 | 274 | #endif |
25 | 25 | |
26 | 26 | Some RapidJSON features are configurable to adapt the library to a wide |
27 | 27 | variety of platforms, environments and usage scenarios. Most of the |
28 | features can be configured in terms of overriden or predefined | |
28 | features can be configured in terms of overridden or predefined | |
29 | 29 | preprocessor macros at compile-time. |
30 | 30 | |
31 | 31 | Some additional customization is available in the \ref CEREAL_RAPIDJSON_ERRORS APIs. |
48 | 48 | // token stringification |
49 | 49 | #define CEREAL_RAPIDJSON_STRINGIFY(x) CEREAL_RAPIDJSON_DO_STRINGIFY(x) |
50 | 50 | #define CEREAL_RAPIDJSON_DO_STRINGIFY(x) #x |
51 | ||
52 | // token concatenation | |
53 | #define CEREAL_RAPIDJSON_JOIN(X, Y) CEREAL_RAPIDJSON_DO_JOIN(X, Y) | |
54 | #define CEREAL_RAPIDJSON_DO_JOIN(X, Y) CEREAL_RAPIDJSON_DO_JOIN2(X, Y) | |
55 | #define CEREAL_RAPIDJSON_DO_JOIN2(X, Y) X##Y | |
51 | 56 | //!@endcond |
52 | 57 | |
53 | 58 | /*! \def CEREAL_RAPIDJSON_MAJOR_VERSION |
67 | 72 | \brief Version of RapidJSON in "<major>.<minor>.<patch>" string format. |
68 | 73 | */ |
69 | 74 | #define CEREAL_RAPIDJSON_MAJOR_VERSION 1 |
70 | #define CEREAL_RAPIDJSON_MINOR_VERSION 0 | |
71 | #define CEREAL_RAPIDJSON_PATCH_VERSION 2 | |
75 | #define CEREAL_RAPIDJSON_MINOR_VERSION 1 | |
76 | #define CEREAL_RAPIDJSON_PATCH_VERSION 0 | |
72 | 77 | #define CEREAL_RAPIDJSON_VERSION_STRING \ |
73 | 78 | CEREAL_RAPIDJSON_STRINGIFY(CEREAL_RAPIDJSON_MAJOR_VERSION.CEREAL_RAPIDJSON_MINOR_VERSION.CEREAL_RAPIDJSON_PATCH_VERSION) |
74 | 79 | |
213 | 218 | # elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ |
214 | 219 | # define CEREAL_RAPIDJSON_ENDIAN CEREAL_RAPIDJSON_BIGENDIAN |
215 | 220 | # else |
216 | # error Unknown machine endianess detected. User needs to define CEREAL_RAPIDJSON_ENDIAN. | |
221 | # error Unknown machine endianness detected. User needs to define CEREAL_RAPIDJSON_ENDIAN. | |
217 | 222 | # endif // __BYTE_ORDER__ |
218 | 223 | // Detect with GLIBC's endian.h |
219 | 224 | # elif defined(__GLIBC__) |
223 | 228 | # elif (__BYTE_ORDER == __BIG_ENDIAN) |
224 | 229 | # define CEREAL_RAPIDJSON_ENDIAN CEREAL_RAPIDJSON_BIGENDIAN |
225 | 230 | # else |
226 | # error Unknown machine endianess detected. User needs to define CEREAL_RAPIDJSON_ENDIAN. | |
231 | # error Unknown machine endianness detected. User needs to define CEREAL_RAPIDJSON_ENDIAN. | |
227 | 232 | # endif // __GLIBC__ |
228 | 233 | // Detect with _LITTLE_ENDIAN and _BIG_ENDIAN macro |
229 | 234 | # elif defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN) |
235 | 240 | # define CEREAL_RAPIDJSON_ENDIAN CEREAL_RAPIDJSON_BIGENDIAN |
236 | 241 | # elif defined(__i386__) || defined(__alpha__) || defined(__ia64) || defined(__ia64__) || defined(_M_IX86) || defined(_M_IA64) || defined(_M_ALPHA) || defined(__amd64) || defined(__amd64__) || defined(_M_AMD64) || defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || defined(__bfin__) |
237 | 242 | # define CEREAL_RAPIDJSON_ENDIAN CEREAL_RAPIDJSON_LITTLEENDIAN |
238 | # elif defined(_MSC_VER) && defined(_M_ARM) | |
243 | # elif defined(_MSC_VER) && (defined(_M_ARM) || defined(_M_ARM64)) | |
239 | 244 | # define CEREAL_RAPIDJSON_ENDIAN CEREAL_RAPIDJSON_LITTLEENDIAN |
240 | 245 | # elif defined(CEREAL_RAPIDJSON_DOXYGEN_RUNNING) |
241 | 246 | # define CEREAL_RAPIDJSON_ENDIAN |
242 | 247 | # else |
243 | # error Unknown machine endianess detected. User needs to define CEREAL_RAPIDJSON_ENDIAN. | |
248 | # error Unknown machine endianness detected. User needs to define CEREAL_RAPIDJSON_ENDIAN. | |
244 | 249 | # endif |
245 | 250 | #endif // CEREAL_RAPIDJSON_ENDIAN |
246 | 251 | |
263 | 268 | /*! \ingroup CEREAL_RAPIDJSON_CONFIG |
264 | 269 | \param x pointer to align |
265 | 270 | |
266 | Some machines require strict data alignment. Currently the default uses 4 bytes | |
267 | alignment on 32-bit platforms and 8 bytes alignment for 64-bit platforms. | |
271 | Some machines require strict data alignment. The default is 8 bytes. | |
268 | 272 | User can customize by defining the CEREAL_RAPIDJSON_ALIGN function macro. |
269 | 273 | */ |
270 | 274 | #ifndef CEREAL_RAPIDJSON_ALIGN |
271 | #if CEREAL_RAPIDJSON_64BIT == 1 | |
272 | #define CEREAL_RAPIDJSON_ALIGN(x) (((x) + static_cast<uint64_t>(7u)) & ~static_cast<uint64_t>(7u)) | |
273 | #else | |
274 | #define CEREAL_RAPIDJSON_ALIGN(x) (((x) + 3u) & ~3u) | |
275 | #endif | |
275 | #define CEREAL_RAPIDJSON_ALIGN(x) (((x) + static_cast<size_t>(7u)) & ~static_cast<size_t>(7u)) | |
276 | 276 | #endif |
277 | 277 | |
278 | 278 | /////////////////////////////////////////////////////////////////////////////// |
319 | 319 | #endif |
320 | 320 | |
321 | 321 | /////////////////////////////////////////////////////////////////////////////// |
322 | // CEREAL_RAPIDJSON_SSE2/CEREAL_RAPIDJSON_SSE42/CEREAL_RAPIDJSON_SIMD | |
322 | // CEREAL_RAPIDJSON_SSE2/CEREAL_RAPIDJSON_SSE42/CEREAL_RAPIDJSON_NEON/CEREAL_RAPIDJSON_SIMD | |
323 | 323 | |
324 | 324 | /*! \def CEREAL_RAPIDJSON_SIMD |
325 | 325 | \ingroup CEREAL_RAPIDJSON_CONFIG |
326 | \brief Enable SSE2/SSE4.2 optimization. | |
326 | \brief Enable SSE2/SSE4.2/Neon optimization. | |
327 | 327 | |
328 | 328 | RapidJSON supports optimized implementations for some parsing operations |
329 | based on the SSE2 or SSE4.2 SIMD extensions on modern Intel-compatible | |
330 | processors. | |
331 | ||
332 | To enable these optimizations, two different symbols can be defined; | |
329 | based on the SSE2, SSE4.2 or NEon SIMD extensions on modern Intel | |
330 | or ARM compatible processors. | |
331 | ||
332 | To enable these optimizations, three different symbols can be defined; | |
333 | 333 | \code |
334 | 334 | // Enable SSE2 optimization. |
335 | 335 | #define CEREAL_RAPIDJSON_SSE2 |
338 | 338 | #define CEREAL_RAPIDJSON_SSE42 |
339 | 339 | \endcode |
340 | 340 | |
341 | \c CEREAL_RAPIDJSON_SSE42 takes precedence, if both are defined. | |
341 | // Enable ARM Neon optimization. | |
342 | #define CEREAL_RAPIDJSON_NEON | |
343 | \endcode | |
344 | ||
345 | \c CEREAL_RAPIDJSON_SSE42 takes precedence over SSE2, if both are defined. | |
342 | 346 | |
343 | 347 | If any of these symbols is defined, RapidJSON defines the macro |
344 | 348 | \c CEREAL_RAPIDJSON_SIMD to indicate the availability of the optimized code. |
345 | 349 | */ |
346 | 350 | #if defined(CEREAL_RAPIDJSON_SSE2) || defined(CEREAL_RAPIDJSON_SSE42) \ |
347 | || defined(CEREAL_RAPIDJSON_DOXYGEN_RUNNING) | |
351 | || defined(CEREAL_RAPIDJSON_NEON) || defined(CEREAL_RAPIDJSON_DOXYGEN_RUNNING) | |
348 | 352 | #define CEREAL_RAPIDJSON_SIMD |
349 | 353 | #endif |
350 | 354 | |
404 | 408 | /////////////////////////////////////////////////////////////////////////////// |
405 | 409 | // CEREAL_RAPIDJSON_STATIC_ASSERT |
406 | 410 | |
407 | // Adopt from boost | |
411 | // Prefer C++11 static_assert, if available | |
412 | #ifndef CEREAL_RAPIDJSON_STATIC_ASSERT | |
413 | #if __cplusplus >= 201103L || ( defined(_MSC_VER) && _MSC_VER >= 1800 ) | |
414 | #define CEREAL_RAPIDJSON_STATIC_ASSERT(x) \ | |
415 | static_assert(x, CEREAL_RAPIDJSON_STRINGIFY(x)) | |
416 | #endif // C++11 | |
417 | #endif // CEREAL_RAPIDJSON_STATIC_ASSERT | |
418 | ||
419 | // Adopt C++03 implementation from boost | |
408 | 420 | #ifndef CEREAL_RAPIDJSON_STATIC_ASSERT |
409 | 421 | #ifndef __clang__ |
410 | 422 | //!@cond CEREAL_RAPIDJSON_HIDDEN_FROM_DOXYGEN |
412 | 424 | CEREAL_RAPIDJSON_NAMESPACE_BEGIN |
413 | 425 | template <bool x> struct STATIC_ASSERTION_FAILURE; |
414 | 426 | template <> struct STATIC_ASSERTION_FAILURE<true> { enum { value = 1 }; }; |
415 | template<int x> struct StaticAssertTest {}; | |
427 | template <size_t x> struct StaticAssertTest {}; | |
416 | 428 | CEREAL_RAPIDJSON_NAMESPACE_END |
417 | 429 | |
418 | #define CEREAL_RAPIDJSON_JOIN(X, Y) CEREAL_RAPIDJSON_DO_JOIN(X, Y) | |
419 | #define CEREAL_RAPIDJSON_DO_JOIN(X, Y) CEREAL_RAPIDJSON_DO_JOIN2(X, Y) | |
420 | #define CEREAL_RAPIDJSON_DO_JOIN2(X, Y) X##Y | |
421 | ||
422 | #if defined(__GNUC__) | |
430 | #if defined(__GNUC__) || defined(__clang__) | |
423 | 431 | #define CEREAL_RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE __attribute__((unused)) |
424 | 432 | #else |
425 | 433 | #define CEREAL_RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE |
437 | 445 | typedef ::CEREAL_RAPIDJSON_NAMESPACE::StaticAssertTest< \ |
438 | 446 | sizeof(::CEREAL_RAPIDJSON_NAMESPACE::STATIC_ASSERTION_FAILURE<bool(x) >)> \ |
439 | 447 | CEREAL_RAPIDJSON_JOIN(StaticAssertTypedef, __LINE__) CEREAL_RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE |
440 | #endif | |
448 | #endif // CEREAL_RAPIDJSON_STATIC_ASSERT | |
441 | 449 | |
442 | 450 | /////////////////////////////////////////////////////////////////////////////// |
443 | 451 | // CEREAL_RAPIDJSON_LIKELY, CEREAL_RAPIDJSON_UNLIKELY |
529 | 537 | #ifndef CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS |
530 | 538 | #if defined(__clang__) |
531 | 539 | #if __has_feature(cxx_rvalue_references) && \ |
532 | (defined(_LIBCPP_VERSION) || defined(__GLIBCXX__) && __GLIBCXX__ >= 20080306) | |
540 | (defined(_MSC_VER) || defined(_LIBCPP_VERSION) || defined(__GLIBCXX__) && __GLIBCXX__ >= 20080306) | |
533 | 541 | #define CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS 1 |
534 | 542 | #else |
535 | 543 | #define CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS 0 |
536 | 544 | #endif |
537 | 545 | #elif (defined(CEREAL_RAPIDJSON_GNUC) && (CEREAL_RAPIDJSON_GNUC >= CEREAL_RAPIDJSON_VERSION_CODE(4,3,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__)) || \ |
538 | (defined(_MSC_VER) && _MSC_VER >= 1600) | |
546 | (defined(_MSC_VER) && _MSC_VER >= 1600) || \ | |
547 | (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140 && defined(__GXX_EXPERIMENTAL_CXX0X__)) | |
539 | 548 | |
540 | 549 | #define CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS 1 |
541 | 550 | #else |
546 | 555 | #ifndef CEREAL_RAPIDJSON_HAS_CXX11_NOEXCEPT |
547 | 556 | #if defined(__clang__) |
548 | 557 | #define CEREAL_RAPIDJSON_HAS_CXX11_NOEXCEPT __has_feature(cxx_noexcept) |
549 | #elif (defined(CEREAL_RAPIDJSON_GNUC) && (CEREAL_RAPIDJSON_GNUC >= CEREAL_RAPIDJSON_VERSION_CODE(4,6,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__)) | |
550 | // (defined(_MSC_VER) && _MSC_VER >= ????) // not yet supported | |
558 | #elif (defined(CEREAL_RAPIDJSON_GNUC) && (CEREAL_RAPIDJSON_GNUC >= CEREAL_RAPIDJSON_VERSION_CODE(4,6,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__)) || \ | |
559 | (defined(_MSC_VER) && _MSC_VER >= 1900) || \ | |
560 | (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140 && defined(__GXX_EXPERIMENTAL_CXX0X__)) | |
551 | 561 | #define CEREAL_RAPIDJSON_HAS_CXX11_NOEXCEPT 1 |
552 | 562 | #else |
553 | 563 | #define CEREAL_RAPIDJSON_HAS_CXX11_NOEXCEPT 0 |
561 | 571 | |
562 | 572 | // no automatic detection, yet |
563 | 573 | #ifndef CEREAL_RAPIDJSON_HAS_CXX11_TYPETRAITS |
574 | #if (defined(_MSC_VER) && _MSC_VER >= 1700) | |
575 | #define CEREAL_RAPIDJSON_HAS_CXX11_TYPETRAITS 1 | |
576 | #else | |
564 | 577 | #define CEREAL_RAPIDJSON_HAS_CXX11_TYPETRAITS 0 |
578 | #endif | |
565 | 579 | #endif |
566 | 580 | |
567 | 581 | #ifndef CEREAL_RAPIDJSON_HAS_CXX11_RANGE_FOR |
568 | 582 | #if defined(__clang__) |
569 | 583 | #define CEREAL_RAPIDJSON_HAS_CXX11_RANGE_FOR __has_feature(cxx_range_for) |
570 | #elif (defined(CEREAL_RAPIDJSON_GNUC) && (CEREAL_RAPIDJSON_GNUC >= CEREAL_RAPIDJSON_VERSION_CODE(4,3,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__)) || \ | |
571 | (defined(_MSC_VER) && _MSC_VER >= 1700) | |
584 | #elif (defined(CEREAL_RAPIDJSON_GNUC) && (CEREAL_RAPIDJSON_GNUC >= CEREAL_RAPIDJSON_VERSION_CODE(4,6,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__)) || \ | |
585 | (defined(_MSC_VER) && _MSC_VER >= 1700) || \ | |
586 | (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140 && defined(__GXX_EXPERIMENTAL_CXX0X__)) | |
572 | 587 | #define CEREAL_RAPIDJSON_HAS_CXX11_RANGE_FOR 1 |
573 | 588 | #else |
574 | 589 | #define CEREAL_RAPIDJSON_HAS_CXX11_RANGE_FOR 0 |
576 | 591 | #endif // CEREAL_RAPIDJSON_HAS_CXX11_RANGE_FOR |
577 | 592 | |
578 | 593 | //!@endcond |
594 | ||
595 | //! Assertion (in non-throwing contexts). | |
596 | /*! \ingroup CEREAL_RAPIDJSON_CONFIG | |
597 | Some functions provide a \c noexcept guarantee, if the compiler supports it. | |
598 | In these cases, the \ref CEREAL_RAPIDJSON_ASSERT macro cannot be overridden to | |
599 | throw an exception. This macro adds a separate customization point for | |
600 | such cases. | |
601 | ||
602 | Defaults to C \c assert() (as \ref CEREAL_RAPIDJSON_ASSERT), if \c noexcept is | |
603 | supported, and to \ref CEREAL_RAPIDJSON_ASSERT otherwise. | |
604 | */ | |
605 | ||
606 | /////////////////////////////////////////////////////////////////////////////// | |
607 | // CEREAL_RAPIDJSON_NOEXCEPT_ASSERT | |
608 | ||
609 | #ifndef CEREAL_RAPIDJSON_NOEXCEPT_ASSERT | |
610 | #ifdef CEREAL_RAPIDJSON_ASSERT_THROWS | |
611 | #if CEREAL_RAPIDJSON_HAS_CXX11_NOEXCEPT | |
612 | #define CEREAL_RAPIDJSON_NOEXCEPT_ASSERT(x) | |
613 | #else | |
614 | #define CEREAL_RAPIDJSON_NOEXCEPT_ASSERT(x) CEREAL_RAPIDJSON_ASSERT(x) | |
615 | #endif // CEREAL_RAPIDJSON_HAS_CXX11_NOEXCEPT | |
616 | #else | |
617 | #define CEREAL_RAPIDJSON_NOEXCEPT_ASSERT(x) CEREAL_RAPIDJSON_ASSERT(x) | |
618 | #endif // CEREAL_RAPIDJSON_ASSERT_THROWS | |
619 | #endif // CEREAL_RAPIDJSON_NOEXCEPT_ASSERT | |
579 | 620 | |
580 | 621 | /////////////////////////////////////////////////////////////////////////////// |
581 | 622 | // new/delete |
582 | 623 | |
583 | 624 | #ifndef CEREAL_RAPIDJSON_NEW |
584 | 625 | ///! customization point for global \c new |
585 | #define CEREAL_RAPIDJSON_NEW(x) new x | |
626 | #define CEREAL_RAPIDJSON_NEW(TypeName) new TypeName | |
586 | 627 | #endif |
587 | 628 | #ifndef CEREAL_RAPIDJSON_DELETE |
588 | 629 | ///! customization point for global \c delete |
32 | 32 | #include <nmmintrin.h> |
33 | 33 | #elif defined(CEREAL_RAPIDJSON_SSE2) |
34 | 34 | #include <emmintrin.h> |
35 | #endif | |
36 | ||
37 | #ifdef _MSC_VER | |
38 | CEREAL_RAPIDJSON_DIAG_PUSH | |
39 | CEREAL_RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant | |
40 | CEREAL_RAPIDJSON_DIAG_OFF(4702) // unreachable code | |
35 | #elif defined(CEREAL_RAPIDJSON_NEON) | |
36 | #include <arm_neon.h> | |
41 | 37 | #endif |
42 | 38 | |
43 | 39 | #ifdef __clang__ |
45 | 41 | CEREAL_RAPIDJSON_DIAG_OFF(old-style-cast) |
46 | 42 | CEREAL_RAPIDJSON_DIAG_OFF(padded) |
47 | 43 | CEREAL_RAPIDJSON_DIAG_OFF(switch-enum) |
44 | #elif defined(_MSC_VER) | |
45 | CEREAL_RAPIDJSON_DIAG_PUSH | |
46 | CEREAL_RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant | |
47 | CEREAL_RAPIDJSON_DIAG_OFF(4702) // unreachable code | |
48 | 48 | #endif |
49 | 49 | |
50 | 50 | #ifdef __GNUC__ |
298 | 298 | |
299 | 299 | for (;; p += 16) { |
300 | 300 | const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p)); |
301 | const int r = _mm_cvtsi128_si32(_mm_cmpistrm(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_BIT_MASK | _SIDD_NEGATIVE_POLARITY)); | |
302 | if (r != 0) { // some of characters is non-whitespace | |
303 | #ifdef _MSC_VER // Find the index of first non-whitespace | |
304 | unsigned long offset; | |
305 | _BitScanForward(&offset, r); | |
306 | return p + offset; | |
307 | #else | |
308 | return p + __builtin_ffs(r) - 1; | |
309 | #endif | |
310 | } | |
301 | const int r = _mm_cmpistri(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_LEAST_SIGNIFICANT | _SIDD_NEGATIVE_POLARITY); | |
302 | if (r != 16) // some of characters is non-whitespace | |
303 | return p + r; | |
311 | 304 | } |
312 | 305 | } |
313 | 306 | |
324 | 317 | |
325 | 318 | for (; p <= end - 16; p += 16) { |
326 | 319 | const __m128i s = _mm_loadu_si128(reinterpret_cast<const __m128i *>(p)); |
327 | const int r = _mm_cvtsi128_si32(_mm_cmpistrm(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_BIT_MASK | _SIDD_NEGATIVE_POLARITY)); | |
328 | if (r != 0) { // some of characters is non-whitespace | |
329 | #ifdef _MSC_VER // Find the index of first non-whitespace | |
330 | unsigned long offset; | |
331 | _BitScanForward(&offset, r); | |
332 | return p + offset; | |
333 | #else | |
334 | return p + __builtin_ffs(r) - 1; | |
335 | #endif | |
336 | } | |
320 | const int r = _mm_cmpistri(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_LEAST_SIGNIFICANT | _SIDD_NEGATIVE_POLARITY); | |
321 | if (r != 16) // some of characters is non-whitespace | |
322 | return p + r; | |
337 | 323 | } |
338 | 324 | |
339 | 325 | return SkipWhitespace(p, end); |
424 | 410 | return SkipWhitespace(p, end); |
425 | 411 | } |
426 | 412 | |
427 | #endif // CEREAL_RAPIDJSON_SSE2 | |
413 | #elif defined(CEREAL_RAPIDJSON_NEON) | |
414 | ||
415 | //! Skip whitespace with ARM Neon instructions, testing 16 8-byte characters at once. | |
416 | inline const char *SkipWhitespace_SIMD(const char* p) { | |
417 | // Fast return for single non-whitespace | |
418 | if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') | |
419 | ++p; | |
420 | else | |
421 | return p; | |
422 | ||
423 | // 16-byte align to the next boundary | |
424 | const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); | |
425 | while (p != nextAligned) | |
426 | if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') | |
427 | ++p; | |
428 | else | |
429 | return p; | |
430 | ||
431 | const uint8x16_t w0 = vmovq_n_u8(' '); | |
432 | const uint8x16_t w1 = vmovq_n_u8('\n'); | |
433 | const uint8x16_t w2 = vmovq_n_u8('\r'); | |
434 | const uint8x16_t w3 = vmovq_n_u8('\t'); | |
435 | ||
436 | for (;; p += 16) { | |
437 | const uint8x16_t s = vld1q_u8(reinterpret_cast<const uint8_t *>(p)); | |
438 | uint8x16_t x = vceqq_u8(s, w0); | |
439 | x = vorrq_u8(x, vceqq_u8(s, w1)); | |
440 | x = vorrq_u8(x, vceqq_u8(s, w2)); | |
441 | x = vorrq_u8(x, vceqq_u8(s, w3)); | |
442 | ||
443 | x = vmvnq_u8(x); // Negate | |
444 | x = vrev64q_u8(x); // Rev in 64 | |
445 | uint64_t low = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 0); // extract | |
446 | uint64_t high = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 1); // extract | |
447 | ||
448 | if (low == 0) { | |
449 | if (high != 0) { | |
450 | int lz =__builtin_clzll(high);; | |
451 | return p + 8 + (lz >> 3); | |
452 | } | |
453 | } else { | |
454 | int lz = __builtin_clzll(low);; | |
455 | return p + (lz >> 3); | |
456 | } | |
457 | } | |
458 | } | |
459 | ||
460 | inline const char *SkipWhitespace_SIMD(const char* p, const char* end) { | |
461 | // Fast return for single non-whitespace | |
462 | if (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) | |
463 | ++p; | |
464 | else | |
465 | return p; | |
466 | ||
467 | const uint8x16_t w0 = vmovq_n_u8(' '); | |
468 | const uint8x16_t w1 = vmovq_n_u8('\n'); | |
469 | const uint8x16_t w2 = vmovq_n_u8('\r'); | |
470 | const uint8x16_t w3 = vmovq_n_u8('\t'); | |
471 | ||
472 | for (; p <= end - 16; p += 16) { | |
473 | const uint8x16_t s = vld1q_u8(reinterpret_cast<const uint8_t *>(p)); | |
474 | uint8x16_t x = vceqq_u8(s, w0); | |
475 | x = vorrq_u8(x, vceqq_u8(s, w1)); | |
476 | x = vorrq_u8(x, vceqq_u8(s, w2)); | |
477 | x = vorrq_u8(x, vceqq_u8(s, w3)); | |
478 | ||
479 | x = vmvnq_u8(x); // Negate | |
480 | x = vrev64q_u8(x); // Rev in 64 | |
481 | uint64_t low = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 0); // extract | |
482 | uint64_t high = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 1); // extract | |
483 | ||
484 | if (low == 0) { | |
485 | if (high != 0) { | |
486 | int lz = __builtin_clzll(high); | |
487 | return p + 8 + (lz >> 3); | |
488 | } | |
489 | } else { | |
490 | int lz = __builtin_clzll(low); | |
491 | return p + (lz >> 3); | |
492 | } | |
493 | } | |
494 | ||
495 | return SkipWhitespace(p, end); | |
496 | } | |
497 | ||
498 | #endif // CEREAL_RAPIDJSON_NEON | |
428 | 499 | |
429 | 500 | #ifdef CEREAL_RAPIDJSON_SIMD |
430 | 501 | //! Template function specialization for InsituStringStream |
470 | 541 | /*! \param stackAllocator Optional allocator for allocating stack memory. (Only use for non-destructive parsing) |
471 | 542 | \param stackCapacity stack capacity in bytes for storing a single decoded string. (Only use for non-destructive parsing) |
472 | 543 | */ |
473 | GenericReader(StackAllocator* stackAllocator = 0, size_t stackCapacity = kDefaultStackCapacity) : stack_(stackAllocator, stackCapacity), parseResult_() {} | |
544 | GenericReader(StackAllocator* stackAllocator = 0, size_t stackCapacity = kDefaultStackCapacity) : | |
545 | stack_(stackAllocator, stackCapacity), parseResult_(), state_(IterativeParsingStartState) {} | |
474 | 546 | |
475 | 547 | //! Parse JSON text. |
476 | 548 | /*! \tparam parseFlags Combination of \ref ParseFlag. |
526 | 598 | return Parse<kParseDefaultFlags>(is, handler); |
527 | 599 | } |
528 | 600 | |
529 | //! Whether a parse error has occured in the last parsing. | |
601 | //! Initialize JSON text token-by-token parsing | |
602 | /*! | |
603 | */ | |
604 | void IterativeParseInit() { | |
605 | parseResult_.Clear(); | |
606 | state_ = IterativeParsingStartState; | |
607 | } | |
608 | ||
609 | //! Parse one token from JSON text | |
610 | /*! \tparam InputStream Type of input stream, implementing Stream concept | |
611 | \tparam Handler Type of handler, implementing Handler concept. | |
612 | \param is Input stream to be parsed. | |
613 | \param handler The handler to receive events. | |
614 | \return Whether the parsing is successful. | |
615 | */ | |
616 | template <unsigned parseFlags, typename InputStream, typename Handler> | |
617 | bool IterativeParseNext(InputStream& is, Handler& handler) { | |
618 | while (CEREAL_RAPIDJSON_LIKELY(is.Peek() != '\0')) { | |
619 | SkipWhitespaceAndComments<parseFlags>(is); | |
620 | ||
621 | Token t = Tokenize(is.Peek()); | |
622 | IterativeParsingState n = Predict(state_, t); | |
623 | IterativeParsingState d = Transit<parseFlags>(state_, t, n, is, handler); | |
624 | ||
625 | // If we've finished or hit an error... | |
626 | if (CEREAL_RAPIDJSON_UNLIKELY(IsIterativeParsingCompleteState(d))) { | |
627 | // Report errors. | |
628 | if (d == IterativeParsingErrorState) { | |
629 | HandleError(state_, is); | |
630 | return false; | |
631 | } | |
632 | ||
633 | // Transition to the finish state. | |
634 | CEREAL_RAPIDJSON_ASSERT(d == IterativeParsingFinishState); | |
635 | state_ = d; | |
636 | ||
637 | // If StopWhenDone is not set... | |
638 | if (!(parseFlags & kParseStopWhenDoneFlag)) { | |
639 | // ... and extra non-whitespace data is found... | |
640 | SkipWhitespaceAndComments<parseFlags>(is); | |
641 | if (is.Peek() != '\0') { | |
642 | // ... this is considered an error. | |
643 | HandleError(state_, is); | |
644 | return false; | |
645 | } | |
646 | } | |
647 | ||
648 | // Success! We are done! | |
649 | return true; | |
650 | } | |
651 | ||
652 | // Transition to the new state. | |
653 | state_ = d; | |
654 | ||
655 | // If we parsed anything other than a delimiter, we invoked the handler, so we can return true now. | |
656 | if (!IsIterativeParsingDelimiterState(n)) | |
657 | return true; | |
658 | } | |
659 | ||
660 | // We reached the end of file. | |
661 | stack_.Clear(); | |
662 | ||
663 | if (state_ != IterativeParsingFinishState) { | |
664 | HandleError(state_, is); | |
665 | return false; | |
666 | } | |
667 | ||
668 | return true; | |
669 | } | |
670 | ||
671 | //! Check if token-by-token parsing JSON text is complete | |
672 | /*! \return Whether the JSON has been fully decoded. | |
673 | */ | |
674 | CEREAL_RAPIDJSON_FORCEINLINE bool IterativeParseComplete() const { | |
675 | return IsIterativeParsingCompleteState(state_); | |
676 | } | |
677 | ||
678 | //! Whether a parse error has occurred in the last parsing. | |
530 | 679 | bool HasParseError() const { return parseResult_.IsError(); } |
531 | 680 | |
532 | 681 | //! Get the \ref ParseErrorCode of last parsing. |
574 | 723 | } |
575 | 724 | } |
576 | 725 | else if (CEREAL_RAPIDJSON_LIKELY(Consume(is, '/'))) |
577 | while (is.Peek() != '\0' && is.Take() != '\n'); | |
726 | while (is.Peek() != '\0' && is.Take() != '\n') {} | |
578 | 727 | else |
579 | 728 | CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorUnspecificSyntaxError, is.Tell()); |
580 | 729 | |
749 | 898 | return false; |
750 | 899 | } |
751 | 900 | |
752 | // Helper function to parse four hexidecimal digits in \uXXXX in ParseString(). | |
901 | // Helper function to parse four hexadecimal digits in \uXXXX in ParseString(). | |
753 | 902 | template<typename InputStream> |
754 | 903 | unsigned ParseHex4(InputStream& is, size_t escapeOffset) { |
755 | 904 | unsigned codepoint = 0; |
856 | 1005 | |
857 | 1006 | Ch c = is.Peek(); |
858 | 1007 | if (CEREAL_RAPIDJSON_UNLIKELY(c == '\\')) { // Escape |
859 | size_t escapeOffset = is.Tell(); // For invalid escaping, report the inital '\\' as error offset | |
1008 | size_t escapeOffset = is.Tell(); // For invalid escaping, report the initial '\\' as error offset | |
860 | 1009 | is.Take(); |
861 | 1010 | Ch e = is.Peek(); |
862 | 1011 | if ((sizeof(Ch) == 1 || unsigned(e) < 256) && CEREAL_RAPIDJSON_LIKELY(escape[static_cast<unsigned char>(e)])) { |
891 | 1040 | if (c == '\0') |
892 | 1041 | CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorStringMissQuotationMark, is.Tell()); |
893 | 1042 | else |
894 | CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorStringEscapeInvalid, is.Tell()); | |
1043 | CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorStringInvalidEncoding, is.Tell()); | |
895 | 1044 | } |
896 | 1045 | else { |
897 | 1046 | size_t offset = is.Tell(); |
926 | 1075 | // The rest of string using SIMD |
927 | 1076 | static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' }; |
928 | 1077 | static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; |
929 | static const char space[16] = { 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19 }; | |
1078 | static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F }; | |
930 | 1079 | const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0])); |
931 | 1080 | const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0])); |
932 | 1081 | const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0])); |
935 | 1084 | const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p)); |
936 | 1085 | const __m128i t1 = _mm_cmpeq_epi8(s, dq); |
937 | 1086 | const __m128i t2 = _mm_cmpeq_epi8(s, bs); |
938 | const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x19) == 0x19 | |
1087 | const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F | |
939 | 1088 | const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); |
940 | 1089 | unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x)); |
941 | 1090 | if (CEREAL_RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped |
947 | 1096 | #else |
948 | 1097 | length = static_cast<SizeType>(__builtin_ffs(r) - 1); |
949 | 1098 | #endif |
950 | char* q = reinterpret_cast<char*>(os.Push(length)); | |
951 | for (size_t i = 0; i < length; i++) | |
952 | q[i] = p[i]; | |
953 | ||
954 | p += length; | |
1099 | if (length != 0) { | |
1100 | char* q = reinterpret_cast<char*>(os.Push(length)); | |
1101 | for (size_t i = 0; i < length; i++) | |
1102 | q[i] = p[i]; | |
1103 | ||
1104 | p += length; | |
1105 | } | |
955 | 1106 | break; |
956 | 1107 | } |
957 | 1108 | _mm_storeu_si128(reinterpret_cast<__m128i *>(os.Push(16)), s); |
987 | 1138 | // The rest of string using SIMD |
988 | 1139 | static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' }; |
989 | 1140 | static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; |
990 | static const char space[16] = { 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19 }; | |
1141 | static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F }; | |
991 | 1142 | const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0])); |
992 | 1143 | const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0])); |
993 | 1144 | const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0])); |
996 | 1147 | const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p)); |
997 | 1148 | const __m128i t1 = _mm_cmpeq_epi8(s, dq); |
998 | 1149 | const __m128i t2 = _mm_cmpeq_epi8(s, bs); |
999 | const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x19) == 0x19 | |
1150 | const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F | |
1000 | 1151 | const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); |
1001 | 1152 | unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x)); |
1002 | 1153 | if (CEREAL_RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped |
1035 | 1186 | // The rest of string using SIMD |
1036 | 1187 | static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' }; |
1037 | 1188 | static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; |
1038 | static const char space[16] = { 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19 }; | |
1189 | static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F }; | |
1039 | 1190 | const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0])); |
1040 | 1191 | const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0])); |
1041 | 1192 | const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0])); |
1044 | 1195 | const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p)); |
1045 | 1196 | const __m128i t1 = _mm_cmpeq_epi8(s, dq); |
1046 | 1197 | const __m128i t2 = _mm_cmpeq_epi8(s, bs); |
1047 | const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x19) == 0x19 | |
1198 | const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F | |
1048 | 1199 | const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); |
1049 | 1200 | unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x)); |
1050 | 1201 | if (CEREAL_RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped |
1063 | 1214 | |
1064 | 1215 | is.src_ = is.dst_ = p; |
1065 | 1216 | } |
1066 | #endif | |
1217 | #elif defined(CEREAL_RAPIDJSON_NEON) | |
1218 | // StringStream -> StackStream<char> | |
1219 | static CEREAL_RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(StringStream& is, StackStream<char>& os) { | |
1220 | const char* p = is.src_; | |
1221 | ||
1222 | // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) | |
1223 | const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); | |
1224 | while (p != nextAligned) | |
1225 | if (CEREAL_RAPIDJSON_UNLIKELY(*p == '\"') || CEREAL_RAPIDJSON_UNLIKELY(*p == '\\') || CEREAL_RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) { | |
1226 | is.src_ = p; | |
1227 | return; | |
1228 | } | |
1229 | else | |
1230 | os.Put(*p++); | |
1231 | ||
1232 | // The rest of string using SIMD | |
1233 | const uint8x16_t s0 = vmovq_n_u8('"'); | |
1234 | const uint8x16_t s1 = vmovq_n_u8('\\'); | |
1235 | const uint8x16_t s2 = vmovq_n_u8('\b'); | |
1236 | const uint8x16_t s3 = vmovq_n_u8(32); | |
1237 | ||
1238 | for (;; p += 16) { | |
1239 | const uint8x16_t s = vld1q_u8(reinterpret_cast<const uint8_t *>(p)); | |
1240 | uint8x16_t x = vceqq_u8(s, s0); | |
1241 | x = vorrq_u8(x, vceqq_u8(s, s1)); | |
1242 | x = vorrq_u8(x, vceqq_u8(s, s2)); | |
1243 | x = vorrq_u8(x, vcltq_u8(s, s3)); | |
1244 | ||
1245 | x = vrev64q_u8(x); // Rev in 64 | |
1246 | uint64_t low = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 0); // extract | |
1247 | uint64_t high = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 1); // extract | |
1248 | ||
1249 | SizeType length = 0; | |
1250 | bool escaped = false; | |
1251 | if (low == 0) { | |
1252 | if (high != 0) { | |
1253 | unsigned lz = (unsigned)__builtin_clzll(high);; | |
1254 | length = 8 + (lz >> 3); | |
1255 | escaped = true; | |
1256 | } | |
1257 | } else { | |
1258 | unsigned lz = (unsigned)__builtin_clzll(low);; | |
1259 | length = lz >> 3; | |
1260 | escaped = true; | |
1261 | } | |
1262 | if (CEREAL_RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped | |
1263 | if (length != 0) { | |
1264 | char* q = reinterpret_cast<char*>(os.Push(length)); | |
1265 | for (size_t i = 0; i < length; i++) | |
1266 | q[i] = p[i]; | |
1267 | ||
1268 | p += length; | |
1269 | } | |
1270 | break; | |
1271 | } | |
1272 | vst1q_u8(reinterpret_cast<uint8_t *>(os.Push(16)), s); | |
1273 | } | |
1274 | ||
1275 | is.src_ = p; | |
1276 | } | |
1277 | ||
1278 | // InsituStringStream -> InsituStringStream | |
1279 | static CEREAL_RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(InsituStringStream& is, InsituStringStream& os) { | |
1280 | CEREAL_RAPIDJSON_ASSERT(&is == &os); | |
1281 | (void)os; | |
1282 | ||
1283 | if (is.src_ == is.dst_) { | |
1284 | SkipUnescapedString(is); | |
1285 | return; | |
1286 | } | |
1287 | ||
1288 | char* p = is.src_; | |
1289 | char *q = is.dst_; | |
1290 | ||
1291 | // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) | |
1292 | const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); | |
1293 | while (p != nextAligned) | |
1294 | if (CEREAL_RAPIDJSON_UNLIKELY(*p == '\"') || CEREAL_RAPIDJSON_UNLIKELY(*p == '\\') || CEREAL_RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) { | |
1295 | is.src_ = p; | |
1296 | is.dst_ = q; | |
1297 | return; | |
1298 | } | |
1299 | else | |
1300 | *q++ = *p++; | |
1301 | ||
1302 | // The rest of string using SIMD | |
1303 | const uint8x16_t s0 = vmovq_n_u8('"'); | |
1304 | const uint8x16_t s1 = vmovq_n_u8('\\'); | |
1305 | const uint8x16_t s2 = vmovq_n_u8('\b'); | |
1306 | const uint8x16_t s3 = vmovq_n_u8(32); | |
1307 | ||
1308 | for (;; p += 16, q += 16) { | |
1309 | const uint8x16_t s = vld1q_u8(reinterpret_cast<uint8_t *>(p)); | |
1310 | uint8x16_t x = vceqq_u8(s, s0); | |
1311 | x = vorrq_u8(x, vceqq_u8(s, s1)); | |
1312 | x = vorrq_u8(x, vceqq_u8(s, s2)); | |
1313 | x = vorrq_u8(x, vcltq_u8(s, s3)); | |
1314 | ||
1315 | x = vrev64q_u8(x); // Rev in 64 | |
1316 | uint64_t low = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 0); // extract | |
1317 | uint64_t high = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 1); // extract | |
1318 | ||
1319 | SizeType length = 0; | |
1320 | bool escaped = false; | |
1321 | if (low == 0) { | |
1322 | if (high != 0) { | |
1323 | unsigned lz = (unsigned)__builtin_clzll(high); | |
1324 | length = 8 + (lz >> 3); | |
1325 | escaped = true; | |
1326 | } | |
1327 | } else { | |
1328 | unsigned lz = (unsigned)__builtin_clzll(low); | |
1329 | length = lz >> 3; | |
1330 | escaped = true; | |
1331 | } | |
1332 | if (CEREAL_RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped | |
1333 | for (const char* pend = p + length; p != pend; ) { | |
1334 | *q++ = *p++; | |
1335 | } | |
1336 | break; | |
1337 | } | |
1338 | vst1q_u8(reinterpret_cast<uint8_t *>(q), s); | |
1339 | } | |
1340 | ||
1341 | is.src_ = p; | |
1342 | is.dst_ = q; | |
1343 | } | |
1344 | ||
1345 | // When read/write pointers are the same for insitu stream, just skip unescaped characters | |
1346 | static CEREAL_RAPIDJSON_FORCEINLINE void SkipUnescapedString(InsituStringStream& is) { | |
1347 | CEREAL_RAPIDJSON_ASSERT(is.src_ == is.dst_); | |
1348 | char* p = is.src_; | |
1349 | ||
1350 | // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) | |
1351 | const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); | |
1352 | for (; p != nextAligned; p++) | |
1353 | if (CEREAL_RAPIDJSON_UNLIKELY(*p == '\"') || CEREAL_RAPIDJSON_UNLIKELY(*p == '\\') || CEREAL_RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) { | |
1354 | is.src_ = is.dst_ = p; | |
1355 | return; | |
1356 | } | |
1357 | ||
1358 | // The rest of string using SIMD | |
1359 | const uint8x16_t s0 = vmovq_n_u8('"'); | |
1360 | const uint8x16_t s1 = vmovq_n_u8('\\'); | |
1361 | const uint8x16_t s2 = vmovq_n_u8('\b'); | |
1362 | const uint8x16_t s3 = vmovq_n_u8(32); | |
1363 | ||
1364 | for (;; p += 16) { | |
1365 | const uint8x16_t s = vld1q_u8(reinterpret_cast<uint8_t *>(p)); | |
1366 | uint8x16_t x = vceqq_u8(s, s0); | |
1367 | x = vorrq_u8(x, vceqq_u8(s, s1)); | |
1368 | x = vorrq_u8(x, vceqq_u8(s, s2)); | |
1369 | x = vorrq_u8(x, vcltq_u8(s, s3)); | |
1370 | ||
1371 | x = vrev64q_u8(x); // Rev in 64 | |
1372 | uint64_t low = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 0); // extract | |
1373 | uint64_t high = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 1); // extract | |
1374 | ||
1375 | if (low == 0) { | |
1376 | if (high != 0) { | |
1377 | int lz = __builtin_clzll(high); | |
1378 | p += 8 + (lz >> 3); | |
1379 | break; | |
1380 | } | |
1381 | } else { | |
1382 | int lz = __builtin_clzll(low); | |
1383 | p += lz >> 3; | |
1384 | break; | |
1385 | } | |
1386 | } | |
1387 | ||
1388 | is.src_ = is.dst_ = p; | |
1389 | } | |
1390 | #endif // CEREAL_RAPIDJSON_NEON | |
1067 | 1391 | |
1068 | 1392 | template<typename InputStream, bool backup, bool pushOnTake> |
1069 | 1393 | class NumberStream; |
1074 | 1398 | typedef typename InputStream::Ch Ch; |
1075 | 1399 | |
1076 | 1400 | NumberStream(GenericReader& reader, InputStream& s) : is(s) { (void)reader; } |
1077 | ~NumberStream() {} | |
1078 | 1401 | |
1079 | 1402 | CEREAL_RAPIDJSON_FORCEINLINE Ch Peek() const { return is.Peek(); } |
1080 | 1403 | CEREAL_RAPIDJSON_FORCEINLINE Ch TakePush() { return is.Take(); } |
1096 | 1419 | typedef NumberStream<InputStream, false, false> Base; |
1097 | 1420 | public: |
1098 | 1421 | NumberStream(GenericReader& reader, InputStream& s) : Base(reader, s), stackStream(reader.stack_) {} |
1099 | ~NumberStream() {} | |
1100 | 1422 | |
1101 | 1423 | CEREAL_RAPIDJSON_FORCEINLINE Ch TakePush() { |
1102 | 1424 | stackStream.Put(static_cast<char>(Base::is.Peek())); |
1123 | 1445 | typedef NumberStream<InputStream, true, false> Base; |
1124 | 1446 | public: |
1125 | 1447 | NumberStream(GenericReader& reader, InputStream& is) : Base(reader, is) {} |
1126 | ~NumberStream() {} | |
1127 | 1448 | |
1128 | 1449 | CEREAL_RAPIDJSON_FORCEINLINE Ch Take() { return Base::TakePush(); } |
1129 | 1450 | }; |
1184 | 1505 | } |
1185 | 1506 | // Parse NaN or Infinity here |
1186 | 1507 | else if ((parseFlags & kParseNanAndInfFlag) && CEREAL_RAPIDJSON_LIKELY((s.Peek() == 'I' || s.Peek() == 'N'))) { |
1187 | useNanOrInf = true; | |
1188 | if (CEREAL_RAPIDJSON_LIKELY(Consume(s, 'N') && Consume(s, 'a') && Consume(s, 'N'))) { | |
1189 | d = std::numeric_limits<double>::quiet_NaN(); | |
1190 | } | |
1191 | else if (CEREAL_RAPIDJSON_LIKELY(Consume(s, 'I') && Consume(s, 'n') && Consume(s, 'f'))) { | |
1192 | d = (minus ? -std::numeric_limits<double>::infinity() : std::numeric_limits<double>::infinity()); | |
1193 | if (CEREAL_RAPIDJSON_UNLIKELY(s.Peek() == 'i' && !(Consume(s, 'i') && Consume(s, 'n') | |
1194 | && Consume(s, 'i') && Consume(s, 't') && Consume(s, 'y')))) | |
1195 | CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell()); | |
1196 | } | |
1197 | else | |
1508 | if (Consume(s, 'N')) { | |
1509 | if (Consume(s, 'a') && Consume(s, 'N')) { | |
1510 | d = std::numeric_limits<double>::quiet_NaN(); | |
1511 | useNanOrInf = true; | |
1512 | } | |
1513 | } | |
1514 | else if (CEREAL_RAPIDJSON_LIKELY(Consume(s, 'I'))) { | |
1515 | if (Consume(s, 'n') && Consume(s, 'f')) { | |
1516 | d = (minus ? -std::numeric_limits<double>::infinity() : std::numeric_limits<double>::infinity()); | |
1517 | useNanOrInf = true; | |
1518 | ||
1519 | if (CEREAL_RAPIDJSON_UNLIKELY(s.Peek() == 'i' && !(Consume(s, 'i') && Consume(s, 'n') | |
1520 | && Consume(s, 'i') && Consume(s, 't') && Consume(s, 'y')))) { | |
1521 | CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell()); | |
1522 | } | |
1523 | } | |
1524 | } | |
1525 | ||
1526 | if (CEREAL_RAPIDJSON_UNLIKELY(!useNanOrInf)) { | |
1198 | 1527 | CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell()); |
1528 | } | |
1199 | 1529 | } |
1200 | 1530 | else |
1201 | 1531 | CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell()); |
1230 | 1560 | // Force double for big integer |
1231 | 1561 | if (useDouble) { |
1232 | 1562 | while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { |
1233 | if (CEREAL_RAPIDJSON_UNLIKELY(d >= 1.7976931348623157e307)) // DBL_MAX / 10.0 | |
1234 | CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorNumberTooBig, startOffset); | |
1235 | 1563 | d = d * 10 + (s.TakePush() - '0'); |
1236 | 1564 | } |
1237 | 1565 | } |
1301 | 1629 | if (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { |
1302 | 1630 | exp = static_cast<int>(s.Take() - '0'); |
1303 | 1631 | if (expMinus) { |
1632 | // (exp + expFrac) must not underflow int => we're detecting when -exp gets | |
1633 | // dangerously close to INT_MIN (a pessimistic next digit 9 would push it into | |
1634 | // underflow territory): | |
1635 | // | |
1636 | // -(exp * 10 + 9) + expFrac >= INT_MIN | |
1637 | // <=> exp <= (expFrac - INT_MIN - 9) / 10 | |
1638 | CEREAL_RAPIDJSON_ASSERT(expFrac <= 0); | |
1639 | int maxExp = (expFrac + 2147483639) / 10; | |
1640 | ||
1304 | 1641 | while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { |
1305 | 1642 | exp = exp * 10 + static_cast<int>(s.Take() - '0'); |
1306 | if (exp >= 214748364) { // Issue #313: prevent overflow exponent | |
1643 | if (CEREAL_RAPIDJSON_UNLIKELY(exp > maxExp)) { | |
1307 | 1644 | while (CEREAL_RAPIDJSON_UNLIKELY(s.Peek() >= '0' && s.Peek() <= '9')) // Consume the rest of exponent |
1308 | 1645 | s.Take(); |
1309 | 1646 | } |
1361 | 1698 | d = internal::StrtodFullPrecision(d, p, decimal, length, decimalPosition, exp); |
1362 | 1699 | else |
1363 | 1700 | d = internal::StrtodNormalPrecision(d, p); |
1701 | ||
1702 | // Use > max, instead of == inf, to fix bogus warning -Wfloat-equal | |
1703 | if (d > (std::numeric_limits<double>::max)()) { | |
1704 | // Overflow | |
1705 | // TODO: internal::StrtodX should report overflow (or underflow) | |
1706 | CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorNumberTooBig, startOffset); | |
1707 | } | |
1364 | 1708 | |
1365 | 1709 | cont = handler.Double(minus ? -d : d); |
1366 | 1710 | } |
1407 | 1751 | |
1408 | 1752 | // States |
1409 | 1753 | enum IterativeParsingState { |
1410 | IterativeParsingStartState = 0, | |
1411 | IterativeParsingFinishState, | |
1412 | IterativeParsingErrorState, | |
1754 | IterativeParsingFinishState = 0, // sink states at top | |
1755 | IterativeParsingErrorState, // sink states at top | |
1756 | IterativeParsingStartState, | |
1413 | 1757 | |
1414 | 1758 | // Object states |
1415 | 1759 | IterativeParsingObjectInitialState, |
1416 | 1760 | IterativeParsingMemberKeyState, |
1417 | IterativeParsingKeyValueDelimiterState, | |
1418 | 1761 | IterativeParsingMemberValueState, |
1419 | IterativeParsingMemberDelimiterState, | |
1420 | 1762 | IterativeParsingObjectFinishState, |
1421 | 1763 | |
1422 | 1764 | // Array states |
1423 | 1765 | IterativeParsingArrayInitialState, |
1424 | 1766 | IterativeParsingElementState, |
1767 | IterativeParsingArrayFinishState, | |
1768 | ||
1769 | // Single value state | |
1770 | IterativeParsingValueState, | |
1771 | ||
1772 | // Delimiter states (at bottom) | |
1425 | 1773 | IterativeParsingElementDelimiterState, |
1426 | IterativeParsingArrayFinishState, | |
1427 | ||
1428 | // Single value state | |
1429 | IterativeParsingValueState | |
1774 | IterativeParsingMemberDelimiterState, | |
1775 | IterativeParsingKeyValueDelimiterState, | |
1776 | ||
1777 | cIterativeParsingStateCount | |
1430 | 1778 | }; |
1431 | ||
1432 | enum { cIterativeParsingStateCount = IterativeParsingValueState + 1 }; | |
1433 | 1779 | |
1434 | 1780 | // Tokens |
1435 | 1781 | enum Token { |
1451 | 1797 | kTokenCount |
1452 | 1798 | }; |
1453 | 1799 | |
1454 | CEREAL_RAPIDJSON_FORCEINLINE Token Tokenize(Ch c) { | |
1800 | CEREAL_RAPIDJSON_FORCEINLINE Token Tokenize(Ch c) const { | |
1455 | 1801 | |
1456 | 1802 | //!@cond CEREAL_RAPIDJSON_HIDDEN_FROM_DOXYGEN |
1457 | 1803 | #define N NumberToken |
1478 | 1824 | return NumberToken; |
1479 | 1825 | } |
1480 | 1826 | |
1481 | CEREAL_RAPIDJSON_FORCEINLINE IterativeParsingState Predict(IterativeParsingState state, Token token) { | |
1827 | CEREAL_RAPIDJSON_FORCEINLINE IterativeParsingState Predict(IterativeParsingState state, Token token) const { | |
1482 | 1828 | // current state x one lookahead token -> new state |
1483 | 1829 | static const char G[cIterativeParsingStateCount][kTokenCount] = { |
1830 | // Finish(sink state) | |
1831 | { | |
1832 | IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, | |
1833 | IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, | |
1834 | IterativeParsingErrorState | |
1835 | }, | |
1836 | // Error(sink state) | |
1837 | { | |
1838 | IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, | |
1839 | IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, | |
1840 | IterativeParsingErrorState | |
1841 | }, | |
1484 | 1842 | // Start |
1485 | 1843 | { |
1486 | 1844 | IterativeParsingArrayInitialState, // Left bracket |
1494 | 1852 | IterativeParsingValueState, // True |
1495 | 1853 | IterativeParsingValueState, // Null |
1496 | 1854 | IterativeParsingValueState // Number |
1497 | }, | |
1498 | // Finish(sink state) | |
1499 | { | |
1500 | IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, | |
1501 | IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, | |
1502 | IterativeParsingErrorState | |
1503 | }, | |
1504 | // Error(sink state) | |
1505 | { | |
1506 | IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, | |
1507 | IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, | |
1508 | IterativeParsingErrorState | |
1509 | 1855 | }, |
1510 | 1856 | // ObjectInitial |
1511 | 1857 | { |
1535 | 1881 | IterativeParsingErrorState, // Null |
1536 | 1882 | IterativeParsingErrorState // Number |
1537 | 1883 | }, |
1538 | // KeyValueDelimiter | |
1539 | { | |
1540 | IterativeParsingArrayInitialState, // Left bracket(push MemberValue state) | |
1541 | IterativeParsingErrorState, // Right bracket | |
1542 | IterativeParsingObjectInitialState, // Left curly bracket(push MemberValue state) | |
1543 | IterativeParsingErrorState, // Right curly bracket | |
1544 | IterativeParsingErrorState, // Comma | |
1545 | IterativeParsingErrorState, // Colon | |
1546 | IterativeParsingMemberValueState, // String | |
1547 | IterativeParsingMemberValueState, // False | |
1548 | IterativeParsingMemberValueState, // True | |
1549 | IterativeParsingMemberValueState, // Null | |
1550 | IterativeParsingMemberValueState // Number | |
1551 | }, | |
1552 | 1884 | // MemberValue |
1553 | 1885 | { |
1554 | 1886 | IterativeParsingErrorState, // Left bracket |
1562 | 1894 | IterativeParsingErrorState, // True |
1563 | 1895 | IterativeParsingErrorState, // Null |
1564 | 1896 | IterativeParsingErrorState // Number |
1565 | }, | |
1566 | // MemberDelimiter | |
1567 | { | |
1568 | IterativeParsingErrorState, // Left bracket | |
1569 | IterativeParsingErrorState, // Right bracket | |
1570 | IterativeParsingErrorState, // Left curly bracket | |
1571 | IterativeParsingObjectFinishState, // Right curly bracket | |
1572 | IterativeParsingErrorState, // Comma | |
1573 | IterativeParsingErrorState, // Colon | |
1574 | IterativeParsingMemberKeyState, // String | |
1575 | IterativeParsingErrorState, // False | |
1576 | IterativeParsingErrorState, // True | |
1577 | IterativeParsingErrorState, // Null | |
1578 | IterativeParsingErrorState // Number | |
1579 | 1897 | }, |
1580 | 1898 | // ObjectFinish(sink state) |
1581 | 1899 | { |
1611 | 1929 | IterativeParsingErrorState, // Null |
1612 | 1930 | IterativeParsingErrorState // Number |
1613 | 1931 | }, |
1932 | // ArrayFinish(sink state) | |
1933 | { | |
1934 | IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, | |
1935 | IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, | |
1936 | IterativeParsingErrorState | |
1937 | }, | |
1938 | // Single Value (sink state) | |
1939 | { | |
1940 | IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, | |
1941 | IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, | |
1942 | IterativeParsingErrorState | |
1943 | }, | |
1614 | 1944 | // ElementDelimiter |
1615 | 1945 | { |
1616 | 1946 | IterativeParsingArrayInitialState, // Left bracket(push Element state) |
1625 | 1955 | IterativeParsingElementState, // Null |
1626 | 1956 | IterativeParsingElementState // Number |
1627 | 1957 | }, |
1628 | // ArrayFinish(sink state) | |
1958 | // MemberDelimiter | |
1629 | 1959 | { |
1630 | IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, | |
1631 | IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, | |
1632 | IterativeParsingErrorState | |
1960 | IterativeParsingErrorState, // Left bracket | |
1961 | IterativeParsingErrorState, // Right bracket | |
1962 | IterativeParsingErrorState, // Left curly bracket | |
1963 | IterativeParsingObjectFinishState, // Right curly bracket | |
1964 | IterativeParsingErrorState, // Comma | |
1965 | IterativeParsingErrorState, // Colon | |
1966 | IterativeParsingMemberKeyState, // String | |
1967 | IterativeParsingErrorState, // False | |
1968 | IterativeParsingErrorState, // True | |
1969 | IterativeParsingErrorState, // Null | |
1970 | IterativeParsingErrorState // Number | |
1633 | 1971 | }, |
1634 | // Single Value (sink state) | |
1972 | // KeyValueDelimiter | |
1635 | 1973 | { |
1636 | IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, | |
1637 | IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, | |
1638 | IterativeParsingErrorState | |
1639 | } | |
1974 | IterativeParsingArrayInitialState, // Left bracket(push MemberValue state) | |
1975 | IterativeParsingErrorState, // Right bracket | |
1976 | IterativeParsingObjectInitialState, // Left curly bracket(push MemberValue state) | |
1977 | IterativeParsingErrorState, // Right curly bracket | |
1978 | IterativeParsingErrorState, // Comma | |
1979 | IterativeParsingErrorState, // Colon | |
1980 | IterativeParsingMemberValueState, // String | |
1981 | IterativeParsingMemberValueState, // False | |
1982 | IterativeParsingMemberValueState, // True | |
1983 | IterativeParsingMemberValueState, // Null | |
1984 | IterativeParsingMemberValueState // Number | |
1985 | }, | |
1640 | 1986 | }; // End of G |
1641 | 1987 | |
1642 | 1988 | return static_cast<IterativeParsingState>(G[state][token]); |
1817 | 2163 | } |
1818 | 2164 | } |
1819 | 2165 | |
2166 | CEREAL_RAPIDJSON_FORCEINLINE bool IsIterativeParsingDelimiterState(IterativeParsingState s) const { | |
2167 | return s >= IterativeParsingElementDelimiterState; | |
2168 | } | |
2169 | ||
2170 | CEREAL_RAPIDJSON_FORCEINLINE bool IsIterativeParsingCompleteState(IterativeParsingState s) const { | |
2171 | return s <= IterativeParsingErrorState; | |
2172 | } | |
2173 | ||
1820 | 2174 | template <unsigned parseFlags, typename InputStream, typename Handler> |
1821 | 2175 | ParseResult IterativeParse(InputStream& is, Handler& handler) { |
1822 | 2176 | parseResult_.Clear(); |
1855 | 2209 | static const size_t kDefaultStackCapacity = 256; //!< Default stack capacity in bytes for storing a single decoded string. |
1856 | 2210 | internal::Stack<StackAllocator> stack_; //!< A stack for storing decoded string temporarily during non-destructive parsing. |
1857 | 2211 | ParseResult parseResult_; |
2212 | IterativeParsingState state_; | |
1858 | 2213 | }; // class GenericReader |
1859 | 2214 | |
1860 | 2215 | //! Reader with UTF8 encoding and default allocator. |
1862 | 2217 | |
1863 | 2218 | CEREAL_RAPIDJSON_NAMESPACE_END |
1864 | 2219 | |
1865 | #ifdef __clang__ | |
2220 | #if defined(__clang__) || defined(_MSC_VER) | |
1866 | 2221 | CEREAL_RAPIDJSON_DIAG_POP |
1867 | 2222 | #endif |
1868 | 2223 | |
1871 | 2226 | CEREAL_RAPIDJSON_DIAG_POP |
1872 | 2227 | #endif |
1873 | 2228 | |
1874 | #ifdef _MSC_VER | |
1875 | CEREAL_RAPIDJSON_DIAG_POP | |
1876 | #endif | |
1877 | ||
1878 | 2229 | #endif // CEREAL_RAPIDJSON_READER_H_ |
16 | 16 | |
17 | 17 | #include "document.h" |
18 | 18 | #include "pointer.h" |
19 | #include "stringbuffer.h" | |
19 | 20 | #include <cmath> // abs, floor |
20 | 21 | |
21 | 22 | #if !defined(CEREAL_RAPIDJSON_SCHEMA_USE_INTERNALREGEX) |
24 | 25 | #define CEREAL_RAPIDJSON_SCHEMA_USE_INTERNALREGEX 0 |
25 | 26 | #endif |
26 | 27 | |
27 | #if !CEREAL_RAPIDJSON_SCHEMA_USE_INTERNALREGEX && !defined(CEREAL_RAPIDJSON_SCHEMA_USE_STDREGEX) && (__cplusplus >=201103L || (defined(_MSC_VER) && _MSC_VER >= 1800)) | |
28 | #if !CEREAL_RAPIDJSON_SCHEMA_USE_INTERNALREGEX && defined(CEREAL_RAPIDJSON_SCHEMA_USE_STDREGEX) && (__cplusplus >=201103L || (defined(_MSC_VER) && _MSC_VER >= 1800)) | |
28 | 29 | #define CEREAL_RAPIDJSON_SCHEMA_USE_STDREGEX 1 |
29 | 30 | #else |
30 | 31 | #define CEREAL_RAPIDJSON_SCHEMA_USE_STDREGEX 0 |
61 | 62 | CEREAL_RAPIDJSON_DIAG_OFF(exit-time-destructors) |
62 | 63 | CEREAL_RAPIDJSON_DIAG_OFF(c++98-compat-pedantic) |
63 | 64 | CEREAL_RAPIDJSON_DIAG_OFF(variadic-macros) |
64 | #endif | |
65 | ||
66 | #ifdef _MSC_VER | |
65 | #elif defined(_MSC_VER) | |
67 | 66 | CEREAL_RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated |
68 | 67 | #endif |
69 | 68 | |
157 | 156 | }; |
158 | 157 | |
159 | 158 | /////////////////////////////////////////////////////////////////////////////// |
159 | // IValidationErrorHandler | |
160 | ||
161 | template <typename SchemaType> | |
162 | class IValidationErrorHandler { | |
163 | public: | |
164 | typedef typename SchemaType::Ch Ch; | |
165 | typedef typename SchemaType::SValue SValue; | |
166 | ||
167 | virtual ~IValidationErrorHandler() {} | |
168 | ||
169 | virtual void NotMultipleOf(int64_t actual, const SValue& expected) = 0; | |
170 | virtual void NotMultipleOf(uint64_t actual, const SValue& expected) = 0; | |
171 | virtual void NotMultipleOf(double actual, const SValue& expected) = 0; | |
172 | virtual void AboveMaximum(int64_t actual, const SValue& expected, bool exclusive) = 0; | |
173 | virtual void AboveMaximum(uint64_t actual, const SValue& expected, bool exclusive) = 0; | |
174 | virtual void AboveMaximum(double actual, const SValue& expected, bool exclusive) = 0; | |
175 | virtual void BelowMinimum(int64_t actual, const SValue& expected, bool exclusive) = 0; | |
176 | virtual void BelowMinimum(uint64_t actual, const SValue& expected, bool exclusive) = 0; | |
177 | virtual void BelowMinimum(double actual, const SValue& expected, bool exclusive) = 0; | |
178 | ||
179 | virtual void TooLong(const Ch* str, SizeType length, SizeType expected) = 0; | |
180 | virtual void TooShort(const Ch* str, SizeType length, SizeType expected) = 0; | |
181 | virtual void DoesNotMatch(const Ch* str, SizeType length) = 0; | |
182 | ||
183 | virtual void DisallowedItem(SizeType index) = 0; | |
184 | virtual void TooFewItems(SizeType actualCount, SizeType expectedCount) = 0; | |
185 | virtual void TooManyItems(SizeType actualCount, SizeType expectedCount) = 0; | |
186 | virtual void DuplicateItems(SizeType index1, SizeType index2) = 0; | |
187 | ||
188 | virtual void TooManyProperties(SizeType actualCount, SizeType expectedCount) = 0; | |
189 | virtual void TooFewProperties(SizeType actualCount, SizeType expectedCount) = 0; | |
190 | virtual void StartMissingProperties() = 0; | |
191 | virtual void AddMissingProperty(const SValue& name) = 0; | |
192 | virtual bool EndMissingProperties() = 0; | |
193 | virtual void PropertyViolations(ISchemaValidator** subvalidators, SizeType count) = 0; | |
194 | virtual void DisallowedProperty(const Ch* name, SizeType length) = 0; | |
195 | ||
196 | virtual void StartDependencyErrors() = 0; | |
197 | virtual void StartMissingDependentProperties() = 0; | |
198 | virtual void AddMissingDependentProperty(const SValue& targetName) = 0; | |
199 | virtual void EndMissingDependentProperties(const SValue& sourceName) = 0; | |
200 | virtual void AddDependencySchemaError(const SValue& souceName, ISchemaValidator* subvalidator) = 0; | |
201 | virtual bool EndDependencyErrors() = 0; | |
202 | ||
203 | virtual void DisallowedValue() = 0; | |
204 | virtual void StartDisallowedType() = 0; | |
205 | virtual void AddExpectedType(const typename SchemaType::ValueType& expectedType) = 0; | |
206 | virtual void EndDisallowedType(const typename SchemaType::ValueType& actualType) = 0; | |
207 | virtual void NotAllOf(ISchemaValidator** subvalidators, SizeType count) = 0; | |
208 | virtual void NoneOf(ISchemaValidator** subvalidators, SizeType count) = 0; | |
209 | virtual void NotOneOf(ISchemaValidator** subvalidators, SizeType count) = 0; | |
210 | virtual void Disallowed() = 0; | |
211 | }; | |
212 | ||
213 | ||
214 | /////////////////////////////////////////////////////////////////////////////// | |
160 | 215 | // Hasher |
161 | 216 | |
162 | 217 | // For comparison of compound value |
260 | 315 | struct SchemaValidationContext { |
261 | 316 | typedef Schema<SchemaDocumentType> SchemaType; |
262 | 317 | typedef ISchemaStateFactory<SchemaType> SchemaValidatorFactoryType; |
318 | typedef IValidationErrorHandler<SchemaType> ErrorHandlerType; | |
263 | 319 | typedef typename SchemaType::ValueType ValueType; |
264 | 320 | typedef typename ValueType::Ch Ch; |
265 | 321 | |
269 | 325 | kPatternValidatorWithAdditionalProperty |
270 | 326 | }; |
271 | 327 | |
272 | SchemaValidationContext(SchemaValidatorFactoryType& f, const SchemaType* s) : | |
328 | SchemaValidationContext(SchemaValidatorFactoryType& f, ErrorHandlerType& eh, const SchemaType* s) : | |
273 | 329 | factory(f), |
330 | error_handler(eh), | |
274 | 331 | schema(s), |
275 | 332 | valueSchema(), |
276 | 333 | invalidKeyword(), |
310 | 367 | } |
311 | 368 | |
312 | 369 | SchemaValidatorFactoryType& factory; |
370 | ErrorHandlerType& error_handler; | |
313 | 371 | const SchemaType* schema; |
314 | 372 | const SchemaType* valueSchema; |
315 | 373 | const Ch* invalidKeyword; |
344 | 402 | typedef SchemaValidationContext<SchemaDocumentType> Context; |
345 | 403 | typedef Schema<SchemaDocumentType> SchemaType; |
346 | 404 | typedef GenericValue<EncodingType, AllocatorType> SValue; |
405 | typedef IValidationErrorHandler<Schema> ErrorHandler; | |
347 | 406 | friend class GenericSchemaDocument<ValueType, AllocatorType>; |
348 | 407 | |
349 | 408 | Schema(SchemaDocumentType* schemaDocument, const PointerType& p, const ValueType& value, const ValueType& document, AllocatorType* allocator) : |
350 | 409 | allocator_(allocator), |
410 | uri_(schemaDocument->GetURI(), *allocator), | |
411 | pointer_(p, allocator), | |
412 | typeless_(schemaDocument->GetTypeless()), | |
351 | 413 | enum_(), |
352 | 414 | enumCount_(), |
353 | 415 | not_(), |
354 | 416 | type_((1 << kTotalSchemaType) - 1), // typeless |
355 | 417 | validatorCount_(), |
418 | notValidatorIndex_(), | |
356 | 419 | properties_(), |
357 | 420 | additionalPropertiesSchema_(), |
358 | 421 | patternProperties_(), |
376 | 439 | minLength_(0), |
377 | 440 | maxLength_(~SizeType(0)), |
378 | 441 | exclusiveMinimum_(false), |
379 | exclusiveMaximum_(false) | |
442 | exclusiveMaximum_(false), | |
443 | defaultValueLength_(0) | |
380 | 444 | { |
381 | 445 | typedef typename SchemaDocumentType::ValueType ValueType; |
382 | 446 | typedef typename ValueType::ConstValueIterator ConstValueIterator; |
399 | 463 | enum_ = static_cast<uint64_t*>(allocator_->Malloc(sizeof(uint64_t) * v->Size())); |
400 | 464 | for (ConstValueIterator itr = v->Begin(); itr != v->End(); ++itr) { |
401 | 465 | typedef Hasher<EncodingType, MemoryPoolAllocator<> > EnumHasherType; |
402 | char buffer[256 + 24]; | |
466 | char buffer[256u + 24]; | |
403 | 467 | MemoryPoolAllocator<> hasherAllocator(buffer, sizeof(buffer)); |
404 | 468 | EnumHasherType h(&hasherAllocator, 256); |
405 | 469 | itr->Accept(h); |
452 | 516 | for (SizeType i = 0; i < propertyCount_; i++) { |
453 | 517 | new (&properties_[i]) Property(); |
454 | 518 | properties_[i].name = allProperties[i]; |
455 | properties_[i].schema = GetTypeless(); | |
519 | properties_[i].schema = typeless_; | |
456 | 520 | } |
457 | 521 | } |
458 | 522 | } |
571 | 635 | if (const ValueType* v = GetMember(value, GetMultipleOfString())) |
572 | 636 | if (v->IsNumber() && v->GetDouble() > 0.0) |
573 | 637 | multipleOf_.CopyFrom(*v, *allocator_); |
638 | ||
639 | // Default | |
640 | if (const ValueType* v = GetMember(value, GetDefaultValueString())) | |
641 | if (v->IsString()) | |
642 | defaultValueLength_ = v->GetStringLength(); | |
643 | ||
574 | 644 | } |
575 | 645 | |
576 | 646 | ~Schema() { |
577 | if (allocator_) { | |
578 | allocator_->Free(enum_); | |
579 | } | |
647 | AllocatorType::Free(enum_); | |
580 | 648 | if (properties_) { |
581 | 649 | for (SizeType i = 0; i < propertyCount_; i++) |
582 | 650 | properties_[i].~Property(); |
591 | 659 | #if CEREAL_RAPIDJSON_SCHEMA_HAS_REGEX |
592 | 660 | if (pattern_) { |
593 | 661 | pattern_->~RegexType(); |
594 | allocator_->Free(pattern_); | |
662 | AllocatorType::Free(pattern_); | |
595 | 663 | } |
596 | 664 | #endif |
665 | } | |
666 | ||
667 | const SValue& GetURI() const { | |
668 | return uri_; | |
669 | } | |
670 | ||
671 | const PointerType& GetPointer() const { | |
672 | return pointer_; | |
597 | 673 | } |
598 | 674 | |
599 | 675 | bool BeginValue(Context& context) const { |
609 | 685 | else if (additionalItemsSchema_) |
610 | 686 | context.valueSchema = additionalItemsSchema_; |
611 | 687 | else if (additionalItems_) |
612 | context.valueSchema = GetTypeless(); | |
613 | else | |
688 | context.valueSchema = typeless_; | |
689 | else { | |
690 | context.error_handler.DisallowedItem(context.arrayElementIndex); | |
614 | 691 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetItemsString()); |
692 | } | |
615 | 693 | } |
616 | 694 | else |
617 | context.valueSchema = GetTypeless(); | |
695 | context.valueSchema = typeless_; | |
618 | 696 | |
619 | 697 | context.arrayElementIndex++; |
620 | 698 | } |
636 | 714 | } |
637 | 715 | |
638 | 716 | if (context.objectPatternValidatorType == Context::kPatternValidatorOnly) { |
639 | if (!patternValid) | |
717 | if (!patternValid) { | |
718 | context.error_handler.PropertyViolations(context.patternPropertiesValidators, count); | |
640 | 719 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString()); |
720 | } | |
641 | 721 | } |
642 | 722 | else if (context.objectPatternValidatorType == Context::kPatternValidatorWithProperty) { |
643 | if (!patternValid || !otherValid) | |
723 | if (!patternValid || !otherValid) { | |
724 | context.error_handler.PropertyViolations(context.patternPropertiesValidators, count + 1); | |
644 | 725 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString()); |
645 | } | |
646 | else if (!patternValid && !otherValid) // kPatternValidatorWithAdditionalProperty) | |
726 | } | |
727 | } | |
728 | else if (!patternValid && !otherValid) { // kPatternValidatorWithAdditionalProperty) | |
729 | context.error_handler.PropertyViolations(context.patternPropertiesValidators, count + 1); | |
647 | 730 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString()); |
731 | } | |
648 | 732 | } |
649 | 733 | |
650 | 734 | if (enum_) { |
652 | 736 | for (SizeType i = 0; i < enumCount_; i++) |
653 | 737 | if (enum_[i] == h) |
654 | 738 | goto foundEnum; |
739 | context.error_handler.DisallowedValue(); | |
655 | 740 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetEnumString()); |
656 | 741 | foundEnum:; |
657 | 742 | } |
658 | 743 | |
659 | 744 | if (allOf_.schemas) |
660 | 745 | for (SizeType i = allOf_.begin; i < allOf_.begin + allOf_.count; i++) |
661 | if (!context.validators[i]->IsValid()) | |
746 | if (!context.validators[i]->IsValid()) { | |
747 | context.error_handler.NotAllOf(&context.validators[allOf_.begin], allOf_.count); | |
662 | 748 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetAllOfString()); |
749 | } | |
663 | 750 | |
664 | 751 | if (anyOf_.schemas) { |
665 | 752 | for (SizeType i = anyOf_.begin; i < anyOf_.begin + anyOf_.count; i++) |
666 | 753 | if (context.validators[i]->IsValid()) |
667 | 754 | goto foundAny; |
755 | context.error_handler.NoneOf(&context.validators[anyOf_.begin], anyOf_.count); | |
668 | 756 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetAnyOfString()); |
669 | 757 | foundAny:; |
670 | 758 | } |
673 | 761 | bool oneValid = false; |
674 | 762 | for (SizeType i = oneOf_.begin; i < oneOf_.begin + oneOf_.count; i++) |
675 | 763 | if (context.validators[i]->IsValid()) { |
676 | if (oneValid) | |
764 | if (oneValid) { | |
765 | context.error_handler.NotOneOf(&context.validators[oneOf_.begin], oneOf_.count); | |
677 | 766 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetOneOfString()); |
678 | else | |
767 | } else | |
679 | 768 | oneValid = true; |
680 | 769 | } |
681 | if (!oneValid) | |
770 | if (!oneValid) { | |
771 | context.error_handler.NotOneOf(&context.validators[oneOf_.begin], oneOf_.count); | |
682 | 772 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetOneOfString()); |
683 | } | |
684 | ||
685 | if (not_ && context.validators[notValidatorIndex_]->IsValid()) | |
773 | } | |
774 | } | |
775 | ||
776 | if (not_ && context.validators[notValidatorIndex_]->IsValid()) { | |
777 | context.error_handler.Disallowed(); | |
686 | 778 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetNotString()); |
779 | } | |
687 | 780 | |
688 | 781 | return true; |
689 | 782 | } |
690 | 783 | |
691 | bool Null(Context& context) const { | |
692 | if (!(type_ & (1 << kNullSchemaType))) | |
784 | bool Null(Context& context) const { | |
785 | if (!(type_ & (1 << kNullSchemaType))) { | |
786 | DisallowedType(context, GetNullString()); | |
693 | 787 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); |
788 | } | |
694 | 789 | return CreateParallelValidator(context); |
695 | 790 | } |
696 | 791 | |
697 | bool Bool(Context& context, bool) const { | |
698 | if (!(type_ & (1 << kBooleanSchemaType))) | |
792 | bool Bool(Context& context, bool) const { | |
793 | if (!(type_ & (1 << kBooleanSchemaType))) { | |
794 | DisallowedType(context, GetBooleanString()); | |
699 | 795 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); |
796 | } | |
700 | 797 | return CreateParallelValidator(context); |
701 | 798 | } |
702 | 799 | |
725 | 822 | } |
726 | 823 | |
727 | 824 | bool Double(Context& context, double d) const { |
728 | if (!(type_ & (1 << kNumberSchemaType))) | |
825 | if (!(type_ & (1 << kNumberSchemaType))) { | |
826 | DisallowedType(context, GetNumberString()); | |
729 | 827 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); |
828 | } | |
730 | 829 | |
731 | 830 | if (!minimum_.IsNull() && !CheckDoubleMinimum(context, d)) |
732 | 831 | return false; |
741 | 840 | } |
742 | 841 | |
743 | 842 | bool String(Context& context, const Ch* str, SizeType length, bool) const { |
744 | if (!(type_ & (1 << kStringSchemaType))) | |
843 | if (!(type_ & (1 << kStringSchemaType))) { | |
844 | DisallowedType(context, GetStringString()); | |
745 | 845 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); |
846 | } | |
746 | 847 | |
747 | 848 | if (minLength_ != 0 || maxLength_ != SizeType(~0)) { |
748 | 849 | SizeType count; |
749 | 850 | if (internal::CountStringCodePoint<EncodingType>(str, length, &count)) { |
750 | if (count < minLength_) | |
851 | if (count < minLength_) { | |
852 | context.error_handler.TooShort(str, length, minLength_); | |
751 | 853 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinLengthString()); |
752 | if (count > maxLength_) | |
854 | } | |
855 | if (count > maxLength_) { | |
856 | context.error_handler.TooLong(str, length, maxLength_); | |
753 | 857 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxLengthString()); |
754 | } | |
755 | } | |
756 | ||
757 | if (pattern_ && !IsPatternMatch(pattern_, str, length)) | |
858 | } | |
859 | } | |
860 | } | |
861 | ||
862 | if (pattern_ && !IsPatternMatch(pattern_, str, length)) { | |
863 | context.error_handler.DoesNotMatch(str, length); | |
758 | 864 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternString()); |
865 | } | |
759 | 866 | |
760 | 867 | return CreateParallelValidator(context); |
761 | 868 | } |
762 | 869 | |
763 | bool StartObject(Context& context) const { | |
764 | if (!(type_ & (1 << kObjectSchemaType))) | |
870 | bool StartObject(Context& context) const { | |
871 | if (!(type_ & (1 << kObjectSchemaType))) { | |
872 | DisallowedType(context, GetObjectString()); | |
765 | 873 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); |
874 | } | |
766 | 875 | |
767 | 876 | if (hasDependencies_ || hasRequired_) { |
768 | 877 | context.propertyExist = static_cast<bool*>(context.factory.MallocState(sizeof(bool) * propertyCount_)); |
783 | 892 | if (patternProperties_) { |
784 | 893 | context.patternPropertiesSchemaCount = 0; |
785 | 894 | for (SizeType i = 0; i < patternPropertyCount_; i++) |
786 | if (patternProperties_[i].pattern && IsPatternMatch(patternProperties_[i].pattern, str, len)) | |
895 | if (patternProperties_[i].pattern && IsPatternMatch(patternProperties_[i].pattern, str, len)) { | |
787 | 896 | context.patternPropertiesSchemas[context.patternPropertiesSchemaCount++] = patternProperties_[i].schema; |
897 | context.valueSchema = typeless_; | |
898 | } | |
788 | 899 | } |
789 | 900 | |
790 | 901 | SizeType index; |
791 | 902 | if (FindPropertyIndex(ValueType(str, len).Move(), &index)) { |
792 | 903 | if (context.patternPropertiesSchemaCount > 0) { |
793 | 904 | context.patternPropertiesSchemas[context.patternPropertiesSchemaCount++] = properties_[index].schema; |
794 | context.valueSchema = GetTypeless(); | |
905 | context.valueSchema = typeless_; | |
795 | 906 | context.valuePatternValidatorType = Context::kPatternValidatorWithProperty; |
796 | 907 | } |
797 | 908 | else |
806 | 917 | if (additionalPropertiesSchema_) { |
807 | 918 | if (additionalPropertiesSchema_ && context.patternPropertiesSchemaCount > 0) { |
808 | 919 | context.patternPropertiesSchemas[context.patternPropertiesSchemaCount++] = additionalPropertiesSchema_; |
809 | context.valueSchema = GetTypeless(); | |
920 | context.valueSchema = typeless_; | |
810 | 921 | context.valuePatternValidatorType = Context::kPatternValidatorWithAdditionalProperty; |
811 | 922 | } |
812 | 923 | else |
814 | 925 | return true; |
815 | 926 | } |
816 | 927 | else if (additionalProperties_) { |
817 | context.valueSchema = GetTypeless(); | |
928 | context.valueSchema = typeless_; | |
818 | 929 | return true; |
819 | 930 | } |
820 | 931 | |
821 | if (context.patternPropertiesSchemaCount == 0) // patternProperties are not additional properties | |
932 | if (context.patternPropertiesSchemaCount == 0) { // patternProperties are not additional properties | |
933 | context.error_handler.DisallowedProperty(str, len); | |
822 | 934 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetAdditionalPropertiesString()); |
935 | } | |
823 | 936 | |
824 | 937 | return true; |
825 | 938 | } |
826 | 939 | |
827 | 940 | bool EndObject(Context& context, SizeType memberCount) const { |
828 | if (hasRequired_) | |
941 | if (hasRequired_) { | |
942 | context.error_handler.StartMissingProperties(); | |
829 | 943 | for (SizeType index = 0; index < propertyCount_; index++) |
830 | if (properties_[index].required) | |
831 | if (!context.propertyExist[index]) | |
832 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetRequiredString()); | |
833 | ||
834 | if (memberCount < minProperties_) | |
944 | if (properties_[index].required && !context.propertyExist[index]) | |
945 | if (properties_[index].schema->defaultValueLength_ == 0 ) | |
946 | context.error_handler.AddMissingProperty(properties_[index].name); | |
947 | if (context.error_handler.EndMissingProperties()) | |
948 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetRequiredString()); | |
949 | } | |
950 | ||
951 | if (memberCount < minProperties_) { | |
952 | context.error_handler.TooFewProperties(memberCount, minProperties_); | |
835 | 953 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinPropertiesString()); |
836 | ||
837 | if (memberCount > maxProperties_) | |
954 | } | |
955 | ||
956 | if (memberCount > maxProperties_) { | |
957 | context.error_handler.TooManyProperties(memberCount, maxProperties_); | |
838 | 958 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxPropertiesString()); |
959 | } | |
839 | 960 | |
840 | 961 | if (hasDependencies_) { |
841 | for (SizeType sourceIndex = 0; sourceIndex < propertyCount_; sourceIndex++) | |
962 | context.error_handler.StartDependencyErrors(); | |
963 | for (SizeType sourceIndex = 0; sourceIndex < propertyCount_; sourceIndex++) { | |
964 | const Property& source = properties_[sourceIndex]; | |
842 | 965 | if (context.propertyExist[sourceIndex]) { |
843 | if (properties_[sourceIndex].dependencies) { | |
966 | if (source.dependencies) { | |
967 | context.error_handler.StartMissingDependentProperties(); | |
844 | 968 | for (SizeType targetIndex = 0; targetIndex < propertyCount_; targetIndex++) |
845 | if (properties_[sourceIndex].dependencies[targetIndex] && !context.propertyExist[targetIndex]) | |
846 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetDependenciesString()); | |
969 | if (source.dependencies[targetIndex] && !context.propertyExist[targetIndex]) | |
970 | context.error_handler.AddMissingDependentProperty(properties_[targetIndex].name); | |
971 | context.error_handler.EndMissingDependentProperties(source.name); | |
847 | 972 | } |
848 | else if (properties_[sourceIndex].dependenciesSchema) | |
849 | if (!context.validators[properties_[sourceIndex].dependenciesValidatorIndex]->IsValid()) | |
850 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetDependenciesString()); | |
973 | else if (source.dependenciesSchema) { | |
974 | ISchemaValidator* dependenciesValidator = context.validators[source.dependenciesValidatorIndex]; | |
975 | if (!dependenciesValidator->IsValid()) | |
976 | context.error_handler.AddDependencySchemaError(source.name, dependenciesValidator); | |
977 | } | |
851 | 978 | } |
979 | } | |
980 | if (context.error_handler.EndDependencyErrors()) | |
981 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetDependenciesString()); | |
852 | 982 | } |
853 | 983 | |
854 | 984 | return true; |
855 | 985 | } |
856 | 986 | |
857 | bool StartArray(Context& context) const { | |
858 | if (!(type_ & (1 << kArraySchemaType))) | |
987 | bool StartArray(Context& context) const { | |
988 | if (!(type_ & (1 << kArraySchemaType))) { | |
989 | DisallowedType(context, GetArrayString()); | |
859 | 990 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); |
991 | } | |
860 | 992 | |
861 | 993 | context.arrayElementIndex = 0; |
862 | 994 | context.inArray = true; |
864 | 996 | return CreateParallelValidator(context); |
865 | 997 | } |
866 | 998 | |
867 | bool EndArray(Context& context, SizeType elementCount) const { | |
999 | bool EndArray(Context& context, SizeType elementCount) const { | |
868 | 1000 | context.inArray = false; |
869 | 1001 | |
870 | if (elementCount < minItems_) | |
1002 | if (elementCount < minItems_) { | |
1003 | context.error_handler.TooFewItems(elementCount, minItems_); | |
871 | 1004 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinItemsString()); |
1005 | } | |
872 | 1006 | |
873 | if (elementCount > maxItems_) | |
1007 | if (elementCount > maxItems_) { | |
1008 | context.error_handler.TooManyItems(elementCount, maxItems_); | |
874 | 1009 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxItemsString()); |
1010 | } | |
875 | 1011 | |
876 | 1012 | return true; |
877 | 1013 | } |
880 | 1016 | #define CEREAL_RAPIDJSON_STRING_(name, ...) \ |
881 | 1017 | static const ValueType& Get##name##String() {\ |
882 | 1018 | static const Ch s[] = { __VA_ARGS__, '\0' };\ |
883 | static const ValueType v(s, sizeof(s) / sizeof(Ch) - 1);\ | |
1019 | static const ValueType v(s, static_cast<SizeType>(sizeof(s) / sizeof(Ch) - 1));\ | |
884 | 1020 | return v;\ |
885 | 1021 | } |
886 | 1022 | |
917 | 1053 | CEREAL_RAPIDJSON_STRING_(ExclusiveMinimum, 'e', 'x', 'c', 'l', 'u', 's', 'i', 'v', 'e', 'M', 'i', 'n', 'i', 'm', 'u', 'm') |
918 | 1054 | CEREAL_RAPIDJSON_STRING_(ExclusiveMaximum, 'e', 'x', 'c', 'l', 'u', 's', 'i', 'v', 'e', 'M', 'a', 'x', 'i', 'm', 'u', 'm') |
919 | 1055 | CEREAL_RAPIDJSON_STRING_(MultipleOf, 'm', 'u', 'l', 't', 'i', 'p', 'l', 'e', 'O', 'f') |
1056 | CEREAL_RAPIDJSON_STRING_(DefaultValue, 'd', 'e', 'f', 'a', 'u', 'l', 't') | |
920 | 1057 | |
921 | 1058 | #undef CEREAL_RAPIDJSON_STRING_ |
922 | 1059 | |
933 | 1070 | }; |
934 | 1071 | |
935 | 1072 | #if CEREAL_RAPIDJSON_SCHEMA_USE_INTERNALREGEX |
936 | typedef internal::GenericRegex<EncodingType> RegexType; | |
1073 | typedef internal::GenericRegex<EncodingType, AllocatorType> RegexType; | |
937 | 1074 | #elif CEREAL_RAPIDJSON_SCHEMA_USE_STDREGEX |
938 | 1075 | typedef std::basic_regex<Ch> RegexType; |
939 | 1076 | #else |
947 | 1084 | SizeType begin; // begin index of context.validators |
948 | 1085 | SizeType count; |
949 | 1086 | }; |
950 | ||
951 | static const SchemaType* GetTypeless() { | |
952 | static SchemaType typeless(0, PointerType(), ValueType(kObjectType).Move(), ValueType(kObjectType).Move(), 0); | |
953 | return &typeless; | |
954 | } | |
955 | 1087 | |
956 | 1088 | template <typename V1, typename V2> |
957 | 1089 | void AddUniqueElement(V1& a, const V2& v) { |
998 | 1130 | template <typename ValueType> |
999 | 1131 | RegexType* CreatePattern(const ValueType& value) { |
1000 | 1132 | if (value.IsString()) { |
1001 | RegexType* r = new (allocator_->Malloc(sizeof(RegexType))) RegexType(value.GetString()); | |
1133 | RegexType* r = new (allocator_->Malloc(sizeof(RegexType))) RegexType(value.GetString(), allocator_); | |
1002 | 1134 | if (!r->IsValid()) { |
1003 | 1135 | r->~RegexType(); |
1004 | 1136 | AllocatorType::Free(r); |
1010 | 1142 | } |
1011 | 1143 | |
1012 | 1144 | static bool IsPatternMatch(const RegexType* pattern, const Ch *str, SizeType) { |
1013 | return pattern->Search(str); | |
1145 | GenericRegexSearch<RegexType> rs(*pattern); | |
1146 | return rs.Search(str); | |
1014 | 1147 | } |
1015 | 1148 | #elif CEREAL_RAPIDJSON_SCHEMA_USE_STDREGEX |
1016 | 1149 | template <typename ValueType> |
1017 | 1150 | RegexType* CreatePattern(const ValueType& value) { |
1018 | if (value.IsString()) | |
1151 | if (value.IsString()) { | |
1152 | RegexType *r = static_cast<RegexType*>(allocator_->Malloc(sizeof(RegexType))); | |
1019 | 1153 | try { |
1020 | return new (allocator_->Malloc(sizeof(RegexType))) RegexType(value.GetString(), std::size_t(value.GetStringLength()), std::regex_constants::ECMAScript); | |
1154 | return new (r) RegexType(value.GetString(), std::size_t(value.GetStringLength()), std::regex_constants::ECMAScript); | |
1021 | 1155 | } |
1022 | 1156 | catch (const std::regex_error&) { |
1023 | } | |
1157 | AllocatorType::Free(r); | |
1158 | } | |
1159 | } | |
1024 | 1160 | return 0; |
1025 | 1161 | } |
1026 | 1162 | |
1096 | 1232 | } |
1097 | 1233 | |
1098 | 1234 | bool CheckInt(Context& context, int64_t i) const { |
1099 | if (!(type_ & ((1 << kIntegerSchemaType) | (1 << kNumberSchemaType)))) | |
1235 | if (!(type_ & ((1 << kIntegerSchemaType) | (1 << kNumberSchemaType)))) { | |
1236 | DisallowedType(context, GetIntegerString()); | |
1100 | 1237 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); |
1238 | } | |
1101 | 1239 | |
1102 | 1240 | if (!minimum_.IsNull()) { |
1103 | 1241 | if (minimum_.IsInt64()) { |
1104 | if (exclusiveMinimum_ ? i <= minimum_.GetInt64() : i < minimum_.GetInt64()) | |
1242 | if (exclusiveMinimum_ ? i <= minimum_.GetInt64() : i < minimum_.GetInt64()) { | |
1243 | context.error_handler.BelowMinimum(i, minimum_, exclusiveMinimum_); | |
1105 | 1244 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); |
1245 | } | |
1106 | 1246 | } |
1107 | 1247 | else if (minimum_.IsUint64()) { |
1248 | context.error_handler.BelowMinimum(i, minimum_, exclusiveMinimum_); | |
1108 | 1249 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); // i <= max(int64_t) < minimum.GetUint64() |
1109 | 1250 | } |
1110 | 1251 | else if (!CheckDoubleMinimum(context, static_cast<double>(i))) |
1113 | 1254 | |
1114 | 1255 | if (!maximum_.IsNull()) { |
1115 | 1256 | if (maximum_.IsInt64()) { |
1116 | if (exclusiveMaximum_ ? i >= maximum_.GetInt64() : i > maximum_.GetInt64()) | |
1257 | if (exclusiveMaximum_ ? i >= maximum_.GetInt64() : i > maximum_.GetInt64()) { | |
1258 | context.error_handler.AboveMaximum(i, maximum_, exclusiveMaximum_); | |
1117 | 1259 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); |
1118 | } | |
1119 | else if (maximum_.IsUint64()) | |
1120 | /* do nothing */; // i <= max(int64_t) < maximum_.GetUint64() | |
1260 | } | |
1261 | } | |
1262 | else if (maximum_.IsUint64()) { } | |
1263 | /* do nothing */ // i <= max(int64_t) < maximum_.GetUint64() | |
1121 | 1264 | else if (!CheckDoubleMaximum(context, static_cast<double>(i))) |
1122 | 1265 | return false; |
1123 | 1266 | } |
1124 | 1267 | |
1125 | 1268 | if (!multipleOf_.IsNull()) { |
1126 | 1269 | if (multipleOf_.IsUint64()) { |
1127 | if (static_cast<uint64_t>(i >= 0 ? i : -i) % multipleOf_.GetUint64() != 0) | |
1270 | if (static_cast<uint64_t>(i >= 0 ? i : -i) % multipleOf_.GetUint64() != 0) { | |
1271 | context.error_handler.NotMultipleOf(i, multipleOf_); | |
1128 | 1272 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString()); |
1273 | } | |
1129 | 1274 | } |
1130 | 1275 | else if (!CheckDoubleMultipleOf(context, static_cast<double>(i))) |
1131 | 1276 | return false; |
1135 | 1280 | } |
1136 | 1281 | |
1137 | 1282 | bool CheckUint(Context& context, uint64_t i) const { |
1138 | if (!(type_ & ((1 << kIntegerSchemaType) | (1 << kNumberSchemaType)))) | |
1283 | if (!(type_ & ((1 << kIntegerSchemaType) | (1 << kNumberSchemaType)))) { | |
1284 | DisallowedType(context, GetIntegerString()); | |
1139 | 1285 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); |
1286 | } | |
1140 | 1287 | |
1141 | 1288 | if (!minimum_.IsNull()) { |
1142 | 1289 | if (minimum_.IsUint64()) { |
1143 | if (exclusiveMinimum_ ? i <= minimum_.GetUint64() : i < minimum_.GetUint64()) | |
1290 | if (exclusiveMinimum_ ? i <= minimum_.GetUint64() : i < minimum_.GetUint64()) { | |
1291 | context.error_handler.BelowMinimum(i, minimum_, exclusiveMinimum_); | |
1144 | 1292 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); |
1293 | } | |
1145 | 1294 | } |
1146 | 1295 | else if (minimum_.IsInt64()) |
1147 | 1296 | /* do nothing */; // i >= 0 > minimum.Getint64() |
1151 | 1300 | |
1152 | 1301 | if (!maximum_.IsNull()) { |
1153 | 1302 | if (maximum_.IsUint64()) { |
1154 | if (exclusiveMaximum_ ? i >= maximum_.GetUint64() : i > maximum_.GetUint64()) | |
1303 | if (exclusiveMaximum_ ? i >= maximum_.GetUint64() : i > maximum_.GetUint64()) { | |
1304 | context.error_handler.AboveMaximum(i, maximum_, exclusiveMaximum_); | |
1155 | 1305 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); |
1156 | } | |
1157 | else if (maximum_.IsInt64()) | |
1306 | } | |
1307 | } | |
1308 | else if (maximum_.IsInt64()) { | |
1309 | context.error_handler.AboveMaximum(i, maximum_, exclusiveMaximum_); | |
1158 | 1310 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); // i >= 0 > maximum_ |
1311 | } | |
1159 | 1312 | else if (!CheckDoubleMaximum(context, static_cast<double>(i))) |
1160 | 1313 | return false; |
1161 | 1314 | } |
1162 | 1315 | |
1163 | 1316 | if (!multipleOf_.IsNull()) { |
1164 | 1317 | if (multipleOf_.IsUint64()) { |
1165 | if (i % multipleOf_.GetUint64() != 0) | |
1318 | if (i % multipleOf_.GetUint64() != 0) { | |
1319 | context.error_handler.NotMultipleOf(i, multipleOf_); | |
1166 | 1320 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString()); |
1321 | } | |
1167 | 1322 | } |
1168 | 1323 | else if (!CheckDoubleMultipleOf(context, static_cast<double>(i))) |
1169 | 1324 | return false; |
1173 | 1328 | } |
1174 | 1329 | |
1175 | 1330 | bool CheckDoubleMinimum(Context& context, double d) const { |
1176 | if (exclusiveMinimum_ ? d <= minimum_.GetDouble() : d < minimum_.GetDouble()) | |
1331 | if (exclusiveMinimum_ ? d <= minimum_.GetDouble() : d < minimum_.GetDouble()) { | |
1332 | context.error_handler.BelowMinimum(d, minimum_, exclusiveMinimum_); | |
1177 | 1333 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); |
1334 | } | |
1178 | 1335 | return true; |
1179 | 1336 | } |
1180 | 1337 | |
1181 | 1338 | bool CheckDoubleMaximum(Context& context, double d) const { |
1182 | if (exclusiveMaximum_ ? d >= maximum_.GetDouble() : d > maximum_.GetDouble()) | |
1339 | if (exclusiveMaximum_ ? d >= maximum_.GetDouble() : d > maximum_.GetDouble()) { | |
1340 | context.error_handler.AboveMaximum(d, maximum_, exclusiveMaximum_); | |
1183 | 1341 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); |
1342 | } | |
1184 | 1343 | return true; |
1185 | 1344 | } |
1186 | 1345 | |
1188 | 1347 | double a = std::abs(d), b = std::abs(multipleOf_.GetDouble()); |
1189 | 1348 | double q = std::floor(a / b); |
1190 | 1349 | double r = a - q * b; |
1191 | if (r > 0.0) | |
1350 | if (r > 0.0) { | |
1351 | context.error_handler.NotMultipleOf(d, multipleOf_); | |
1192 | 1352 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString()); |
1353 | } | |
1193 | 1354 | return true; |
1355 | } | |
1356 | ||
1357 | void DisallowedType(Context& context, const ValueType& actualType) const { | |
1358 | ErrorHandler& eh = context.error_handler; | |
1359 | eh.StartDisallowedType(); | |
1360 | ||
1361 | if (type_ & (1 << kNullSchemaType)) eh.AddExpectedType(GetNullString()); | |
1362 | if (type_ & (1 << kBooleanSchemaType)) eh.AddExpectedType(GetBooleanString()); | |
1363 | if (type_ & (1 << kObjectSchemaType)) eh.AddExpectedType(GetObjectString()); | |
1364 | if (type_ & (1 << kArraySchemaType)) eh.AddExpectedType(GetArrayString()); | |
1365 | if (type_ & (1 << kStringSchemaType)) eh.AddExpectedType(GetStringString()); | |
1366 | ||
1367 | if (type_ & (1 << kNumberSchemaType)) eh.AddExpectedType(GetNumberString()); | |
1368 | else if (type_ & (1 << kIntegerSchemaType)) eh.AddExpectedType(GetIntegerString()); | |
1369 | ||
1370 | eh.EndDisallowedType(actualType); | |
1194 | 1371 | } |
1195 | 1372 | |
1196 | 1373 | struct Property { |
1217 | 1394 | }; |
1218 | 1395 | |
1219 | 1396 | AllocatorType* allocator_; |
1397 | SValue uri_; | |
1398 | PointerType pointer_; | |
1399 | const SchemaType* typeless_; | |
1220 | 1400 | uint64_t* enum_; |
1221 | 1401 | SizeType enumCount_; |
1222 | 1402 | SchemaArray allOf_; |
1257 | 1437 | SValue multipleOf_; |
1258 | 1438 | bool exclusiveMinimum_; |
1259 | 1439 | bool exclusiveMaximum_; |
1440 | ||
1441 | SizeType defaultValueLength_; | |
1260 | 1442 | }; |
1261 | 1443 | |
1262 | 1444 | template<typename Stack, typename Ch> |
1266 | 1448 | char buffer[21]; |
1267 | 1449 | size_t length = static_cast<size_t>((sizeof(SizeType) == 4 ? u32toa(index, buffer) : u64toa(index, buffer)) - buffer); |
1268 | 1450 | for (size_t i = 0; i < length; i++) |
1269 | *documentStack.template Push<Ch>() = buffer[i]; | |
1451 | *documentStack.template Push<Ch>() = static_cast<Ch>(buffer[i]); | |
1270 | 1452 | } |
1271 | 1453 | }; |
1272 | 1454 | |
1325 | 1507 | typedef typename EncodingType::Ch Ch; |
1326 | 1508 | typedef internal::Schema<GenericSchemaDocument> SchemaType; |
1327 | 1509 | typedef GenericPointer<ValueType, Allocator> PointerType; |
1510 | typedef GenericValue<EncodingType, Allocator> URIType; | |
1328 | 1511 | friend class internal::Schema<GenericSchemaDocument>; |
1329 | 1512 | template <typename, typename, typename> |
1330 | 1513 | friend class GenericSchemaValidator; |
1334 | 1517 | Compile a JSON document into schema document. |
1335 | 1518 | |
1336 | 1519 | \param document A JSON document as source. |
1520 | \param uri The base URI of this schema document for purposes of violation reporting. | |
1521 | \param uriLength Length of \c name, in code points. | |
1337 | 1522 | \param remoteProvider An optional remote schema document provider for resolving remote reference. Can be null. |
1338 | 1523 | \param allocator An optional allocator instance for allocating memory. Can be null. |
1339 | 1524 | */ |
1340 | explicit GenericSchemaDocument(const ValueType& document, IRemoteSchemaDocumentProviderType* remoteProvider = 0, Allocator* allocator = 0) : | |
1525 | explicit GenericSchemaDocument(const ValueType& document, const Ch* uri = 0, SizeType uriLength = 0, | |
1526 | IRemoteSchemaDocumentProviderType* remoteProvider = 0, Allocator* allocator = 0) : | |
1341 | 1527 | remoteProvider_(remoteProvider), |
1342 | 1528 | allocator_(allocator), |
1343 | 1529 | ownAllocator_(), |
1344 | 1530 | root_(), |
1531 | typeless_(), | |
1345 | 1532 | schemaMap_(allocator, kInitialSchemaMapSize), |
1346 | 1533 | schemaRef_(allocator, kInitialSchemaRefSize) |
1347 | 1534 | { |
1348 | 1535 | if (!allocator_) |
1349 | ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator()); | |
1536 | ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator)(); | |
1537 | ||
1538 | Ch noUri[1] = {0}; | |
1539 | uri_.SetString(uri ? uri : noUri, uriLength, *allocator_); | |
1540 | ||
1541 | typeless_ = static_cast<SchemaType*>(allocator_->Malloc(sizeof(SchemaType))); | |
1542 | new (typeless_) SchemaType(this, PointerType(), ValueType(kObjectType).Move(), ValueType(kObjectType).Move(), allocator_); | |
1350 | 1543 | |
1351 | 1544 | // Generate root schema, it will call CreateSchema() to create sub-schemas, |
1352 | 1545 | // And call AddRefSchema() if there are $ref. |
1364 | 1557 | new (schemaMap_.template Push<SchemaEntry>()) SchemaEntry(refEntry->source, const_cast<SchemaType*>(s), false, allocator_); |
1365 | 1558 | } |
1366 | 1559 | } |
1560 | else if (refEntry->schema) | |
1561 | *refEntry->schema = typeless_; | |
1562 | ||
1367 | 1563 | refEntry->~SchemaRefEntry(); |
1368 | 1564 | } |
1369 | 1565 | |
1379 | 1575 | allocator_(rhs.allocator_), |
1380 | 1576 | ownAllocator_(rhs.ownAllocator_), |
1381 | 1577 | root_(rhs.root_), |
1578 | typeless_(rhs.typeless_), | |
1382 | 1579 | schemaMap_(std::move(rhs.schemaMap_)), |
1383 | schemaRef_(std::move(rhs.schemaRef_)) | |
1580 | schemaRef_(std::move(rhs.schemaRef_)), | |
1581 | uri_(std::move(rhs.uri_)) | |
1384 | 1582 | { |
1385 | 1583 | rhs.remoteProvider_ = 0; |
1386 | 1584 | rhs.allocator_ = 0; |
1387 | 1585 | rhs.ownAllocator_ = 0; |
1586 | rhs.typeless_ = 0; | |
1388 | 1587 | } |
1389 | 1588 | #endif |
1390 | 1589 | |
1393 | 1592 | while (!schemaMap_.Empty()) |
1394 | 1593 | schemaMap_.template Pop<SchemaEntry>(1)->~SchemaEntry(); |
1395 | 1594 | |
1595 | if (typeless_) { | |
1596 | typeless_->~SchemaType(); | |
1597 | Allocator::Free(typeless_); | |
1598 | } | |
1599 | ||
1396 | 1600 | CEREAL_RAPIDJSON_DELETE(ownAllocator_); |
1397 | 1601 | } |
1602 | ||
1603 | const URIType& GetURI() const { return uri_; } | |
1398 | 1604 | |
1399 | 1605 | //! Get the root schema. |
1400 | 1606 | const SchemaType& GetRoot() const { return *root_; } |
1427 | 1633 | |
1428 | 1634 | void CreateSchemaRecursive(const SchemaType** schema, const PointerType& pointer, const ValueType& v, const ValueType& document) { |
1429 | 1635 | if (schema) |
1430 | *schema = SchemaType::GetTypeless(); | |
1636 | *schema = typeless_; | |
1431 | 1637 | |
1432 | 1638 | if (v.GetType() == kObjectType) { |
1433 | 1639 | const SchemaType* s = GetSchema(pointer); |
1472 | 1678 | |
1473 | 1679 | if (i > 0) { // Remote reference, resolve immediately |
1474 | 1680 | if (remoteProvider_) { |
1475 | if (const GenericSchemaDocument* remoteDocument = remoteProvider_->GetRemoteDocument(s, i - 1)) { | |
1681 | if (const GenericSchemaDocument* remoteDocument = remoteProvider_->GetRemoteDocument(s, i)) { | |
1476 | 1682 | PointerType pointer(&s[i], len - i, allocator_); |
1477 | 1683 | if (pointer.IsValid()) { |
1478 | 1684 | if (const SchemaType* sc = remoteDocument->GetSchema(pointer)) { |
1479 | 1685 | if (schema) |
1480 | 1686 | *schema = sc; |
1687 | new (schemaMap_.template Push<SchemaEntry>()) SchemaEntry(source, const_cast<SchemaType*>(sc), false, allocator_); | |
1481 | 1688 | return true; |
1482 | 1689 | } |
1483 | 1690 | } |
1514 | 1721 | return PointerType(); |
1515 | 1722 | } |
1516 | 1723 | |
1724 | const SchemaType* GetTypeless() const { return typeless_; } | |
1725 | ||
1517 | 1726 | static const size_t kInitialSchemaMapSize = 64; |
1518 | 1727 | static const size_t kInitialSchemaRefSize = 64; |
1519 | 1728 | |
1521 | 1730 | Allocator *allocator_; |
1522 | 1731 | Allocator *ownAllocator_; |
1523 | 1732 | const SchemaType* root_; //!< Root schema. |
1733 | SchemaType* typeless_; | |
1524 | 1734 | internal::Stack<Allocator> schemaMap_; // Stores created Pointer -> Schemas |
1525 | 1735 | internal::Stack<Allocator> schemaRef_; // Stores Pointer from $ref and schema which holds the $ref |
1736 | URIType uri_; | |
1526 | 1737 | }; |
1527 | 1738 | |
1528 | 1739 | //! GenericSchemaDocument using Value type. |
1551 | 1762 | typename StateAllocator = CrtAllocator> |
1552 | 1763 | class GenericSchemaValidator : |
1553 | 1764 | public internal::ISchemaStateFactory<typename SchemaDocumentType::SchemaType>, |
1554 | public internal::ISchemaValidator | |
1765 | public internal::ISchemaValidator, | |
1766 | public internal::IValidationErrorHandler<typename SchemaDocumentType::SchemaType> | |
1555 | 1767 | { |
1556 | 1768 | public: |
1557 | 1769 | typedef typename SchemaDocumentType::SchemaType SchemaType; |
1558 | 1770 | typedef typename SchemaDocumentType::PointerType PointerType; |
1559 | 1771 | typedef typename SchemaType::EncodingType EncodingType; |
1772 | typedef typename SchemaType::SValue SValue; | |
1560 | 1773 | typedef typename EncodingType::Ch Ch; |
1774 | typedef GenericStringRef<Ch> StringRefType; | |
1775 | typedef GenericValue<EncodingType, StateAllocator> ValueType; | |
1561 | 1776 | |
1562 | 1777 | //! Constructor without output handler. |
1563 | 1778 | /*! |
1574 | 1789 | : |
1575 | 1790 | schemaDocument_(&schemaDocument), |
1576 | 1791 | root_(schemaDocument.GetRoot()), |
1577 | outputHandler_(GetNullHandler()), | |
1578 | 1792 | stateAllocator_(allocator), |
1579 | 1793 | ownStateAllocator_(0), |
1580 | 1794 | schemaStack_(allocator, schemaStackCapacity), |
1581 | 1795 | documentStack_(allocator, documentStackCapacity), |
1796 | outputHandler_(0), | |
1797 | error_(kObjectType), | |
1798 | currentError_(), | |
1799 | missingDependents_(), | |
1582 | 1800 | valid_(true) |
1583 | 1801 | #if CEREAL_RAPIDJSON_SCHEMA_VERBOSE |
1584 | 1802 | , depth_(0) |
1602 | 1820 | : |
1603 | 1821 | schemaDocument_(&schemaDocument), |
1604 | 1822 | root_(schemaDocument.GetRoot()), |
1605 | outputHandler_(outputHandler), | |
1606 | 1823 | stateAllocator_(allocator), |
1607 | 1824 | ownStateAllocator_(0), |
1608 | 1825 | schemaStack_(allocator, schemaStackCapacity), |
1609 | 1826 | documentStack_(allocator, documentStackCapacity), |
1827 | outputHandler_(&outputHandler), | |
1828 | error_(kObjectType), | |
1829 | currentError_(), | |
1830 | missingDependents_(), | |
1610 | 1831 | valid_(true) |
1611 | 1832 | #if CEREAL_RAPIDJSON_SCHEMA_VERBOSE |
1612 | 1833 | , depth_(0) |
1625 | 1846 | while (!schemaStack_.Empty()) |
1626 | 1847 | PopSchema(); |
1627 | 1848 | documentStack_.Clear(); |
1849 | error_.SetObject(); | |
1850 | currentError_.SetNull(); | |
1851 | missingDependents_.SetNull(); | |
1628 | 1852 | valid_ = true; |
1629 | 1853 | } |
1630 | 1854 | |
1632 | 1856 | // Implementation of ISchemaValidator |
1633 | 1857 | virtual bool IsValid() const { return valid_; } |
1634 | 1858 | |
1859 | //! Gets the error object. | |
1860 | ValueType& GetError() { return error_; } | |
1861 | const ValueType& GetError() const { return error_; } | |
1862 | ||
1635 | 1863 | //! Gets the JSON pointer pointed to the invalid schema. |
1636 | 1864 | PointerType GetInvalidSchemaPointer() const { |
1637 | return schemaStack_.Empty() ? PointerType() : schemaDocument_->GetPointer(&CurrentSchema()); | |
1865 | return schemaStack_.Empty() ? PointerType() : CurrentSchema().GetPointer(); | |
1638 | 1866 | } |
1639 | 1867 | |
1640 | 1868 | //! Gets the keyword of invalid schema. |
1644 | 1872 | |
1645 | 1873 | //! Gets the JSON pointer pointed to the invalid value. |
1646 | 1874 | PointerType GetInvalidDocumentPointer() const { |
1647 | return documentStack_.Empty() ? PointerType() : PointerType(documentStack_.template Bottom<Ch>(), documentStack_.GetSize() / sizeof(Ch)); | |
1648 | } | |
1875 | if (documentStack_.Empty()) { | |
1876 | return PointerType(); | |
1877 | } | |
1878 | else { | |
1879 | return PointerType(documentStack_.template Bottom<Ch>(), documentStack_.GetSize() / sizeof(Ch)); | |
1880 | } | |
1881 | } | |
1882 | ||
1883 | void NotMultipleOf(int64_t actual, const SValue& expected) { | |
1884 | AddNumberError(SchemaType::GetMultipleOfString(), ValueType(actual).Move(), expected); | |
1885 | } | |
1886 | void NotMultipleOf(uint64_t actual, const SValue& expected) { | |
1887 | AddNumberError(SchemaType::GetMultipleOfString(), ValueType(actual).Move(), expected); | |
1888 | } | |
1889 | void NotMultipleOf(double actual, const SValue& expected) { | |
1890 | AddNumberError(SchemaType::GetMultipleOfString(), ValueType(actual).Move(), expected); | |
1891 | } | |
1892 | void AboveMaximum(int64_t actual, const SValue& expected, bool exclusive) { | |
1893 | AddNumberError(SchemaType::GetMaximumString(), ValueType(actual).Move(), expected, | |
1894 | exclusive ? &SchemaType::GetExclusiveMaximumString : 0); | |
1895 | } | |
1896 | void AboveMaximum(uint64_t actual, const SValue& expected, bool exclusive) { | |
1897 | AddNumberError(SchemaType::GetMaximumString(), ValueType(actual).Move(), expected, | |
1898 | exclusive ? &SchemaType::GetExclusiveMaximumString : 0); | |
1899 | } | |
1900 | void AboveMaximum(double actual, const SValue& expected, bool exclusive) { | |
1901 | AddNumberError(SchemaType::GetMaximumString(), ValueType(actual).Move(), expected, | |
1902 | exclusive ? &SchemaType::GetExclusiveMaximumString : 0); | |
1903 | } | |
1904 | void BelowMinimum(int64_t actual, const SValue& expected, bool exclusive) { | |
1905 | AddNumberError(SchemaType::GetMinimumString(), ValueType(actual).Move(), expected, | |
1906 | exclusive ? &SchemaType::GetExclusiveMinimumString : 0); | |
1907 | } | |
1908 | void BelowMinimum(uint64_t actual, const SValue& expected, bool exclusive) { | |
1909 | AddNumberError(SchemaType::GetMinimumString(), ValueType(actual).Move(), expected, | |
1910 | exclusive ? &SchemaType::GetExclusiveMinimumString : 0); | |
1911 | } | |
1912 | void BelowMinimum(double actual, const SValue& expected, bool exclusive) { | |
1913 | AddNumberError(SchemaType::GetMinimumString(), ValueType(actual).Move(), expected, | |
1914 | exclusive ? &SchemaType::GetExclusiveMinimumString : 0); | |
1915 | } | |
1916 | ||
1917 | void TooLong(const Ch* str, SizeType length, SizeType expected) { | |
1918 | AddNumberError(SchemaType::GetMaxLengthString(), | |
1919 | ValueType(str, length, GetStateAllocator()).Move(), SValue(expected).Move()); | |
1920 | } | |
1921 | void TooShort(const Ch* str, SizeType length, SizeType expected) { | |
1922 | AddNumberError(SchemaType::GetMinLengthString(), | |
1923 | ValueType(str, length, GetStateAllocator()).Move(), SValue(expected).Move()); | |
1924 | } | |
1925 | void DoesNotMatch(const Ch* str, SizeType length) { | |
1926 | currentError_.SetObject(); | |
1927 | currentError_.AddMember(GetActualString(), ValueType(str, length, GetStateAllocator()).Move(), GetStateAllocator()); | |
1928 | AddCurrentError(SchemaType::GetPatternString()); | |
1929 | } | |
1930 | ||
1931 | void DisallowedItem(SizeType index) { | |
1932 | currentError_.SetObject(); | |
1933 | currentError_.AddMember(GetDisallowedString(), ValueType(index).Move(), GetStateAllocator()); | |
1934 | AddCurrentError(SchemaType::GetAdditionalItemsString(), true); | |
1935 | } | |
1936 | void TooFewItems(SizeType actualCount, SizeType expectedCount) { | |
1937 | AddNumberError(SchemaType::GetMinItemsString(), | |
1938 | ValueType(actualCount).Move(), SValue(expectedCount).Move()); | |
1939 | } | |
1940 | void TooManyItems(SizeType actualCount, SizeType expectedCount) { | |
1941 | AddNumberError(SchemaType::GetMaxItemsString(), | |
1942 | ValueType(actualCount).Move(), SValue(expectedCount).Move()); | |
1943 | } | |
1944 | void DuplicateItems(SizeType index1, SizeType index2) { | |
1945 | ValueType duplicates(kArrayType); | |
1946 | duplicates.PushBack(index1, GetStateAllocator()); | |
1947 | duplicates.PushBack(index2, GetStateAllocator()); | |
1948 | currentError_.SetObject(); | |
1949 | currentError_.AddMember(GetDuplicatesString(), duplicates, GetStateAllocator()); | |
1950 | AddCurrentError(SchemaType::GetUniqueItemsString(), true); | |
1951 | } | |
1952 | ||
1953 | void TooManyProperties(SizeType actualCount, SizeType expectedCount) { | |
1954 | AddNumberError(SchemaType::GetMaxPropertiesString(), | |
1955 | ValueType(actualCount).Move(), SValue(expectedCount).Move()); | |
1956 | } | |
1957 | void TooFewProperties(SizeType actualCount, SizeType expectedCount) { | |
1958 | AddNumberError(SchemaType::GetMinPropertiesString(), | |
1959 | ValueType(actualCount).Move(), SValue(expectedCount).Move()); | |
1960 | } | |
1961 | void StartMissingProperties() { | |
1962 | currentError_.SetArray(); | |
1963 | } | |
1964 | void AddMissingProperty(const SValue& name) { | |
1965 | currentError_.PushBack(ValueType(name, GetStateAllocator()).Move(), GetStateAllocator()); | |
1966 | } | |
1967 | bool EndMissingProperties() { | |
1968 | if (currentError_.Empty()) | |
1969 | return false; | |
1970 | ValueType error(kObjectType); | |
1971 | error.AddMember(GetMissingString(), currentError_, GetStateAllocator()); | |
1972 | currentError_ = error; | |
1973 | AddCurrentError(SchemaType::GetRequiredString()); | |
1974 | return true; | |
1975 | } | |
1976 | void PropertyViolations(ISchemaValidator** subvalidators, SizeType count) { | |
1977 | for (SizeType i = 0; i < count; ++i) | |
1978 | MergeError(static_cast<GenericSchemaValidator*>(subvalidators[i])->GetError()); | |
1979 | } | |
1980 | void DisallowedProperty(const Ch* name, SizeType length) { | |
1981 | currentError_.SetObject(); | |
1982 | currentError_.AddMember(GetDisallowedString(), ValueType(name, length, GetStateAllocator()).Move(), GetStateAllocator()); | |
1983 | AddCurrentError(SchemaType::GetAdditionalPropertiesString(), true); | |
1984 | } | |
1985 | ||
1986 | void StartDependencyErrors() { | |
1987 | currentError_.SetObject(); | |
1988 | } | |
1989 | void StartMissingDependentProperties() { | |
1990 | missingDependents_.SetArray(); | |
1991 | } | |
1992 | void AddMissingDependentProperty(const SValue& targetName) { | |
1993 | missingDependents_.PushBack(ValueType(targetName, GetStateAllocator()).Move(), GetStateAllocator()); | |
1994 | } | |
1995 | void EndMissingDependentProperties(const SValue& sourceName) { | |
1996 | if (!missingDependents_.Empty()) | |
1997 | currentError_.AddMember(ValueType(sourceName, GetStateAllocator()).Move(), | |
1998 | missingDependents_, GetStateAllocator()); | |
1999 | } | |
2000 | void AddDependencySchemaError(const SValue& sourceName, ISchemaValidator* subvalidator) { | |
2001 | currentError_.AddMember(ValueType(sourceName, GetStateAllocator()).Move(), | |
2002 | static_cast<GenericSchemaValidator*>(subvalidator)->GetError(), GetStateAllocator()); | |
2003 | } | |
2004 | bool EndDependencyErrors() { | |
2005 | if (currentError_.ObjectEmpty()) | |
2006 | return false; | |
2007 | ValueType error(kObjectType); | |
2008 | error.AddMember(GetErrorsString(), currentError_, GetStateAllocator()); | |
2009 | currentError_ = error; | |
2010 | AddCurrentError(SchemaType::GetDependenciesString()); | |
2011 | return true; | |
2012 | } | |
2013 | ||
2014 | void DisallowedValue() { | |
2015 | currentError_.SetObject(); | |
2016 | AddCurrentError(SchemaType::GetEnumString()); | |
2017 | } | |
2018 | void StartDisallowedType() { | |
2019 | currentError_.SetArray(); | |
2020 | } | |
2021 | void AddExpectedType(const typename SchemaType::ValueType& expectedType) { | |
2022 | currentError_.PushBack(ValueType(expectedType, GetStateAllocator()).Move(), GetStateAllocator()); | |
2023 | } | |
2024 | void EndDisallowedType(const typename SchemaType::ValueType& actualType) { | |
2025 | ValueType error(kObjectType); | |
2026 | error.AddMember(GetExpectedString(), currentError_, GetStateAllocator()); | |
2027 | error.AddMember(GetActualString(), ValueType(actualType, GetStateAllocator()).Move(), GetStateAllocator()); | |
2028 | currentError_ = error; | |
2029 | AddCurrentError(SchemaType::GetTypeString()); | |
2030 | } | |
2031 | void NotAllOf(ISchemaValidator** subvalidators, SizeType count) { | |
2032 | for (SizeType i = 0; i < count; ++i) { | |
2033 | MergeError(static_cast<GenericSchemaValidator*>(subvalidators[i])->GetError()); | |
2034 | } | |
2035 | } | |
2036 | void NoneOf(ISchemaValidator** subvalidators, SizeType count) { | |
2037 | AddErrorArray(SchemaType::GetAnyOfString(), subvalidators, count); | |
2038 | } | |
2039 | void NotOneOf(ISchemaValidator** subvalidators, SizeType count) { | |
2040 | AddErrorArray(SchemaType::GetOneOfString(), subvalidators, count); | |
2041 | } | |
2042 | void Disallowed() { | |
2043 | currentError_.SetObject(); | |
2044 | AddCurrentError(SchemaType::GetNotString()); | |
2045 | } | |
2046 | ||
2047 | #define CEREAL_RAPIDJSON_STRING_(name, ...) \ | |
2048 | static const StringRefType& Get##name##String() {\ | |
2049 | static const Ch s[] = { __VA_ARGS__, '\0' };\ | |
2050 | static const StringRefType v(s, static_cast<SizeType>(sizeof(s) / sizeof(Ch) - 1)); \ | |
2051 | return v;\ | |
2052 | } | |
2053 | ||
2054 | CEREAL_RAPIDJSON_STRING_(InstanceRef, 'i', 'n', 's', 't', 'a', 'n', 'c', 'e', 'R', 'e', 'f') | |
2055 | CEREAL_RAPIDJSON_STRING_(SchemaRef, 's', 'c', 'h', 'e', 'm', 'a', 'R', 'e', 'f') | |
2056 | CEREAL_RAPIDJSON_STRING_(Expected, 'e', 'x', 'p', 'e', 'c', 't', 'e', 'd') | |
2057 | CEREAL_RAPIDJSON_STRING_(Actual, 'a', 'c', 't', 'u', 'a', 'l') | |
2058 | CEREAL_RAPIDJSON_STRING_(Disallowed, 'd', 'i', 's', 'a', 'l', 'l', 'o', 'w', 'e', 'd') | |
2059 | CEREAL_RAPIDJSON_STRING_(Missing, 'm', 'i', 's', 's', 'i', 'n', 'g') | |
2060 | CEREAL_RAPIDJSON_STRING_(Errors, 'e', 'r', 'r', 'o', 'r', 's') | |
2061 | CEREAL_RAPIDJSON_STRING_(Duplicates, 'd', 'u', 'p', 'l', 'i', 'c', 'a', 't', 'e', 's') | |
2062 | ||
2063 | #undef CEREAL_RAPIDJSON_STRING_ | |
1649 | 2064 | |
1650 | 2065 | #if CEREAL_RAPIDJSON_SCHEMA_VERBOSE |
1651 | 2066 | #define CEREAL_RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_() \ |
1678 | 2093 | } |
1679 | 2094 | |
1680 | 2095 | #define CEREAL_RAPIDJSON_SCHEMA_HANDLE_END_(method, arg2)\ |
1681 | return valid_ = EndValue() && outputHandler_.method arg2 | |
2096 | return valid_ = EndValue() && (!outputHandler_ || outputHandler_->method arg2) | |
1682 | 2097 | |
1683 | 2098 | #define CEREAL_RAPIDJSON_SCHEMA_HANDLE_VALUE_(method, arg1, arg2) \ |
1684 | 2099 | CEREAL_RAPIDJSON_SCHEMA_HANDLE_BEGIN_ (method, arg1);\ |
1685 | 2100 | CEREAL_RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(method, arg2);\ |
1686 | 2101 | CEREAL_RAPIDJSON_SCHEMA_HANDLE_END_ (method, arg2) |
1687 | 2102 | |
1688 | bool Null() { CEREAL_RAPIDJSON_SCHEMA_HANDLE_VALUE_(Null, (CurrentContext() ), ( )); } | |
2103 | bool Null() { CEREAL_RAPIDJSON_SCHEMA_HANDLE_VALUE_(Null, (CurrentContext()), ( )); } | |
1689 | 2104 | bool Bool(bool b) { CEREAL_RAPIDJSON_SCHEMA_HANDLE_VALUE_(Bool, (CurrentContext(), b), (b)); } |
1690 | 2105 | bool Int(int i) { CEREAL_RAPIDJSON_SCHEMA_HANDLE_VALUE_(Int, (CurrentContext(), i), (i)); } |
1691 | 2106 | bool Uint(unsigned u) { CEREAL_RAPIDJSON_SCHEMA_HANDLE_VALUE_(Uint, (CurrentContext(), u), (u)); } |
1700 | 2115 | bool StartObject() { |
1701 | 2116 | CEREAL_RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartObject, (CurrentContext())); |
1702 | 2117 | CEREAL_RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(StartObject, ()); |
1703 | return valid_ = outputHandler_.StartObject(); | |
2118 | return valid_ = !outputHandler_ || outputHandler_->StartObject(); | |
1704 | 2119 | } |
1705 | 2120 | |
1706 | 2121 | bool Key(const Ch* str, SizeType len, bool copy) { |
1708 | 2123 | AppendToken(str, len); |
1709 | 2124 | if (!CurrentSchema().Key(CurrentContext(), str, len, copy)) return valid_ = false; |
1710 | 2125 | CEREAL_RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(Key, (str, len, copy)); |
1711 | return valid_ = outputHandler_.Key(str, len, copy); | |
2126 | return valid_ = !outputHandler_ || outputHandler_->Key(str, len, copy); | |
1712 | 2127 | } |
1713 | 2128 | |
1714 | 2129 | bool EndObject(SizeType memberCount) { |
1721 | 2136 | bool StartArray() { |
1722 | 2137 | CEREAL_RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartArray, (CurrentContext())); |
1723 | 2138 | CEREAL_RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(StartArray, ()); |
1724 | return valid_ = outputHandler_.StartArray(); | |
2139 | return valid_ = !outputHandler_ || outputHandler_->StartArray(); | |
1725 | 2140 | } |
1726 | 2141 | |
1727 | 2142 | bool EndArray(SizeType elementCount) { |
1738 | 2153 | |
1739 | 2154 | // Implementation of ISchemaStateFactory<SchemaType> |
1740 | 2155 | virtual ISchemaValidator* CreateSchemaValidator(const SchemaType& root) { |
1741 | return new (GetStateAllocator().Malloc(sizeof(GenericSchemaValidator))) GenericSchemaValidator(*schemaDocument_, root, | |
2156 | return new (GetStateAllocator().Malloc(sizeof(GenericSchemaValidator))) GenericSchemaValidator(*schemaDocument_, root, documentStack_.template Bottom<char>(), documentStack_.GetSize(), | |
1742 | 2157 | #if CEREAL_RAPIDJSON_SCHEMA_VERBOSE |
1743 | 2158 | depth_ + 1, |
1744 | 2159 | #endif |
1770 | 2185 | } |
1771 | 2186 | |
1772 | 2187 | virtual void FreeState(void* p) { |
1773 | return StateAllocator::Free(p); | |
2188 | StateAllocator::Free(p); | |
1774 | 2189 | } |
1775 | 2190 | |
1776 | 2191 | private: |
1781 | 2196 | GenericSchemaValidator( |
1782 | 2197 | const SchemaDocumentType& schemaDocument, |
1783 | 2198 | const SchemaType& root, |
2199 | const char* basePath, size_t basePathSize, | |
1784 | 2200 | #if CEREAL_RAPIDJSON_SCHEMA_VERBOSE |
1785 | 2201 | unsigned depth, |
1786 | 2202 | #endif |
1790 | 2206 | : |
1791 | 2207 | schemaDocument_(&schemaDocument), |
1792 | 2208 | root_(root), |
1793 | outputHandler_(GetNullHandler()), | |
1794 | 2209 | stateAllocator_(allocator), |
1795 | 2210 | ownStateAllocator_(0), |
1796 | 2211 | schemaStack_(allocator, schemaStackCapacity), |
1797 | 2212 | documentStack_(allocator, documentStackCapacity), |
2213 | outputHandler_(0), | |
2214 | error_(kObjectType), | |
2215 | currentError_(), | |
2216 | missingDependents_(), | |
1798 | 2217 | valid_(true) |
1799 | 2218 | #if CEREAL_RAPIDJSON_SCHEMA_VERBOSE |
1800 | 2219 | , depth_(depth) |
1801 | 2220 | #endif |
1802 | 2221 | { |
2222 | if (basePath && basePathSize) | |
2223 | memcpy(documentStack_.template Push<char>(basePathSize), basePath, basePathSize); | |
1803 | 2224 | } |
1804 | 2225 | |
1805 | 2226 | StateAllocator& GetStateAllocator() { |
1806 | 2227 | if (!stateAllocator_) |
1807 | stateAllocator_ = ownStateAllocator_ = CEREAL_RAPIDJSON_NEW(StateAllocator()); | |
2228 | stateAllocator_ = ownStateAllocator_ = CEREAL_RAPIDJSON_NEW(StateAllocator)(); | |
1808 | 2229 | return *stateAllocator_; |
1809 | 2230 | } |
1810 | 2231 | |
1822 | 2243 | const SchemaType** sa = CurrentContext().patternPropertiesSchemas; |
1823 | 2244 | typename Context::PatternValidatorType patternValidatorType = CurrentContext().valuePatternValidatorType; |
1824 | 2245 | bool valueUniqueness = CurrentContext().valueUniqueness; |
1825 | if (CurrentContext().valueSchema) | |
1826 | PushSchema(*CurrentContext().valueSchema); | |
2246 | CEREAL_RAPIDJSON_ASSERT(CurrentContext().valueSchema); | |
2247 | PushSchema(*CurrentContext().valueSchema); | |
1827 | 2248 | |
1828 | 2249 | if (count > 0) { |
1829 | 2250 | CurrentContext().objectPatternValidatorType = patternValidatorType; |
1863 | 2284 | if (!a) |
1864 | 2285 | CurrentContext().arrayElementHashCodes = a = new (GetStateAllocator().Malloc(sizeof(HashCodeArray))) HashCodeArray(kArrayType); |
1865 | 2286 | for (typename HashCodeArray::ConstValueIterator itr = a->Begin(); itr != a->End(); ++itr) |
1866 | if (itr->GetUint64() == h) | |
2287 | if (itr->GetUint64() == h) { | |
2288 | DuplicateItems(static_cast<SizeType>(itr - a->Begin()), a->Size()); | |
1867 | 2289 | CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(SchemaType::GetUniqueItemsString()); |
2290 | } | |
1868 | 2291 | a->PushBack(h, GetStateAllocator()); |
1869 | 2292 | } |
1870 | 2293 | } |
1893 | 2316 | } |
1894 | 2317 | } |
1895 | 2318 | |
1896 | CEREAL_RAPIDJSON_FORCEINLINE void PushSchema(const SchemaType& schema) { new (schemaStack_.template Push<Context>()) Context(*this, &schema); } | |
2319 | CEREAL_RAPIDJSON_FORCEINLINE void PushSchema(const SchemaType& schema) { new (schemaStack_.template Push<Context>()) Context(*this, *this, &schema); } | |
1897 | 2320 | |
1898 | 2321 | CEREAL_RAPIDJSON_FORCEINLINE void PopSchema() { |
1899 | 2322 | Context* c = schemaStack_.template Pop<Context>(1); |
1904 | 2327 | c->~Context(); |
1905 | 2328 | } |
1906 | 2329 | |
2330 | void AddErrorLocation(ValueType& result, bool parent) { | |
2331 | GenericStringBuffer<EncodingType> sb; | |
2332 | PointerType instancePointer = GetInvalidDocumentPointer(); | |
2333 | ((parent && instancePointer.GetTokenCount() > 0) | |
2334 | ? PointerType(instancePointer.GetTokens(), instancePointer.GetTokenCount() - 1) | |
2335 | : instancePointer).StringifyUriFragment(sb); | |
2336 | ValueType instanceRef(sb.GetString(), static_cast<SizeType>(sb.GetSize() / sizeof(Ch)), | |
2337 | GetStateAllocator()); | |
2338 | result.AddMember(GetInstanceRefString(), instanceRef, GetStateAllocator()); | |
2339 | sb.Clear(); | |
2340 | memcpy(sb.Push(CurrentSchema().GetURI().GetStringLength()), | |
2341 | CurrentSchema().GetURI().GetString(), | |
2342 | CurrentSchema().GetURI().GetStringLength() * sizeof(Ch)); | |
2343 | GetInvalidSchemaPointer().StringifyUriFragment(sb); | |
2344 | ValueType schemaRef(sb.GetString(), static_cast<SizeType>(sb.GetSize() / sizeof(Ch)), | |
2345 | GetStateAllocator()); | |
2346 | result.AddMember(GetSchemaRefString(), schemaRef, GetStateAllocator()); | |
2347 | } | |
2348 | ||
2349 | void AddError(ValueType& keyword, ValueType& error) { | |
2350 | typename ValueType::MemberIterator member = error_.FindMember(keyword); | |
2351 | if (member == error_.MemberEnd()) | |
2352 | error_.AddMember(keyword, error, GetStateAllocator()); | |
2353 | else { | |
2354 | if (member->value.IsObject()) { | |
2355 | ValueType errors(kArrayType); | |
2356 | errors.PushBack(member->value, GetStateAllocator()); | |
2357 | member->value = errors; | |
2358 | } | |
2359 | member->value.PushBack(error, GetStateAllocator()); | |
2360 | } | |
2361 | } | |
2362 | ||
2363 | void AddCurrentError(const typename SchemaType::ValueType& keyword, bool parent = false) { | |
2364 | AddErrorLocation(currentError_, parent); | |
2365 | AddError(ValueType(keyword, GetStateAllocator(), false).Move(), currentError_); | |
2366 | } | |
2367 | ||
2368 | void MergeError(ValueType& other) { | |
2369 | for (typename ValueType::MemberIterator it = other.MemberBegin(), end = other.MemberEnd(); it != end; ++it) { | |
2370 | AddError(it->name, it->value); | |
2371 | } | |
2372 | } | |
2373 | ||
2374 | void AddNumberError(const typename SchemaType::ValueType& keyword, ValueType& actual, const SValue& expected, | |
2375 | const typename SchemaType::ValueType& (*exclusive)() = 0) { | |
2376 | currentError_.SetObject(); | |
2377 | currentError_.AddMember(GetActualString(), actual, GetStateAllocator()); | |
2378 | currentError_.AddMember(GetExpectedString(), ValueType(expected, GetStateAllocator()).Move(), GetStateAllocator()); | |
2379 | if (exclusive) | |
2380 | currentError_.AddMember(ValueType(exclusive(), GetStateAllocator()).Move(), true, GetStateAllocator()); | |
2381 | AddCurrentError(keyword); | |
2382 | } | |
2383 | ||
2384 | void AddErrorArray(const typename SchemaType::ValueType& keyword, | |
2385 | ISchemaValidator** subvalidators, SizeType count) { | |
2386 | ValueType errors(kArrayType); | |
2387 | for (SizeType i = 0; i < count; ++i) | |
2388 | errors.PushBack(static_cast<GenericSchemaValidator*>(subvalidators[i])->GetError(), GetStateAllocator()); | |
2389 | currentError_.SetObject(); | |
2390 | currentError_.AddMember(GetErrorsString(), errors, GetStateAllocator()); | |
2391 | AddCurrentError(keyword); | |
2392 | } | |
2393 | ||
1907 | 2394 | const SchemaType& CurrentSchema() const { return *schemaStack_.template Top<Context>()->schema; } |
1908 | 2395 | Context& CurrentContext() { return *schemaStack_.template Top<Context>(); } |
1909 | 2396 | const Context& CurrentContext() const { return *schemaStack_.template Top<Context>(); } |
1910 | ||
1911 | static OutputHandler& GetNullHandler() { | |
1912 | static OutputHandler nullHandler; | |
1913 | return nullHandler; | |
1914 | } | |
1915 | 2397 | |
1916 | 2398 | static const size_t kDefaultSchemaStackCapacity = 1024; |
1917 | 2399 | static const size_t kDefaultDocumentStackCapacity = 256; |
1918 | 2400 | const SchemaDocumentType* schemaDocument_; |
1919 | 2401 | const SchemaType& root_; |
1920 | OutputHandler& outputHandler_; | |
1921 | 2402 | StateAllocator* stateAllocator_; |
1922 | 2403 | StateAllocator* ownStateAllocator_; |
1923 | 2404 | internal::Stack<StateAllocator> schemaStack_; //!< stack to store the current path of schema (BaseSchemaType *) |
1924 | 2405 | internal::Stack<StateAllocator> documentStack_; //!< stack to store the current path of validating document (Ch) |
2406 | OutputHandler* outputHandler_; | |
2407 | ValueType error_; | |
2408 | ValueType currentError_; | |
2409 | ValueType missingDependents_; | |
1925 | 2410 | bool valid_; |
1926 | 2411 | #if CEREAL_RAPIDJSON_SCHEMA_VERBOSE |
1927 | 2412 | unsigned depth_; |
1953 | 2438 | public: |
1954 | 2439 | typedef typename SchemaDocumentType::PointerType PointerType; |
1955 | 2440 | typedef typename InputStream::Ch Ch; |
2441 | typedef GenericValue<SourceEncoding, StackAllocator> ValueType; | |
1956 | 2442 | |
1957 | 2443 | //! Constructor |
1958 | 2444 | /*! |
1959 | 2445 | \param is Input stream. |
1960 | 2446 | \param sd Schema document. |
1961 | 2447 | */ |
1962 | SchemaValidatingReader(InputStream& is, const SchemaDocumentType& sd) : is_(is), sd_(sd), invalidSchemaKeyword_(), isValid_(true) {} | |
2448 | SchemaValidatingReader(InputStream& is, const SchemaDocumentType& sd) : is_(is), sd_(sd), invalidSchemaKeyword_(), error_(kObjectType), isValid_(true) {} | |
1963 | 2449 | |
1964 | 2450 | template <typename Handler> |
1965 | 2451 | bool operator()(Handler& handler) { |
1972 | 2458 | invalidSchemaPointer_ = PointerType(); |
1973 | 2459 | invalidSchemaKeyword_ = 0; |
1974 | 2460 | invalidDocumentPointer_ = PointerType(); |
2461 | error_.SetObject(); | |
1975 | 2462 | } |
1976 | 2463 | else { |
1977 | 2464 | invalidSchemaPointer_ = validator.GetInvalidSchemaPointer(); |
1978 | 2465 | invalidSchemaKeyword_ = validator.GetInvalidSchemaKeyword(); |
1979 | 2466 | invalidDocumentPointer_ = validator.GetInvalidDocumentPointer(); |
2467 | error_.CopyFrom(validator.GetError(), allocator_); | |
1980 | 2468 | } |
1981 | 2469 | |
1982 | 2470 | return parseResult_; |
1987 | 2475 | const PointerType& GetInvalidSchemaPointer() const { return invalidSchemaPointer_; } |
1988 | 2476 | const Ch* GetInvalidSchemaKeyword() const { return invalidSchemaKeyword_; } |
1989 | 2477 | const PointerType& GetInvalidDocumentPointer() const { return invalidDocumentPointer_; } |
2478 | const ValueType& GetError() const { return error_; } | |
1990 | 2479 | |
1991 | 2480 | private: |
1992 | 2481 | InputStream& is_; |
1996 | 2485 | PointerType invalidSchemaPointer_; |
1997 | 2486 | const Ch* invalidSchemaKeyword_; |
1998 | 2487 | PointerType invalidDocumentPointer_; |
2488 | StackAllocator allocator_; | |
2489 | ValueType error_; | |
1999 | 2490 | bool isValid_; |
2000 | 2491 | }; |
2001 | 2492 |
0 | 0 | // Tencent is pleased to support the open source community by making RapidJSON available. |
1 | // | |
1 | // | |
2 | 2 | // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. |
3 | 3 | // |
4 | 4 | // Licensed under the MIT License (the "License"); you may not use this file except |
6 | 6 | // |
7 | 7 | // http://opensource.org/licenses/MIT |
8 | 8 | // |
9 | // Unless required by applicable law or agreed to in writing, software distributed | |
10 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR | |
11 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the | |
9 | // Unless required by applicable law or agreed to in writing, software distributed | |
10 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR | |
11 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the | |
12 | 12 | // specific language governing permissions and limitations under the License. |
13 | 13 | |
14 | 14 | #include "rapidjson.h" |
100 | 100 | } |
101 | 101 | |
102 | 102 | /////////////////////////////////////////////////////////////////////////////// |
103 | // GenericStreamWrapper | |
104 | ||
105 | //! A Stream Wrapper | |
106 | /*! \tThis string stream is a wrapper for any stream by just forwarding any | |
107 | \treceived message to the origin stream. | |
108 | \note implements Stream concept | |
109 | */ | |
110 | ||
111 | #if defined(_MSC_VER) && _MSC_VER <= 1800 | |
112 | CEREAL_RAPIDJSON_DIAG_PUSH | |
113 | CEREAL_RAPIDJSON_DIAG_OFF(4702) // unreachable code | |
114 | CEREAL_RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated | |
115 | #endif | |
116 | ||
117 | template <typename InputStream, typename Encoding = UTF8<> > | |
118 | class GenericStreamWrapper { | |
119 | public: | |
120 | typedef typename Encoding::Ch Ch; | |
121 | GenericStreamWrapper(InputStream& is): is_(is) {} | |
122 | ||
123 | Ch Peek() const { return is_.Peek(); } | |
124 | Ch Take() { return is_.Take(); } | |
125 | size_t Tell() { return is_.Tell(); } | |
126 | Ch* PutBegin() { return is_.PutBegin(); } | |
127 | void Put(Ch ch) { is_.Put(ch); } | |
128 | void Flush() { is_.Flush(); } | |
129 | size_t PutEnd(Ch* ch) { return is_.PutEnd(ch); } | |
130 | ||
131 | // wrapper for MemoryStream | |
132 | const Ch* Peek4() const { return is_.Peek4(); } | |
133 | ||
134 | // wrapper for AutoUTFInputStream | |
135 | UTFType GetType() const { return is_.GetType(); } | |
136 | bool HasBOM() const { return is_.HasBOM(); } | |
137 | ||
138 | protected: | |
139 | InputStream& is_; | |
140 | }; | |
141 | ||
142 | #if defined(_MSC_VER) && _MSC_VER <= 1800 | |
143 | CEREAL_RAPIDJSON_DIAG_POP | |
144 | #endif | |
145 | ||
146 | /////////////////////////////////////////////////////////////////////////////// | |
103 | 147 | // StringStream |
104 | 148 | |
105 | 149 | //! Read-only string stream. |
77 | 77 | return stack_.template Bottom<Ch>(); |
78 | 78 | } |
79 | 79 | |
80 | //! Get the size of string in bytes in the string buffer. | |
80 | 81 | size_t GetSize() const { return stack_.GetSize(); } |
82 | ||
83 | //! Get the length of string in Ch in the string buffer. | |
84 | size_t GetLength() const { return stack_.GetSize() / sizeof(Ch); } | |
81 | 85 | |
82 | 86 | static const size_t kDefaultCapacity = 256; |
83 | 87 | mutable internal::Stack<Allocator> stack_; |
15 | 15 | #define CEREAL_RAPIDJSON_WRITER_H_ |
16 | 16 | |
17 | 17 | #include "stream.h" |
18 | #include "internal/meta.h" | |
18 | 19 | #include "internal/stack.h" |
19 | 20 | #include "internal/strfunc.h" |
20 | 21 | #include "internal/dtoa.h" |
30 | 31 | #include <nmmintrin.h> |
31 | 32 | #elif defined(CEREAL_RAPIDJSON_SSE2) |
32 | 33 | #include <emmintrin.h> |
33 | #endif | |
34 | ||
35 | #ifdef _MSC_VER | |
36 | CEREAL_RAPIDJSON_DIAG_PUSH | |
37 | CEREAL_RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant | |
34 | #elif defined(CEREAL_RAPIDJSON_NEON) | |
35 | #include <arm_neon.h> | |
38 | 36 | #endif |
39 | 37 | |
40 | 38 | #ifdef __clang__ |
41 | 39 | CEREAL_RAPIDJSON_DIAG_PUSH |
42 | 40 | CEREAL_RAPIDJSON_DIAG_OFF(padded) |
43 | 41 | CEREAL_RAPIDJSON_DIAG_OFF(unreachable-code) |
42 | CEREAL_RAPIDJSON_DIAG_OFF(c++98-compat) | |
43 | #elif defined(_MSC_VER) | |
44 | CEREAL_RAPIDJSON_DIAG_PUSH | |
45 | CEREAL_RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant | |
44 | 46 | #endif |
45 | 47 | |
46 | 48 | CEREAL_RAPIDJSON_NAMESPACE_BEGIN |
62 | 64 | enum WriteFlag { |
63 | 65 | kWriteNoFlags = 0, //!< No flags are set. |
64 | 66 | kWriteValidateEncodingFlag = 1, //!< Validate encoding of JSON strings. |
65 | kWriteNanAndInfFlag = 2, //!< Allow writing of Inf, -Inf and NaN. | |
67 | kWriteNanAndInfFlag = 2, //!< Allow writing of Infinity, -Infinity and NaN. | |
66 | 68 | kWriteDefaultFlags = CEREAL_RAPIDJSON_WRITE_DEFAULT_FLAGS //!< Default write flags. Can be customized by defining CEREAL_RAPIDJSON_WRITE_DEFAULT_FLAGS |
67 | 69 | }; |
68 | 70 | |
102 | 104 | Writer(StackAllocator* allocator = 0, size_t levelDepth = kDefaultLevelDepth) : |
103 | 105 | os_(0), level_stack_(allocator, levelDepth * sizeof(Level)), maxDecimalPlaces_(kDefaultMaxDecimalPlaces), hasRoot_(false) {} |
104 | 106 | |
107 | #if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS | |
108 | Writer(Writer&& rhs) : | |
109 | os_(rhs.os_), level_stack_(std::move(rhs.level_stack_)), maxDecimalPlaces_(rhs.maxDecimalPlaces_), hasRoot_(rhs.hasRoot_) { | |
110 | rhs.os_ = 0; | |
111 | } | |
112 | #endif | |
113 | ||
105 | 114 | //! Reset the writer with a new stream. |
106 | 115 | /*! |
107 | 116 | This function reset the writer with a new stream and default settings, |
183 | 192 | bool Double(double d) { Prefix(kNumberType); return EndValue(WriteDouble(d)); } |
184 | 193 | |
185 | 194 | bool RawNumber(const Ch* str, SizeType length, bool copy = false) { |
195 | CEREAL_RAPIDJSON_ASSERT(str != 0); | |
186 | 196 | (void)copy; |
187 | 197 | Prefix(kNumberType); |
188 | 198 | return EndValue(WriteString(str, length)); |
189 | 199 | } |
190 | 200 | |
191 | 201 | bool String(const Ch* str, SizeType length, bool copy = false) { |
202 | CEREAL_RAPIDJSON_ASSERT(str != 0); | |
192 | 203 | (void)copy; |
193 | 204 | Prefix(kStringType); |
194 | 205 | return EndValue(WriteString(str, length)); |
208 | 219 | |
209 | 220 | bool Key(const Ch* str, SizeType length, bool copy = false) { return String(str, length, copy); } |
210 | 221 | |
222 | #if CEREAL_RAPIDJSON_HAS_STDSTRING | |
223 | bool Key(const std::basic_string<Ch>& str) | |
224 | { | |
225 | return Key(str.data(), SizeType(str.size())); | |
226 | } | |
227 | #endif | |
228 | ||
211 | 229 | bool EndObject(SizeType memberCount = 0) { |
212 | 230 | (void)memberCount; |
213 | CEREAL_RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level)); | |
214 | CEREAL_RAPIDJSON_ASSERT(!level_stack_.template Top<Level>()->inArray); | |
231 | CEREAL_RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level)); // not inside an Object | |
232 | CEREAL_RAPIDJSON_ASSERT(!level_stack_.template Top<Level>()->inArray); // currently inside an Array, not Object | |
233 | CEREAL_RAPIDJSON_ASSERT(0 == level_stack_.template Top<Level>()->valueCount % 2); // Object has a Key without a Value | |
215 | 234 | level_stack_.template Pop<Level>(1); |
216 | 235 | return EndValue(WriteEndObject()); |
217 | 236 | } |
235 | 254 | //@{ |
236 | 255 | |
237 | 256 | //! Simpler but slower overload. |
238 | bool String(const Ch* str) { return String(str, internal::StrLen(str)); } | |
239 | bool Key(const Ch* str) { return Key(str, internal::StrLen(str)); } | |
240 | ||
257 | bool String(const Ch* const& str) { return String(str, internal::StrLen(str)); } | |
258 | bool Key(const Ch* const& str) { return Key(str, internal::StrLen(str)); } | |
259 | ||
241 | 260 | //@} |
242 | 261 | |
243 | 262 | //! Write a raw JSON value. |
248 | 267 | \param length Length of the json. |
249 | 268 | \param type Type of the root of json. |
250 | 269 | */ |
251 | bool RawValue(const Ch* json, size_t length, Type type) { Prefix(type); return EndValue(WriteRawValue(json, length)); } | |
270 | bool RawValue(const Ch* json, size_t length, Type type) { | |
271 | CEREAL_RAPIDJSON_ASSERT(json != 0); | |
272 | Prefix(type); | |
273 | return EndValue(WriteRawValue(json, length)); | |
274 | } | |
275 | ||
276 | //! Flush the output stream. | |
277 | /*! | |
278 | Allows the user to flush the output stream immediately. | |
279 | */ | |
280 | void Flush() { | |
281 | os_->Flush(); | |
282 | } | |
252 | 283 | |
253 | 284 | protected: |
254 | 285 | //! Information for each nested level |
282 | 313 | const char* end = internal::i32toa(i, buffer); |
283 | 314 | PutReserve(*os_, static_cast<size_t>(end - buffer)); |
284 | 315 | for (const char* p = buffer; p != end; ++p) |
285 | PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p)); | |
316 | PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p)); | |
286 | 317 | return true; |
287 | 318 | } |
288 | 319 | |
291 | 322 | const char* end = internal::u32toa(u, buffer); |
292 | 323 | PutReserve(*os_, static_cast<size_t>(end - buffer)); |
293 | 324 | for (const char* p = buffer; p != end; ++p) |
294 | PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p)); | |
325 | PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p)); | |
295 | 326 | return true; |
296 | 327 | } |
297 | 328 | |
300 | 331 | const char* end = internal::i64toa(i64, buffer); |
301 | 332 | PutReserve(*os_, static_cast<size_t>(end - buffer)); |
302 | 333 | for (const char* p = buffer; p != end; ++p) |
303 | PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p)); | |
334 | PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p)); | |
304 | 335 | return true; |
305 | 336 | } |
306 | 337 | |
309 | 340 | char* end = internal::u64toa(u64, buffer); |
310 | 341 | PutReserve(*os_, static_cast<size_t>(end - buffer)); |
311 | 342 | for (char* p = buffer; p != end; ++p) |
312 | PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p)); | |
343 | PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p)); | |
313 | 344 | return true; |
314 | 345 | } |
315 | 346 | |
337 | 368 | char* end = internal::dtoa(d, buffer, maxDecimalPlaces_); |
338 | 369 | PutReserve(*os_, static_cast<size_t>(end - buffer)); |
339 | 370 | for (char* p = buffer; p != end; ++p) |
340 | PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p)); | |
371 | PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p)); | |
341 | 372 | return true; |
342 | 373 | } |
343 | 374 | |
344 | 375 | bool WriteString(const Ch* str, SizeType length) { |
345 | static const typename TargetEncoding::Ch hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; | |
376 | static const typename OutputStream::Ch hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; | |
346 | 377 | static const char escape[256] = { |
347 | 378 | #define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 |
348 | 379 | //0 1 2 3 4 5 6 7 8 9 A B C D E F |
398 | 429 | else if ((sizeof(Ch) == 1 || static_cast<unsigned>(c) < 256) && CEREAL_RAPIDJSON_UNLIKELY(escape[static_cast<unsigned char>(c)])) { |
399 | 430 | is.Take(); |
400 | 431 | PutUnsafe(*os_, '\\'); |
401 | PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(escape[static_cast<unsigned char>(c)])); | |
432 | PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(escape[static_cast<unsigned char>(c)])); | |
402 | 433 | if (escape[static_cast<unsigned char>(c)] == 'u') { |
403 | 434 | PutUnsafe(*os_, '0'); |
404 | 435 | PutUnsafe(*os_, '0'); |
426 | 457 | |
427 | 458 | bool WriteRawValue(const Ch* json, size_t length) { |
428 | 459 | PutReserve(*os_, length); |
429 | for (size_t i = 0; i < length; i++) { | |
430 | CEREAL_RAPIDJSON_ASSERT(json[i] != '\0'); | |
431 | PutUnsafe(*os_, json[i]); | |
460 | GenericStringStream<SourceEncoding> is(json); | |
461 | while (CEREAL_RAPIDJSON_LIKELY(is.Tell() < length)) { | |
462 | CEREAL_RAPIDJSON_ASSERT(is.Peek() != '\0'); | |
463 | if (CEREAL_RAPIDJSON_UNLIKELY(!(writeFlags & kWriteValidateEncodingFlag ? | |
464 | Transcoder<SourceEncoding, TargetEncoding>::Validate(is, *os_) : | |
465 | Transcoder<SourceEncoding, TargetEncoding>::TranscodeUnsafe(is, *os_)))) | |
466 | return false; | |
432 | 467 | } |
433 | 468 | return true; |
434 | 469 | } |
456 | 491 | // Flush the value if it is the top level one. |
457 | 492 | bool EndValue(bool ret) { |
458 | 493 | if (CEREAL_RAPIDJSON_UNLIKELY(level_stack_.Empty())) // end of json text |
459 | os_->Flush(); | |
494 | Flush(); | |
460 | 495 | return ret; |
461 | 496 | } |
462 | 497 | |
560 | 595 | // The rest of string using SIMD |
561 | 596 | static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' }; |
562 | 597 | static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; |
563 | static const char space[16] = { 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19 }; | |
598 | static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F }; | |
564 | 599 | const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0])); |
565 | 600 | const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0])); |
566 | 601 | const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0])); |
569 | 604 | const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p)); |
570 | 605 | const __m128i t1 = _mm_cmpeq_epi8(s, dq); |
571 | 606 | const __m128i t2 = _mm_cmpeq_epi8(s, bs); |
572 | const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x19) == 0x19 | |
607 | const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F | |
573 | 608 | const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); |
574 | 609 | unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x)); |
575 | 610 | if (CEREAL_RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped |
594 | 629 | is.src_ = p; |
595 | 630 | return CEREAL_RAPIDJSON_LIKELY(is.Tell() < length); |
596 | 631 | } |
597 | #endif // defined(CEREAL_RAPIDJSON_SSE2) || defined(CEREAL_RAPIDJSON_SSE42) | |
632 | #elif defined(CEREAL_RAPIDJSON_NEON) | |
633 | template<> | |
634 | inline bool Writer<StringBuffer>::ScanWriteUnescapedString(StringStream& is, size_t length) { | |
635 | if (length < 16) | |
636 | return CEREAL_RAPIDJSON_LIKELY(is.Tell() < length); | |
637 | ||
638 | if (!CEREAL_RAPIDJSON_LIKELY(is.Tell() < length)) | |
639 | return false; | |
640 | ||
641 | const char* p = is.src_; | |
642 | const char* end = is.head_ + length; | |
643 | const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); | |
644 | const char* endAligned = reinterpret_cast<const char*>(reinterpret_cast<size_t>(end) & static_cast<size_t>(~15)); | |
645 | if (nextAligned > end) | |
646 | return true; | |
647 | ||
648 | while (p != nextAligned) | |
649 | if (*p < 0x20 || *p == '\"' || *p == '\\') { | |
650 | is.src_ = p; | |
651 | return CEREAL_RAPIDJSON_LIKELY(is.Tell() < length); | |
652 | } | |
653 | else | |
654 | os_->PutUnsafe(*p++); | |
655 | ||
656 | // The rest of string using SIMD | |
657 | const uint8x16_t s0 = vmovq_n_u8('"'); | |
658 | const uint8x16_t s1 = vmovq_n_u8('\\'); | |
659 | const uint8x16_t s2 = vmovq_n_u8('\b'); | |
660 | const uint8x16_t s3 = vmovq_n_u8(32); | |
661 | ||
662 | for (; p != endAligned; p += 16) { | |
663 | const uint8x16_t s = vld1q_u8(reinterpret_cast<const uint8_t *>(p)); | |
664 | uint8x16_t x = vceqq_u8(s, s0); | |
665 | x = vorrq_u8(x, vceqq_u8(s, s1)); | |
666 | x = vorrq_u8(x, vceqq_u8(s, s2)); | |
667 | x = vorrq_u8(x, vcltq_u8(s, s3)); | |
668 | ||
669 | x = vrev64q_u8(x); // Rev in 64 | |
670 | uint64_t low = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 0); // extract | |
671 | uint64_t high = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 1); // extract | |
672 | ||
673 | SizeType len = 0; | |
674 | bool escaped = false; | |
675 | if (low == 0) { | |
676 | if (high != 0) { | |
677 | unsigned lz = (unsigned)__builtin_clzll(high); | |
678 | len = 8 + (lz >> 3); | |
679 | escaped = true; | |
680 | } | |
681 | } else { | |
682 | unsigned lz = (unsigned)__builtin_clzll(low); | |
683 | len = lz >> 3; | |
684 | escaped = true; | |
685 | } | |
686 | if (CEREAL_RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped | |
687 | char* q = reinterpret_cast<char*>(os_->PushUnsafe(len)); | |
688 | for (size_t i = 0; i < len; i++) | |
689 | q[i] = p[i]; | |
690 | ||
691 | p += len; | |
692 | break; | |
693 | } | |
694 | vst1q_u8(reinterpret_cast<uint8_t *>(os_->PushUnsafe(16)), s); | |
695 | } | |
696 | ||
697 | is.src_ = p; | |
698 | return CEREAL_RAPIDJSON_LIKELY(is.Tell() < length); | |
699 | } | |
700 | #endif // CEREAL_RAPIDJSON_NEON | |
598 | 701 | |
599 | 702 | CEREAL_RAPIDJSON_NAMESPACE_END |
600 | 703 | |
601 | #ifdef _MSC_VER | |
704 | #if defined(_MSC_VER) || defined(__clang__) | |
602 | 705 | CEREAL_RAPIDJSON_DIAG_POP |
603 | 706 | #endif |
604 | 707 | |
605 | #ifdef __clang__ | |
606 | CEREAL_RAPIDJSON_DIAG_POP | |
607 | #endif | |
608 | ||
609 | 708 | #endif // CEREAL_RAPIDJSON_CEREAL_RAPIDJSON_H_ |
84 | 84 | |
85 | 85 | //! Gets human readable description of error. |
86 | 86 | //! \return Pointer to null terminated description of the error. |
87 | virtual const char *what() const throw() | |
87 | virtual const char *what() const CEREAL_NOEXCEPT override | |
88 | 88 | { |
89 | 89 | return m_what; |
90 | 90 | } |
316 | 316 | const Ch *tmp = p; |
317 | 317 | while (*tmp) |
318 | 318 | ++tmp; |
319 | return tmp - p; | |
319 | return static_cast<std::size_t>(tmp - p); | |
320 | 320 | } |
321 | 321 | |
322 | 322 | // Compare strings for equality |
386 | 386 | //! If required, you can tweak <code>CEREAL_RAPIDXML_STATIC_POOL_SIZE</code>, <code>CEREAL_RAPIDXML_DYNAMIC_POOL_SIZE</code> and <code>CEREAL_RAPIDXML_ALIGNMENT</code> |
387 | 387 | //! to obtain best wasted memory to performance compromise. |
388 | 388 | //! To do it, define their values before rapidxml.hpp file is included. |
389 | //! \param Ch Character type of created nodes. | |
389 | //! \tparam Ch Character type of created nodes. | |
390 | 390 | template<class Ch = char> |
391 | 391 | class memory_pool |
392 | 392 | { |
655 | 655 | |
656 | 656 | //! Base class for xml_node and xml_attribute implementing common functions: |
657 | 657 | //! name(), name_size(), value(), value_size() and parent(). |
658 | //! \param Ch Character type to use | |
658 | //! \tparam Ch Character type to use | |
659 | 659 | template<class Ch = char> |
660 | 660 | class xml_base |
661 | 661 | { |
728 | 728 | //! <br><br> |
729 | 729 | //! Size of name must be specified separately, because name does not have to be zero terminated. |
730 | 730 | //! Use name(const Ch *) function to have the length automatically calculated (string must be zero terminated). |
731 | //! \param name Name of node to set. Does not have to be zero terminated. | |
731 | //! \param name_ Name of node to set. Does not have to be zero terminated. | |
732 | 732 | //! \param size Size of name, in characters. This does not include zero terminator, if one is present. |
733 | 733 | void name(const Ch *name_, std::size_t size) |
734 | 734 | { |
738 | 738 | |
739 | 739 | //! Sets name of node to a zero-terminated string. |
740 | 740 | //! See also \ref ownership_of_strings and xml_node::name(const Ch *, std::size_t). |
741 | //! \param name Name of node to set. Must be zero terminated. | |
741 | //! \param name_ Name of node to set. Must be zero terminated. | |
742 | 742 | void name(const Ch *name_) |
743 | 743 | { |
744 | 744 | this->name(name_, internal::measure(name_)); |
758 | 758 | //! <br><br> |
759 | 759 | //! If an element has a child node of type node_data, it will take precedence over element value when printing. |
760 | 760 | //! If you want to manipulate data of elements using values, use parser flag rapidxml::parse_no_data_nodes to prevent creation of data nodes by the parser. |
761 | //! \param value value of node to set. Does not have to be zero terminated. | |
761 | //! \param value_ value of node to set. Does not have to be zero terminated. | |
762 | 762 | //! \param size Size of value, in characters. This does not include zero terminator, if one is present. |
763 | 763 | void value(const Ch *value_, std::size_t size) |
764 | 764 | { |
768 | 768 | |
769 | 769 | //! Sets value of node to a zero-terminated string. |
770 | 770 | //! See also \ref ownership_of_strings and xml_node::value(const Ch *, std::size_t). |
771 | //! \param value Vame of node to set. Must be zero terminated. | |
771 | //! \param value_ Vame of node to set. Must be zero terminated. | |
772 | 772 | void value(const Ch *value_) |
773 | 773 | { |
774 | 774 | this->value(value_, internal::measure(value_)); |
805 | 805 | //! Each attribute has name and value strings, which are available through name() and value() functions (inherited from xml_base). |
806 | 806 | //! Note that after parse, both name and value of attribute will point to interior of source text used for parsing. |
807 | 807 | //! Thus, this text must persist in memory for the lifetime of attribute. |
808 | //! \param Ch Character type to use. | |
808 | //! \tparam Ch Character type to use. | |
809 | 809 | template<class Ch = char> |
810 | 810 | class xml_attribute: public xml_base<Ch> |
811 | 811 | { |
861 | 861 | } |
862 | 862 | |
863 | 863 | //! Gets next attribute, optionally matching attribute name. |
864 | //! \param name Name of attribute to find, or 0 to return next attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero | |
865 | //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string | |
864 | //! \param name_ Name of attribute to find, or 0 to return next attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero | |
865 | //! \param name_size_ Size of name, in characters, or 0 to have size calculated automatically from string | |
866 | 866 | //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters |
867 | 867 | //! \return Pointer to found attribute, or 0 if not found. |
868 | 868 | xml_attribute<Ch> *next_attribute(const Ch *name_ = 0, std::size_t name_size_ = 0, bool case_sensitive = true) const |
897 | 897 | //! <br><br> |
898 | 898 | //! Note that after parse, both name and value of node, if any, will point interior of source text used for parsing. |
899 | 899 | //! Thus, this text must persist in the memory for the lifetime of node. |
900 | //! \param Ch Character type to use. | |
900 | //! \tparam Ch Character type to use. | |
901 | 901 | template<class Ch = char> |
902 | 902 | class xml_node: public xml_base<Ch> |
903 | 903 | { |
909 | 909 | |
910 | 910 | //! Constructs an empty node with the specified type. |
911 | 911 | //! Consider using memory_pool of appropriate document to allocate nodes manually. |
912 | //! \param type Type of node to construct. | |
912 | //! \param type_ Type of node to construct. | |
913 | 913 | xml_node(node_type type_) |
914 | 914 | : m_type(type_) |
915 | 915 | , m_first_node(0) |
941 | 941 | } |
942 | 942 | |
943 | 943 | //! Gets first child node, optionally matching node name. |
944 | //! \param name Name of child to find, or 0 to return first child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero | |
945 | //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string | |
944 | //! \param name_ Name of child to find, or 0 to return first child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero | |
945 | //! \param name_size_ Size of name, in characters, or 0 to have size calculated automatically from string | |
946 | 946 | //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters |
947 | 947 | //! \return Pointer to found child, or 0 if not found. |
948 | 948 | xml_node<Ch> *first_node(const Ch *name_ = 0, std::size_t name_size_ = 0, bool case_sensitive = true) const |
1009 | 1009 | //! Gets next sibling node, optionally matching node name. |
1010 | 1010 | //! Behaviour is undefined if node has no parent. |
1011 | 1011 | //! Use parent() to test if node has a parent. |
1012 | //! \param name Name of sibling to find, or 0 to return next sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero | |
1013 | //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string | |
1012 | //! \param name_ Name of sibling to find, or 0 to return next sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero | |
1013 | //! \param name_size_ Size of name, in characters, or 0 to have size calculated automatically from string | |
1014 | 1014 | //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters |
1015 | 1015 | //! \return Pointer to found sibling, or 0 if not found. |
1016 | 1016 | xml_node<Ch> *next_sibling(const Ch *name_ = 0, std::size_t name_size_ = 0, bool case_sensitive = true) const |
1030 | 1030 | } |
1031 | 1031 | |
1032 | 1032 | //! Gets first attribute of node, optionally matching attribute name. |
1033 | //! \param name Name of attribute to find, or 0 to return first attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero | |
1034 | //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string | |
1033 | //! \param name_ Name of attribute to find, or 0 to return first attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero | |
1034 | //! \param name_size_ Size of name, in characters, or 0 to have size calculated automatically from string | |
1035 | 1035 | //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters |
1036 | 1036 | //! \return Pointer to found attribute, or 0 if not found. |
1037 | 1037 | xml_attribute<Ch> *first_attribute(const Ch *name_ = 0, std::size_t name_size_ = 0, bool case_sensitive = true) const |
1073 | 1073 | // Node modification |
1074 | 1074 | |
1075 | 1075 | //! Sets type of node. |
1076 | //! \param type Type of node to set. | |
1076 | //! \param type_ Type of node to set. | |
1077 | 1077 | void type(node_type type_) |
1078 | 1078 | { |
1079 | 1079 | m_type = type_; |
1365 | 1365 | //! parse() function allocates memory for nodes and attributes by using functions of xml_document, |
1366 | 1366 | //! which are inherited from memory_pool. |
1367 | 1367 | //! To access root node of the document, use the document itself, as if it was an xml_node. |
1368 | //! \param Ch Character type to use. | |
1368 | //! \tparam Ch Character type to use. | |
1369 | 1369 | template<class Ch = char> |
1370 | 1370 | class xml_document: public xml_node<Ch>, public memory_pool<Ch> |
1371 | 1371 | { |
1526 | 1526 | { |
1527 | 1527 | // Insert 8-bit ASCII character |
1528 | 1528 | // Todo: possibly verify that code is less than 256 and use replacement char otherwise? |
1529 | text[0] = static_cast<unsigned char>(code); | |
1529 | text[0] = static_cast<Ch>(code); | |
1530 | 1530 | text += 1; |
1531 | 1531 | } |
1532 | 1532 | else |
1534 | 1534 | // Insert UTF8 sequence |
1535 | 1535 | if (code < 0x80) // 1 byte sequence |
1536 | 1536 | { |
1537 | text[0] = static_cast<unsigned char>(code); | |
1537 | text[0] = static_cast<Ch>(code); | |
1538 | 1538 | text += 1; |
1539 | 1539 | } |
1540 | 1540 | else if (code < 0x800) // 2 byte sequence |
1541 | 1541 | { |
1542 | text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; | |
1543 | text[0] = static_cast<unsigned char>(code | 0xC0); | |
1542 | text[1] = static_cast<Ch>((code | 0x80) & 0xBF); code >>= 6; | |
1543 | text[0] = static_cast<Ch>(code | 0xC0); | |
1544 | 1544 | text += 2; |
1545 | 1545 | } |
1546 | 1546 | else if (code < 0x10000) // 3 byte sequence |
1547 | 1547 | { |
1548 | text[2] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; | |
1549 | text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; | |
1550 | text[0] = static_cast<unsigned char>(code | 0xE0); | |
1548 | text[2] = static_cast<Ch>((code | 0x80) & 0xBF); code >>= 6; | |
1549 | text[1] = static_cast<Ch>((code | 0x80) & 0xBF); code >>= 6; | |
1550 | text[0] = static_cast<Ch>(code | 0xE0); | |
1551 | 1551 | text += 3; |
1552 | 1552 | } |
1553 | 1553 | else if (code < 0x110000) // 4 byte sequence |
1554 | 1554 | { |
1555 | text[3] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; | |
1556 | text[2] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; | |
1557 | text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6; | |
1558 | text[0] = static_cast<unsigned char>(code | 0xF0); | |
1555 | text[3] = static_cast<Ch>((code | 0x80) & 0xBF); code >>= 6; | |
1556 | text[2] = static_cast<Ch>((code | 0x80) & 0xBF); code >>= 6; | |
1557 | text[1] = static_cast<Ch>((code | 0x80) & 0xBF); code >>= 6; | |
1558 | text[0] = static_cast<Ch>(code | 0xF0); | |
1559 | 1559 | text += 4; |
1560 | 1560 | } |
1561 | 1561 | else // Invalid, only codes up to 0x10FFFF are allowed in Unicode |
1811 | 1811 | |
1812 | 1812 | // Create comment node |
1813 | 1813 | xml_node<Ch> *comment = this->allocate_node(node_comment); |
1814 | comment->value(value_, text - value_); | |
1814 | comment->value(value_, static_cast<std::size_t>(text - value_)); | |
1815 | 1815 | |
1816 | 1816 | // Place zero terminator after comment value |
1817 | 1817 | if (!(Flags & parse_no_string_terminators)) |
1870 | 1870 | { |
1871 | 1871 | // Create a new doctype node |
1872 | 1872 | xml_node<Ch> *doctype = this->allocate_node(node_doctype); |
1873 | doctype->value(value_, text - value_); | |
1873 | doctype->value(value_, static_cast<std::size_t>(text - value_)); | |
1874 | 1874 | |
1875 | 1875 | // Place zero terminator after value |
1876 | 1876 | if (!(Flags & parse_no_string_terminators)) |
1902 | 1902 | skip<node_name_pred, Flags>(text); |
1903 | 1903 | if (text == name_) |
1904 | 1904 | CEREAL_RAPIDXML_PARSE_ERROR("expected PI target", text); |
1905 | pi->name(name_, text - name_); | |
1905 | pi->name(name_, static_cast<std::size_t>(text - name_)); | |
1906 | 1906 | |
1907 | 1907 | // Skip whitespace between pi target and pi |
1908 | 1908 | skip<whitespace_pred, Flags>(text); |
1919 | 1919 | } |
1920 | 1920 | |
1921 | 1921 | // Set pi value (verbatim, no entity expansion or whitespace normalization) |
1922 | pi->value(value_, text - value_); | |
1922 | pi->value(value_, static_cast<std::size_t>(text - value_)); | |
1923 | 1923 | |
1924 | 1924 | // Place zero terminator after name and value |
1925 | 1925 | if (!(Flags & parse_no_string_terminators)) |
1986 | 1986 | if (!(Flags & parse_no_data_nodes)) |
1987 | 1987 | { |
1988 | 1988 | xml_node<Ch> *data = this->allocate_node(node_data); |
1989 | data->value(value_, end - value_); | |
1989 | data->value(value_, static_cast<std::size_t>(end - value_)); | |
1990 | 1990 | node->append_node(data); |
1991 | 1991 | } |
1992 | 1992 | |
1993 | 1993 | // Add data to parent node if no data exists yet |
1994 | 1994 | if (!(Flags & parse_no_element_values)) |
1995 | 1995 | if (*node->value() == Ch('\0')) |
1996 | node->value(value_, end - value_); | |
1996 | node->value(value_, static_cast<std::size_t>(end - value_)); | |
1997 | 1997 | |
1998 | 1998 | // Place zero terminator after value |
1999 | 1999 | if (!(Flags & parse_no_string_terminators)) |
2036 | 2036 | |
2037 | 2037 | // Create new cdata node |
2038 | 2038 | xml_node<Ch> *cdata = this->allocate_node(node_cdata); |
2039 | cdata->value(value_, text - value_); | |
2039 | cdata->value(value_, static_cast<std::size_t>(text - value_)); | |
2040 | 2040 | |
2041 | 2041 | // Place zero terminator after value |
2042 | 2042 | if (!(Flags & parse_no_string_terminators)) |
2058 | 2058 | skip<node_name_pred, Flags>(text); |
2059 | 2059 | if (text == name_) |
2060 | 2060 | CEREAL_RAPIDXML_PARSE_ERROR("expected element name", text); |
2061 | element->name(name_, text - name_); | |
2061 | element->name(name_, static_cast<std::size_t>(text - name_)); | |
2062 | 2062 | |
2063 | 2063 | // Skip whitespace between element name and attributes or > |
2064 | 2064 | skip<whitespace_pred, Flags>(text); |
2215 | 2215 | // Skip and validate closing tag name |
2216 | 2216 | Ch *closing_name = text; |
2217 | 2217 | skip<node_name_pred, Flags>(text); |
2218 | if (!internal::compare(node->name(), node->name_size(), closing_name, text - closing_name, true)) | |
2218 | if (!internal::compare(node->name(), node->name_size(), closing_name, static_cast<std::size_t>(text - closing_name), true)) | |
2219 | 2219 | CEREAL_RAPIDXML_PARSE_ERROR("invalid closing tag name", text); |
2220 | 2220 | } |
2221 | 2221 | else |
2231 | 2231 | |
2232 | 2232 | if (contents_end && contents_end != contents_start) |
2233 | 2233 | { |
2234 | node->value(contents_start, contents_end - contents_start); | |
2234 | node->value(contents_start, static_cast<std::size_t>(contents_end - contents_start)); | |
2235 | 2235 | node->value()[node->value_size()] = Ch('\0'); |
2236 | 2236 | } |
2237 | 2237 | return; // Node closed, finished parsing contents |
2274 | 2274 | |
2275 | 2275 | // Create new attribute |
2276 | 2276 | xml_attribute<Ch> *attribute = this->allocate_attribute(); |
2277 | attribute->name(name_, text - name_); | |
2277 | attribute->name(name_, static_cast<std::size_t>(text - name_)); | |
2278 | 2278 | node->append_attribute(attribute); |
2279 | 2279 | |
2280 | 2280 | // Skip whitespace after attribute name |
2307 | 2307 | end = skip_and_expand_character_refs<attribute_value_pred<Ch('"')>, attribute_value_pure_pred<Ch('"')>, AttFlags>(text, false); |
2308 | 2308 | |
2309 | 2309 | // Set attribute value |
2310 | attribute->value(value_, end - value_); | |
2310 | attribute->value(value_, static_cast<std::size_t>(end - value_)); | |
2311 | 2311 | |
2312 | 2312 | // Make sure that end quote is present |
2313 | 2313 | if (*text != quote) |
362 | 362 | out = print_pi_node(out, node, flags, indent); |
363 | 363 | break; |
364 | 364 | |
365 | #ifndef __GNUC__ | |
365 | 366 | // Unknown |
366 | 367 | default: |
367 | 368 | assert(0); |
368 | 369 | break; |
370 | #endif | |
369 | 371 | } |
370 | 372 | |
371 | 373 | // If indenting not disabled, add line break after node |
131 | 131 | #endif // end !defined(CEREAL_HAS_NOEXCEPT) |
132 | 132 | #endif // ifndef CEREAL_NOEXCEPT |
133 | 133 | |
134 | // ###################################################################### | |
135 | //! Checks if C++17 is available | |
136 | #if __cplusplus >= 201703L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) | |
137 | #define CEREAL_HAS_CPP17 | |
138 | #endif | |
139 | ||
140 | //! Checks if C++14 is available | |
141 | #if __cplusplus >= 201402L | |
142 | #define CEREAL_HAS_CPP14 | |
143 | #endif | |
144 | ||
145 | // ###################################################################### | |
146 | //! Defines the CEREAL_ALIGNOF macro to use instead of alignof | |
147 | #if defined(_MSC_VER) && _MSC_VER < 1900 | |
148 | #define CEREAL_ALIGNOF __alignof | |
149 | #else // not MSVC 2013 or older | |
150 | #define CEREAL_ALIGNOF alignof | |
151 | #endif // end MSVC check | |
152 | ||
134 | 153 | #endif // CEREAL_MACROS_HPP_ |
0 | /*! \file specialize.hpp | |
1 | \brief Serialization disambiguation */ | |
2 | /* | |
3 | Copyright (c) 2014, Randolph Voorhies, Shane Grant | |
4 | All rights reserved. | |
5 | ||
6 | Redistribution and use in source and binary forms, with or without | |
7 | modification, are permitted provided that the following conditions are met: | |
8 | * Redistributions of source code must retain the above copyright | |
9 | notice, this list of conditions and the following disclaimer. | |
10 | * Redistributions in binary form must reproduce the above copyright | |
11 | notice, this list of conditions and the following disclaimer in the | |
12 | documentation and/or other materials provided with the distribution. | |
13 | * Neither the name of cereal nor the | |
14 | names of its contributors may be used to endorse or promote products | |
15 | derived from this software without specific prior written permission. | |
16 | ||
17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND | |
18 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED | |
19 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | |
20 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY | |
21 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES | |
22 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | |
23 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND | |
24 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
25 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | |
26 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
27 | */ | |
28 | ||
29 | #ifndef CEREAL_SPECIALIZE_HPP_ | |
30 | #define CEREAL_SPECIALIZE_HPP_ | |
31 | ||
32 | namespace cereal | |
33 | { | |
34 | // Forward declaration of access class that users can become friends with | |
35 | class access; | |
36 | ||
37 | // ###################################################################### | |
38 | //! A specifier used in conjunction with cereal::specialize to disambiguate | |
39 | //! serialization in special cases | |
40 | /*! @relates specialize | |
41 | @ingroup Access */ | |
42 | enum class specialization | |
43 | { | |
44 | member_serialize, //!< Force the use of a member serialize function | |
45 | member_load_save, //!< Force the use of a member load/save pair | |
46 | member_load_save_minimal, //!< Force the use of a member minimal load/save pair | |
47 | non_member_serialize, //!< Force the use of a non-member serialize function | |
48 | non_member_load_save, //!< Force the use of a non-member load/save pair | |
49 | non_member_load_save_minimal //!< Force the use of a non-member minimal load/save pair | |
50 | }; | |
51 | ||
52 | //! A class used to disambiguate cases where cereal cannot detect a unique way of serializing a class | |
53 | /*! cereal attempts to figure out which method of serialization (member vs. non-member serialize | |
54 | or load/save pair) at compile time. If for some reason cereal cannot find a non-ambiguous way | |
55 | of serializing a type, it will produce a static assertion complaining about this. | |
56 | ||
57 | This can happen because you have both a serialize and load/save pair, or even because a base | |
58 | class has a serialize (public or private with friend access) and a derived class does not | |
59 | overwrite this due to choosing some other serialization type. | |
60 | ||
61 | Specializing this class will tell cereal to explicitly use the serialization type you specify | |
62 | and it will not complain about ambiguity in its compile time selection. However, if cereal detects | |
63 | an ambiguity in specializations, it will continue to issue a static assertion. | |
64 | ||
65 | @code{.cpp} | |
66 | class MyParent | |
67 | { | |
68 | friend class cereal::access; | |
69 | template <class Archive> | |
70 | void serialize( Archive & ar ) {} | |
71 | }; | |
72 | ||
73 | // Although serialize is private in MyParent, to cereal::access it will look public, | |
74 | // even through MyDerived | |
75 | class MyDerived : public MyParent | |
76 | { | |
77 | public: | |
78 | template <class Archive> | |
79 | void load( Archive & ar ) {} | |
80 | ||
81 | template <class Archive> | |
82 | void save( Archive & ar ) {} | |
83 | }; | |
84 | ||
85 | // The load/save pair in MyDerived is ambiguous because serialize in MyParent can | |
86 | // be accessed from cereal::access. This looks the same as making serialize public | |
87 | // in MyParent, making it seem as though MyDerived has both a serialize and a load/save pair. | |
88 | // cereal will complain about this at compile time unless we disambiguate: | |
89 | ||
90 | namespace cereal | |
91 | { | |
92 | // This struct specialization will tell cereal which is the right way to serialize the ambiguity | |
93 | template <class Archive> struct specialize<Archive, MyDerived, cereal::specialization::member_load_save> {}; | |
94 | ||
95 | // If we only had a disambiguation for a specific archive type, it would look something like this | |
96 | template <> struct specialize<cereal::BinaryOutputArchive, MyDerived, cereal::specialization::member_load_save> {}; | |
97 | } | |
98 | @endcode | |
99 | ||
100 | You can also choose to use the macros CEREAL_SPECIALIZE_FOR_ALL_ARCHIVES or | |
101 | CEREAL_SPECIALIZE_FOR_ARCHIVE if you want to type a little bit less. | |
102 | ||
103 | @tparam T The type to specialize the serialization for | |
104 | @tparam S The specialization type to use for T | |
105 | @ingroup Access */ | |
106 | template <class Archive, class T, specialization S> | |
107 | struct specialize : public std::false_type {}; | |
108 | ||
109 | //! Convenient macro for performing specialization for all archive types | |
110 | /*! This performs specialization for the specific type for all types of archives. | |
111 | This macro should be placed at the global namespace. | |
112 | ||
113 | @code{cpp} | |
114 | struct MyType {}; | |
115 | CEREAL_SPECIALIZE_FOR_ALL_ARCHIVES( MyType, cereal::specialization::member_load_save ); | |
116 | @endcode | |
117 | ||
118 | @relates specialize | |
119 | @ingroup Access */ | |
120 | #define CEREAL_SPECIALIZE_FOR_ALL_ARCHIVES( Type, Specialization ) \ | |
121 | namespace cereal { template <class Archive> struct specialize<Archive, Type, Specialization> {}; } | |
122 | ||
123 | //! Convenient macro for performing specialization for a single archive type | |
124 | /*! This performs specialization for the specific type for a single type of archive. | |
125 | This macro should be placed at the global namespace. | |
126 | ||
127 | @code{cpp} | |
128 | struct MyType {}; | |
129 | CEREAL_SPECIALIZE_FOR_ARCHIVE( cereal::XMLInputArchive, MyType, cereal::specialization::member_load_save ); | |
130 | @endcode | |
131 | ||
132 | @relates specialize | |
133 | @ingroup Access */ | |
134 | #define CEREAL_SPECIALIZE_FOR_ARCHIVE( Archive, Type, Specialization ) \ | |
135 | namespace cereal { template <> struct specialize<Archive, Type, Specialization> {}; } | |
136 | } | |
137 | ||
138 | #endif |
0 | /*! \file atomic.hpp | |
1 | \brief Support for types found in \<atomic\> | |
2 | \ingroup STLSupport */ | |
3 | /* | |
4 | Copyright (c) 2014, Randolph Voorhies, Shane Grant | |
5 | All rights reserved. | |
6 | ||
7 | Redistribution and use in source and binary forms, with or without | |
8 | modification, are permitted provided that the following conditions are met: | |
9 | * Redistributions of source code must retain the above copyright | |
10 | notice, this list of conditions and the following disclaimer. | |
11 | * Redistributions in binary form must reproduce the above copyright | |
12 | notice, this list of conditions and the following disclaimer in the | |
13 | documentation and/or other materials provided with the distribution. | |
14 | * Neither the name of cereal nor the | |
15 | names of its contributors may be used to endorse or promote products | |
16 | derived from this software without specific prior written permission. | |
17 | ||
18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND | |
19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED | |
20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | |
21 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY | |
22 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES | |
23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | |
24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND | |
25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | |
27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
28 | */ | |
29 | #ifndef CEREAL_TYPES_ATOMIC_HPP_ | |
30 | #define CEREAL_TYPES_ATOMIC_HPP_ | |
31 | ||
32 | #include <cereal/cereal.hpp> | |
33 | #include <atomic> | |
34 | ||
35 | namespace cereal | |
36 | { | |
37 | //! Serializing (save) for std::atomic | |
38 | template <class Archive, class T> inline | |
39 | void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::atomic<T> const & a ) | |
40 | { | |
41 | ar( CEREAL_NVP_("atomic_data", a.load()) ); | |
42 | } | |
43 | ||
44 | //! Serializing (load) for std::atomic | |
45 | template <class Archive, class T> inline | |
46 | void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::atomic<T> & a ) | |
47 | { | |
48 | T tmp; | |
49 | ar( CEREAL_NVP_("atomic_data", tmp) ); | |
50 | a.store( tmp ); | |
51 | } | |
52 | } // namespace cereal | |
53 | ||
54 | #endif // CEREAL_TYPES_ATOMIC_HPP_ |
62 | 62 | |
63 | 63 | This also automatically registers polymorphic relation between the base and derived class, assuming they |
64 | 64 | are indeed polymorphic. Note this is not the same as polymorphic type registration. For more information |
65 | see the documentation on polymorphism. | |
65 | see the documentation on polymorphism. If using a polymorphic class, be sure to include support for | |
66 | polymorphism (cereal/types/polymorphic.hpp). | |
66 | 67 | |
67 | 68 | \sa virtual_base_class |
68 | 69 | |
119 | 120 | |
120 | 121 | This also automatically registers polymorphic relation between the base and derived class, assuming they |
121 | 122 | are indeed polymorphic. Note this is not the same as polymorphic type registration. For more information |
122 | see the documentation on polymorphism. | |
123 | see the documentation on polymorphism. If using a polymorphic class, be sure to include support for | |
124 | polymorphism (cereal/types/polymorphic.hpp). | |
123 | 125 | |
124 | 126 | \sa base_class |
125 | 127 |
66 | 66 | if( bits[i] ) |
67 | 67 | chunk |= mask; |
68 | 68 | |
69 | mask >>= 1; | |
69 | mask = static_cast<std::uint8_t>(mask >> 1); | |
70 | 70 | |
71 | 71 | // output current chunk when mask is empty (8 bits) |
72 | 72 | if( mask == 0 ) |
162 | 162 | if( chunk & mask ) |
163 | 163 | bits[i] = 1; |
164 | 164 | |
165 | mask >>= 1; | |
165 | mask = static_cast<std::uint8_t>(mask >> 1); | |
166 | 166 | } |
167 | 167 | break; |
168 | 168 | } |
29 | 29 | #ifndef CEREAL_TYPES_BOOST_VARIANT_HPP_ |
30 | 30 | #define CEREAL_TYPES_BOOST_VARIANT_HPP_ |
31 | 31 | |
32 | //! @internal | |
33 | #if defined(_MSC_VER) && _MSC_VER < 1911 | |
34 | #define CEREAL_CONSTEXPR_LAMBDA | |
35 | #else // MSVC 2017 or newer, all other compilers | |
36 | #define CEREAL_CONSTEXPR_LAMBDA constexpr | |
37 | #endif | |
38 | ||
32 | 39 | #include "cereal/cereal.hpp" |
33 | #include <boost/variant.hpp> | |
34 | #include <boost/mpl/size.hpp> | |
40 | #include <boost/variant/variant_fwd.hpp> | |
41 | #include <boost/variant/static_visitor.hpp> | |
35 | 42 | |
36 | 43 | namespace cereal |
37 | 44 | { |
38 | namespace variant_detail | |
45 | namespace boost_variant_detail | |
39 | 46 | { |
40 | 47 | //! @internal |
41 | 48 | template <class Archive> |
44 | 51 | variant_save_visitor(Archive & ar_) : ar(ar_) {} |
45 | 52 | |
46 | 53 | template<class T> |
47 | void operator()(T const & value) const | |
48 | { | |
49 | ar( CEREAL_NVP_("data", value) ); | |
50 | } | |
54 | void operator()(T const & value) const | |
55 | { | |
56 | ar( CEREAL_NVP_("data", value) ); | |
57 | } | |
51 | 58 | |
52 | 59 | Archive & ar; |
53 | 60 | }; |
54 | 61 | |
55 | 62 | //! @internal |
56 | template<int N, class Variant, class ... Args, class Archive> | |
57 | typename std::enable_if<N == boost::mpl::size<typename Variant::types>::value, void>::type | |
58 | load_variant(Archive & /*ar*/, int /*target*/, Variant & /*variant*/) | |
63 | template <class Archive, class T> | |
64 | struct LoadAndConstructLoadWrapper | |
59 | 65 | { |
60 | throw ::cereal::Exception("Error traversing variant during load"); | |
61 | } | |
66 | using ST = typename std::aligned_storage<sizeof(T), CEREAL_ALIGNOF(T)>::type; | |
67 | ||
68 | LoadAndConstructLoadWrapper() : | |
69 | construct( reinterpret_cast<T *>( &st ) ) | |
70 | { } | |
71 | ||
72 | ~LoadAndConstructLoadWrapper() | |
73 | { | |
74 | if (construct.itsValid) | |
75 | { | |
76 | construct->~T(); | |
77 | } | |
78 | } | |
79 | ||
80 | void CEREAL_SERIALIZE_FUNCTION_NAME( Archive & ar ) | |
81 | { | |
82 | ::cereal::detail::Construct<T, Archive>::load_andor_construct( ar, construct ); | |
83 | } | |
84 | ||
85 | ST st; | |
86 | ::cereal::construct<T> construct; | |
87 | }; | |
62 | 88 | |
63 | 89 | //! @internal |
64 | template<int N, class Variant, class H, class ... T, class Archive> | |
65 | typename std::enable_if<N < boost::mpl::size<typename Variant::types>::value, void>::type | |
66 | load_variant(Archive & ar, int target, Variant & variant) | |
90 | template <class T> struct load_variant_wrapper; | |
91 | ||
92 | //! Avoid serializing variant void_ type | |
93 | /*! @internal */ | |
94 | template <> | |
95 | struct load_variant_wrapper<boost::detail::variant::void_> | |
67 | 96 | { |
68 | if(N == target) | |
97 | template <class Variant, class Archive> | |
98 | static void load_variant( Archive &, Variant & ) | |
99 | { } | |
100 | }; | |
101 | ||
102 | //! @internal | |
103 | template <class T> | |
104 | struct load_variant_wrapper | |
105 | { | |
106 | // default constructible | |
107 | template <class Archive, class Variant> | |
108 | static void load_variant_impl( Archive & ar, Variant & variant, std::true_type ) | |
69 | 109 | { |
70 | H value; | |
110 | T value; | |
71 | 111 | ar( CEREAL_NVP_("data", value) ); |
72 | variant = value; | |
112 | variant = std::move(value); | |
73 | 113 | } |
74 | else | |
75 | load_variant<N+1, Variant, T...>(ar, target, variant); | |
76 | } | |
77 | 114 | |
78 | } // namespace variant_detail | |
115 | // not default constructible | |
116 | template<class Variant, class Archive> | |
117 | static void load_variant_impl(Archive & ar, Variant & variant, std::false_type ) | |
118 | { | |
119 | LoadAndConstructLoadWrapper<Archive, T> loadWrapper; | |
120 | ||
121 | ar( CEREAL_NVP_("data", loadWrapper) ); | |
122 | variant = std::move(*loadWrapper.construct.ptr()); | |
123 | } | |
124 | ||
125 | //! @internal | |
126 | template<class Variant, class Archive> | |
127 | static void load_variant(Archive & ar, Variant & variant) | |
128 | { | |
129 | load_variant_impl( ar, variant, typename std::is_default_constructible<T>::type() ); | |
130 | } | |
131 | }; | |
132 | } // namespace boost_variant_detail | |
79 | 133 | |
80 | 134 | //! Saving for boost::variant |
81 | template <class Archive, typename VariantType1, typename... VariantTypes> inline | |
82 | void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, boost::variant<VariantType1, VariantTypes...> const & variant ) | |
135 | template <class Archive, typename ... VariantTypes> inline | |
136 | void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, boost::variant<VariantTypes...> const & variant ) | |
83 | 137 | { |
84 | 138 | int32_t which = variant.which(); |
85 | 139 | ar( CEREAL_NVP_("which", which) ); |
86 | variant_detail::variant_save_visitor<Archive> visitor(ar); | |
140 | boost_variant_detail::variant_save_visitor<Archive> visitor(ar); | |
87 | 141 | variant.apply_visitor(visitor); |
88 | 142 | } |
89 | 143 | |
90 | 144 | //! Loading for boost::variant |
91 | template <class Archive, typename VariantType1, typename... VariantTypes> inline | |
92 | void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, boost::variant<VariantType1, VariantTypes...> & variant ) | |
145 | template <class Archive, typename ... VariantTypes> inline | |
146 | void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, boost::variant<VariantTypes...> & variant ) | |
93 | 147 | { |
94 | typedef typename boost::variant<VariantType1, VariantTypes...>::types types; | |
95 | ||
96 | 148 | int32_t which; |
97 | 149 | ar( CEREAL_NVP_("which", which) ); |
98 | if(which >= boost::mpl::size<types>::value) | |
150 | ||
151 | using LoadFuncType = void(*)(Archive &, boost::variant<VariantTypes...> &); | |
152 | CEREAL_CONSTEXPR_LAMBDA LoadFuncType loadFuncArray[] = {&boost_variant_detail::load_variant_wrapper<VariantTypes>::load_variant...}; | |
153 | ||
154 | if(which >= int32_t(sizeof(loadFuncArray)/sizeof(loadFuncArray[0]))) | |
99 | 155 | throw Exception("Invalid 'which' selector when deserializing boost::variant"); |
100 | 156 | |
101 | variant_detail::load_variant<0, boost::variant<VariantType1, VariantTypes...>, VariantType1, VariantTypes...>(ar, which, variant); | |
157 | loadFuncArray[which](ar, variant); | |
102 | 158 | } |
103 | 159 | } // namespace cereal |
104 | 160 | |
161 | #undef CEREAL_CONSTEXPR_LAMBDA | |
162 | ||
105 | 163 | #endif // CEREAL_TYPES_BOOST_VARIANT_HPP_ |
33 | 33 | #include <memory> |
34 | 34 | #include <cstring> |
35 | 35 | |
36 | // Work around MSVC not having alignof | |
37 | #if defined(_MSC_VER) && _MSC_VER < 1900 | |
38 | #define CEREAL_ALIGNOF __alignof | |
39 | #else // not MSVC 2013 or older | |
40 | #define CEREAL_ALIGNOF alignof | |
41 | #endif // end MSVC check | |
42 | ||
43 | 36 | namespace cereal |
44 | 37 | { |
45 | 38 | namespace memory_detail |
53 | 46 | PtrWrapper(T && p) : ptr(std::forward<T>(p)) {} |
54 | 47 | T & ptr; |
55 | 48 | |
49 | PtrWrapper( PtrWrapper const & ) = default; | |
56 | 50 | PtrWrapper & operator=( PtrWrapper const & ) = delete; |
57 | 51 | }; |
58 | 52 | |
108 | 102 | To get around these issues, we will store the memory for the enable_shared_from_this |
109 | 103 | portion of the class and replace it after whatever happens to modify it (e.g. the |
110 | 104 | user performing construction or the wrapper shared_ptr in saving). |
105 | ||
106 | Note that this goes into undefined behavior territory, but as of the initial writing | |
107 | of this, all standard library implementations of std::enable_shared_from_this are | |
108 | compatible with this memory manipulation. It is entirely possible that this may someday | |
109 | break or may not work with convoluted use cases. | |
111 | 110 | |
112 | 111 | Example usage: |
113 | 112 | |
135 | 134 | using BaseType = typename ::cereal::traits::get_shared_from_this_base<T>::type; |
136 | 135 | using ParentType = std::enable_shared_from_this<BaseType>; |
137 | 136 | using StorageType = typename std::aligned_storage<sizeof(ParentType), CEREAL_ALIGNOF(ParentType)>::type; |
138 | ||
137 | ||
139 | 138 | public: |
140 | 139 | //! Saves the state of some type inheriting from enable_shared_from_this |
141 | 140 | /*! @param ptr The raw pointer held by the shared_ptr */ |
152 | 151 | { |
153 | 152 | if( !itsRestored ) |
154 | 153 | { |
155 | std::memcpy( itsPtr, &itsState, sizeof(ParentType) ); | |
154 | // void * cast needed when type has no trivial copy-assignment | |
155 | std::memcpy( static_cast<void *>(itsPtr), &itsState, sizeof(ParentType) ); | |
156 | 156 | itsRestored = true; |
157 | 157 | } |
158 | 158 | } |
277 | 277 | typename std::enable_if<traits::has_load_and_construct<T, Archive>::value, void>::type |
278 | 278 | CEREAL_LOAD_FUNCTION_NAME( Archive & ar, memory_detail::PtrWrapper<std::shared_ptr<T> &> & wrapper ) |
279 | 279 | { |
280 | auto & ptr = wrapper.ptr; | |
281 | ||
282 | 280 | uint32_t id; |
283 | 281 | |
284 | 282 | ar( CEREAL_NVP_("id", id) ); |
296 | 294 | |
297 | 295 | // Allocate our storage, which we will treat as |
298 | 296 | // uninitialized until initialized with placement new |
299 | ptr.reset( reinterpret_cast<T *>( new ST() ), | |
300 | [=]( T * t ) | |
297 | using NonConstT = typename std::remove_const<T>::type; | |
298 | std::shared_ptr<NonConstT> ptr(reinterpret_cast<NonConstT *>(new ST()), | |
299 | [=]( NonConstT * t ) | |
301 | 300 | { |
302 | 301 | if( *valid ) |
303 | 302 | t->~T(); |
309 | 308 | ar.registerSharedPointer( id, ptr ); |
310 | 309 | |
311 | 310 | // Perform the actual loading and allocation |
312 | memory_detail::loadAndConstructSharedPtr( ar, ptr.get(), typename ::cereal::traits::has_shared_from_this<T>::type() ); | |
311 | memory_detail::loadAndConstructSharedPtr( ar, ptr.get(), typename ::cereal::traits::has_shared_from_this<NonConstT>::type() ); | |
313 | 312 | |
314 | 313 | // Mark pointer as valid (initialized) |
315 | 314 | *valid = true; |
315 | wrapper.ptr = std::move(ptr); | |
316 | 316 | } |
317 | 317 | else |
318 | ptr = std::static_pointer_cast<T>(ar.getSharedPointer(id)); | |
318 | wrapper.ptr = std::static_pointer_cast<T>(ar.getSharedPointer(id)); | |
319 | 319 | } |
320 | 320 | |
321 | 321 | //! Loading std::shared_ptr, case when no user load and construct (wrapper implementation) |
324 | 324 | typename std::enable_if<!traits::has_load_and_construct<T, Archive>::value, void>::type |
325 | 325 | CEREAL_LOAD_FUNCTION_NAME( Archive & ar, memory_detail::PtrWrapper<std::shared_ptr<T> &> & wrapper ) |
326 | 326 | { |
327 | auto & ptr = wrapper.ptr; | |
328 | ||
329 | 327 | uint32_t id; |
330 | 328 | |
331 | 329 | ar( CEREAL_NVP_("id", id) ); |
332 | 330 | |
333 | 331 | if( id & detail::msb_32bit ) |
334 | 332 | { |
335 | ptr.reset( detail::Construct<T, Archive>::load_andor_construct() ); | |
333 | using NonConstT = typename std::remove_const<T>::type; | |
334 | std::shared_ptr<NonConstT> ptr( detail::Construct<NonConstT, Archive>::load_andor_construct() ); | |
336 | 335 | ar.registerSharedPointer( id, ptr ); |
337 | 336 | ar( CEREAL_NVP_("data", *ptr) ); |
337 | wrapper.ptr = std::move(ptr); | |
338 | 338 | } |
339 | 339 | else |
340 | ptr = std::static_pointer_cast<T>(ar.getSharedPointer(id)); | |
340 | wrapper.ptr = std::static_pointer_cast<T>(ar.getSharedPointer(id)); | |
341 | 341 | } |
342 | 342 | |
343 | 343 | //! Saving std::unique_ptr (wrapper implementation) |
373 | 373 | |
374 | 374 | if( isValid ) |
375 | 375 | { |
376 | using NonConstT = typename std::remove_const<T>::type; | |
376 | 377 | // Storage type for the pointer - since we can't default construct this type, |
377 | 378 | // we'll allocate it using std::aligned_storage |
378 | using ST = typename std::aligned_storage<sizeof(T), CEREAL_ALIGNOF(T)>::type; | |
379 | using ST = typename std::aligned_storage<sizeof(NonConstT), CEREAL_ALIGNOF(NonConstT)>::type; | |
379 | 380 | |
380 | 381 | // Allocate storage - note the ST type so that deleter is correct if |
381 | 382 | // an exception is thrown before we are initialized |
382 | 383 | std::unique_ptr<ST> stPtr( new ST() ); |
383 | 384 | |
384 | 385 | // Use wrapper to enter into "data" nvp of ptr_wrapper |
385 | memory_detail::LoadAndConstructLoadWrapper<Archive, T> loadWrapper( reinterpret_cast<T *>( stPtr.get() ) ); | |
386 | memory_detail::LoadAndConstructLoadWrapper<Archive, NonConstT> loadWrapper( reinterpret_cast<NonConstT *>( stPtr.get() ) ); | |
386 | 387 | |
387 | 388 | // Initialize storage |
388 | 389 | ar( CEREAL_NVP_("data", loadWrapper) ); |
403 | 404 | uint8_t isValid; |
404 | 405 | ar( CEREAL_NVP_("valid", isValid) ); |
405 | 406 | |
406 | auto & ptr = wrapper.ptr; | |
407 | ||
408 | 407 | if( isValid ) |
409 | 408 | { |
410 | ptr.reset( detail::Construct<T, Archive>::load_andor_construct() ); | |
409 | using NonConstT = typename std::remove_const<T>::type; | |
410 | std::unique_ptr<NonConstT, D> ptr( detail::Construct<NonConstT, Archive>::load_andor_construct() ); | |
411 | 411 | ar( CEREAL_NVP_( "data", *ptr ) ); |
412 | wrapper.ptr = std::move(ptr); | |
412 | 413 | } |
413 | 414 | else |
414 | 415 | { |
415 | ptr.reset( nullptr ); | |
416 | wrapper.ptr.reset( nullptr ); | |
416 | 417 | } |
417 | 418 | } |
418 | 419 | } // namespace cereal |
420 | 421 | // automatically include polymorphic support |
421 | 422 | #include "cereal/types/polymorphic.hpp" |
422 | 423 | |
423 | #undef CEREAL_ALIGNOF | |
424 | #endif // CEREAL_TYPES_SHARED_PTR_HPP_⏎ | |
424 | #endif // CEREAL_TYPES_SHARED_PTR_HPP_ |
0 | /*! \file optional.hpp | |
1 | \brief Support for std::optional | |
2 | \ingroup STLSupport */ | |
3 | /* | |
4 | Copyright (c) 2017, Juan Pedro Bolivar Puente | |
5 | All rights reserved. | |
6 | ||
7 | Redistribution and use in source and binary forms, with or without | |
8 | modification, are permitted provided that the following conditions are met: | |
9 | * Redistributions of source code must retain the above copyright | |
10 | notice, this list of conditions and the following disclaimer. | |
11 | * Redistributions in binary form must reproduce the above copyright | |
12 | notice, this list of conditions and the following disclaimer in the | |
13 | documentation and/or other materials provided with the distribution. | |
14 | * Neither the name of cereal nor the | |
15 | names of its contributors may be used to endorse or promote products | |
16 | derived from this software without specific prior written permission. | |
17 | ||
18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND | |
19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED | |
20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | |
21 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY | |
22 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES | |
23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | |
24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND | |
25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | |
27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
28 | */ | |
29 | #ifndef CEREAL_TYPES_STD_OPTIONAL_ | |
30 | #define CEREAL_TYPES_STD_OPTIONAL_ | |
31 | ||
32 | #include "cereal/cereal.hpp" | |
33 | #include <optional> | |
34 | ||
35 | namespace cereal { | |
36 | //! Saving for std::optional | |
37 | template <class Archive, typename T> inline | |
38 | void CEREAL_SAVE_FUNCTION_NAME(Archive& ar, const std::optional<T>& optional) | |
39 | { | |
40 | if(!optional) { | |
41 | ar(CEREAL_NVP_("nullopt", true)); | |
42 | } else { | |
43 | ar(CEREAL_NVP_("nullopt", false), | |
44 | CEREAL_NVP_("data", *optional)); | |
45 | } | |
46 | } | |
47 | ||
48 | //! Loading for std::optional | |
49 | template <class Archive, typename T> inline | |
50 | void CEREAL_LOAD_FUNCTION_NAME(Archive& ar, std::optional<T>& optional) | |
51 | { | |
52 | bool nullopt; | |
53 | ar(CEREAL_NVP_("nullopt", nullopt)); | |
54 | ||
55 | if (nullopt) { | |
56 | optional = std::nullopt; | |
57 | } else { | |
58 | T value; | |
59 | ar(CEREAL_NVP_("data", value)); | |
60 | optional = std::move(value); | |
61 | } | |
62 | } | |
63 | } // namespace cereal | |
64 | ||
65 | #endif // CEREAL_TYPES_STD_OPTIONAL_ |
164 | 164 | See CEREAL_REGISTER_DYNAMIC_INIT for detailed explanation |
165 | 165 | of how this macro should be used. The name used should |
166 | 166 | match that for CEREAL_REGISTER_DYNAMIC_INIT. */ |
167 | #define CEREAL_FORCE_DYNAMIC_INIT(LibName) \ | |
168 | namespace cereal { \ | |
169 | namespace detail { \ | |
170 | void dynamic_init_dummy_##LibName(); \ | |
171 | } /* end detail */ \ | |
172 | namespace { \ | |
173 | void dynamic_init_##LibName() \ | |
174 | { \ | |
175 | ::cereal::detail::dynamic_init_dummy_##LibName(); \ | |
176 | } \ | |
177 | } } /* end namespaces */ | |
167 | #define CEREAL_FORCE_DYNAMIC_INIT(LibName) \ | |
168 | namespace cereal { \ | |
169 | namespace detail { \ | |
170 | void CEREAL_DLL_EXPORT dynamic_init_dummy_##LibName(); \ | |
171 | } /* end detail */ \ | |
172 | } /* end cereal */ \ | |
173 | namespace { \ | |
174 | struct dynamic_init_##LibName { \ | |
175 | dynamic_init_##LibName() { \ | |
176 | ::cereal::detail::dynamic_init_dummy_##LibName(); \ | |
177 | } \ | |
178 | } dynamic_init_instance_##LibName; \ | |
179 | } /* end anonymous namespace */ | |
178 | 180 | |
179 | 181 | namespace cereal |
180 | 182 | { |
37 | 37 | namespace tuple_detail |
38 | 38 | { |
39 | 39 | //! Creates a c string from a sequence of characters |
40 | /*! The c string created will alwas be prefixed by "tuple_element" | |
40 | /*! The c string created will always be prefixed by "tuple_element" | |
41 | 41 | Based on code from: http://stackoverflow/a/20973438/710791 |
42 | 42 | @internal */ |
43 | 43 | template<char...Cs> |
62 | 62 | template <size_t Q, size_t R, char ... C> |
63 | 63 | struct to_string_impl |
64 | 64 | { |
65 | using type = typename to_string_impl<Q/10, Q%10, R+'0', C...>::type; | |
65 | using type = typename to_string_impl<Q/10, Q%10, static_cast<char>(R+std::size_t{'0'}), C...>::type; | |
66 | 66 | }; |
67 | 67 | |
68 | 68 | //! Base case with no quotient |
70 | 70 | template <size_t R, char ... C> |
71 | 71 | struct to_string_impl<0, R, C...> |
72 | 72 | { |
73 | using type = char_seq_to_c_str<R+'0', C...>; | |
73 | using type = char_seq_to_c_str<static_cast<char>(R+std::size_t{'0'}), C...>; | |
74 | 74 | }; |
75 | 75 | |
76 | 76 | //! Generates a c string for a given index of a tuple |
83 | 83 | struct tuple_element_name |
84 | 84 | { |
85 | 85 | using type = typename to_string_impl<T/10, T%10>::type; |
86 | static const typename type::arr_type c_str(){ return type::str; }; | |
86 | static const typename type::arr_type c_str(){ return type::str; } | |
87 | 87 | }; |
88 | 88 | |
89 | 89 | // unwinds a tuple to save it |
0 | /*! \file variant.hpp | |
1 | \brief Support for std::variant | |
2 | \ingroup STLSupport */ | |
3 | /* | |
4 | Copyright (c) 2014, 2017, Randolph Voorhies, Shane Grant, Juan Pedro | |
5 | Bolivar Puente. All rights reserved. | |
6 | ||
7 | Redistribution and use in source and binary forms, with or without | |
8 | modification, are permitted provided that the following conditions are met: | |
9 | * Redistributions of source code must retain the above copyright | |
10 | notice, this list of conditions and the following disclaimer. | |
11 | * Redistributions in binary form must reproduce the above copyright | |
12 | notice, this list of conditions and the following disclaimer in the | |
13 | documentation and/or other materials provided with the distribution. | |
14 | * Neither the name of cereal nor the | |
15 | names of its contributors may be used to endorse or promote products | |
16 | derived from this software without specific prior written permission. | |
17 | ||
18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND | |
19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED | |
20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | |
21 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY | |
22 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES | |
23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | |
24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND | |
25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | |
27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
28 | */ | |
29 | #ifndef CEREAL_TYPES_STD_VARIANT_HPP_ | |
30 | #define CEREAL_TYPES_STD_VARIANT_HPP_ | |
31 | ||
32 | #include "cereal/cereal.hpp" | |
33 | #include <variant> | |
34 | #include <cstdint> | |
35 | ||
36 | namespace cereal | |
37 | { | |
38 | namespace variant_detail | |
39 | { | |
40 | //! @internal | |
41 | template <class Archive> | |
42 | struct variant_save_visitor | |
43 | { | |
44 | variant_save_visitor(Archive & ar_) : ar(ar_) {} | |
45 | ||
46 | template<class T> | |
47 | void operator()(T const & value) const | |
48 | { | |
49 | ar( CEREAL_NVP_("data", value) ); | |
50 | } | |
51 | ||
52 | Archive & ar; | |
53 | }; | |
54 | ||
55 | //! @internal | |
56 | template<int N, class Variant, class ... Args, class Archive> | |
57 | typename std::enable_if<N == std::variant_size_v<Variant>, void>::type | |
58 | load_variant(Archive & /*ar*/, int /*target*/, Variant & /*variant*/) | |
59 | { | |
60 | throw ::cereal::Exception("Error traversing variant during load"); | |
61 | } | |
62 | //! @internal | |
63 | template<int N, class Variant, class H, class ... T, class Archive> | |
64 | typename std::enable_if<N < std::variant_size_v<Variant>, void>::type | |
65 | load_variant(Archive & ar, int target, Variant & variant) | |
66 | { | |
67 | if(N == target) | |
68 | { | |
69 | H value; | |
70 | ar( CEREAL_NVP_("data", value) ); | |
71 | variant = std::move(value); | |
72 | } | |
73 | else | |
74 | load_variant<N+1, Variant, T...>(ar, target, variant); | |
75 | } | |
76 | ||
77 | } // namespace variant_detail | |
78 | ||
79 | //! Saving for std::variant | |
80 | template <class Archive, typename VariantType1, typename... VariantTypes> inline | |
81 | void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::variant<VariantType1, VariantTypes...> const & variant ) | |
82 | { | |
83 | std::int32_t index = static_cast<std::int32_t>(variant.index()); | |
84 | ar( CEREAL_NVP_("index", index) ); | |
85 | variant_detail::variant_save_visitor<Archive> visitor(ar); | |
86 | std::visit(visitor, variant); | |
87 | } | |
88 | ||
89 | //! Loading for std::variant | |
90 | template <class Archive, typename... VariantTypes> inline | |
91 | void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::variant<VariantTypes...> & variant ) | |
92 | { | |
93 | using variant_t = typename std::variant<VariantTypes...>; | |
94 | ||
95 | std::int32_t index; | |
96 | ar( CEREAL_NVP_("index", index) ); | |
97 | if(index >= static_cast<std::int32_t>(std::variant_size_v<variant_t>)) | |
98 | throw Exception("Invalid 'index' selector when deserializing std::variant"); | |
99 | ||
100 | variant_detail::load_variant<0, variant_t, VariantTypes...>(ar, index, variant); | |
101 | } | |
102 | ||
103 | //! Serializing a std::monostate | |
104 | template <class Archive> | |
105 | void CEREAL_SERIALIZE_FUNCTION_NAME( Archive &, std::monostate const & ) {} | |
106 | } // namespace cereal | |
107 | ||
108 | #endif // CEREAL_TYPES_STD_VARIANT_HPP_ |
59 | 59 | |
60 | 60 | //! Serialization for non-arithmetic vector types |
61 | 61 | template <class Archive, class T, class A> inline |
62 | typename std::enable_if<!traits::is_output_serializable<BinaryData<T>, Archive>::value | |
63 | || !std::is_arithmetic<T>::value, void>::type | |
62 | typename std::enable_if<(!traits::is_output_serializable<BinaryData<T>, Archive>::value | |
63 | || !std::is_arithmetic<T>::value) && !std::is_same<T, bool>::value, void>::type | |
64 | 64 | CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::vector<T, A> const & vector ) |
65 | 65 | { |
66 | 66 | ar( make_size_tag( static_cast<size_type>(vector.size()) ) ); // number of elements |
70 | 70 | |
71 | 71 | //! Serialization for non-arithmetic vector types |
72 | 72 | template <class Archive, class T, class A> inline |
73 | typename std::enable_if<!traits::is_input_serializable<BinaryData<T>, Archive>::value | |
74 | || !std::is_arithmetic<T>::value, void>::type | |
73 | typename std::enable_if<(!traits::is_input_serializable<BinaryData<T>, Archive>::value | |
74 | || !std::is_arithmetic<T>::value) && !std::is_same<T, bool>::value, void>::type | |
75 | 75 | CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::vector<T, A> & vector ) |
76 | 76 | { |
77 | 77 | size_type size; |
87 | 87 | void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::vector<bool, A> const & vector ) |
88 | 88 | { |
89 | 89 | ar( make_size_tag( static_cast<size_type>(vector.size()) ) ); // number of elements |
90 | for(auto && v : vector) | |
90 | for(const auto v : vector) | |
91 | 91 | ar( static_cast<bool>(v) ); |
92 | 92 | } |
93 | 93 | |
99 | 99 | ar( make_size_tag( size ) ); |
100 | 100 | |
101 | 101 | vector.resize( static_cast<std::size_t>( size ) ); |
102 | for(auto && v : vector) | |
102 | for(auto v : vector) | |
103 | 103 | { |
104 | 104 | bool b; |
105 | 105 | ar( b ); |
0 | /*! \file version.hpp | |
1 | \brief Macros to detect cereal version | |
2 | ||
3 | These macros can assist in determining the version of cereal. Be | |
4 | warned that cereal is not guaranteed to be compatible across | |
5 | different versions. For more information on releases of cereal, | |
6 | see https://github.com/USCiLab/cereal/releases. | |
7 | ||
8 | \ingroup utility */ | |
9 | /* | |
10 | Copyright (c) 2018, Shane Grant | |
11 | All rights reserved. | |
12 | ||
13 | Redistribution and use in source and binary forms, with or without | |
14 | modification, are permitted provided that the following conditions are met: | |
15 | * Redistributions of source code must retain the above copyright | |
16 | notice, this list of conditions and the following disclaimer. | |
17 | * Redistributions in binary form must reproduce the above copyright | |
18 | notice, this list of conditions and the following disclaimer in the | |
19 | documentation and/or other materials provided with the distribution. | |
20 | * Neither the name of cereal nor the | |
21 | names of its contributors may be used to endorse or promote products | |
22 | derived from this software without specific prior written permission. | |
23 | ||
24 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND | |
25 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED | |
26 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | |
27 | DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY | |
28 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES | |
29 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | |
30 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND | |
31 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
32 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | |
33 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
34 | */ | |
35 | ||
36 | #ifndef CEREAL_VERSION_HPP_ | |
37 | #define CEREAL_VERSION_HPP_ | |
38 | ||
39 | //! The major version | |
40 | #define CEREAL_VERSION_MAJOR 1 | |
41 | //! The minor version | |
42 | #define CEREAL_VERSION_MINOR 3 | |
43 | //! The patch version | |
44 | #define CEREAL_VERSION_PATCH 0 | |
45 | ||
46 | //! The full version as a single number | |
47 | #define CEREAL_VERSION (CEREAL_VERSION_MAJOR * 10000 \ | |
48 | + CEREAL_VERSION_MINOR * 100 \ | |
49 | + CEREAL_VERSION_PATCH) | |
50 | ||
51 | #endif // CEREAL_VERSION_HPP_ |
58 | 58 | return labels[text].get(); |
59 | 59 | } |
60 | 60 | |
61 | Button::Button() { | |
62 | label = ""; | |
63 | marked = false; | |
64 | action = nullptr; | |
65 | popOnRun = false; | |
66 | } | |
67 | ||
68 | Button::~Button() { | |
69 | } | |
70 | ||
71 | 61 | Button::Button(const Button& b) : action{b.action}, label{b.label}, marked{b.marked} { |
72 | 62 | } |
73 | 63 | |
151 | 141 | placeButtons(); |
152 | 142 | } |
153 | 143 | |
154 | Menu::Menu(SDL_Renderer* screen) { | |
155 | this->screen = screen; | |
156 | buttons = std::vector<Button*>(10); | |
157 | isSubmenu = true; | |
144 | Menu::Menu(SDL_Renderer* screen) : buttons{std::vector<Button*>(10)}, isSubmenu{true}, screen{screen} { | |
158 | 145 | exit.setLabel( _("Back") ); |
159 | 146 | } |
160 | 147 | |
161 | Menu::Menu(SDL_Renderer* screen,bool submenu) { | |
162 | this->screen = screen; | |
163 | buttons = std::vector<Button*>(0); | |
164 | isSubmenu = submenu; | |
148 | Menu::Menu(SDL_Renderer* screen,bool submenu) : buttons{std::vector<Button*>(0)}, isSubmenu{submenu}, screen{screen} { | |
165 | 149 | if (isSubmenu) { |
166 | 150 | exit.setLabel( _("Back") ); |
167 | 151 | } |
170 | 154 | } |
171 | 155 | } |
172 | 156 | |
173 | Menu::Menu(SDL_Renderer* screen, const std::string& title, bool submenu) : title{title} { | |
174 | this->screen = screen; | |
175 | buttons = std::vector<Button*>(0); | |
176 | isSubmenu = submenu; | |
157 | Menu::Menu(SDL_Renderer* screen, const std::string& title, bool submenu) : buttons{std::vector<Button*>(0)}, isSubmenu{submenu}, screen{screen}, title{title} { | |
177 | 158 | if (isSubmenu) { |
178 | 159 | exit.setLabel(_("Back") ); |
179 | 160 | } |
188 | 169 | return true; |
189 | 170 | } |
190 | 171 | } |
172 | return isControllerUpEvent(event); | |
173 | } | |
174 | ||
175 | bool isDownEvent(const SDL_Event& event) { | |
176 | if ( event.type == SDL_KEYDOWN ) { | |
177 | if (event.key.keysym.sym == SDLK_DOWN) { | |
178 | return true; | |
179 | } | |
180 | } | |
181 | return isControllerDownEvent(event); | |
182 | } | |
183 | ||
184 | bool isLeftEvent(const SDL_Event& event) { | |
185 | if ( event.type == SDL_KEYDOWN ) { | |
186 | if (event.key.keysym.sym == SDLK_LEFT) { | |
187 | return true; | |
188 | } | |
189 | } | |
190 | return isControllerLeftEvent(event); | |
191 | } | |
192 | ||
193 | bool isRightEvent(const SDL_Event& event) { | |
194 | if ( event.type == SDL_KEYDOWN ) { | |
195 | if (event.key.keysym.sym == SDLK_RIGHT) { | |
196 | return true; | |
197 | } | |
198 | } | |
199 | return isControllerRightEvent(event); | |
200 | } | |
201 | ||
202 | bool isEscapeEvent(const SDL_Event& event) { | |
203 | if ( event.type == SDL_KEYDOWN ) { | |
204 | if ( event.key.keysym.sym == SDLK_ESCAPE ) { | |
205 | return true; | |
206 | } | |
207 | } | |
191 | 208 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { |
192 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_UP ) { | |
193 | return true; | |
194 | } | |
195 | } | |
196 | if (event.type == SDL_CONTROLLERAXISMOTION && event.caxis.axis == SDL_CONTROLLER_AXIS_LEFTY ) { | |
197 | checkDeadZone(event); | |
198 | const SDL_ControllerAxisEvent& a = event.caxis; | |
199 | if (getDeadZone(a.which, a.axis)) { | |
200 | if (event.caxis.value < -deadZoneLimit) { | |
201 | setDeadZone(a.which,a.axis,false); | |
202 | return true; | |
203 | } | |
209 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_B || event.cbutton.button == SDL_CONTROLLER_BUTTON_BACK ) { | |
210 | return true; | |
204 | 211 | } |
205 | 212 | } |
206 | 213 | return false; |
207 | 214 | } |
208 | 215 | |
209 | bool isDownEvent(const SDL_Event& event) { | |
210 | if ( event.type == SDL_KEYDOWN ) { | |
211 | if (event.key.keysym.sym == SDLK_DOWN) { | |
216 | bool isConfirmEvent(const SDL_Event& event) { | |
217 | if ( event.type == SDL_KEYDOWN ) { | |
218 | if (event.key.keysym.sym == SDLK_RETURN || event.key.keysym.sym == SDLK_KP_ENTER ) { | |
212 | 219 | return true; |
213 | 220 | } |
214 | 221 | } |
215 | 222 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { |
216 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN ) { | |
217 | return true; | |
218 | } | |
219 | } | |
220 | if (event.type == SDL_CONTROLLERAXISMOTION && event.caxis.axis == SDL_CONTROLLER_AXIS_LEFTY ) { | |
221 | checkDeadZone(event); | |
222 | const SDL_ControllerAxisEvent& a = event.caxis; | |
223 | if (getDeadZone(a.which, a.axis)) { | |
224 | if (event.caxis.value > deadZoneLimit) { | |
225 | setDeadZone(a.which,a.axis,false); | |
226 | return true; | |
227 | } | |
228 | } | |
229 | } | |
230 | return false; | |
231 | } | |
232 | ||
233 | bool isLeftEvent(const SDL_Event& event) { | |
234 | if ( event.type == SDL_KEYDOWN ) { | |
235 | if (event.key.keysym.sym == SDLK_LEFT) { | |
236 | return true; | |
237 | } | |
238 | } | |
239 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
240 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT ) { | |
241 | return true; | |
242 | } | |
243 | } | |
244 | if (event.type == SDL_CONTROLLERAXISMOTION && event.caxis.axis == SDL_CONTROLLER_AXIS_LEFTX ) { | |
245 | checkDeadZone(event); | |
246 | const SDL_ControllerAxisEvent& a = event.caxis; | |
247 | if (getDeadZone(a.which, a.axis)) { | |
248 | if (event.caxis.value < -deadZoneLimit) { | |
249 | setDeadZone(a.which,a.axis,false); | |
250 | return true; | |
251 | } | |
252 | } | |
253 | } | |
254 | return false; | |
255 | } | |
256 | ||
257 | bool isRightEvent(const SDL_Event& event) { | |
258 | if ( event.type == SDL_KEYDOWN ) { | |
259 | if (event.key.keysym.sym == SDLK_RIGHT) { | |
260 | return true; | |
261 | } | |
262 | } | |
263 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
264 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_RIGHT ) { | |
265 | return true; | |
266 | } | |
267 | } | |
268 | if (event.type == SDL_CONTROLLERAXISMOTION && event.caxis.axis == SDL_CONTROLLER_AXIS_LEFTX ) { | |
269 | checkDeadZone(event); | |
270 | const SDL_ControllerAxisEvent& a = event.caxis; | |
271 | if (getDeadZone(a.which, a.axis)) { | |
272 | if (event.caxis.value > deadZoneLimit) { | |
273 | setDeadZone(a.which,a.axis,false); | |
274 | return true; | |
275 | } | |
276 | } | |
277 | } | |
278 | return false; | |
279 | } | |
280 | ||
281 | bool isEscapeEvent(const SDL_Event& event) { | |
282 | if ( event.type == SDL_KEYDOWN ) { | |
283 | if ( event.key.keysym.sym == SDLK_ESCAPE ) { | |
284 | return true; | |
285 | } | |
286 | } | |
287 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
288 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_Y || event.cbutton.button == SDL_CONTROLLER_BUTTON_BACK ) { | |
289 | return true; | |
290 | } | |
291 | } | |
292 | return false; | |
293 | } | |
294 | ||
295 | bool isConfirmEvent(const SDL_Event& event) { | |
296 | if ( event.type == SDL_KEYDOWN ) { | |
297 | if (event.key.keysym.sym == SDLK_RETURN || event.key.keysym.sym == SDLK_KP_ENTER ) { | |
298 | return true; | |
299 | } | |
300 | } | |
301 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
302 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_A || event.cbutton.button == SDL_CONTROLLER_BUTTON_B ) { | |
223 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_A ) { | |
303 | 224 | return true; |
304 | 225 | } |
305 | 226 | } |
333 | 254 | #endif |
334 | 255 | } |
335 | 256 | void Menu::ProcessInput(const SDL_Event& event, bool& processed) { |
257 | if (isGameControllerConnectionEvent(event)) { | |
258 | UnInitGameControllers(); | |
259 | InitGameControllers(); | |
260 | processed = true; | |
261 | } | |
262 | ||
336 | 263 | if (isUpEvent(event)) { |
337 | 264 | marked--; |
338 | 265 | if (marked<0) { |
66 | 66 | int x = 0; |
67 | 67 | int y = 0; |
68 | 68 | |
69 | Button(); | |
69 | Button() = default; | |
70 | 70 | Button(const Button& b); |
71 | 71 | Button& operator=(const Button& other); |
72 | virtual ~Button(); | |
72 | virtual ~Button() = default; | |
73 | 73 | |
74 | 74 | |
75 | 75 | //Set the text to write on the button |
103 | 103 | //numberOfItems is the expected numberOfItems for vector initialization |
104 | 104 | //SubMenu is true by default |
105 | 105 | Menu(SDL_Renderer *screen,bool isSubmenu); |
106 | Menu(SDL_Renderer *screen); | |
106 | explicit Menu(SDL_Renderer *screen); | |
107 | 107 | Menu(SDL_Renderer *screen, const std::string& title, bool isSubmenu); |
108 | 108 | virtual ~Menu() {} |
109 | ||
109 | ||
110 | 110 | //Add a button to the menu |
111 | 111 | void addButton(Button *b); |
112 | ||
112 | ||
113 | 113 | bool IsActive() override; |
114 | 114 | void Draw(SDL_Renderer* target) override; |
115 | 115 | void ProcessInput(const SDL_Event& event, bool &processed) override; |
70 | 70 | return ReadKey(key.key.keysym.sym); |
71 | 71 | } |
72 | 72 | |
73 | bool ReadKeyboard::cursorLeft() { | |
74 | if (position>text_string.begin()) { | |
75 | utf8::prior(position, text_string.begin()); | |
76 | return true; | |
77 | } | |
78 | return false; | |
79 | } | |
80 | bool ReadKeyboard::cursorRight() { | |
81 | if (position<text_string.end()) { | |
82 | utf8::next(position, text_string.end()); | |
83 | return true; | |
84 | } | |
85 | return false; | |
86 | } | |
87 | ||
88 | bool ReadKeyboard::emulateBackspace() { | |
89 | if (position>text_string.begin()) { | |
90 | utf8::prior(position, text_string.begin()); | |
91 | ReadKeyboard::removeChar(); | |
92 | return true; | |
93 | } | |
94 | return false; | |
95 | } | |
96 | ||
73 | 97 | bool ReadKeyboard::ReadKey(SDL_Keycode keyPressed) { |
74 | 98 | if (keyPressed == SDLK_DELETE) { |
75 | 99 | if ((text_string.length()>0)&& (position<text_string.end())) { |
78 | 102 | return true; |
79 | 103 | } |
80 | 104 | if (keyPressed == SDLK_BACKSPACE) { |
81 | if (position>text_string.begin()) { | |
82 | utf8::prior(position, text_string.begin()); | |
83 | ReadKeyboard::removeChar(); | |
84 | return true; | |
85 | } | |
86 | return false; | |
105 | return emulateBackspace(); | |
87 | 106 | } |
88 | 107 | if (keyPressed == SDLK_HOME) { |
89 | 108 | position = text_string.begin(); |
93 | 112 | position=text_string.end(); |
94 | 113 | return true; |
95 | 114 | } |
96 | if ((keyPressed == SDLK_LEFT) && (position>text_string.begin())) { | |
97 | utf8::prior(position, text_string.begin()); | |
115 | if (keyPressed == SDLK_LEFT) { | |
116 | cursorLeft(); | |
98 | 117 | return true; |
99 | 118 | } |
100 | if ((keyPressed == SDLK_RIGHT) && (position<text_string.end())) { | |
101 | utf8::next(position, text_string.end()); | |
119 | if ((keyPressed == SDLK_RIGHT)) { | |
120 | cursorRight(); | |
102 | 121 | return true; |
103 | 122 | } |
104 | 123 | return true; |
36 | 36 | int maxLength = 0; |
37 | 37 | std::string::iterator position; |
38 | 38 | std::string text_string; |
39 | void putchar(const std::string& ); | |
40 | 39 | void removeChar(); |
41 | 40 | public: |
42 | 41 | ReadKeyboard(void); |
43 | 42 | ~ReadKeyboard(void); |
44 | ReadKeyboard(const char*); | |
43 | explicit ReadKeyboard(const char*); | |
45 | 44 | int CharsBeforeCursor(); //Where should the cursor be placed? |
45 | void putchar(const std::string& ); | |
46 | bool cursorLeft(); | |
47 | bool cursorRight(); | |
48 | bool emulateBackspace(); | |
46 | 49 | bool ReadKey(const SDL_Event&); |
47 | 50 | bool ReadKey(SDL_Keycode); //true if key accepted |
48 | 51 | const std::string& GetString(void) const; |
69 | 69 | if (endless) { |
70 | 70 | std::string header; |
71 | 71 | switch (level) { |
72 | case 1: | |
73 | header = _("Endless (Fast):"); | |
74 | break; | |
75 | case 2: | |
76 | header = _("Endless (Faster):"); | |
77 | break; | |
78 | case 3: | |
79 | header = _("Endless (Even faster):"); | |
80 | break; | |
81 | case 4: | |
82 | header = _("Endless (Fastest):"); | |
83 | break; | |
84 | default: | |
85 | header = _("Endless:"); | |
72 | case 1: | |
73 | header = _("Endless (Fast):"); | |
74 | break; | |
75 | case 2: | |
76 | header = _("Endless (Faster):"); | |
77 | break; | |
78 | case 3: | |
79 | header = _("Endless (Even faster):"); | |
80 | break; | |
81 | case 4: | |
82 | header = _("Endless (Fastest):"); | |
83 | break; | |
84 | default: | |
85 | header = _("Endless:"); | |
86 | 86 | }; |
87 | 87 | Write(globalData.screen, x+100,y+100, header.c_str() ); |
88 | 88 | } |
92 | 92 | for (int i =0; i<10; i++) { |
93 | 93 | record r; |
94 | 94 | if (endless) { |
95 | switch(level) { | |
96 | case 1: | |
97 | r = theTopScoresEndless1.getScoreNumber(i); | |
98 | break; | |
99 | case 2: | |
100 | r = theTopScoresEndless2.getScoreNumber(i); | |
101 | break; | |
102 | case 3: | |
103 | r = theTopScoresEndless3.getScoreNumber(i); | |
104 | break; | |
105 | case 4: | |
106 | r = theTopScoresEndless4.getScoreNumber(i); | |
107 | break; | |
108 | default: | |
109 | r = theTopScoresEndless0.getScoreNumber(i); | |
95 | switch (level) { | |
96 | case 1: | |
97 | r = theTopScoresEndless1.getScoreNumber(i); | |
98 | break; | |
99 | case 2: | |
100 | r = theTopScoresEndless2.getScoreNumber(i); | |
101 | break; | |
102 | case 3: | |
103 | r = theTopScoresEndless3.getScoreNumber(i); | |
104 | break; | |
105 | case 4: | |
106 | r = theTopScoresEndless4.getScoreNumber(i); | |
107 | break; | |
108 | default: | |
109 | r = theTopScoresEndless0.getScoreNumber(i); | |
110 | 110 | } |
111 | 111 | } |
112 | 112 | else { |
194 | 194 | |
195 | 195 | void ScoresDisplay::Draw(SDL_Renderer*) { |
196 | 196 | switch (page) { |
197 | case 0: | |
198 | case 1: | |
199 | case 2: | |
200 | case 3: | |
201 | case 4: | |
202 | //Highscores, endless | |
203 | DrawHighscores(100,100,true, page); | |
204 | break; | |
205 | case 5: | |
206 | //Highscores, Time Trial | |
207 | DrawHighscores(100,100,false); | |
208 | break; | |
209 | case 6: | |
210 | default: | |
211 | DrawStats(); | |
197 | case 0: | |
198 | case 1: | |
199 | case 2: | |
200 | case 3: | |
201 | case 4: | |
202 | //Highscores, endless | |
203 | DrawHighscores(100,100,true, page); | |
204 | break; | |
205 | case 5: | |
206 | //Highscores, Time Trial | |
207 | DrawHighscores(100,100,false); | |
208 | break; | |
209 | case 6: | |
210 | default: | |
211 | DrawStats(); | |
212 | 212 | }; |
213 | 213 | |
214 | 214 | const sago::SagoDataHolder* holder = &globalData.spriteHolder->GetDataHolder(); |
16 | 16 | =========================================================================== |
17 | 17 | */ |
18 | 18 | |
19 | #include "DialogBox.hpp" | |
20 | #include "HelpCommon.hpp" | |
19 | 21 | #include "ShowFileState.hpp" |
20 | 22 | #include "global.hpp" |
21 | 23 | #include "common.h" |
33 | 35 | field.SetText(text); |
34 | 36 | } |
35 | 37 | |
36 | static void setHelpGamepadFont(const sago::SagoDataHolder* holder, sago::SagoTextBox& field, const char* text) { | |
37 | field.SetHolder(holder); | |
38 | field.SetFont("freeserif"); | |
39 | field.SetColor({255,255,255,255}); | |
40 | field.SetColor({0,0,0,255}); | |
41 | field.SetFontSize(20); | |
42 | field.SetOutline(0, {0,0,0,255}); | |
43 | field.SetText(text); | |
44 | } | |
45 | ||
46 | 38 | ShowFileState::ShowFileState() { |
47 | 39 | setHelpGamepadFont(&globalData.spriteHolder->GetDataHolder(), titleField, ""); |
48 | setHelpGamepadFont(&globalData.spriteHolder->GetDataHolder(), infoBox, ""); | |
49 | setHelpGamepadFont(&globalData.spriteHolder->GetDataHolder(), filenameField, ""); | |
40 | setHelpBoxFont(&globalData.spriteHolder->GetDataHolder(), infoBox, ""); | |
41 | setHelpBoxFont(&globalData.spriteHolder->GetDataHolder(), filenameField, ""); | |
50 | 42 | } |
51 | 43 | |
52 | 44 | ShowFileState::~ShowFileState() { |
65 | 57 | processed = true; |
66 | 58 | } |
67 | 59 | } |
68 | ||
69 | extern void DrawRectYellow(SDL_Renderer* target, int topx, int topy, int height, int width); | |
70 | 60 | |
71 | 61 | void ShowFileState::Draw(SDL_Renderer* target) { |
72 | 62 | DrawBackground(target); |
103 | 93 | } |
104 | 94 | |
105 | 95 | } |
106 | }⏎ | |
96 | } |
38 | 38 | static std::map<SDL_JoystickID, ControllerStatus> controllerStatusMap; |
39 | 39 | static std::map<std::string, int> gamecontrollers_assigned; |
40 | 40 | static std::vector<std::string> supportedControllers; |
41 | static std::vector<SDL_GameController*> controllersOpened; | |
41 | 42 | |
42 | 43 | |
43 | 44 | void GameControllerSetVerbose(bool value) { |
79 | 80 | return 2; //Even number means player 2 |
80 | 81 | } |
81 | 82 | return 1; |
83 | } | |
84 | ||
85 | void UnInitGameControllers() { | |
86 | if (controllersOpened.empty()) { | |
87 | return; | |
88 | } | |
89 | for (SDL_GameController* t : controllersOpened) { | |
90 | SDL_GameControllerClose(t); | |
91 | } | |
92 | controllersOpened.clear(); | |
93 | controllerStatusMap.clear(); | |
94 | gamecontrollers_assigned.clear(); | |
95 | supportedControllers.clear(); | |
82 | 96 | } |
83 | 97 | |
84 | 98 | void InitGameControllers() { |
100 | 114 | int assingToPlayer = GetNextPlayerByGui(guid); |
101 | 115 | controllerStatusMap[instanceId].player = assingToPlayer; |
102 | 116 | supportedControllers.push_back(GameControllerGetName(controller)); |
117 | controllersOpened.push_back(controller); | |
103 | 118 | if (verbose) { |
104 | 119 | std::cout << "Supported game controller detected: " << GameControllerGetName(controller) << ", mapping: " << SDL_GameControllerMapping(controller) << "\n"; |
105 | 120 | std::cout << "Assigned to player: " << controllerStatusMap[instanceId].player << "\n"; |
147 | 162 | return true; |
148 | 163 | } |
149 | 164 | |
165 | ||
166 | bool isGameControllerConnectionEvent(const SDL_Event& event) { | |
167 | if ( event.type == SDL_CONTROLLERDEVICEADDED | |
168 | || event.type == SDL_CONTROLLERDEVICEREMOVED | |
169 | || event.type == SDL_CONTROLLERDEVICEREMAPPED ) { | |
170 | return true; | |
171 | } | |
172 | return false; | |
173 | } | |
174 | ||
175 | bool isControllerDownEvent(const SDL_Event& event) { | |
176 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
177 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN ) { | |
178 | return true; | |
179 | } | |
180 | } | |
181 | if (event.type == SDL_CONTROLLERAXISMOTION && event.caxis.axis == SDL_CONTROLLER_AXIS_LEFTY ) { | |
182 | const SDL_ControllerAxisEvent& a = event.caxis; | |
183 | checkDeadZone(event); | |
184 | if (getDeadZone(a.which, a.axis)) { | |
185 | if (event.caxis.value > deadZoneLimit) { | |
186 | setDeadZone(a.which,a.axis,false); | |
187 | return true; | |
188 | } | |
189 | } | |
190 | } | |
191 | return false; | |
192 | } | |
193 | ||
150 | 194 | bool isPlayerDownEvent(int playerNumber, const SDL_Event& event) { |
151 | 195 | if (skipThisPlayer(playerNumber, event)) { |
152 | 196 | return false; |
153 | 197 | } |
154 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
155 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN ) { | |
198 | return isControllerDownEvent(event); | |
199 | } | |
200 | ||
201 | bool isControllerUpEvent(const SDL_Event& event) { | |
202 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
203 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_UP ) { | |
156 | 204 | return true; |
157 | 205 | } |
158 | 206 | } |
159 | 207 | if (event.type == SDL_CONTROLLERAXISMOTION && event.caxis.axis == SDL_CONTROLLER_AXIS_LEFTY ) { |
160 | const SDL_ControllerAxisEvent& a = event.caxis; | |
161 | checkDeadZone(event); | |
208 | checkDeadZone(event); | |
209 | const SDL_ControllerAxisEvent& a = event.caxis; | |
210 | if (getDeadZone(a.which, a.axis)) { | |
211 | if (event.caxis.value < -deadZoneLimit) { | |
212 | setDeadZone(a.which,a.axis,false); | |
213 | return true; | |
214 | } | |
215 | } | |
216 | } | |
217 | return false; | |
218 | } | |
219 | ||
220 | bool isPlayerUpEvent(int playerNumber, const SDL_Event& event) { | |
221 | if (skipThisPlayer(playerNumber, event)) { | |
222 | return false; | |
223 | } | |
224 | return isControllerUpEvent(event); | |
225 | } | |
226 | ||
227 | bool isControllerLeftEvent(const SDL_Event& event) { | |
228 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
229 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT ) { | |
230 | return true; | |
231 | } | |
232 | } | |
233 | if (event.type == SDL_CONTROLLERAXISMOTION && event.caxis.axis == SDL_CONTROLLER_AXIS_LEFTX ) { | |
234 | checkDeadZone(event); | |
235 | const SDL_ControllerAxisEvent& a = event.caxis; | |
236 | if (getDeadZone(a.which, a.axis)) { | |
237 | if (event.caxis.value < -deadZoneLimit) { | |
238 | setDeadZone(a.which,a.axis,false); | |
239 | return true; | |
240 | } | |
241 | } | |
242 | } | |
243 | return false; | |
244 | } | |
245 | ||
246 | bool isPlayerLeftEvent(int playerNumber, const SDL_Event& event) { | |
247 | if (skipThisPlayer(playerNumber, event)) { | |
248 | return false; | |
249 | } | |
250 | return isControllerLeftEvent(event); | |
251 | } | |
252 | ||
253 | bool isControllerRightEvent(const SDL_Event& event) { | |
254 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
255 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_RIGHT ) { | |
256 | return true; | |
257 | } | |
258 | } | |
259 | if (event.type == SDL_CONTROLLERAXISMOTION && event.caxis.axis == SDL_CONTROLLER_AXIS_LEFTX ) { | |
260 | checkDeadZone(event); | |
261 | const SDL_ControllerAxisEvent& a = event.caxis; | |
162 | 262 | if (getDeadZone(a.which, a.axis)) { |
163 | 263 | if (event.caxis.value > deadZoneLimit) { |
164 | 264 | setDeadZone(a.which,a.axis,false); |
169 | 269 | return false; |
170 | 270 | } |
171 | 271 | |
172 | bool isPlayerUpEvent(int playerNumber, const SDL_Event& event) { | |
173 | if (skipThisPlayer(playerNumber, event)) { | |
174 | return false; | |
175 | } | |
176 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
177 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_UP ) { | |
178 | return true; | |
179 | } | |
180 | } | |
181 | if (event.type == SDL_CONTROLLERAXISMOTION && event.caxis.axis == SDL_CONTROLLER_AXIS_LEFTY ) { | |
182 | checkDeadZone(event); | |
183 | const SDL_ControllerAxisEvent& a = event.caxis; | |
184 | if (getDeadZone(a.which, a.axis)) { | |
185 | if (event.caxis.value < -deadZoneLimit) { | |
186 | setDeadZone(a.which,a.axis,false); | |
187 | return true; | |
188 | } | |
189 | } | |
190 | } | |
191 | return false; | |
192 | } | |
193 | ||
194 | bool isPlayerLeftEvent(int playerNumber, const SDL_Event& event) { | |
195 | if (skipThisPlayer(playerNumber, event)) { | |
196 | return false; | |
197 | } | |
198 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
199 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_LEFT ) { | |
200 | return true; | |
201 | } | |
202 | } | |
203 | if (event.type == SDL_CONTROLLERAXISMOTION && event.caxis.axis == SDL_CONTROLLER_AXIS_LEFTX ) { | |
204 | checkDeadZone(event); | |
205 | const SDL_ControllerAxisEvent& a = event.caxis; | |
206 | if (getDeadZone(a.which, a.axis)) { | |
207 | if (event.caxis.value < -deadZoneLimit) { | |
208 | setDeadZone(a.which,a.axis,false); | |
209 | return true; | |
210 | } | |
211 | } | |
212 | } | |
213 | return false; | |
214 | } | |
215 | ||
216 | 272 | bool isPlayerRightEvent(int playerNumber, const SDL_Event& event) { |
217 | 273 | if (skipThisPlayer(playerNumber, event)) { |
218 | 274 | return false; |
219 | 275 | } |
220 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
221 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_DPAD_RIGHT ) { | |
222 | return true; | |
223 | } | |
224 | } | |
225 | if (event.type == SDL_CONTROLLERAXISMOTION && event.caxis.axis == SDL_CONTROLLER_AXIS_LEFTX ) { | |
276 | return isControllerRightEvent(event); | |
277 | } | |
278 | ||
279 | bool isPlayerSwitchEvent(int playerNumber, const SDL_Event& event) { | |
280 | if (skipThisPlayer(playerNumber, event)) { | |
281 | return false; | |
282 | } | |
283 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
284 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_A || event.cbutton.button == SDL_CONTROLLER_BUTTON_B ) { | |
285 | return true; | |
286 | } | |
287 | } | |
288 | return false; | |
289 | } | |
290 | ||
291 | bool isPlayerPushEvent(int playerNumber, const SDL_Event& event) { | |
292 | if (skipThisPlayer(playerNumber, event)) { | |
293 | return false; | |
294 | } | |
295 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
296 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_LEFTSHOULDER || event.cbutton.button == SDL_CONTROLLER_BUTTON_RIGHTSHOULDER ) { | |
297 | return true; | |
298 | } | |
299 | } | |
300 | if (event.type == SDL_CONTROLLERAXISMOTION && (event.caxis.axis == SDL_CONTROLLER_AXIS_TRIGGERLEFT || event.caxis.axis == SDL_CONTROLLER_AXIS_TRIGGERRIGHT ) ) { | |
226 | 301 | checkDeadZone(event); |
227 | 302 | const SDL_ControllerAxisEvent& a = event.caxis; |
228 | 303 | if (getDeadZone(a.which, a.axis)) { |
234 | 309 | } |
235 | 310 | return false; |
236 | 311 | } |
237 | ||
238 | bool isPlayerSwitchEvent(int playerNumber, const SDL_Event& event) { | |
239 | if (skipThisPlayer(playerNumber, event)) { | |
240 | return false; | |
241 | } | |
242 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
243 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_A || event.cbutton.button == SDL_CONTROLLER_BUTTON_B ) { | |
244 | return true; | |
245 | } | |
246 | } | |
247 | return false; | |
248 | } | |
249 | ||
250 | bool isPlayerPushEvent(int playerNumber, const SDL_Event& event) { | |
251 | if (skipThisPlayer(playerNumber, event)) { | |
252 | return false; | |
253 | } | |
254 | if (event.type == SDL_CONTROLLERBUTTONDOWN) { | |
255 | if (event.cbutton.button == SDL_CONTROLLER_BUTTON_LEFTSHOULDER || event.cbutton.button == SDL_CONTROLLER_BUTTON_RIGHTSHOULDER ) { | |
256 | return true; | |
257 | } | |
258 | } | |
259 | if (event.type == SDL_CONTROLLERAXISMOTION && (event.caxis.axis == SDL_CONTROLLER_AXIS_TRIGGERLEFT || event.caxis.axis == SDL_CONTROLLER_AXIS_TRIGGERRIGHT ) ) { | |
260 | checkDeadZone(event); | |
261 | const SDL_ControllerAxisEvent& a = event.caxis; | |
262 | if (getDeadZone(a.which, a.axis)) { | |
263 | if (event.caxis.value > deadZoneLimit) { | |
264 | setDeadZone(a.which,a.axis,false); | |
265 | return true; | |
266 | } | |
267 | } | |
268 | } | |
269 | return false; | |
270 | } |
30 | 30 | const int deadZoneLimit = 20000; |
31 | 31 | |
32 | 32 | void InitGameControllers(); |
33 | void UnInitGameControllers(); | |
34 | ||
35 | bool isControllerDownEvent(const SDL_Event& event); | |
36 | bool isControllerUpEvent(const SDL_Event& event); | |
37 | bool isControllerLeftEvent(const SDL_Event& event); | |
38 | bool isControllerRightEvent(const SDL_Event& event); | |
33 | 39 | |
34 | 40 | bool isPlayerDownEvent(int playerNumber, const SDL_Event& event); |
35 | 41 | bool isPlayerUpEvent(int playerNumber, const SDL_Event& event); |
37 | 43 | bool isPlayerRightEvent(int playerNumber, const SDL_Event& event); |
38 | 44 | bool isPlayerSwitchEvent(int playerNumber, const SDL_Event& event); |
39 | 45 | bool isPlayerPushEvent(int playerNumber, const SDL_Event& event); |
46 | bool isGameControllerConnectionEvent(const SDL_Event& event); | |
40 | 47 | void GameControllerSetVerbose(bool value); |
41 | 48 | const std::vector<std::string>& GetSupportedControllerNames(); |
42 | 49 |
65 | 65 | //Loads the levels, if they havn't been loaded: |
66 | 66 | if (Type == 0) { |
67 | 67 | LoadPuzzleStages(); |
68 | } | |
69 | if (Type == 0) { | |
70 | 68 | nrOfLevels = PuzzleGetNumberOfPuzzles(); |
71 | 69 | } |
72 | 70 | if (Type == 1) { |
210 | 208 | } |
211 | 209 | DrawBackground(globalData.screen); |
212 | 210 | return levelNr; |
213 | }⏎ | |
211 | } |
79 | 79 | *******************************************************************************/ |
80 | 80 | #include "mainVars.inc" |
81 | 81 | |
82 | using std::string; | |
83 | using std::cerr; | |
84 | using std::cout; | |
85 | using std::exception; | |
86 | using std::vector; | |
87 | ||
88 | 82 | GlobalData globalData; |
89 | 83 | |
90 | 84 | static int InitImages(sago::SagoSpriteHolder& holder); |
91 | 85 | |
92 | 86 | static void FsSearchParthMainAppend(std::vector<std::string>& paths) { |
93 | paths.push_back((string)SHAREDIR+"/blockattack.data"); | |
94 | paths.push_back((string)PHYSFS_getBaseDir()+"/blockattack.data"); | |
95 | paths.push_back((string)PHYSFS_getBaseDir()+"/data"); | |
96 | } | |
97 | ||
98 | static void PhysFsSetSearchPath(const vector<string>& paths, const string& savepath) { | |
99 | for (const string& path : paths) { | |
87 | paths.push_back((std::string)SHAREDIR+"/blockattack.data"); | |
88 | paths.push_back((std::string)PHYSFS_getBaseDir()+"/blockattack.data"); | |
89 | paths.push_back((std::string)PHYSFS_getBaseDir()+"/data"); | |
90 | } | |
91 | ||
92 | static void PhysFsSetSearchPath(const std::vector<std::string>& paths, const std::string& savepath) { | |
93 | for (const std::string& path : paths) { | |
100 | 94 | PHYSFS_mount(path.c_str(), "/", 0); |
101 | 95 | } |
102 | 96 | PHYSFS_mount(savepath.c_str(), "/", 0); |
336 | 330 | //writeScreenShot saves the screen as a bmp file, it uses the time to get a unique filename |
337 | 331 | void writeScreenShot() { |
338 | 332 | if (globalData.verboseLevel) { |
339 | cout << "Saving screenshot" << "\n"; | |
333 | std::cout << "Saving screenshot" << "\n"; | |
340 | 334 | } |
341 | 335 | int rightNow = (int)time(nullptr); |
342 | 336 | SDL_Surface* infoSurface = SDL_GetWindowSurface(sdlWindow); |
369 | 363 | } |
370 | 364 | |
371 | 365 | //Function to return the name of a key, to be displayed... |
372 | string getKeyName(SDL_Keycode key); | |
366 | std::string getKeyName(SDL_Keycode key); | |
373 | 367 | |
374 | 368 | |
375 | 369 | void RunGameState(sago::GameStateInterface& state ) { |
488 | 482 | DrawBackground(globalData.screen); |
489 | 483 | theGame->DoPaintJob(); |
490 | 484 | theGame2->DoPaintJob(); |
491 | string strHolder; | |
485 | std::string strHolder; | |
492 | 486 | strHolder = std::to_string(theGame->GetScore()+theGame->GetHandicap()); |
493 | 487 | player1score.SetText(strHolder); |
494 | 488 | player1score.Draw(globalData.screen, theGame->GetTopX()+310,theGame->GetTopY()+100); |
567 | 561 | //Blank player2's board: |
568 | 562 | DrawIMG(backBoard,globalData.screen,theGame2->GetTopX(),theGame2->GetTopY()); |
569 | 563 | //Write a description: |
570 | string gametypeName; | |
571 | string infostring; | |
564 | std::string gametypeName; | |
565 | std::string infostring; | |
572 | 566 | if (theGame->isTimeTrial()) { |
573 | 567 | gametypeName = _("Time Trial"); |
574 | 568 | infostring = _("Score as much as possible in 2 minutes"); |
830 | 824 | } |
831 | 825 | |
832 | 826 | struct globalConfig { |
833 | string savepath; | |
834 | vector<string> search_paths; | |
835 | string puzzleName; | |
827 | std::string savepath; | |
828 | std::vector<std::string> search_paths; | |
829 | std::string puzzleName; | |
836 | 830 | bool allowResize = true; |
837 | 831 | bool autoScale = true; |
838 | 832 | bool softwareRenderer = false; |
853 | 847 | desc.add_options() |
854 | 848 | ("help,h", "Displays this message") |
855 | 849 | ("version", "Display the version information") |
856 | ("config,c", boost::program_options::value<vector<string> >(), "Read a config file with the values. Can be given multiple times") | |
850 | ("config,c", boost::program_options::value<std::vector<std::string> >(), "Read a config file with the values. Can be given multiple times") | |
857 | 851 | ("nosound", "Disables the sound. Can be used if sound errors prevents you from starting") |
858 | 852 | ("priority", "Causes the game to not sleep between frames.") |
859 | 853 | ("software-renderer", "Asks SDL2 to use software renderer") |
862 | 856 | ("print-search-path", "Prints the search path and quits") |
863 | 857 | ("no-auto-scale", "Do not automatically auto scale") |
864 | 858 | ("always-sixteen-nine", "Use 16:9 format even in Window mode") |
865 | ("puzzle-level-file", boost::program_options::value<string>(), "Sets the default puzzle file to load") | |
859 | ("puzzle-level-file", boost::program_options::value<std::string>(), "Sets the default puzzle file to load") | |
866 | 860 | ("puzzle-single-level", boost::program_options::value<int>(), "Start the specific puzzle level directly") |
867 | 861 | #ifdef REPLAY_IMPLEMENTED |
868 | ("play-replay", boost::program_options::value<string>(), "Start a replay") | |
862 | ("play-replay", boost::program_options::value<std::string>(), "Start a replay") | |
869 | 863 | #endif |
870 | ("bind-text-domain", boost::program_options::value<string>(), SPrintStringF("Overwrites the bind text domain used for finding translations. " | |
864 | ("bind-text-domain", boost::program_options::value<std::string>(), SPrintStringF("Overwrites the bind text domain used for finding translations. " | |
871 | 865 | "Default: \"%s\"", LOCALEDIR).c_str()) |
872 | ("homepath", boost::program_options::value<string>(), SPrintStringF("Set the home folder where settings are saved. The directory will be created if it does not exist." | |
866 | ("homepath", boost::program_options::value<std::string>(), SPrintStringF("Set the home folder where settings are saved. The directory will be created if it does not exist." | |
873 | 867 | " Default: \"%s\"", getPathToSaveFiles().c_str()).c_str()) |
874 | 868 | |
875 | 869 | ; |
878 | 872 | boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm); |
879 | 873 | boost::program_options::notify(vm); |
880 | 874 | } |
881 | catch (exception& e) { | |
882 | cerr << e.what() << "\n"; | |
883 | cerr << desc << "\n"; | |
875 | catch (std::exception& e) { | |
876 | std::cerr << e.what() << "\n"; | |
877 | std::cerr << desc << "\n"; | |
884 | 878 | throw; |
885 | 879 | } |
886 | 880 | if (vm.count("config")) { |
887 | vector<string> config_filenames = vm["config"].as<vector<string> >(); | |
888 | for ( const string& s : config_filenames) { | |
881 | std::vector<std::string> config_filenames = vm["config"].as<std::vector<std::string> >(); | |
882 | for ( const std::string& s : config_filenames) { | |
889 | 883 | std::ifstream config_file(s); |
890 | 884 | store(parse_config_file(config_file, desc), vm); |
891 | 885 | notify(vm); |
892 | 886 | } |
893 | 887 | } |
894 | 888 | if (vm.count("bind-text-domain")) { |
895 | string s = vm["bind-text-domain"].as<string>(); | |
889 | std::string s = vm["bind-text-domain"].as<std::string>(); | |
896 | 890 | bindtextdomain (PACKAGE, s.c_str()); |
897 | 891 | } |
898 | 892 | if (vm.count("homepath")) { |
899 | string s = vm["homepath"].as<string>(); | |
893 | std::string s = vm["homepath"].as<std::string>(); | |
900 | 894 | setPathToSaveFiles(s); |
901 | 895 | conf.savepath = getPathToSaveFiles(); |
902 | 896 | } |
903 | 897 | if (vm.count("help")) { |
904 | cout << SPrintStringF("Block Attack - Rise of the blocks %s\n\n" | |
905 | "Block Attack - Rise of the Blocks is a puzzle/blockfall game inspired by Tetris Attack for the SNES.\n\n" | |
906 | "%s\n\n", VERSION_NUMBER, "www.blockattack.net"); | |
907 | cout << "Usage: "<< commandname << " [OPTION]..." << "\n"; | |
908 | cout << desc << "\n"; | |
909 | cout << "Examples:" << "\n"; | |
910 | cout << "\tblockattack \tStart the game normally" << "\n"; | |
911 | cout << "\tblockattack --nosound\tStart the game without sound. Can be used if sound problems prevents the game from starting" << "\n"; | |
912 | cout << "\tblockattack --puzzle-level-file puzzle.levels --puzzle-single-level 3\tStart the game with the default puzzles in level 3" << "\n"; | |
913 | cout << "\tblockattack --bind-text-domain /dev/null\t Disables translations" << "\n"; | |
914 | cout << "\n"; | |
915 | cout << "Report bugs to the issue tracker here: <https://github.com/blockattack/blockattack-game/issues>" << "\n"; | |
898 | std::cout << SPrintStringF("Block Attack - Rise of the blocks %s\n\n" | |
899 | "Block Attack - Rise of the Blocks is a puzzle/blockfall game inspired by Tetris Attack for the SNES.\n\n" | |
900 | "%s\n\n", VERSION_NUMBER, "www.blockattack.net"); | |
901 | std::cout << "Usage: "<< commandname << " [OPTION]..." << "\n"; | |
902 | std::cout << desc << "\n"; | |
903 | std::cout << "Examples:" << "\n"; | |
904 | std::cout << "\tblockattack \tStart the game normally" << "\n"; | |
905 | std::cout << "\tblockattack --nosound\tStart the game without sound. Can be used if sound problems prevents the game from starting" << "\n"; | |
906 | std::cout << "\tblockattack --puzzle-level-file puzzle.levels --puzzle-single-level 3\tStart the game with the default puzzles in level 3" << "\n"; | |
907 | std::cout << "\tblockattack --bind-text-domain /dev/null\t Disables translations" << "\n"; | |
908 | std::cout << "\n"; | |
909 | std::cout << "Report bugs to the issue tracker here: <https://github.com/blockattack/blockattack-game/issues>" << "\n"; | |
916 | 910 | exit(0); |
917 | 911 | } |
918 | 912 | if (vm.count("version")) { |
919 | cout << "blockattack " << VERSION_NUMBER << "\n"; | |
920 | cout << "\n"; | |
921 | cout << "Copyright (C) 2005-2016 Poul Sander" << "\n"; | |
922 | cout << "License GPLv2+: GNU GPL version 2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html> or later <http://gnu.org/licenses/gpl.html>" << "\n"; | |
923 | cout << "This is free software: you are free to change and redistribute it." << "\n"; | |
924 | cout << "There is NO WARRANTY, to the extent permitted by law." << "\n"; | |
913 | std::cout << "blockattack " << VERSION_NUMBER << "\n"; | |
914 | std::cout << "\n"; | |
915 | std::cout << "Copyright (C) 2005-2016 Poul Sander" << "\n"; | |
916 | std::cout << "License GPLv2+: GNU GPL version 2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html> or later <http://gnu.org/licenses/gpl.html>" << "\n"; | |
917 | std::cout << "This is free software: you are free to change and redistribute it." << "\n"; | |
918 | std::cout << "There is NO WARRANTY, to the extent permitted by law." << "\n"; | |
925 | 919 | exit(0); |
926 | 920 | } |
927 | 921 | if (vm.count("nosound")) { |
940 | 934 | GameControllerSetVerbose(true); |
941 | 935 | } |
942 | 936 | if (vm.count("print-search-path")) { |
943 | for (const string& s : conf.search_paths) { | |
944 | cout << s << "\n"; | |
945 | } | |
946 | cout << conf.savepath << "\n"; | |
937 | for (const std::string& s : conf.search_paths) { | |
938 | std::cout << s << "\n"; | |
939 | } | |
940 | std::cout << conf.savepath << "\n"; | |
947 | 941 | exit(0); |
948 | 942 | } |
949 | 943 | if (vm.count("puzzle-single-level")) { |
957 | 951 | globalData.alwaysSixteenNine = true; |
958 | 952 | } |
959 | 953 | if (vm.count("puzzle-level-file")) { |
960 | conf.puzzleName = vm["puzzle-level-file"].as<string>(); | |
954 | conf.puzzleName = vm["puzzle-level-file"].as<std::string>(); | |
961 | 955 | } |
962 | 956 | if (vm.count("play-replay")) { |
963 | globalData.replayArgument = vm["play-replay"].as<string>(); | |
957 | globalData.replayArgument = vm["play-replay"].as<std::string>(); | |
964 | 958 | } |
965 | 959 | |
966 | 960 | } |
1004 | 998 | sago::SagoFatalErrorF("Unable to init SDL: %s", SDL_GetError()); |
1005 | 999 | } |
1006 | 1000 | if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER ) != 0) { |
1007 | cerr << "Warning: Game controller failed to initialize. Reason: " << SDL_GetError() << "\n"; | |
1001 | std::cerr << "Warning: Game controller failed to initialize. Reason: " << SDL_GetError() << "\n"; | |
1008 | 1002 | } |
1009 | 1003 | InitGameControllers(); |
1010 | 1004 | TTF_Init(); |
1015 | 1009 | if (!globalData.NoSound) { |
1016 | 1010 | //If sound has not been disabled, then load the sound system |
1017 | 1011 | if (Mix_OpenAudio(44100, AUDIO_S16SYS, 2, 2048) < 0) { |
1018 | cerr << "Warning: Couldn't set 44100 Hz 16-bit audio - Reason: " << SDL_GetError() << "\n" | |
1019 | << "Sound will be disabled!" << "\n"; | |
1012 | std::cerr << "Warning: Couldn't set 44100 Hz 16-bit audio - Reason: " << SDL_GetError() << "\n" | |
1013 | << "Sound will be disabled!" << "\n"; | |
1020 | 1014 | globalData.NoSound = true; //Tries to stop all sound from playing/loading |
1021 | 1015 | } |
1022 | 1016 | } |
1024 | 1018 | |
1025 | 1019 | if (globalData.verboseLevel) { |
1026 | 1020 | //Copyright notice: |
1027 | cout << "Block Attack - Rise of the Blocks (" << VERSION_NUMBER << ")" << "\n" << "http://www.blockattack.net" << "\n" << "Copyright 2004-2016 Poul Sander" << "\n" << | |
1028 | "A SDL2 based game (see www.libsdl.org)" << "\n" << | |
1029 | "The game is available under the GPL, see COPYING for details." << "\n"; | |
1030 | cout << "-------------------------------------------" << "\n"; | |
1021 | std::cout << "Block Attack - Rise of the Blocks (" << VERSION_NUMBER << ")" << "\n" << "http://www.blockattack.net" << "\n" << "Copyright 2004-2016 Poul Sander" << "\n" << | |
1022 | "A SDL2 based game (see www.libsdl.org)" << "\n" << | |
1023 | "The game is available under the GPL, see COPYING for details." << "\n"; | |
1024 | std::cout << "-------------------------------------------" << "\n"; | |
1031 | 1025 | } |
1032 | 1026 | |
1033 | 1027 | |
1110 | 1104 | screenHeight = configSettings->getInt("screenHeight"); |
1111 | 1105 | } |
1112 | 1106 | if (globalData.verboseLevel) { |
1113 | cout << "Data loaded from config file" << "\n"; | |
1107 | std::cout << "Data loaded from config file" << "\n"; | |
1114 | 1108 | } |
1115 | 1109 | } |
1116 | 1110 | else { |
1117 | 1111 | if (globalData.verboseLevel) { |
1118 | cout << "Unable to load options file, using default values" << "\n"; | |
1112 | std::cout << "Unable to load options file, using default values" << "\n"; | |
1119 | 1113 | } |
1120 | 1114 | } |
1121 | 1115 | if (configSettings->getInt("always-software")) { |
1157 | 1151 | if (globalData.verboseLevel) { |
1158 | 1152 | SDL_RendererInfo info; |
1159 | 1153 | SDL_GetRendererInfo(renderer, &info); |
1160 | cout << "Renderer: " << info.name << "\n"; | |
1154 | std::cout << "Renderer: " << info.name << "\n"; | |
1161 | 1155 | } |
1162 | 1156 | globalData.screen = renderer; |
1163 | 1157 | ResetFullscreen(); |
1164 | 1158 | SetSDLIcon(sdlWindow); |
1165 | 1159 | |
1166 | 1160 | if (globalData.verboseLevel) { |
1167 | cout << "Images loaded" << "\n"; | |
1161 | std::cout << "Images loaded" << "\n"; | |
1168 | 1162 | } |
1169 | 1163 | |
1170 | 1164 | BlockGameSdl theGame = BlockGameSdl(globalData.xsize/2-426, 100, &globalData.spriteHolder->GetDataHolder()); //creates game objects |
1233 | 1227 | |
1234 | 1228 | configSettings->setString("player1name", globalData.player1name); |
1235 | 1229 | configSettings->setString("player2name", globalData.player2name); |
1236 | if (!globalData.bFullscreen){ | |
1230 | if (!globalData.bFullscreen) { | |
1237 | 1231 | //Store physical height of window |
1238 | 1232 | int height = 0; |
1239 | 1233 | SDL_GetWindowSize(sdlWindow, nullptr, &height); |
1247 | 1241 | commonTime ct = TimeHandler::ms2ct(SDL_GetTicks()); |
1248 | 1242 | |
1249 | 1243 | if (globalData.verboseLevel) { |
1250 | cout << SPrintStringF("Block Attack - Rise of the Blocks ran for: %i hours %i mins and %i secs", ct.hours, ct.minutes, ct.seconds) << "\n"; | |
1244 | std::cout << SPrintStringF("Block Attack - Rise of the Blocks ran for: %i hours %i mins and %i secs", ct.hours, ct.minutes, ct.seconds) << "\n"; | |
1251 | 1245 | } |
1252 | 1246 | |
1253 | 1247 | ct = TimeHandler::addTime("totalTime",ct); |
1254 | 1248 | if (globalData.verboseLevel) { |
1255 | cout << "Total run time is now: " << ct.days << " days " << ct.hours << " hours " << ct.minutes << " mins and " << ct.seconds << " secs" << "\n"; | |
1249 | std::cout << "Total run time is now: " << ct.days << " days " << ct.hours << " hours " << ct.minutes << " mins and " << ct.seconds << " secs" << "\n"; | |
1256 | 1250 | } |
1257 | 1251 | |
1258 | 1252 | Stats::getInstance()->save(); |
1259 | 1253 | Config::getInstance()->save(); |
1260 | 1254 | } |
1261 | catch (exception& e) { | |
1255 | catch (std::exception& e) { | |
1262 | 1256 | sago::SagoFatalError(e.what()); |
1263 | 1257 | } |
1264 | 1258 | PHYSFS_delete("gameRunning"); |
1304 | 1298 | //game loop |
1305 | 1299 | int done = 0; |
1306 | 1300 | if (globalData.verboseLevel) { |
1307 | cout << "Starting game loop" << "\n"; | |
1301 | std::cout << "Starting game loop" << "\n"; | |
1308 | 1302 | } |
1309 | 1303 | |
1310 | 1304 | |
1388 | 1382 | bool mustWriteScreenshot = false; |
1389 | 1383 | |
1390 | 1384 | BlockGameAction a; |
1391 | a.action = BlockGameAction::Action::NONE; | |
1392 | 1385 | a.tick = SDL_GetTicks(); |
1393 | 1386 | if (true) { |
1394 | 1387 | SDL_Event event; |
1768 | 1761 | a.action = BlockGameAction::Action::SET_WON; |
1769 | 1762 | theGame.DoAction(a); |
1770 | 1763 | } |
1771 | vector<GarbageStruct> gs; | |
1764 | std::vector<GarbageStruct> gs; | |
1772 | 1765 | theGame.PopSendGarbage(gs); |
1773 | 1766 | for (const GarbageStruct& g : gs ) { |
1774 | 1767 | BlockGameAction a; |
29 | 29 | #include "HelpAboutState.hpp" |
30 | 30 | #include "ShowFileState.hpp" |
31 | 31 | |
32 | using std::string; | |
33 | using std::cerr; | |
34 | using std::cout; | |
35 | using std::vector; | |
36 | 32 | |
37 | 33 | #if 0 |
38 | 34 | //Menu |
55 | 51 | extern control keySettings[3]; |
56 | 52 | |
57 | 53 | //Function to return the name of a key, to be displayed... |
58 | string getKeyName(SDL_Keycode key) { | |
59 | string keyname(SDL_GetKeyName(key)); | |
54 | std::string getKeyName(SDL_Keycode key) { | |
55 | std::string keyname(SDL_GetKeyName(key)); | |
60 | 56 | if (key == SDLK_UP) { |
61 | 57 | keyname = _("Up arrow"); |
62 | 58 | } |
94 | 90 | keyname = _("Space"); |
95 | 91 | } |
96 | 92 | if (globalData.verboseLevel) { |
97 | cout << key << " translated to " << keyname << "\n"; | |
93 | std::cout << key << " translated to " << keyname << "\n"; | |
98 | 94 | } |
99 | 95 | return keyname; |
100 | 96 | } |
102 | 98 | class Button_changekey : public Button { |
103 | 99 | private: |
104 | 100 | SDL_Keycode* m_key2change; |
105 | string m_keyname; | |
101 | std::string m_keyname; | |
106 | 102 | public: |
107 | Button_changekey(SDL_Keycode* key, string keyname); | |
103 | Button_changekey(SDL_Keycode* key, const char* keyname); | |
108 | 104 | void doAction(); |
109 | 105 | }; |
110 | 106 | |
111 | 107 | |
112 | Button_changekey::Button_changekey(SDL_Keycode* key, string keyname) { | |
113 | m_key2change = key; | |
114 | m_keyname = keyname; | |
108 | Button_changekey::Button_changekey(SDL_Keycode* key, const char* keyname) | |
109 | : m_key2change{key}, m_keyname{keyname} { | |
115 | 110 | setLabel(m_keyname+" : "+getKeyName(*m_key2change)); |
116 | 111 | } |
117 | 112 | |
211 | 206 | |
212 | 207 | static void SetAlwaysSoftwareLabel(Button* b) { |
213 | 208 | b->setLabel(Config::getInstance()->getInt("always-software")? |
214 | _("Always use software render: On") | |
215 | : _("Always use software render: Off")); | |
209 | _("Always use software render: On") | |
210 | : _("Always use software render: Off")); | |
216 | 211 | } |
217 | 212 | |
218 | 213 | static void SetMusicLabel (Button* b) { |
448 | 443 | bOnce.setLabel(_("Use software renderer this time")); |
449 | 444 | bAlways.setLabel(_("Always use software renderer")); |
450 | 445 | bOnce.setPopOnRun(true); |
451 | bAlways.setAction([]() {Config::getInstance()->setInt("always-software", 1); }); | |
446 | bAlways.setAction([]() { | |
447 | Config::getInstance()->setInt("always-software", 1); | |
448 | }); | |
452 | 449 | bAlways.setPopOnRun(true); |
453 | 450 | safeMode.addButton(&bOnce); |
454 | 451 | safeMode.addButton(&bAlways); |
20 | 20 | =========================================================================== |
21 | 21 | */ |
22 | 22 | |
23 | #if defined(_WIN32) | |
23 | #ifndef OS_HPP | |
24 | #define OS_HPP | |
25 | ||
26 | #if defined(_WIN32) | |
24 | 27 | #include "windows.h" |
25 | 28 | #include "shlobj.h" |
26 | 29 | #endif |
40 | 43 | bool OsPathIsRelative(const std::string& path); |
41 | 44 | |
42 | 45 | void OsCreateFolder(const std::string& path); |
46 | ||
47 | #endif /* OS_HPP */ |
29 | 29 | #include "cereal/types/vector.hpp" |
30 | 30 | #include "cereal/archives/json.hpp" |
31 | 31 | #include "sago/SagoMisc.hpp" |
32 | ||
33 | using std::string; | |
34 | using std::cerr; | |
35 | using std::vector; | |
36 | 32 | |
37 | 33 | const int maxNrOfPuzzleStages = 50; //Maximum number of puzzle stages |
38 | 34 |
30 | 30 | #include <memory> |
31 | 31 | #include <SDL_mixer.h> |
32 | 32 | #include "SagoMiscSdl2.hpp" |
33 | #include "SagoMisc.hpp" | |
33 | 34 | |
34 | 35 | #if PHYSFS_VER_MAJOR < 3 |
35 | 36 | #define PHYSFS_readBytes(X,Y,Z) PHYSFS_read(X,Y,1,Z) |
114 | 115 | if (!PHYSFS_exists(path.c_str())) { |
115 | 116 | sago::SagoFatalErrorF("getTextureFailed - Texture does not exist: %s", path.c_str()); |
116 | 117 | } |
117 | PHYSFS_file* myfile = PHYSFS_openRead(path.c_str()); | |
118 | unsigned int m_size = PHYSFS_fileLength(myfile); | |
119 | std::unique_ptr<char[]> m_data(new char[m_size]); | |
120 | int length_read = PHYSFS_readBytes (myfile, m_data.get(), m_size); | |
121 | if (length_read != (int)m_size) { | |
122 | PHYSFS_close(myfile); | |
123 | std::cerr << "Error: Corrupt data file: " << path << "\n"; | |
124 | return ret; | |
125 | } | |
126 | PHYSFS_close(myfile); | |
118 | unsigned int m_size = 0; | |
119 | std::unique_ptr<char[]> m_data; | |
120 | ReadBytesFromFile(path.c_str(), m_data, m_size); | |
127 | 121 | SDL_RWops* rw = SDL_RWFromMem (m_data.get(), m_size); |
128 | 122 | //The above might fail an return null. |
129 | 123 | if (!rw) { |
130 | PHYSFS_close(myfile); | |
131 | 124 | std::cerr << "Error. Corrupt data file!\n"; |
132 | 125 | return NULL; |
133 | 126 | } |
156 | 149 | std::cerr << "getFontPtr - Font does not exists: " << path << "\n"; |
157 | 150 | return ret; |
158 | 151 | } |
159 | PHYSFS_file* myfile = PHYSFS_openRead(path.c_str()); | |
160 | unsigned int m_size = PHYSFS_fileLength(myfile); | |
161 | std::unique_ptr<char[]> m_data(new char[m_size]); | |
162 | int length_read = PHYSFS_readBytes (myfile, m_data.get(), m_size); | |
163 | if (length_read != (int)m_size) { | |
164 | PHYSFS_close(myfile); | |
165 | std::cerr << "Error: Corrupt data file: " << path << "\n"; | |
166 | return ret; | |
167 | } | |
168 | PHYSFS_close(myfile); | |
152 | unsigned int m_size = 0; | |
153 | std::unique_ptr<char[]> m_data; | |
154 | ReadBytesFromFile(path.c_str(), m_data, m_size); | |
169 | 155 | |
170 | 156 | SDL_RWops* rw = SDL_RWFromMem (m_data.get(), m_size); |
171 | 157 | |
172 | 158 | //The above might fail an return null. |
173 | 159 | if (!rw) { |
174 | PHYSFS_close(myfile); | |
175 | 160 | std::cerr << "Error: Corrupt data file!\n"; |
176 | 161 | return ret; |
177 | 162 | } |
199 | 184 | std::cerr << "getMusicPtr - Music file does not exists: " << path << "\n"; |
200 | 185 | return ret; |
201 | 186 | } |
202 | PHYSFS_file* myfile = PHYSFS_openRead(path.c_str()); | |
203 | unsigned int m_size = PHYSFS_fileLength(myfile); | |
204 | std::unique_ptr<char[]> m_data(new char[m_size]); | |
205 | int length_read = PHYSFS_readBytes (myfile, m_data.get(), m_size); | |
206 | if (length_read != (int)m_size) { | |
207 | PHYSFS_close(myfile); | |
208 | std::cerr << "Error: Corrupt data file: " << path << "\n"; | |
209 | return ret; | |
210 | } | |
211 | PHYSFS_close(myfile); | |
187 | unsigned int m_size = 0; | |
188 | std::unique_ptr<char[]> m_data; | |
189 | ReadBytesFromFile(path.c_str(), m_data, m_size); | |
212 | 190 | SDL_RWops* rw = SDL_RWFromMem (m_data.get(), m_size); |
213 | 191 | |
214 | 192 | //The above might fail an return null. |
215 | 193 | if (!rw) { |
216 | PHYSFS_close(myfile); | |
217 | 194 | std::cerr << "Error. Corrupt data file!\n"; |
218 | 195 | return NULL; |
219 | 196 | } |
242 | 219 | std::cerr << "getSoundPtr - Sound file does not exists: " << path << "\n"; |
243 | 220 | return ret; |
244 | 221 | } |
245 | PHYSFS_file* myfile = PHYSFS_openRead(path.c_str()); | |
246 | unsigned int m_size = PHYSFS_fileLength(myfile); | |
247 | std::unique_ptr<char[]> m_data(new char[m_size]); | |
248 | int length_read = PHYSFS_readBytes (myfile, m_data.get(), m_size); | |
249 | if (length_read != (int)m_size) { | |
250 | PHYSFS_close(myfile); | |
251 | std::cerr << "Error: Corrupt data file: " << path << "\n"; | |
252 | return ret; | |
253 | } | |
254 | PHYSFS_close(myfile); | |
222 | unsigned int m_size = 0; | |
223 | std::unique_ptr<char[]> m_data; | |
224 | ReadBytesFromFile(path.c_str(), m_data, m_size); | |
255 | 225 | SDL_RWops* rw = SDL_RWFromMem (m_data.get(), m_size); |
256 | 226 | |
257 | 227 | //The above might fail an return null. |
258 | 228 | if (!rw) { |
259 | PHYSFS_close(myfile); | |
260 | 229 | std::cerr << "Error. Corrupt data file!\n"; |
261 | 230 | return NULL; |
262 | 231 | } |
81 | 81 | */ |
82 | 82 | SagoDataHolder(); |
83 | 83 | explicit SagoDataHolder(SDL_Renderer* renderer); |
84 | ||
84 | 85 | /** |
85 | 86 | * Return a pointer to the given texture. The pointer is valid for the lifetime of SagoDataHolder object it was taken from or until invalidateAll is called. |
86 | 87 | * @param textureName Name of the texture |
87 | 88 | * @return Pointer to the loaded texture |
88 | 89 | */ |
89 | 90 | SDL_Texture* getTexturePtr(const std::string &textureName) const; |
91 | ||
90 | 92 | TextureHandler getTextureHandler(const std::string &textureName) const; |
91 | 93 | TTF_Font* getFontPtr(const std::string &fontName, int ptsize) const; |
92 | 94 | Mix_Music* getMusicPtr(const std::string &musicName) const; |
94 | 96 | Mix_Chunk* getSoundPtr(const std::string &soundName) const; |
95 | 97 | SoundHandler getSoundHandler(const std::string &soundName) const; |
96 | 98 | void setVerbose(bool value); |
99 | ||
97 | 100 | /** |
98 | 101 | * Invalidates all pointers returned by any of the get variables |
99 | 102 | */ |
100 | 103 | void invalidateAll(); |
104 | ||
101 | 105 | /** |
102 | 106 | * Invalidates all pointers returned by any of the get variables. |
103 | 107 | * Also sets a new renderer. |
105 | 109 | * Setting a new renderer might cause all old textures to no longer match the renderer format. |
106 | 110 | */ |
107 | 111 | void invalidateAll(SDL_Renderer* renderer); |
112 | ||
108 | 113 | /** |
109 | 114 | * The version number. Changes everytime the pointers are invalidated. |
110 | 115 | * Can be used to determen if it is neccecary to get a new pointer. |
111 | 116 | * @return A globally unique number. |
112 | 117 | */ |
113 | 118 | Uint64 getVersion() const; |
119 | ||
114 | 120 | ~SagoDataHolder(); |
115 | 121 | private: |
116 | 122 | SagoDataHolder(const SagoDataHolder& base) = delete; |
26 | 26 | #include <iostream> |
27 | 27 | #include <iconv.h> |
28 | 28 | #include <string.h> |
29 | #include <memory> | |
30 | 29 | |
31 | 30 | #if PHYSFS_VER_MAJOR < 3 |
32 | 31 | #define PHYSFS_readBytes(X,Y,Z) PHYSFS_read(X,Y,1,Z) |
33 | 32 | #define PHYSFS_writeBytes(X,Y,Z) PHYSFS_write(X,Y,1,Z) |
34 | 33 | #endif |
35 | 34 | |
36 | using std::string; | |
37 | using std::cerr; | |
38 | using std::vector; | |
39 | ||
40 | 35 | namespace sago { |
41 | 36 | |
42 | 37 | |
43 | 38 | std::vector<std::string> GetFileList(const char* dir) { |
44 | vector<string> ret; | |
39 | std::vector<std::string> ret; | |
45 | 40 | char** rc = PHYSFS_enumerateFiles(dir); |
46 | 41 | for (char** i = rc; *i != NULL; i++) { |
47 | 42 | ret.push_back(*i); |
54 | 49 | return PHYSFS_exists(filename); |
55 | 50 | } |
56 | 51 | |
57 | std::string GetFileContent(const char* filename) { | |
58 | string ret; | |
52 | void ReadBytesFromFile(const char* filename, std::unique_ptr<char[]>& dest, unsigned int& bytes) { | |
53 | bytes = 0; | |
59 | 54 | if (!PHYSFS_exists(filename)) { |
60 | cerr << "GetFileContent - File does not exists: " << filename << "\n"; | |
61 | return ret; | |
55 | std::cerr << "ReadBytesFromFile - File does not exists: " << filename << "\n"; | |
56 | return; | |
62 | 57 | } |
63 | 58 | PHYSFS_file* myfile = PHYSFS_openRead(filename); |
64 | 59 | unsigned int m_size = PHYSFS_fileLength(myfile); |
66 | 61 | int length_read = PHYSFS_readBytes (myfile, m_data.get(), m_size); |
67 | 62 | if (length_read != (int)m_size) { |
68 | 63 | PHYSFS_close(myfile); |
69 | cerr << "Error: Curropt data file: " << filename << "\n"; | |
64 | std::cerr << "Error: Curropt data file: " << filename << "\n"; | |
65 | return; | |
66 | } | |
67 | PHYSFS_close(myfile); | |
68 | std::swap(m_data, dest); | |
69 | bytes = m_size; | |
70 | } | |
71 | ||
72 | std::string GetFileContent(const char* filename) { | |
73 | std::string ret; | |
74 | if (!PHYSFS_exists(filename)) { | |
75 | std::cerr << "GetFileContent - File does not exists: " << filename << "\n"; | |
70 | 76 | return ret; |
71 | 77 | } |
72 | PHYSFS_close(myfile); | |
73 | //Now create a std::string | |
74 | ret = string(m_data.get(), m_data.get()+m_size); | |
78 | unsigned int m_size = 0; | |
79 | std::unique_ptr<char[]> m_data; | |
80 | ReadBytesFromFile(filename, m_data, m_size); | |
81 | //Now create a std::string | |
82 | ret = std::string(m_data.get(), m_data.get()+m_size); | |
75 | 83 | return ret; |
76 | 84 | } |
77 | 85 |
26 | 26 | |
27 | 27 | #include <vector> |
28 | 28 | #include <string> |
29 | #include <memory> | |
29 | 30 | |
30 | 31 | namespace sago { |
31 | 32 | |
36 | 37 | * @return A vector with the filenames in the given directory. If empty the directory was empty or did not exist |
37 | 38 | */ |
38 | 39 | std::vector<std::string> GetFileList(const char* dir); |
40 | ||
41 | /** | |
42 | * Reads an entire file into memory. | |
43 | * PHYSFS must be setup before hand | |
44 | * @param filename The file to read | |
45 | * @param dest The unique pointer in which the bytes will be written | |
46 | * @param bytes Number of bytes written | |
47 | * @return The content of the file. If empty either the file was empty, did not exist or could not be opened | |
48 | */ | |
49 | void ReadBytesFromFile(const char* filename, std::unique_ptr<char[]>& dest, unsigned int& bytes); | |
39 | 50 | |
40 | 51 | /** |
41 | 52 | * Reads an entire file into memory. |
23 | 23 | |
24 | 24 | #include "SagoSprite.hpp" |
25 | 25 | #include <iostream> |
26 | ||
27 | #ifndef M_PI | |
28 | // M_PI is a custom extension that most C++ toolchains provide. Out Windows compiler does not provide it. | |
29 | # define M_PI 3.14159265358979323846 | |
30 | #endif | |
26 | 31 | |
27 | 32 | namespace sago { |
28 | 33 | |
63 | 68 | DrawScaled(target, frameTime, x, y, data->imgCord.w, data->imgCord.h); |
64 | 69 | } |
65 | 70 | |
71 | void SagoSprite::DrawRotated(SDL_Renderer* target, Sint32 frameTime, int x, int y, const double angleRadian) const { | |
72 | SDL_Point center = {this->data->origin.x, this->data->origin.y}; | |
73 | DrawScaledAndRotated(target, frameTime, x, y, data->imgCord.w, data->imgCord.h, angleRadian, ¢er, SDL_FLIP_NONE); | |
74 | } | |
75 | ||
66 | 76 | void SagoSprite::DrawScaled(SDL_Renderer* target, Sint32 frameTime, int x, int y, int w, int h) const { |
77 | DrawScaledAndRotated(target, frameTime, x, y, w, h, 0.0, nullptr, SDL_FLIP_NONE); | |
78 | } | |
79 | ||
80 | void SagoSprite::DrawScaledAndRotated(SDL_Renderer* target, Sint32 frameTime, int x, int y, int w, int h, const double angleRadian, const SDL_Point* center, const SDL_RendererFlip flip) const { | |
67 | 81 | if (!data->tex.get()) { |
68 | 82 | std::cerr << "Texture is null!\n"; |
69 | 83 | } |
78 | 92 | if (h > 0) { |
79 | 93 | pos.h = h; |
80 | 94 | } |
81 | SDL_RenderCopy(target, data->tex.get(), &rect, &pos); | |
95 | double angleDegress = angleRadian/M_PI*180.0; | |
96 | SDL_RenderCopyEx(target, data->tex.get(), &rect, &pos, angleDegress, center, flip); | |
82 | 97 | } |
83 | 98 | |
84 | 99 | void SagoSprite::Draw(SDL_Renderer* target, Sint32 frameTime, int x, int y, const SDL_Rect& part) const { |
157 | 172 | return data->imgCord.h; |
158 | 173 | } |
159 | 174 | |
160 | } //namespace sago⏎ | |
175 | } //namespace sago |
32 | 32 | public: |
33 | 33 | SagoSprite(); |
34 | 34 | SagoSprite(const SagoDataHolder &texHolder, const std::string &texture,const SDL_Rect& initImage,const int animationFrames, const int animationFrameLength); |
35 | ||
35 | 36 | /** |
36 | 37 | * Draws the sprite to a given render window |
37 | 38 | * @param target The render window to draw on |
40 | 41 | * @param y Place to draw the sprite |
41 | 42 | */ |
42 | 43 | void Draw(SDL_Renderer* target, Sint32 frameTime, int x, int y) const; |
44 | ||
45 | /** | |
46 | * Draws the sprite to a given render window | |
47 | * @param target The render window to draw on | |
48 | * @param frameTime The time in milliseonds since gamestart. Used to determen the place in the animation | |
49 | * @param x Place to draw the sprite | |
50 | * @param y Place to draw the sprite | |
51 | * @param angleRadian Angle to rotate the sprite around origin before drawing | |
52 | */ | |
53 | void DrawRotated(SDL_Renderer* target, Sint32 frameTime, int x, int y, const double angleRadian) const; | |
54 | ||
43 | 55 | /** |
44 | 56 | * Draws part of the sprite to a given render window |
45 | 57 | * @param target The render window to draw on |
49 | 61 | * @param part the part of the sprite that should be drawn. |
50 | 62 | */ |
51 | 63 | void Draw(SDL_Renderer* target, Sint32 frameTime, int x, int y, const SDL_Rect& part) const; |
64 | ||
52 | 65 | /** |
53 | 66 | * Draws the wprite to the given renderer but makes sure to not draw outside th bounds given |
54 | 67 | * @param target The render window to draw on |
57 | 70 | * @param y Place to draw the sprite |
58 | 71 | * @param bounds A recagular area that we must not draw outside. |
59 | 72 | */ |
60 | void DrawBounded(SDL_Renderer* target, Sint32 frameTime, int x, int y, const SDL_Rect& bounds) const;/** | |
73 | void DrawBounded(SDL_Renderer* target, Sint32 frameTime, int x, int y, const SDL_Rect& bounds) const; | |
74 | ||
75 | /** | |
61 | 76 | * Draws the sprite to a given render window |
62 | 77 | * @param target The render window to draw on |
63 | 78 | * @param progress A float with value from 0.0f to 1.0f. Tells how far in the animation that we got |
65 | 80 | * @param y Place to draw the sprite |
66 | 81 | */ |
67 | 82 | void DrawProgressive(SDL_Renderer* target, float progress, int x, int y) const; |
83 | ||
68 | 84 | void DrawScaled(SDL_Renderer* target, Sint32 frameTime, int x, int y, int w, int h) const; |
85 | void DrawScaledAndRotated(SDL_Renderer* target, Sint32 frameTime, int x, int y, int w, int h, | |
86 | const double angleRadian, const SDL_Point* center, const SDL_RendererFlip flip) const; | |
87 | ||
69 | 88 | /** |
70 | 89 | * Set a different origin. Normally it is the top left cornor. But in some cases you might want to center the origin or tranform it for other reasons |
71 | 90 | * @param newOrigin the coordinates that should be the new origin. Call with {0,0} to reset to default |
30 | 30 | #include <string.h> |
31 | 31 | #include <boost/algorithm/string/predicate.hpp> |
32 | 32 | |
33 | using std::string; | |
34 | using std::cerr; | |
35 | using std::cout; | |
36 | using std::vector; | |
37 | 33 | |
38 | 34 | namespace sago { |
39 | 35 | |
79 | 75 | } |
80 | 76 | |
81 | 77 | void SagoSpriteHolder::ReadSpriteFile(const std::string& filename) { |
82 | string fullfile = "sprites/"+filename; | |
83 | string content = sago::GetFileContent(fullfile.c_str()); | |
78 | std::string fullfile = "sprites/"+filename; | |
79 | std::string content = sago::GetFileContent(fullfile.c_str()); | |
84 | 80 | rapidjson::Document document; |
85 | 81 | document.Parse(content.c_str()); |
86 | 82 | if ( !document.IsObject() ) { |
87 | cerr << "Failed to parse: " << fullfile << "\n"; | |
83 | std::cerr << "Failed to parse: " << fullfile << "\n"; | |
88 | 84 | return; |
89 | 85 | } |
90 | 86 | for (auto& m : document.GetObject()) { |
95 | 91 | } |
96 | 92 | continue; |
97 | 93 | } |
98 | string textureName = getDefaultValue(m.value, "texture", "fallback"); | |
94 | std::string textureName = getDefaultValue(m.value, "texture", "fallback"); | |
99 | 95 | int topx = getDefaultValue(m.value, "topx", 0); |
100 | 96 | int topy = getDefaultValue(m.value, "topy",0); |
101 | 97 | int height = getDefaultValue(m.value, "height",0); |
122 | 118 | for (std::string& item : spritefiles ) { |
123 | 119 | if (boost::algorithm::ends_with(item,".sprite")) { |
124 | 120 | if (data->verbose) { |
125 | cout << "Found " << item << "\n"; | |
121 | std::cout << "Found " << item << "\n"; | |
126 | 122 | } |
127 | 123 | ReadSpriteFile(item); |
128 | 124 | } |
129 | 125 | else { |
130 | 126 | if (data->verbose) { |
131 | cout << "Ignoreing " << item << "\n"; | |
127 | std::cout << "Ignoreing " << item << "\n"; | |
132 | 128 | } |
133 | 129 | } |
134 | 130 | } |
46 | 46 | void SetFont(const char* fontName); |
47 | 47 | void SetFontSize(int fontSize); |
48 | 48 | void SetOutline(int outlineSize, const SDL_Color& color); |
49 | ||
49 | 50 | /** |
50 | 51 | * Sets the max width to generate. SagoTextBox will insert line breaks to keep the width below this number. |
51 | 52 | * Outline is not included in the width: If you have a 2 pixels outline the rendere may go 2 pixels beyond. |
44 | 44 | SagoTextField& operator=(const SagoTextField&& base) = delete; |
45 | 45 | SagoTextField& operator=(const SagoTextField& base) = delete; |
46 | 46 | ~SagoTextField(); |
47 | ||
47 | 48 | /** |
48 | 49 | * This method creates a copy of a given font. |
49 | 50 | * The cache will not be copied. |
52 | 53 | * @return A reference to this object. |
53 | 54 | */ |
54 | 55 | SagoTextField& CopyFrom(const SagoTextField& base); |
56 | ||
55 | 57 | /** |
56 | 58 | * Sets the data holder. This is MANDATORY |
57 | 59 | * @param holder The data holder to fetch the fonts from |
58 | 60 | */ |
59 | 61 | void SetHolder(const SagoDataHolder* holder); |
62 | ||
60 | 63 | /** |
61 | 64 | * Set the text to display. |
62 | 65 | * @param text The actual UTF-8 encoded text |
63 | 66 | */ |
64 | 67 | void SetText(const char* text); |
68 | ||
65 | 69 | /** |
66 | 70 | * Set the text to display. |
67 | 71 | * @param text The actual UTF-8 encoded text |
68 | 72 | */ |
69 | 73 | void SetText(const std::string& text); |
74 | ||
70 | 75 | void SetColor(const SDL_Color& color); |
76 | ||
71 | 77 | /** |
72 | 78 | * Set the name of the font. Must be known to the data holder. |
73 | 79 | * The name could for instance be "freeserif". |
74 | 80 | * @param fontName Name of the font as required by SagoDataHolder |
75 | 81 | */ |
76 | 82 | void SetFont(const char* fontName); |
83 | ||
77 | 84 | void SetFontSize(int fontSize); |
85 | ||
78 | 86 | /** |
79 | 87 | * Enable outline against the font. |
80 | 88 | * @param outlineSize Number of pixels of outline. |
81 | 89 | * @param color The color of the outline. |
82 | 90 | */ |
83 | 91 | void SetOutline(int outlineSize, const SDL_Color& color); |
92 | ||
84 | 93 | /** |
85 | 94 | * Get the text we are currently drawing |
86 | 95 | * @return The text |
87 | 96 | */ |
88 | 97 | const std::string& GetText() const; |
98 | ||
89 | 99 | /** |
90 | 100 | * A Shorthand for calling TTF_SizeUTF8 on the right font |
91 | 101 | * The size is measuered WITHOUT the outline! |
95 | 105 | * @param h Pointer to an int where the hight of the text will be stored. Maybe null. |
96 | 106 | */ |
97 | 107 | void GetRenderedSize(const char* text, int* w = nullptr, int* h = nullptr); |
108 | ||
98 | 109 | enum class Alignment { left = 0, right=1, center = 2 }; |
99 | 110 | enum class VerticalAlignment { top = 0, center = 1, bottom = 2}; |
100 | 111 | void Draw(SDL_Renderer* target, int x, int y, Alignment alignment = Alignment::left, VerticalAlignment verticalAlignment = VerticalAlignment::top); |
112 | ||
101 | 113 | /** |
102 | 114 | * Updates the cache. |
103 | 115 | * You normally do not want to call this from the outside as it is done just in time. |
105 | 117 | * @param target Target the the text will eventually be rendered to |
106 | 118 | */ |
107 | 119 | void UpdateCache(SDL_Renderer* target); |
120 | ||
108 | 121 | /** |
109 | 122 | * Clears the cache and forces the SagoTextField to render it again the next time it is drawn. |
110 | 123 | * Can be used if you have changed font, color or sizes. |
52 | 52 | Sint32 totalScore = 0; |
53 | 53 | Sint32 totalTime = 0; |
54 | 54 | |
55 | using std::string; | |
56 | using std::cerr; | |
57 | using std::vector; | |
58 | 55 | |
59 | 56 | static void SaveStageClearStages() { |
60 | 57 | std::stringstream ss; |
26 | 26 | #include "sago/SagoMisc.hpp" |
27 | 27 | #include <sstream> |
28 | 28 | |
29 | using std::string; | |
30 | using std::stringstream; | |
31 | using std::cerr; | |
32 | using std::map; | |
33 | using std::vector; | |
34 | 29 | |
35 | 30 | Stats* Stats::instance = nullptr; |
36 | 31 | |
42 | 37 | } |
43 | 38 | |
44 | 39 | void Stats::load() { |
45 | string fileContent = sago::GetFileContent(statsFileName); | |
46 | stringstream inFile(fileContent); | |
47 | string key; | |
48 | string value; | |
40 | std::string fileContent = sago::GetFileContent(statsFileName); | |
41 | std::stringstream inFile(fileContent); | |
42 | std::string key; | |
43 | std::string value; | |
49 | 44 | if (inFile) { |
50 | 45 | while (!inFile.eof()) { |
51 | 46 | inFile >> key; // The key is first on line |
66 | 61 | |
67 | 62 | void Stats::save() { |
68 | 63 | std::stringstream outFile; |
69 | map<string,unsigned int>::iterator iter; | |
64 | std::map<std::string, unsigned int>::iterator iter; | |
70 | 65 | for (iter = statMap.begin(); iter != statMap.end(); ++iter) { |
71 | 66 | outFile << iter->first << " " << iter->second << "\n"; |
72 | 67 | } |
73 | 68 | sago::WriteFileContent(statsFileName, outFile.str()); |
74 | 69 | } |
75 | 70 | |
76 | unsigned int Stats::getNumberOf(const string& statName) { | |
71 | unsigned int Stats::getNumberOf(const std::string& statName) { | |
77 | 72 | if (exists(statName)) { |
78 | 73 | return statMap[statName]; |
79 | 74 | } |
82 | 77 | } |
83 | 78 | } |
84 | 79 | |
85 | void Stats::addOne(const string& statName) { | |
86 | map<string,unsigned int>::iterator iter = statMap.find(statName); | |
80 | void Stats::addOne(const std::string& statName) { | |
81 | std::map<std::string, unsigned int>::iterator iter = statMap.find(statName); | |
87 | 82 | if (iter == statMap.end()) { |
88 | 83 | statMap[statName] = 1; |
89 | 84 | } |
92 | 87 | } |
93 | 88 | } |
94 | 89 | |
95 | bool Stats::exists(const string& statName) { | |
90 | bool Stats::exists(const std::string& statName) { | |
96 | 91 | //Using that 'find' returns an iterator to the end of the map if not found |
97 | 92 | return statMap.find(statName) != statMap.end(); |
98 | 93 | } |
29 | 29 | #define GAMENAME "blockattack" |
30 | 30 | |
31 | 31 | #ifndef VERSION_NUMBER |
32 | #define VERSION_NUMBER "2.5.0" | |
32 | #define VERSION_NUMBER "2.6.0" | |
33 | 33 | #endif |
14 | 14 | |
15 | 15 | COPY . /staging/blockattack-game |
16 | 16 | |
17 | ENV BLOCKATTACK_VERSION 2.5.0 | |
17 | ENV BLOCKATTACK_VERSION 2.6.0 | |
18 | 18 | |
19 | 19 | RUN cd /staging/blockattack-game && \ |
20 | 20 | ./packdata.sh && \ |
14 | 14 | |
15 | 15 | COPY . /staging/blockattack-game |
16 | 16 | |
17 | ENV BLOCKATTACK_VERSION 2.5.0 | |
17 | ENV BLOCKATTACK_VERSION 2.6.0 | |
18 | 18 | |
19 | 19 | RUN cd /staging/blockattack-game && \ |
20 | 20 | ./packdata.sh && \ |
15 | 15 | |
16 | 16 | COPY . /staging/blockattack-game |
17 | 17 | |
18 | ENV BLOCKATTACK_VERSION 2.5.0 | |
18 | ENV BLOCKATTACK_VERSION 2.6.0 | |
19 | 19 | |
20 | 20 | RUN cd /staging/blockattack-game && \ |
21 | 21 | ./packdata.sh && \ |
5 | 5 | |
6 | 6 | COPY . /staging/blockattack-game |
7 | 7 | |
8 | ENV BLOCKATTACK_VERSION 2.5.0 | |
8 | ENV BLOCKATTACK_VERSION 2.6.0 | |
9 | 9 | |
10 | 10 | RUN cd /staging/blockattack-game && \ |
11 | 11 | ./packdata.sh && \ |
6 | 6 | |
7 | 7 | COPY . /staging/blockattack-game |
8 | 8 | |
9 | ENV BLOCKATTACK_VERSION 2.5.0 | |
9 | ENV BLOCKATTACK_VERSION 2.6.0 | |
10 | 10 | |
11 | 11 | RUN cd /staging/blockattack-game && \ |
12 | 12 | ./packdata.sh && \ |
6 | 6 | |
7 | 7 | COPY . /staging/blockattack-game |
8 | 8 | |
9 | ENV BLOCKATTACK_VERSION 2.5.0 | |
9 | ENV BLOCKATTACK_VERSION 2.6.0 | |
10 | 10 | |
11 | 11 | RUN cd /staging/blockattack-game && \ |
12 | 12 | ./packdata.sh && \ |
5 | 5 | |
6 | 6 | COPY . /staging/blockattack-game |
7 | 7 | |
8 | ENV BLOCKATTACK_VERSION 2.5.0 | |
8 | ENV BLOCKATTACK_VERSION 2.6.0 | |
9 | 9 | |
10 | 10 | RUN cd /staging/blockattack-game && \ |
11 | 11 | ./packdata.sh && \ |
7 | 7 | |
8 | 8 | COPY . /staging/blockattack-game |
9 | 9 | |
10 | ENV BLOCKATTACK_VERSION 2.5.0 | |
10 | ENV BLOCKATTACK_VERSION 2.6.0 | |
11 | 11 | |
12 | 12 | RUN cd /staging/blockattack-game && \ |
13 | 13 | ./packdata.sh && \ |
25 | 25 | cp /staging/blockattack-game/COPYING ./COPYING.txt && \ |
26 | 26 | cp -r /staging/blockattack-game/source/misc/translation/locale ./ && \ |
27 | 27 | echo "[InternetShortcut]" > "Block Attack - Rise Of the Blocks.url" && \ |
28 | echo "URL=http://www.blockattack.net" >> "Block Attack - Rise Of the Blocks.url" && \ | |
28 | echo "URL=https://blockattack.net" >> "Block Attack - Rise Of the Blocks.url" && \ | |
29 | 29 | cd /staging/package/ && \ |
30 | 30 | zip -r /output/blockattack-${BLOCKATTACK_VERSION}-windows-no-installer.zip "blockattack-${BLOCKATTACK_VERSION}" && \ |
31 | 31 | cd /output && chown nobody * && chmod 666 * && ls -lh |
6 | 6 | Some systems might require the game to be launched from the command line. |
7 | 7 | PulseAudio is required for sound. |
8 | 8 | |
9 | Check www.blockattack.net for more info. | |
9 | Check https://blockattack.net for more info. |
1 | 1 | set -e |
2 | 2 | set -x |
3 | 3 | |
4 | mkdir -p /staging/deps && cd /staging/deps && curl https://libsdl.org/release/SDL2-2.0.9.tar.gz | tar -zx && cd SDL2-2.0.9 && ls -lrt | |
5 | cd /staging/deps/SDL2-2.0.9 && ./configure --enable-shared --enable-static && make && make install | |
4 | mkdir -p /staging/deps && cd /staging/deps && curl https://libsdl.org/release/SDL2-2.0.12.tar.gz | tar -zx && cd SDL2-2.0.12 && ls -lrt | |
5 | cd /staging/deps/SDL2-2.0.12 && ./configure --enable-shared --enable-static && make && make install | |
6 | 6 | |
7 | #https://www.libsdl.org/projects/SDL_image/release/SDL2_image-2.0.4.tar.gz | |
8 | mkdir -p /staging/deps && cd /staging/deps && curl https://www.libsdl.org/projects/SDL_image/release/SDL2_image-2.0.4.tar.gz | tar -zx && cd SDL2_image-2.0.4 && ls -lrt | |
9 | cd /staging/deps/SDL2_image-2.0.4 && ./configure --enable-shared --enable-static && make && make install | |
7 | #https://www.libsdl.org/projects/SDL_image/release/SDL2_image-2.0.5.tar.gz | |
8 | mkdir -p /staging/deps && cd /staging/deps && curl https://www.libsdl.org/projects/SDL_image/release/SDL2_image-2.0.5.tar.gz | tar -zx && cd SDL2_image-2.0.5 && ls -lrt | |
9 | cd /staging/deps/SDL2_image-2.0.5 && ./configure --enable-shared --enable-static && make && make install | |
10 | 10 | |
11 | 11 | #https://www.libsdl.org/projects/SDL_mixer/release/SDL2_mixer-2.0.4.tar.gz |
12 | 12 | mkdir -p /staging/deps && cd /staging/deps && curl https://www.libsdl.org/projects/SDL_mixer/release/SDL2_mixer-2.0.4.tar.gz | tar -zx && cd SDL2_mixer-2.0.4 && ls -lrt |
13 | 13 | cd /staging/deps/SDL2_mixer-2.0.4 && ./configure --enable-shared --enable-static && make && make install |
14 | 14 | |
15 | #https://www.libsdl.org/projects/SDL_ttf/release/SDL2_ttf-2.0.14.tar.gz | |
16 | mkdir -p /staging/deps && cd /staging/deps && curl https://www.libsdl.org/projects/SDL_ttf/release/SDL2_ttf-2.0.14.tar.gz | tar -zx && cd SDL2_ttf-2.0.14 && ls -lrt | |
17 | cd /staging/deps/SDL2_ttf-2.0.14 && ./configure --enable-shared --enable-static && make && make install | |
15 | #https://www.libsdl.org/projects/SDL_ttf/release/SDL2_ttf-2.0.15.tar.gz | |
16 | mkdir -p /staging/deps && cd /staging/deps && curl https://www.libsdl.org/projects/SDL_ttf/release/SDL2_ttf-2.0.15.tar.gz | tar -zx && cd SDL2_ttf-2.0.15 && ls -lrt | |
17 | cd /staging/deps/SDL2_ttf-2.0.15 && ./configure --enable-shared --enable-static && make && make install | |
18 | 18 | mkdir -p /staging/blockattack-game |
19 | 19 | |
20 | mkdir -p /staging/deps && cd /staging/deps && curl http://icculus.org/physfs/downloads/physfs-2.0.3.tar.bz2 | tar -jx && cd physfs-2.0.3 && ls -lrt | |
21 | cd /staging/deps/physfs-2.0.3 && cmake . && make && make install | |
20 | mkdir -p /staging/deps && cd /staging/deps && curl https://icculus.org/physfs/downloads/physfs-3.0.2.tar.bz2 | tar -jx && cd physfs-3.0.2 && ls -lrt | |
21 | cd /staging/deps/physfs-3.0.2 && cmake . && make && make install | |
22 | 22 | |
23 | 23 | # boost |
24 | 24 | cd ~ |
4 | 4 | # Poul Sander <poul@poulsander.com>, 2019. #zanata |
5 | 5 | msgid "" |
6 | 6 | msgstr "" |
7 | "Project-Id-Version: PACKAGE VERSION\n" | |
7 | "Project-Id-Version: \n" | |
8 | 8 | "Report-Msgid-Bugs-To: \n" |
9 | "POT-Creation-Date: 2019-05-02 19:35+0200\n" | |
9 | "POT-Creation-Date: 2020-06-27 14:06+0200\n" | |
10 | "PO-Revision-Date: 2020-06-27 14:08+0200\n" | |
11 | "Last-Translator: Poul Sander <poul@poulsander.com>\n" | |
12 | "Language-Team: \n" | |
13 | "Language: da\n" | |
10 | 14 | "MIME-Version: 1.0\n" |
11 | 15 | "Content-Type: text/plain; charset=UTF-8\n" |
12 | 16 | "Content-Transfer-Encoding: 8bit\n" |
13 | "PO-Revision-Date: 2019-05-02 05:39+0000\n" | |
14 | "Last-Translator: Poul Sander <poul@poulsander.com>\n" | |
15 | "Language-Team: \n" | |
16 | "Language: da\n" | |
17 | "X-Generator: Zanata 4.6.2\n" | |
17 | "X-Generator: Poedit 2.0.6\n" | |
18 | 18 | "Plural-Forms: nplurals=2; plural=(n != 1);\n" |
19 | 19 | |
20 | #: ../../code/DialogBox.cpp:92 | |
20 | #: ../../code/DialogBox.cpp:94 | |
21 | 21 | msgid "Enter to accept" |
22 | 22 | msgstr "Bekræft med Enter" |
23 | 23 | |
24 | #: ../../code/DialogBox.cpp:93 | |
24 | #: ../../code/DialogBox.cpp:95 | |
25 | 25 | msgid "Esc to cancel" |
26 | 26 | msgstr "Annuller med Esc" |
27 | 27 | |
33 | 33 | msgid "Name:" |
34 | 34 | msgstr "Navn:" |
35 | 35 | |
36 | #: ../../code/HelpAboutState.cpp:71 | |
36 | #: ../../code/HelpAboutState.cpp:71 ../../code/main.cpp:329 | |
37 | 37 | msgid "Block Attack - Rise of the Blocks" |
38 | 38 | msgstr "Block Attack - Blokkenes opstand" |
39 | 39 | |
169 | 169 | msgid "DRAW" |
170 | 170 | msgstr "UAFGJORT" |
171 | 171 | |
172 | #: ../../code/main.cpp:487 ../../code/main.cpp:618 | |
172 | #: ../../code/main.cpp:497 ../../code/main.cpp:628 | |
173 | 173 | msgid "AI" |
174 | 174 | msgstr "Computer" |
175 | 175 | |
176 | #: ../../code/main.cpp:490 | |
176 | #: ../../code/main.cpp:500 | |
177 | 177 | msgid "Playing field" |
178 | 178 | msgstr "Spilleflade" |
179 | 179 | |
180 | #: ../../code/main.cpp:564 | |
180 | #: ../../code/main.cpp:574 | |
181 | 181 | msgid "Time Trial" |
182 | 182 | msgstr "På tid" |
183 | 183 | |
184 | #: ../../code/main.cpp:565 | |
184 | #: ../../code/main.cpp:575 | |
185 | 185 | msgid "Score as much as possible in 2 minutes" |
186 | 186 | msgstr "Se hvor mange point du kan opnå på 2 minutter" |
187 | 187 | |
188 | #: ../../code/main.cpp:569 | |
188 | #: ../../code/main.cpp:579 | |
189 | 189 | msgid "Stage Clear" |
190 | 190 | msgstr "Stage Clear" |
191 | 191 | |
192 | #: ../../code/main.cpp:570 | |
192 | #: ../../code/main.cpp:580 | |
193 | 193 | msgid "You must clear a number of lines. Speed is rapidly increased." |
194 | 194 | msgstr "Fjern et specifik antal linjer. Hastigheden stiger hurtigt." |
195 | 195 | |
196 | #: ../../code/main.cpp:573 | |
196 | #: ../../code/main.cpp:583 | |
197 | 197 | msgid "Puzzle" |
198 | 198 | msgstr "Gåde" |
199 | 199 | |
200 | #: ../../code/main.cpp:574 | |
200 | #: ../../code/main.cpp:584 | |
201 | 201 | msgid "Clear the entire board with a limited number of moves." |
202 | 202 | msgstr "Fjern alle blokke med et begrænset antal flyt." |
203 | 203 | |
204 | #: ../../code/main.cpp:577 | |
204 | #: ../../code/main.cpp:587 | |
205 | 205 | msgid "Endless" |
206 | 206 | msgstr "Evighed" |
207 | 207 | |
208 | #: ../../code/main.cpp:578 | |
208 | #: ../../code/main.cpp:588 | |
209 | 209 | msgid "Score as much as possible. No time limit." |
210 | 210 | msgstr "Opnå så mange point som muligt. Ingen tidsbegrænsning." |
211 | 211 | |
212 | #: ../../code/main.cpp:588 | |
212 | #: ../../code/main.cpp:598 | |
213 | 213 | msgid "Objective:" |
214 | 214 | msgstr "Formål:" |
215 | 215 | |
216 | #: ../../code/main.cpp:598 | |
216 | #: ../../code/main.cpp:608 | |
217 | 217 | msgid "Movement keys:" |
218 | 218 | msgstr "Bevægelsestaster:" |
219 | 219 | |
220 | #: ../../code/main.cpp:600 | |
220 | #: ../../code/main.cpp:610 | |
221 | 221 | msgid "Switch: " |
222 | 222 | msgstr "Skift: " |
223 | 223 | |
224 | #: ../../code/main.cpp:602 | |
224 | #: ../../code/main.cpp:612 | |
225 | 225 | msgid "Restart: " |
226 | 226 | msgstr "Genstart: " |
227 | 227 | |
228 | #: ../../code/main.cpp:605 | |
228 | #: ../../code/main.cpp:615 | |
229 | 229 | msgid "Push line: " |
230 | 230 | msgstr "Skub linje: " |
231 | 231 | |
232 | #: ../../code/main.cpp:1040 | |
232 | #: ../../code/main.cpp:1050 | |
233 | 233 | msgid "Player 2" |
234 | 234 | msgstr "Spiller 2" |
235 | 235 | |
506 | 506 | msgstr "Bedste resultater" |
507 | 507 | |
508 | 508 | #: ../../code/MenuSystem.cpp:159 ../../code/MenuSystem.cpp:167 |
509 | #: ../../code/MenuSystem.cpp:179 ../../code/ScoresDisplay.cpp:216 | |
509 | #: ../../code/MenuSystem.cpp:179 ../../code/ScoresDisplay.cpp:220 | |
510 | 510 | msgid "Back" |
511 | 511 | msgstr "Tilbage" |
512 | 512 | |
514 | 514 | msgid "Exit" |
515 | 515 | msgstr "Afslut" |
516 | 516 | |
517 | #: ../../code/os.cpp:99 | |
517 | #: ../../code/os.cpp:101 | |
518 | 518 | msgid "Player 1" |
519 | 519 | msgstr "Spiller 1" |
520 | 520 | |
521 | #: ../../code/ScoresDisplay.cpp:70 | |
521 | #: ../../code/ScoresDisplay.cpp:74 | |
522 | 522 | msgid "Endless (Fast):" |
523 | 523 | msgstr "Evighed (Hurtig):" |
524 | 524 | |
525 | #: ../../code/ScoresDisplay.cpp:73 | |
525 | #: ../../code/ScoresDisplay.cpp:77 | |
526 | 526 | msgid "Endless (Faster):" |
527 | 527 | msgstr "Evighed (Hurtigere):" |
528 | 528 | |
529 | #: ../../code/ScoresDisplay.cpp:76 | |
529 | #: ../../code/ScoresDisplay.cpp:80 | |
530 | 530 | msgid "Endless (Even faster):" |
531 | 531 | msgstr "Evighed (Endnu hurtigere):" |
532 | 532 | |
533 | #: ../../code/ScoresDisplay.cpp:79 | |
533 | #: ../../code/ScoresDisplay.cpp:83 | |
534 | 534 | msgid "Endless (Fastest):" |
535 | 535 | msgstr "Evighed (Hurtigst):" |
536 | 536 | |
537 | #: ../../code/ScoresDisplay.cpp:82 | |
537 | #: ../../code/ScoresDisplay.cpp:86 | |
538 | 538 | msgid "Endless:" |
539 | 539 | msgstr "Evighed:" |
540 | 540 | |
541 | #: ../../code/ScoresDisplay.cpp:87 | |
541 | #: ../../code/ScoresDisplay.cpp:91 | |
542 | 542 | msgid "Time Trial:" |
543 | 543 | msgstr "På tid:" |
544 | 544 | |
545 | #: ../../code/ScoresDisplay.cpp:125 | |
545 | #: ../../code/ScoresDisplay.cpp:129 | |
546 | 546 | msgid "Stats" |
547 | 547 | msgstr "Statistik" |
548 | 548 | |
549 | #: ../../code/ScoresDisplay.cpp:127 | |
549 | #: ../../code/ScoresDisplay.cpp:131 | |
550 | 550 | msgid "Chains" |
551 | 551 | msgstr "Kæder" |
552 | 552 | |
553 | #: ../../code/ScoresDisplay.cpp:135 | |
553 | #: ../../code/ScoresDisplay.cpp:139 | |
554 | 554 | msgid "Lines Pushed: " |
555 | 555 | msgstr "Linjer skubbet: " |
556 | 556 | |
557 | #: ../../code/ScoresDisplay.cpp:140 | |
557 | #: ../../code/ScoresDisplay.cpp:144 | |
558 | 558 | msgid "Puzzles solved: " |
559 | 559 | msgstr "Gåder løst: " |
560 | 560 | |
561 | #: ../../code/ScoresDisplay.cpp:145 | |
561 | #: ../../code/ScoresDisplay.cpp:149 | |
562 | 562 | msgid "Run time: " |
563 | 563 | msgstr "Kørselstid: " |
564 | 564 | |
565 | #: ../../code/ScoresDisplay.cpp:148 ../../code/ScoresDisplay.cpp:161 | |
565 | #: ../../code/ScoresDisplay.cpp:152 ../../code/ScoresDisplay.cpp:165 | |
566 | 566 | #, c-format |
567 | 567 | msgid "Days: %i" |
568 | 568 | msgstr "Dage: %i" |
569 | 569 | |
570 | #: ../../code/ScoresDisplay.cpp:150 ../../code/ScoresDisplay.cpp:163 | |
570 | #: ../../code/ScoresDisplay.cpp:154 ../../code/ScoresDisplay.cpp:167 | |
571 | 571 | #, c-format |
572 | 572 | msgid "Hours: %i" |
573 | 573 | msgstr "Timer: %i" |
574 | 574 | |
575 | #: ../../code/ScoresDisplay.cpp:152 ../../code/ScoresDisplay.cpp:165 | |
575 | #: ../../code/ScoresDisplay.cpp:156 ../../code/ScoresDisplay.cpp:169 | |
576 | 576 | #, c-format |
577 | 577 | msgid "Minutes: %i" |
578 | 578 | msgstr "Minutter: %i" |
579 | 579 | |
580 | #: ../../code/ScoresDisplay.cpp:154 ../../code/ScoresDisplay.cpp:167 | |
580 | #: ../../code/ScoresDisplay.cpp:158 ../../code/ScoresDisplay.cpp:171 | |
581 | 581 | #, c-format |
582 | 582 | msgid "Seconds: %i" |
583 | 583 | msgstr "Sekunder: %i" |
584 | 584 | |
585 | #: ../../code/ScoresDisplay.cpp:158 | |
585 | #: ../../code/ScoresDisplay.cpp:162 | |
586 | 586 | msgid "Play time: " |
587 | 587 | msgstr "Spilletid: " |
588 | 588 | |
589 | #: ../../code/ScoresDisplay.cpp:171 | |
589 | #: ../../code/ScoresDisplay.cpp:175 | |
590 | 590 | msgid "VS CPU (win/loss)" |
591 | 591 | msgstr "Mod computeren (vundet/tabt)" |
592 | 592 | |
593 | #: ../../code/ScoresDisplay.cpp:220 ../../code/BlockGameSdl.inc:55 | |
593 | #: ../../code/ScoresDisplay.cpp:224 ../../code/BlockGameSdl.inc:55 | |
594 | 594 | msgid "Next" |
595 | 595 | msgstr "Næste" |
596 | 596 | |
597 | #: ../../code/ScoresDisplay.cpp:224 | |
597 | #: ../../code/ScoresDisplay.cpp:228 | |
598 | 598 | #, c-format |
599 | 599 | msgid "Page %i of %i" |
600 | 600 | msgstr "Side %i af %i" |
635 | 635 | msgid "Last stage" |
636 | 636 | msgstr "Sidste bane" |
637 | 637 | |
638 | #: ../../code/DialogBox.hpp:38 | |
639 | msgid "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,:!?+_^@#%&=*" | |
640 | msgstr "ABCDEFGHIJKLMNOPQRSTUVWXYZÆØÅabcdefghijklmnopqrstuvwxyzæøå.,:!?+_^@#%&=*" | |
641 | ||
638 | 642 | #: ../../code/ShowFileState.hpp:45 |
639 | 643 | #, c-format |
640 | 644 | msgid "Showing content of: %s" |
641 | 645 | msgstr "Viser indhold af: %s" |
642 |
7 | 7 | msgstr "" |
8 | 8 | "Project-Id-Version: PACKAGE VERSION\n" |
9 | 9 | "Report-Msgid-Bugs-To: \n" |
10 | "POT-Creation-Date: 2019-05-02 19:35+0200\n" | |
10 | "POT-Creation-Date: 2020-06-27 14:06+0200\n" | |
11 | 11 | "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" |
12 | 12 | "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" |
13 | 13 | "Language-Team: LANGUAGE <LL@li.org>\n" |
16 | 16 | "Content-Type: text/plain; charset=CHARSET\n" |
17 | 17 | "Content-Transfer-Encoding: 8bit\n" |
18 | 18 | |
19 | #: ../../code/DialogBox.cpp:92 | |
19 | #: ../../code/DialogBox.cpp:94 | |
20 | 20 | msgid "Enter to accept" |
21 | 21 | msgstr "" |
22 | 22 | |
23 | #: ../../code/DialogBox.cpp:93 | |
23 | #: ../../code/DialogBox.cpp:95 | |
24 | 24 | msgid "Esc to cancel" |
25 | 25 | msgstr "" |
26 | 26 | |
32 | 32 | msgid "Name:" |
33 | 33 | msgstr "" |
34 | 34 | |
35 | #: ../../code/HelpAboutState.cpp:71 | |
35 | #: ../../code/HelpAboutState.cpp:71 ../../code/main.cpp:329 | |
36 | 36 | msgid "Block Attack - Rise of the Blocks" |
37 | 37 | msgstr "" |
38 | 38 | |
166 | 166 | msgid "DRAW" |
167 | 167 | msgstr "" |
168 | 168 | |
169 | #: ../../code/main.cpp:487 ../../code/main.cpp:618 | |
169 | #: ../../code/main.cpp:497 ../../code/main.cpp:628 | |
170 | 170 | msgid "AI" |
171 | 171 | msgstr "" |
172 | 172 | |
173 | #: ../../code/main.cpp:490 | |
173 | #: ../../code/main.cpp:500 | |
174 | 174 | msgid "Playing field" |
175 | 175 | msgstr "" |
176 | 176 | |
177 | #: ../../code/main.cpp:564 | |
177 | #: ../../code/main.cpp:574 | |
178 | 178 | msgid "Time Trial" |
179 | 179 | msgstr "" |
180 | 180 | |
181 | #: ../../code/main.cpp:565 | |
181 | #: ../../code/main.cpp:575 | |
182 | 182 | msgid "Score as much as possible in 2 minutes" |
183 | 183 | msgstr "" |
184 | 184 | |
185 | #: ../../code/main.cpp:569 | |
185 | #: ../../code/main.cpp:579 | |
186 | 186 | msgid "Stage Clear" |
187 | 187 | msgstr "" |
188 | 188 | |
189 | #: ../../code/main.cpp:570 | |
189 | #: ../../code/main.cpp:580 | |
190 | 190 | msgid "You must clear a number of lines. Speed is rapidly increased." |
191 | 191 | msgstr "" |
192 | 192 | |
193 | #: ../../code/main.cpp:573 | |
193 | #: ../../code/main.cpp:583 | |
194 | 194 | msgid "Puzzle" |
195 | 195 | msgstr "" |
196 | 196 | |
197 | #: ../../code/main.cpp:574 | |
197 | #: ../../code/main.cpp:584 | |
198 | 198 | msgid "Clear the entire board with a limited number of moves." |
199 | 199 | msgstr "" |
200 | 200 | |
201 | #: ../../code/main.cpp:577 | |
201 | #: ../../code/main.cpp:587 | |
202 | 202 | msgid "Endless" |
203 | 203 | msgstr "" |
204 | 204 | |
205 | #: ../../code/main.cpp:578 | |
205 | #: ../../code/main.cpp:588 | |
206 | 206 | msgid "Score as much as possible. No time limit." |
207 | 207 | msgstr "" |
208 | 208 | |
209 | #: ../../code/main.cpp:588 | |
209 | #: ../../code/main.cpp:598 | |
210 | 210 | msgid "Objective:" |
211 | 211 | msgstr "" |
212 | 212 | |
213 | #: ../../code/main.cpp:598 | |
213 | #: ../../code/main.cpp:608 | |
214 | 214 | msgid "Movement keys:" |
215 | 215 | msgstr "" |
216 | 216 | |
217 | #: ../../code/main.cpp:600 | |
217 | #: ../../code/main.cpp:610 | |
218 | 218 | msgid "Switch: " |
219 | 219 | msgstr "" |
220 | 220 | |
221 | #: ../../code/main.cpp:602 | |
221 | #: ../../code/main.cpp:612 | |
222 | 222 | msgid "Restart: " |
223 | 223 | msgstr "" |
224 | 224 | |
225 | #: ../../code/main.cpp:605 | |
225 | #: ../../code/main.cpp:615 | |
226 | 226 | msgid "Push line: " |
227 | 227 | msgstr "" |
228 | 228 | |
229 | #: ../../code/main.cpp:1040 | |
229 | #: ../../code/main.cpp:1050 | |
230 | 230 | msgid "Player 2" |
231 | 231 | msgstr "" |
232 | 232 | |
503 | 503 | msgstr "" |
504 | 504 | |
505 | 505 | #: ../../code/MenuSystem.cpp:159 ../../code/MenuSystem.cpp:167 |
506 | #: ../../code/MenuSystem.cpp:179 ../../code/ScoresDisplay.cpp:216 | |
506 | #: ../../code/MenuSystem.cpp:179 ../../code/ScoresDisplay.cpp:220 | |
507 | 507 | msgid "Back" |
508 | 508 | msgstr "" |
509 | 509 | |
511 | 511 | msgid "Exit" |
512 | 512 | msgstr "" |
513 | 513 | |
514 | #: ../../code/os.cpp:99 | |
514 | #: ../../code/os.cpp:101 | |
515 | 515 | msgid "Player 1" |
516 | 516 | msgstr "" |
517 | 517 | |
518 | #: ../../code/ScoresDisplay.cpp:70 | |
518 | #: ../../code/ScoresDisplay.cpp:74 | |
519 | 519 | msgid "Endless (Fast):" |
520 | 520 | msgstr "" |
521 | 521 | |
522 | #: ../../code/ScoresDisplay.cpp:73 | |
522 | #: ../../code/ScoresDisplay.cpp:77 | |
523 | 523 | msgid "Endless (Faster):" |
524 | 524 | msgstr "" |
525 | 525 | |
526 | #: ../../code/ScoresDisplay.cpp:76 | |
526 | #: ../../code/ScoresDisplay.cpp:80 | |
527 | 527 | msgid "Endless (Even faster):" |
528 | 528 | msgstr "" |
529 | 529 | |
530 | #: ../../code/ScoresDisplay.cpp:79 | |
530 | #: ../../code/ScoresDisplay.cpp:83 | |
531 | 531 | msgid "Endless (Fastest):" |
532 | 532 | msgstr "" |
533 | 533 | |
534 | #: ../../code/ScoresDisplay.cpp:82 | |
534 | #: ../../code/ScoresDisplay.cpp:86 | |
535 | 535 | msgid "Endless:" |
536 | 536 | msgstr "" |
537 | 537 | |
538 | #: ../../code/ScoresDisplay.cpp:87 | |
538 | #: ../../code/ScoresDisplay.cpp:91 | |
539 | 539 | msgid "Time Trial:" |
540 | 540 | msgstr "" |
541 | 541 | |
542 | #: ../../code/ScoresDisplay.cpp:125 | |
542 | #: ../../code/ScoresDisplay.cpp:129 | |
543 | 543 | msgid "Stats" |
544 | 544 | msgstr "" |
545 | 545 | |
546 | #: ../../code/ScoresDisplay.cpp:127 | |
546 | #: ../../code/ScoresDisplay.cpp:131 | |
547 | 547 | msgid "Chains" |
548 | 548 | msgstr "" |
549 | 549 | |
550 | #: ../../code/ScoresDisplay.cpp:135 | |
550 | #: ../../code/ScoresDisplay.cpp:139 | |
551 | 551 | msgid "Lines Pushed: " |
552 | 552 | msgstr "" |
553 | 553 | |
554 | #: ../../code/ScoresDisplay.cpp:140 | |
554 | #: ../../code/ScoresDisplay.cpp:144 | |
555 | 555 | msgid "Puzzles solved: " |
556 | 556 | msgstr "" |
557 | 557 | |
558 | #: ../../code/ScoresDisplay.cpp:145 | |
558 | #: ../../code/ScoresDisplay.cpp:149 | |
559 | 559 | msgid "Run time: " |
560 | 560 | msgstr "" |
561 | 561 | |
562 | #: ../../code/ScoresDisplay.cpp:148 ../../code/ScoresDisplay.cpp:161 | |
562 | #: ../../code/ScoresDisplay.cpp:152 ../../code/ScoresDisplay.cpp:165 | |
563 | 563 | #, c-format |
564 | 564 | msgid "Days: %i" |
565 | 565 | msgstr "" |
566 | 566 | |
567 | #: ../../code/ScoresDisplay.cpp:150 ../../code/ScoresDisplay.cpp:163 | |
567 | #: ../../code/ScoresDisplay.cpp:154 ../../code/ScoresDisplay.cpp:167 | |
568 | 568 | #, c-format |
569 | 569 | msgid "Hours: %i" |
570 | 570 | msgstr "" |
571 | 571 | |
572 | #: ../../code/ScoresDisplay.cpp:152 ../../code/ScoresDisplay.cpp:165 | |
572 | #: ../../code/ScoresDisplay.cpp:156 ../../code/ScoresDisplay.cpp:169 | |
573 | 573 | #, c-format |
574 | 574 | msgid "Minutes: %i" |
575 | 575 | msgstr "" |
576 | 576 | |
577 | #: ../../code/ScoresDisplay.cpp:154 ../../code/ScoresDisplay.cpp:167 | |
577 | #: ../../code/ScoresDisplay.cpp:158 ../../code/ScoresDisplay.cpp:171 | |
578 | 578 | #, c-format |
579 | 579 | msgid "Seconds: %i" |
580 | 580 | msgstr "" |
581 | 581 | |
582 | #: ../../code/ScoresDisplay.cpp:158 | |
582 | #: ../../code/ScoresDisplay.cpp:162 | |
583 | 583 | msgid "Play time: " |
584 | 584 | msgstr "" |
585 | 585 | |
586 | #: ../../code/ScoresDisplay.cpp:171 | |
586 | #: ../../code/ScoresDisplay.cpp:175 | |
587 | 587 | msgid "VS CPU (win/loss)" |
588 | 588 | msgstr "" |
589 | 589 | |
590 | #: ../../code/ScoresDisplay.cpp:220 ../../code/BlockGameSdl.inc:55 | |
590 | #: ../../code/ScoresDisplay.cpp:224 ../../code/BlockGameSdl.inc:55 | |
591 | 591 | msgid "Next" |
592 | 592 | msgstr "" |
593 | 593 | |
594 | #: ../../code/ScoresDisplay.cpp:224 | |
594 | #: ../../code/ScoresDisplay.cpp:228 | |
595 | 595 | #, c-format |
596 | 596 | msgid "Page %i of %i" |
597 | 597 | msgstr "" |
632 | 632 | msgid "Last stage" |
633 | 633 | msgstr "" |
634 | 634 | |
635 | #: ../../code/DialogBox.hpp:38 | |
636 | msgid "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,:!?+_^@#%&=*" | |
637 | msgstr "" | |
638 | ||
635 | 639 | #: ../../code/ShowFileState.hpp:45 |
636 | 640 | #, c-format |
637 | 641 | msgid "Showing content of: %s" |
1 | 1 | |
2 | 2 | ; HM NIS Edit Wizard helper defines |
3 | 3 | !define PRODUCT_NAME "Block Attack - Rise Of the Blocks" |
4 | !define PRODUCT_VERSION "2.5.0" | |
4 | !define PRODUCT_VERSION "2.6.0" | |
5 | 5 | !define PRODUCT_PUBLISHER "Poul Sander" |
6 | 6 | !define PRODUCT_WEB_SITE "http://www.blockattack.net" |
7 | 7 | !define PRODUCT_DIR_REGKEY "Software\Microsoft\Windows\CurrentVersion\App Paths\blockattack.exe" |