From 235d06c6508e88f44e298547f90cfa9163a7b1db Mon Sep 17 00:00:00 2001 From: "D. Quan" <60545346+sudoker0@users.noreply.github.com> Date: Thu, 15 Jan 2026 22:53:47 +0700 Subject: [PATCH 001/215] clean --- .DS_Store | Bin 10244 -> 0 bytes .gitignore | 60 - .gitmodules | 9 - LICENSE | 22 - README.md | 35 - docs/building.md | 16 - docs/index.md | 15 - docs/javascripts/mathjax.js | 16 - docs/javascripts/tablesort.js | 6 - docs/logo.png | Bin 467 -> 0 bytes docs/overrides/partials/copyright.html | 17 - docs/stylesheets/doxide.css | 58 - doxide.yaml | 5 - include/.DS_Store | Bin 10244 -> 0 bytes include/actor.hpp | 121 - include/atlasTile.hpp | 33 - include/cereal/access.hpp | 351 - include/cereal/archives/adapters.hpp | 163 - include/cereal/archives/binary.hpp | 169 - include/cereal/archives/json.hpp | 1024 - include/cereal/archives/portable_binary.hpp | 334 - include/cereal/archives/xml.hpp | 956 - include/cereal/cereal.hpp | 1120 - include/cereal/details/helpers.hpp | 422 - include/cereal/details/polymorphic_impl.hpp | 825 - .../cereal/details/polymorphic_impl_fwd.hpp | 65 - include/cereal/details/static_object.hpp | 128 - include/cereal/details/traits.hpp | 1411 - include/cereal/details/util.hpp | 84 - include/cereal/external/LICENSE | 21 - include/cereal/external/base64.hpp | 134 - include/cereal/external/rapidjson/LICENSE | 13 - .../cereal/external/rapidjson/allocators.h | 284 - .../external/rapidjson/cursorstreamwrapper.h | 78 - include/cereal/external/rapidjson/document.h | 2659 -- .../cereal/external/rapidjson/encodedstream.h | 299 - include/cereal/external/rapidjson/encodings.h | 716 - include/cereal/external/rapidjson/error/en.h | 74 - .../cereal/external/rapidjson/error/error.h | 161 - .../external/rapidjson/filereadstream.h | 99 - .../external/rapidjson/filewritestream.h | 104 - include/cereal/external/rapidjson/fwd.h | 151 - .../external/rapidjson/internal/biginteger.h | 290 - .../external/rapidjson/internal/diyfp.h | 271 - .../cereal/external/rapidjson/internal/dtoa.h | 245 - .../external/rapidjson/internal/ieee754.h | 78 - .../cereal/external/rapidjson/internal/itoa.h | 308 - .../cereal/external/rapidjson/internal/meta.h | 186 - .../external/rapidjson/internal/pow10.h | 55 - .../external/rapidjson/internal/regex.h | 740 - .../external/rapidjson/internal/stack.h | 232 - .../external/rapidjson/internal/strfunc.h | 69 - .../external/rapidjson/internal/strtod.h | 290 - .../cereal/external/rapidjson/internal/swap.h | 46 - .../external/rapidjson/istreamwrapper.h | 128 - .../cereal/external/rapidjson/memorybuffer.h | 70 - .../cereal/external/rapidjson/memorystream.h | 71 - .../external/rapidjson/msinttypes/LICENSE | 29 - .../external/rapidjson/msinttypes/inttypes.h | 316 - .../external/rapidjson/msinttypes/stdint.h | 300 - .../external/rapidjson/ostreamwrapper.h | 81 - include/cereal/external/rapidjson/pointer.h | 1414 - .../cereal/external/rapidjson/prettywriter.h | 277 - include/cereal/external/rapidjson/rapidjson.h | 656 - include/cereal/external/rapidjson/reader.h | 2230 -- include/cereal/external/rapidjson/schema.h | 2497 -- include/cereal/external/rapidjson/stream.h | 223 - .../cereal/external/rapidjson/stringbuffer.h | 121 - include/cereal/external/rapidjson/writer.h | 709 - include/cereal/external/rapidxml/license.txt | 52 - include/cereal/external/rapidxml/manual.html | 406 - include/cereal/external/rapidxml/rapidxml.hpp | 2624 -- .../external/rapidxml/rapidxml_iterators.hpp | 175 - .../external/rapidxml/rapidxml_print.hpp | 428 - .../external/rapidxml/rapidxml_utils.hpp | 123 - include/cereal/macros.hpp | 156 - include/cereal/specialize.hpp | 139 - include/cereal/types/array.hpp | 79 - include/cereal/types/atomic.hpp | 55 - include/cereal/types/base_class.hpp | 203 - include/cereal/types/bitset.hpp | 176 - include/cereal/types/boost_variant.hpp | 164 - include/cereal/types/chrono.hpp | 72 - include/cereal/types/common.hpp | 129 - include/cereal/types/complex.hpp | 56 - .../concepts/pair_associative_container.hpp | 73 - include/cereal/types/deque.hpp | 62 - include/cereal/types/forward_list.hpp | 68 - include/cereal/types/functional.hpp | 43 - include/cereal/types/list.hpp | 62 - include/cereal/types/map.hpp | 36 - include/cereal/types/memory.hpp | 425 - include/cereal/types/optional.hpp | 65 - include/cereal/types/polymorphic.hpp | 483 - include/cereal/types/queue.hpp | 132 - include/cereal/types/set.hpp | 103 - include/cereal/types/stack.hpp | 76 - include/cereal/types/string.hpp | 61 - include/cereal/types/tuple.hpp | 123 - include/cereal/types/unordered_map.hpp | 36 - include/cereal/types/unordered_set.hpp | 99 - include/cereal/types/utility.hpp | 47 - include/cereal/types/valarray.hpp | 89 - include/cereal/types/variant.hpp | 108 - include/cereal/types/vector.hpp | 112 - include/cereal/version.hpp | 52 - include/collisionsContainer.hpp | 23 - include/colorRect.hpp | 19 - include/dialogueBalloon.hpp | 54 - include/editor/actorInfoPanel.hpp | 23 - include/editor/actorPanelView.hpp | 24 - include/editor/actorPropertiesBox.hpp | 23 - include/editor/actorView.hpp | 41 - include/editor/animationsView.hpp | 31 - include/editor/collisionInfoPanel.hpp | 19 - include/editor/collisionbox.hpp | 34 - include/editor/dialoguePanelView.hpp | 20 - include/editor/dialogueParser.hpp | 12 - include/editor/dialogueViewer.hpp | 24 - include/editor/editor.hpp | 26 - include/editor/editorInterfaceService.hpp | 53 - include/editor/fileSystemService.hpp | 60 - include/editor/interactableInfoPanel.hpp | 39 - include/editor/interactablePropsState.hpp | 20 - include/editor/layoutContainer.hpp | 16 - include/editor/mainView.hpp | 17 - include/editor/mainViewPanel.hpp | 18 - include/editor/mapPanelView.hpp | 37 - include/editor/mapPropertiesBox.hpp | 28 - include/editor/mapToolsBox.hpp | 21 - include/editor/mouseInput.hpp | 28 - include/editor/panelView.hpp | 29 - include/editor/project.hpp | 45 - include/editor/projectCompiler.hpp | 16 - include/editor/projectFile.hpp | 58 - include/editor/projectGenerator.hpp | 34 - include/editor/projectMenuBox.hpp | 16 - include/editor/propInfoPanel.hpp | 27 - include/editor/propInitWindow.hpp | 21 - include/editor/propPanelView.hpp | 22 - include/editor/propPropertiesBox.hpp | 26 - include/editor/propView.hpp | 25 - include/editor/propertiesBox.hpp | 29 - include/editor/resourceViewerBox.hpp | 25 - include/editor/tabList.hpp | 34 - include/editor/tileSetPanelView.hpp | 22 - include/editor/tileSetPropertiesBox.hpp | 30 - include/editor/windowContainer.hpp | 32 - include/editor/windowPopup.hpp | 26 - include/editor/windows/aboutWindow.hpp | 18 - include/editor/windows/actorInitWindow.hpp | 24 - .../editor/windows/deleteConfirmWindow.hpp | 18 - include/editor/windows/dialogueInitWindow.hpp | 20 - include/editor/windows/dialogueLineWindow.hpp | 19 - include/editor/windows/errorWindow.hpp | 18 - include/editor/windows/mapInitWindow.hpp | 24 - .../windows/projectBinaryViewWindow.hpp | 42 - include/editor/windows/projectInitWindow.hpp | 25 - .../editor/windows/tileSetDialogWindow.hpp | 30 - include/editor/windows/tileSetInitWindow.hpp | 24 - include/editor/worldViewBox.hpp | 125 - include/extras/IconsFontAwesome6.h | 1396 - include/game.hpp | 45 - include/gamedata.hpp | 123 - include/imageRect.hpp | 22 - include/imgui/IconsFontAwesome6.h | 1396 - include/imgui/IconsKenney.h | 242 - include/imgui/Str.h | 660 - include/imgui/imconfig.h | 145 - include/imgui/imgui.h | 4121 --- include/imgui/imgui_impl_raylib.h | 53 - include/imgui/imgui_internal.h | 3906 --- include/imgui/imgui_stdlib.h | 25 - include/imgui/imstb_rectpack.h | 627 - include/imgui/imstb_textedit.h | 1488 - include/imgui/imstb_truetype.h | 5085 --- include/imgui/rlImGui.h | 195 - include/imgui/rlImGuiColors.h | 47 - include/interactable.hpp | 106 - include/interactablesContainer.hpp | 40 - include/interfaceService.hpp | 41 - include/interfaceView.hpp | 21 - include/luajit/buildvm.h | 105 - include/luajit/buildvm_libbc.h | 81 - include/luajit/lauxlib.h | 161 - include/luajit/lj_alloc.h | 18 - include/luajit/lj_arch.h | 778 - include/luajit/lj_asm.h | 17 - include/luajit/lj_asm_arm.h | 2345 -- include/luajit/lj_asm_arm64.h | 2100 -- include/luajit/lj_asm_mips.h | 2820 -- include/luajit/lj_asm_ppc.h | 2338 -- include/luajit/lj_asm_x86.h | 3165 -- include/luajit/lj_bc.h | 270 - include/luajit/lj_bcdump.h | 70 - include/luajit/lj_buf.h | 198 - include/luajit/lj_carith.h | 37 - include/luajit/lj_ccall.h | 201 - include/luajit/lj_ccallback.h | 25 - include/luajit/lj_cconv.h | 71 - include/luajit/lj_cdata.h | 79 - include/luajit/lj_char.h | 42 - include/luajit/lj_clib.h | 29 - include/luajit/lj_cparse.h | 67 - include/luajit/lj_crecord.h | 43 - include/luajit/lj_ctype.h | 485 - include/luajit/lj_debug.h | 66 - include/luajit/lj_def.h | 394 - include/luajit/lj_dispatch.h | 164 - include/luajit/lj_emit_arm.h | 366 - include/luajit/lj_emit_arm64.h | 480 - include/luajit/lj_emit_mips.h | 313 - include/luajit/lj_emit_ppc.h | 241 - include/luajit/lj_emit_x86.h | 590 - include/luajit/lj_err.h | 59 - include/luajit/lj_errmsg.h | 201 - include/luajit/lj_ff.h | 18 - include/luajit/lj_ffrecord.h | 24 - include/luajit/lj_frame.h | 297 - include/luajit/lj_func.h | 24 - include/luajit/lj_gc.h | 136 - include/luajit/lj_gdbjit.h | 22 - include/luajit/lj_ir.h | 615 - include/luajit/lj_ircall.h | 353 - include/luajit/lj_iropt.h | 168 - include/luajit/lj_jit.h | 529 - include/luajit/lj_lex.h | 94 - include/luajit/lj_lib.h | 117 - include/luajit/lj_mcode.h | 30 - include/luajit/lj_meta.h | 38 - include/luajit/lj_obj.h | 1089 - include/luajit/lj_parse.h | 18 - include/luajit/lj_prng.h | 24 - include/luajit/lj_profile.h | 21 - include/luajit/lj_record.h | 47 - include/luajit/lj_serialize.h | 28 - include/luajit/lj_snap.h | 35 - include/luajit/lj_state.h | 38 - include/luajit/lj_str.h | 31 - include/luajit/lj_strfmt.h | 131 - include/luajit/lj_strscan.h | 40 - include/luajit/lj_tab.h | 93 - include/luajit/lj_target.h | 164 - include/luajit/lj_target_arm.h | 273 - include/luajit/lj_target_arm64.h | 351 - include/luajit/lj_target_mips.h | 417 - include/luajit/lj_target_ppc.h | 281 - include/luajit/lj_target_x86.h | 361 - include/luajit/lj_trace.h | 58 - include/luajit/lj_traceerr.h | 61 - include/luajit/lj_udata.h | 17 - include/luajit/lj_vm.h | 122 - include/luajit/lj_vmevent.h | 62 - include/luajit/lua.h | 402 - include/luajit/lua.hpp | 9 - include/luajit/luaconf.h | 156 - include/luajit/luajit.h | 79 - include/luajit/luajit_rolling.h | 80 - include/luajit/lualib.h | 44 - include/nfd.h | 564 - include/nlohmann/json.hpp | 25712 ---------------- include/nlohmann/json_fwd.hpp | 187 - include/player.hpp | 49 - include/prop.hpp | 50 - include/raylib.h | 1727 -- include/raylib/config.h | 298 - include/raylib/raylib.h | 1727 -- include/raylib/raymath.h | 3020 -- include/raylib/rcamera.h | 555 - include/raylib/rgestures.h | 555 - include/raylib/rlgl.h | 5383 ---- include/raymath.h | 3020 -- include/reproc++/arguments.hpp | 59 - include/reproc++/detail/array.hpp | 53 - include/reproc++/detail/type_traits.hpp | 18 - include/reproc++/drain.hpp | 152 - include/reproc++/env.hpp | 76 - include/reproc++/export.hpp | 21 - include/reproc++/input.hpp | 37 - include/reproc++/reproc.hpp | 227 - include/reproc++/run.hpp | 41 - include/resourceService.hpp | 20 - include/room.hpp | 124 - include/sol/abort.hpp | 47 - include/sol/as_args.hpp | 54 - include/sol/as_returns.hpp | 62 - include/sol/assert.hpp | 99 - include/sol/base_traits.hpp | 156 - include/sol/bind_traits.hpp | 553 - include/sol/bytecode.hpp | 121 - include/sol/call.hpp | 965 - include/sol/compatibility.hpp | 51 - include/sol/compatibility/compat-5.3.c.h | 900 - include/sol/compatibility/compat-5.3.h | 430 - include/sol/compatibility/compat-5.4.h | 31 - include/sol/compatibility/lua_version.hpp | 245 - include/sol/config.hpp | 50 - include/sol/coroutine.hpp | 251 - include/sol/debug.hpp | 63 - include/sol/demangle.hpp | 192 - include/sol/deprecate.hpp | 44 - include/sol/detail/build_version.hpp | 232 - include/sol/dump_handler.hpp | 77 - include/sol/ebco.hpp | 161 - include/sol/environment.hpp | 264 - include/sol/epilogue.hpp | 39 - include/sol/error.hpp | 102 - include/sol/error_handler.hpp | 186 - include/sol/forward.hpp | 266 - include/sol/forward_as.hpp | 44 - include/sol/forward_detail.hpp | 56 - include/sol/function.hpp | 142 - include/sol/function_result.hpp | 78 - include/sol/function_types.hpp | 769 - include/sol/function_types_core.hpp | 46 - include/sol/function_types_overloaded.hpp | 65 - include/sol/function_types_stateful.hpp | 158 - include/sol/function_types_stateless.hpp | 385 - include/sol/function_types_templated.hpp | 154 - include/sol/in_place.hpp | 48 - include/sol/inheritance.hpp | 195 - include/sol/load_result.hpp | 152 - include/sol/lua_table.hpp | 95 - include/sol/lua_value.hpp | 162 - include/sol/make_reference.hpp | 74 - include/sol/metatable.hpp | 203 - include/sol/object.hpp | 150 - include/sol/object_base.hpp | 86 - include/sol/optional.hpp | 83 - include/sol/optional_implementation.hpp | 2301 -- include/sol/overload.hpp | 49 - include/sol/packaged_coroutine.hpp | 262 - include/sol/pairs_iterator.hpp | 275 - include/sol/pointer_like.hpp | 103 - include/sol/policies.hpp | 98 - include/sol/prologue.hpp | 47 - include/sol/property.hpp | 151 - include/sol/protect.hpp | 53 - include/sol/protected_function.hpp | 385 - include/sol/protected_function_result.hpp | 244 - include/sol/protected_handler.hpp | 108 - include/sol/proxy_base.hpp | 68 - include/sol/raii.hpp | 162 - include/sol/reference.hpp | 900 - include/sol/resolve.hpp | 173 - include/sol/sol.hpp | 81 - include/sol/stack.hpp | 384 - include/sol/stack/detail/pairs.hpp | 98 - include/sol/stack_check.hpp | 30 - include/sol/stack_check_get.hpp | 30 - include/sol/stack_check_get_qualified.hpp | 150 - include/sol/stack_check_get_unqualified.hpp | 186 - include/sol/stack_check_qualified.hpp | 89 - include/sol/stack_check_unqualified.hpp | 738 - include/sol/stack_core.hpp | 1446 - include/sol/stack_field.hpp | 279 - include/sol/stack_get.hpp | 30 - include/sol/stack_get_qualified.hpp | 37 - include/sol/stack_get_unqualified.hpp | 1057 - include/sol/stack_guard.hpp | 67 - include/sol/stack_iterator.hpp | 153 - include/sol/stack_pop.hpp | 51 - include/sol/stack_probe.hpp | 94 - include/sol/stack_proxy.hpp | 64 - include/sol/stack_proxy_base.hpp | 96 - include/sol/stack_push.hpp | 1385 - include/sol/stack_reference.hpp | 314 - include/sol/state.hpp | 62 - include/sol/state_handling.hpp | 194 - include/sol/state_view.hpp | 874 - include/sol/string_view.hpp | 45 - include/sol/table.hpp | 116 - include/sol/table_core.hpp | 733 - include/sol/table_iterator.hpp | 114 - include/sol/table_proxy.hpp | 353 - include/sol/thread.hpp | 189 - include/sol/tie.hpp | 98 - include/sol/traits.hpp | 750 - include/sol/trampoline.hpp | 215 - include/sol/tuple.hpp | 93 - include/sol/types.hpp | 1557 - include/sol/unicode.hpp | 308 - include/sol/unique_usertype_traits.hpp | 240 - include/sol/unreachable.hpp | 37 - include/sol/unsafe_function.hpp | 170 - include/sol/unsafe_function_result.hpp | 182 - include/sol/userdata.hpp | 134 - include/sol/usertype.hpp | 131 - include/sol/usertype_container.hpp | 1592 - include/sol/usertype_container_launch.hpp | 432 - include/sol/usertype_core.hpp | 214 - include/sol/usertype_proxy.hpp | 187 - include/sol/usertype_storage.hpp | 1165 - include/sol/usertype_traits.hpp | 61 - include/sol/utility/is_integer.hpp | 43 - include/sol/utility/to_string.hpp | 59 - include/sol/variadic_args.hpp | 181 - include/sol/variadic_results.hpp | 105 - include/sol/version.hpp | 863 - include/sol/wrapper.hpp | 280 - include/soundService.hpp | 20 - include/stateService.hpp | 22 - include/textArea.hpp | 21 - include/tile.hpp | 51 - include/tilemap.hpp | 82 - include/tileset.hpp | 59 - include/uiElement.hpp | 13 - include/winapi.hpp | 16 - include/worldService.hpp | 48 - libs/SDL2/include/SDL.h | 234 - libs/SDL2/include/SDL_assert.h | 324 - libs/SDL2/include/SDL_atomic.h | 408 - libs/SDL2/include/SDL_audio.h | 1512 - libs/SDL2/include/SDL_bits.h | 132 - libs/SDL2/include/SDL_blendmode.h | 199 - libs/SDL2/include/SDL_clipboard.h | 141 - libs/SDL2/include/SDL_config.h | 59 - libs/SDL2/include/SDL_config.h.cmake | 571 - libs/SDL2/include/SDL_config.h.in | 500 - libs/SDL2/include/SDL_config_android.h | 194 - libs/SDL2/include/SDL_config_emscripten.h | 218 - libs/SDL2/include/SDL_config_iphoneos.h | 217 - libs/SDL2/include/SDL_config_macosx.h | 277 - libs/SDL2/include/SDL_config_minimal.h | 95 - libs/SDL2/include/SDL_config_ngage.h | 89 - libs/SDL2/include/SDL_config_os2.h | 204 - libs/SDL2/include/SDL_config_pandora.h | 141 - libs/SDL2/include/SDL_config_windows.h | 333 - libs/SDL2/include/SDL_config_wingdk.h | 253 - libs/SDL2/include/SDL_config_winrt.h | 220 - libs/SDL2/include/SDL_config_xbox.h | 240 - libs/SDL2/include/SDL_copying.h | 20 - libs/SDL2/include/SDL_cpuinfo.h | 603 - libs/SDL2/include/SDL_egl.h | 2351 -- libs/SDL2/include/SDL_endian.h | 396 - libs/SDL2/include/SDL_error.h | 163 - libs/SDL2/include/SDL_events.h | 1196 - libs/SDL2/include/SDL_filesystem.h | 149 - libs/SDL2/include/SDL_gamecontroller.h | 1127 - libs/SDL2/include/SDL_gesture.h | 117 - libs/SDL2/include/SDL_guid.h | 107 - libs/SDL2/include/SDL_haptic.h | 1354 - libs/SDL2/include/SDL_hidapi.h | 444 - libs/SDL2/include/SDL_hints.h | 3334 -- libs/SDL2/include/SDL_joystick.h | 1096 - libs/SDL2/include/SDL_keyboard.h | 364 - libs/SDL2/include/SDL_keycode.h | 364 - libs/SDL2/include/SDL_loadso.h | 117 - libs/SDL2/include/SDL_locale.h | 103 - libs/SDL2/include/SDL_log.h | 404 - libs/SDL2/include/SDL_main.h | 282 - libs/SDL2/include/SDL_messagebox.h | 196 - libs/SDL2/include/SDL_metal.h | 122 - libs/SDL2/include/SDL_misc.h | 79 - libs/SDL2/include/SDL_mouse.h | 464 - libs/SDL2/include/SDL_mutex.h | 545 - libs/SDL2/include/SDL_name.h | 33 - libs/SDL2/include/SDL_opengl.h | 2126 -- libs/SDL2/include/SDL_opengl_glext.h | 13213 -------- libs/SDL2/include/SDL_opengles.h | 38 - libs/SDL2/include/SDL_opengles2.h | 51 - libs/SDL2/include/SDL_opengles2_gl2.h | 656 - libs/SDL2/include/SDL_opengles2_gl2ext.h | 4033 --- libs/SDL2/include/SDL_opengles2_gl2platform.h | 27 - libs/SDL2/include/SDL_opengles2_khrplatform.h | 311 - libs/SDL2/include/SDL_pixels.h | 686 - libs/SDL2/include/SDL_platform.h | 275 - libs/SDL2/include/SDL_power.h | 87 - libs/SDL2/include/SDL_quit.h | 50 - libs/SDL2/include/SDL_rect.h | 403 - libs/SDL2/include/SDL_render.h | 1933 -- libs/SDL2/include/SDL_revision.h | 6 - libs/SDL2/include/SDL_revision.h.cmake | 8 - libs/SDL2/include/SDL_rwops.h | 844 - libs/SDL2/include/SDL_scancode.h | 438 - libs/SDL2/include/SDL_sensor.h | 329 - libs/SDL2/include/SDL_shape.h | 155 - libs/SDL2/include/SDL_stdinc.h | 909 - libs/SDL2/include/SDL_surface.h | 1053 - libs/SDL2/include/SDL_system.h | 663 - libs/SDL2/include/SDL_syswm.h | 386 - libs/SDL2/include/SDL_test.h | 69 - libs/SDL2/include/SDL_test_assert.h | 105 - libs/SDL2/include/SDL_test_common.h | 236 - libs/SDL2/include/SDL_test_compare.h | 69 - libs/SDL2/include/SDL_test_crc32.h | 124 - libs/SDL2/include/SDL_test_font.h | 168 - libs/SDL2/include/SDL_test_fuzzer.h | 387 - libs/SDL2/include/SDL_test_harness.h | 134 - libs/SDL2/include/SDL_test_images.h | 78 - libs/SDL2/include/SDL_test_log.h | 67 - libs/SDL2/include/SDL_test_md5.h | 129 - libs/SDL2/include/SDL_test_memory.h | 63 - libs/SDL2/include/SDL_test_random.h | 115 - libs/SDL2/include/SDL_thread.h | 468 - libs/SDL2/include/SDL_timer.h | 222 - libs/SDL2/include/SDL_touch.h | 157 - libs/SDL2/include/SDL_types.h | 24 - libs/SDL2/include/SDL_version.h | 205 - libs/SDL2/include/SDL_video.h | 2231 -- libs/SDL2/include/SDL_vulkan.h | 219 - libs/SDL2/include/begin_code.h | 189 - libs/SDL2/include/close_code.h | 40 - libs/luajit | 1 - libs/raylib | 1 - licenses/Kenney-license.txt | 14 - licenses/lua-LICENSE | 6 - licenses/nlohmann_json-LICENSE.MIT | 21 - licenses/raylib-LICENSE | 16 - licenses/vswhere-LICENSE | 8 - mkdocs.yaml | 53 - resources/Kenney-Icon-Font.ttf | Bin 49180 -> 0 bytes resources/LanaPixel.ttf | Bin 3154436 -> 0 bytes resources/LanaPixel_OpenFontLicense.txt | 94 - resources/app-icon.png | Bin 1280 -> 0 bytes resources/close.png | Bin 137 -> 0 bytes resources/cross.png | Bin 15480 -> 0 bytes resources/dialog.png | Bin 477 -> 0 bytes resources/figurine.png | Bin 15601 -> 0 bytes resources/logo-ups.png | Bin 747 -> 0 bytes resources/logo.png | Bin 467 -> 0 bytes rlImGui | 1 - src/actor.cpp | 450 - src/atlasTile.cpp | 18 - src/collisionsContainer.cpp | 26 - src/colorRect.cpp | 27 - src/dialogueBalloon.cpp | 196 - src/editor/aboutWindow.cpp | 48 - src/editor/actorInfoPanel.cpp | 64 - src/editor/actorInitWindow.cpp | 96 - src/editor/actorPanelView.cpp | 82 - src/editor/actorPropertiesBox.cpp | 64 - src/editor/actorView.cpp | 238 - src/editor/animationsView.cpp | 232 - src/editor/collisionInfoPanel.cpp | 46 - src/editor/collisionbox.cpp | 236 - src/editor/deleteConfirmWindow.cpp | 61 - src/editor/dialogueInitWindow.cpp | 73 - src/editor/dialogueLineWindow.cpp | 54 - src/editor/dialoguePanelView.cpp | 50 - src/editor/dialogueParser.cpp | 137 - src/editor/dialogueViewer.cpp | 131 - src/editor/editor.cpp | 57 - src/editor/editorInterfaceService.cpp | 215 - src/editor/errorWindow.cpp | 38 - src/editor/fileSystemService.cpp | 244 - src/editor/imgui_stdlib.cpp | 88 - src/editor/interactableInfoPanel.cpp | 180 - src/editor/interactablePropsState.cpp | 61 - src/editor/layoutContainer.cpp | 33 - src/editor/main.cpp | 55 - src/editor/mainView.cpp | 27 - src/editor/mainViewPanel.cpp | 56 - src/editor/mapInitWindow.cpp | 107 - src/editor/mapPanelView.cpp | 220 - src/editor/mapPropertiesBox.cpp | 108 - src/editor/mapToolsBox.cpp | 74 - src/editor/mapViewBox.cpp | 451 - src/editor/mouseInput.cpp | 97 - src/editor/panelView.cpp | 84 - src/editor/project.cpp | 240 - src/editor/projectBinaryViewWindow.cpp | 208 - src/editor/projectCompiler.cpp | 122 - src/editor/projectFile.cpp | 71 - src/editor/projectGenerator.cpp | 289 - src/editor/projectInitWindow.cpp | 84 - src/editor/projectMenuBox.cpp | 118 - src/editor/propInfoPanel.cpp | 87 - src/editor/propInitWindow.cpp | 81 - src/editor/propPanelView.cpp | 54 - src/editor/propPropertiesBox.cpp | 93 - src/editor/propView.cpp | 131 - src/editor/propertiesBox.cpp | 118 - src/editor/resourceViewerBox.cpp | 204 - src/editor/tabList.cpp | 173 - src/editor/tileSetDialogWindow.cpp | 88 - src/editor/tileSetInitWindow.cpp | 95 - src/editor/tileSetPanelView.cpp | 79 - src/editor/tileSetPropertiesBox.cpp | 96 - src/editor/tileSetViewBox.cpp | 181 - src/editor/windowContainer.cpp | 101 - src/editor/windowPopup.cpp | 43 - src/editor/worldViewBox.cpp | 241 - src/game.cpp | 112 - src/game/main.cpp | 32 - src/gamedata.cpp | 135 - src/imageRect.cpp | 34 - src/interactable.cpp | 150 - src/interactablesContainer.cpp | 140 - src/interfaceService.cpp | 100 - src/interfaceView.cpp | 33 - src/main.cpp | 33 - src/player.cpp | 209 - src/prop.cpp | 235 - src/resourceService.cpp | 40 - src/room.cpp | 443 - src/rpgpplua/rpgpplua.cpp | 54 - src/soundService.cpp | 66 - src/stateService.cpp | 17 - src/textArea.cpp | 43 - src/tile.cpp | 36 - src/tilemap.cpp | 393 - src/tileset.cpp | 132 - src/uiElement.cpp | 6 - src/winapi.cpp | 178 - src/worldService.cpp | 92 - xmake.lua | 103 - 607 files changed, 222026 deletions(-) delete mode 100644 .DS_Store delete mode 100644 .gitignore delete mode 100644 .gitmodules delete mode 100644 LICENSE delete mode 100644 README.md delete mode 100644 docs/building.md delete mode 100644 docs/index.md delete mode 100644 docs/javascripts/mathjax.js delete mode 100644 docs/javascripts/tablesort.js delete mode 100644 docs/logo.png delete mode 100644 docs/overrides/partials/copyright.html delete mode 100644 docs/stylesheets/doxide.css delete mode 100644 doxide.yaml delete mode 100644 include/.DS_Store delete mode 100644 include/actor.hpp delete mode 100644 include/atlasTile.hpp delete mode 100644 include/cereal/access.hpp delete mode 100644 include/cereal/archives/adapters.hpp delete mode 100644 include/cereal/archives/binary.hpp delete mode 100644 include/cereal/archives/json.hpp delete mode 100644 include/cereal/archives/portable_binary.hpp delete mode 100644 include/cereal/archives/xml.hpp delete mode 100644 include/cereal/cereal.hpp delete mode 100644 include/cereal/details/helpers.hpp delete mode 100644 include/cereal/details/polymorphic_impl.hpp delete mode 100644 include/cereal/details/polymorphic_impl_fwd.hpp delete mode 100644 include/cereal/details/static_object.hpp delete mode 100644 include/cereal/details/traits.hpp delete mode 100644 include/cereal/details/util.hpp delete mode 100644 include/cereal/external/LICENSE delete mode 100644 include/cereal/external/base64.hpp delete mode 100644 include/cereal/external/rapidjson/LICENSE delete mode 100644 include/cereal/external/rapidjson/allocators.h delete mode 100644 include/cereal/external/rapidjson/cursorstreamwrapper.h delete mode 100644 include/cereal/external/rapidjson/document.h delete mode 100644 include/cereal/external/rapidjson/encodedstream.h delete mode 100644 include/cereal/external/rapidjson/encodings.h delete mode 100644 include/cereal/external/rapidjson/error/en.h delete mode 100644 include/cereal/external/rapidjson/error/error.h delete mode 100644 include/cereal/external/rapidjson/filereadstream.h delete mode 100644 include/cereal/external/rapidjson/filewritestream.h delete mode 100644 include/cereal/external/rapidjson/fwd.h delete mode 100644 include/cereal/external/rapidjson/internal/biginteger.h delete mode 100644 include/cereal/external/rapidjson/internal/diyfp.h delete mode 100644 include/cereal/external/rapidjson/internal/dtoa.h delete mode 100644 include/cereal/external/rapidjson/internal/ieee754.h delete mode 100644 include/cereal/external/rapidjson/internal/itoa.h delete mode 100644 include/cereal/external/rapidjson/internal/meta.h delete mode 100644 include/cereal/external/rapidjson/internal/pow10.h delete mode 100644 include/cereal/external/rapidjson/internal/regex.h delete mode 100644 include/cereal/external/rapidjson/internal/stack.h delete mode 100644 include/cereal/external/rapidjson/internal/strfunc.h delete mode 100644 include/cereal/external/rapidjson/internal/strtod.h delete mode 100644 include/cereal/external/rapidjson/internal/swap.h delete mode 100644 include/cereal/external/rapidjson/istreamwrapper.h delete mode 100644 include/cereal/external/rapidjson/memorybuffer.h delete mode 100644 include/cereal/external/rapidjson/memorystream.h delete mode 100644 include/cereal/external/rapidjson/msinttypes/LICENSE delete mode 100644 include/cereal/external/rapidjson/msinttypes/inttypes.h delete mode 100644 include/cereal/external/rapidjson/msinttypes/stdint.h delete mode 100644 include/cereal/external/rapidjson/ostreamwrapper.h delete mode 100644 include/cereal/external/rapidjson/pointer.h delete mode 100644 include/cereal/external/rapidjson/prettywriter.h delete mode 100644 include/cereal/external/rapidjson/rapidjson.h delete mode 100644 include/cereal/external/rapidjson/reader.h delete mode 100644 include/cereal/external/rapidjson/schema.h delete mode 100644 include/cereal/external/rapidjson/stream.h delete mode 100644 include/cereal/external/rapidjson/stringbuffer.h delete mode 100644 include/cereal/external/rapidjson/writer.h delete mode 100644 include/cereal/external/rapidxml/license.txt delete mode 100644 include/cereal/external/rapidxml/manual.html delete mode 100644 include/cereal/external/rapidxml/rapidxml.hpp delete mode 100644 include/cereal/external/rapidxml/rapidxml_iterators.hpp delete mode 100644 include/cereal/external/rapidxml/rapidxml_print.hpp delete mode 100644 include/cereal/external/rapidxml/rapidxml_utils.hpp delete mode 100644 include/cereal/macros.hpp delete mode 100644 include/cereal/specialize.hpp delete mode 100644 include/cereal/types/array.hpp delete mode 100644 include/cereal/types/atomic.hpp delete mode 100644 include/cereal/types/base_class.hpp delete mode 100644 include/cereal/types/bitset.hpp delete mode 100644 include/cereal/types/boost_variant.hpp delete mode 100644 include/cereal/types/chrono.hpp delete mode 100644 include/cereal/types/common.hpp delete mode 100644 include/cereal/types/complex.hpp delete mode 100644 include/cereal/types/concepts/pair_associative_container.hpp delete mode 100644 include/cereal/types/deque.hpp delete mode 100644 include/cereal/types/forward_list.hpp delete mode 100644 include/cereal/types/functional.hpp delete mode 100644 include/cereal/types/list.hpp delete mode 100644 include/cereal/types/map.hpp delete mode 100644 include/cereal/types/memory.hpp delete mode 100644 include/cereal/types/optional.hpp delete mode 100644 include/cereal/types/polymorphic.hpp delete mode 100644 include/cereal/types/queue.hpp delete mode 100644 include/cereal/types/set.hpp delete mode 100644 include/cereal/types/stack.hpp delete mode 100644 include/cereal/types/string.hpp delete mode 100644 include/cereal/types/tuple.hpp delete mode 100644 include/cereal/types/unordered_map.hpp delete mode 100644 include/cereal/types/unordered_set.hpp delete mode 100644 include/cereal/types/utility.hpp delete mode 100644 include/cereal/types/valarray.hpp delete mode 100644 include/cereal/types/variant.hpp delete mode 100644 include/cereal/types/vector.hpp delete mode 100644 include/cereal/version.hpp delete mode 100644 include/collisionsContainer.hpp delete mode 100644 include/colorRect.hpp delete mode 100644 include/dialogueBalloon.hpp delete mode 100644 include/editor/actorInfoPanel.hpp delete mode 100644 include/editor/actorPanelView.hpp delete mode 100644 include/editor/actorPropertiesBox.hpp delete mode 100644 include/editor/actorView.hpp delete mode 100644 include/editor/animationsView.hpp delete mode 100644 include/editor/collisionInfoPanel.hpp delete mode 100644 include/editor/collisionbox.hpp delete mode 100644 include/editor/dialoguePanelView.hpp delete mode 100644 include/editor/dialogueParser.hpp delete mode 100644 include/editor/dialogueViewer.hpp delete mode 100644 include/editor/editor.hpp delete mode 100644 include/editor/editorInterfaceService.hpp delete mode 100644 include/editor/fileSystemService.hpp delete mode 100644 include/editor/interactableInfoPanel.hpp delete mode 100644 include/editor/interactablePropsState.hpp delete mode 100644 include/editor/layoutContainer.hpp delete mode 100644 include/editor/mainView.hpp delete mode 100644 include/editor/mainViewPanel.hpp delete mode 100644 include/editor/mapPanelView.hpp delete mode 100644 include/editor/mapPropertiesBox.hpp delete mode 100644 include/editor/mapToolsBox.hpp delete mode 100644 include/editor/mouseInput.hpp delete mode 100644 include/editor/panelView.hpp delete mode 100644 include/editor/project.hpp delete mode 100644 include/editor/projectCompiler.hpp delete mode 100644 include/editor/projectFile.hpp delete mode 100644 include/editor/projectGenerator.hpp delete mode 100644 include/editor/projectMenuBox.hpp delete mode 100644 include/editor/propInfoPanel.hpp delete mode 100644 include/editor/propInitWindow.hpp delete mode 100644 include/editor/propPanelView.hpp delete mode 100644 include/editor/propPropertiesBox.hpp delete mode 100644 include/editor/propView.hpp delete mode 100644 include/editor/propertiesBox.hpp delete mode 100644 include/editor/resourceViewerBox.hpp delete mode 100644 include/editor/tabList.hpp delete mode 100644 include/editor/tileSetPanelView.hpp delete mode 100644 include/editor/tileSetPropertiesBox.hpp delete mode 100644 include/editor/windowContainer.hpp delete mode 100644 include/editor/windowPopup.hpp delete mode 100644 include/editor/windows/aboutWindow.hpp delete mode 100644 include/editor/windows/actorInitWindow.hpp delete mode 100644 include/editor/windows/deleteConfirmWindow.hpp delete mode 100644 include/editor/windows/dialogueInitWindow.hpp delete mode 100644 include/editor/windows/dialogueLineWindow.hpp delete mode 100644 include/editor/windows/errorWindow.hpp delete mode 100644 include/editor/windows/mapInitWindow.hpp delete mode 100644 include/editor/windows/projectBinaryViewWindow.hpp delete mode 100644 include/editor/windows/projectInitWindow.hpp delete mode 100644 include/editor/windows/tileSetDialogWindow.hpp delete mode 100644 include/editor/windows/tileSetInitWindow.hpp delete mode 100644 include/editor/worldViewBox.hpp delete mode 100644 include/extras/IconsFontAwesome6.h delete mode 100644 include/game.hpp delete mode 100644 include/gamedata.hpp delete mode 100644 include/imageRect.hpp delete mode 100644 include/imgui/IconsFontAwesome6.h delete mode 100644 include/imgui/IconsKenney.h delete mode 100644 include/imgui/Str.h delete mode 100644 include/imgui/imconfig.h delete mode 100644 include/imgui/imgui.h delete mode 100644 include/imgui/imgui_impl_raylib.h delete mode 100644 include/imgui/imgui_internal.h delete mode 100644 include/imgui/imgui_stdlib.h delete mode 100644 include/imgui/imstb_rectpack.h delete mode 100644 include/imgui/imstb_textedit.h delete mode 100644 include/imgui/imstb_truetype.h delete mode 100644 include/imgui/rlImGui.h delete mode 100644 include/imgui/rlImGuiColors.h delete mode 100644 include/interactable.hpp delete mode 100644 include/interactablesContainer.hpp delete mode 100644 include/interfaceService.hpp delete mode 100644 include/interfaceView.hpp delete mode 100644 include/luajit/buildvm.h delete mode 100644 include/luajit/buildvm_libbc.h delete mode 100644 include/luajit/lauxlib.h delete mode 100644 include/luajit/lj_alloc.h delete mode 100644 include/luajit/lj_arch.h delete mode 100644 include/luajit/lj_asm.h delete mode 100644 include/luajit/lj_asm_arm.h delete mode 100644 include/luajit/lj_asm_arm64.h delete mode 100644 include/luajit/lj_asm_mips.h delete mode 100644 include/luajit/lj_asm_ppc.h delete mode 100644 include/luajit/lj_asm_x86.h delete mode 100644 include/luajit/lj_bc.h delete mode 100644 include/luajit/lj_bcdump.h delete mode 100644 include/luajit/lj_buf.h delete mode 100644 include/luajit/lj_carith.h delete mode 100644 include/luajit/lj_ccall.h delete mode 100644 include/luajit/lj_ccallback.h delete mode 100644 include/luajit/lj_cconv.h delete mode 100644 include/luajit/lj_cdata.h delete mode 100644 include/luajit/lj_char.h delete mode 100644 include/luajit/lj_clib.h delete mode 100644 include/luajit/lj_cparse.h delete mode 100644 include/luajit/lj_crecord.h delete mode 100644 include/luajit/lj_ctype.h delete mode 100644 include/luajit/lj_debug.h delete mode 100644 include/luajit/lj_def.h delete mode 100644 include/luajit/lj_dispatch.h delete mode 100644 include/luajit/lj_emit_arm.h delete mode 100644 include/luajit/lj_emit_arm64.h delete mode 100644 include/luajit/lj_emit_mips.h delete mode 100644 include/luajit/lj_emit_ppc.h delete mode 100644 include/luajit/lj_emit_x86.h delete mode 100644 include/luajit/lj_err.h delete mode 100644 include/luajit/lj_errmsg.h delete mode 100644 include/luajit/lj_ff.h delete mode 100644 include/luajit/lj_ffrecord.h delete mode 100644 include/luajit/lj_frame.h delete mode 100644 include/luajit/lj_func.h delete mode 100644 include/luajit/lj_gc.h delete mode 100644 include/luajit/lj_gdbjit.h delete mode 100644 include/luajit/lj_ir.h delete mode 100644 include/luajit/lj_ircall.h delete mode 100644 include/luajit/lj_iropt.h delete mode 100644 include/luajit/lj_jit.h delete mode 100644 include/luajit/lj_lex.h delete mode 100644 include/luajit/lj_lib.h delete mode 100644 include/luajit/lj_mcode.h delete mode 100644 include/luajit/lj_meta.h delete mode 100644 include/luajit/lj_obj.h delete mode 100644 include/luajit/lj_parse.h delete mode 100644 include/luajit/lj_prng.h delete mode 100644 include/luajit/lj_profile.h delete mode 100644 include/luajit/lj_record.h delete mode 100644 include/luajit/lj_serialize.h delete mode 100644 include/luajit/lj_snap.h delete mode 100644 include/luajit/lj_state.h delete mode 100644 include/luajit/lj_str.h delete mode 100644 include/luajit/lj_strfmt.h delete mode 100644 include/luajit/lj_strscan.h delete mode 100644 include/luajit/lj_tab.h delete mode 100644 include/luajit/lj_target.h delete mode 100644 include/luajit/lj_target_arm.h delete mode 100644 include/luajit/lj_target_arm64.h delete mode 100644 include/luajit/lj_target_mips.h delete mode 100644 include/luajit/lj_target_ppc.h delete mode 100644 include/luajit/lj_target_x86.h delete mode 100644 include/luajit/lj_trace.h delete mode 100644 include/luajit/lj_traceerr.h delete mode 100644 include/luajit/lj_udata.h delete mode 100644 include/luajit/lj_vm.h delete mode 100644 include/luajit/lj_vmevent.h delete mode 100644 include/luajit/lua.h delete mode 100644 include/luajit/lua.hpp delete mode 100644 include/luajit/luaconf.h delete mode 100644 include/luajit/luajit.h delete mode 100644 include/luajit/luajit_rolling.h delete mode 100644 include/luajit/lualib.h delete mode 100644 include/nfd.h delete mode 100644 include/nlohmann/json.hpp delete mode 100644 include/nlohmann/json_fwd.hpp delete mode 100644 include/player.hpp delete mode 100644 include/prop.hpp delete mode 100644 include/raylib.h delete mode 100644 include/raylib/config.h delete mode 100644 include/raylib/raylib.h delete mode 100644 include/raylib/raymath.h delete mode 100644 include/raylib/rcamera.h delete mode 100644 include/raylib/rgestures.h delete mode 100644 include/raylib/rlgl.h delete mode 100644 include/raymath.h delete mode 100644 include/reproc++/arguments.hpp delete mode 100644 include/reproc++/detail/array.hpp delete mode 100644 include/reproc++/detail/type_traits.hpp delete mode 100644 include/reproc++/drain.hpp delete mode 100644 include/reproc++/env.hpp delete mode 100644 include/reproc++/export.hpp delete mode 100644 include/reproc++/input.hpp delete mode 100644 include/reproc++/reproc.hpp delete mode 100644 include/reproc++/run.hpp delete mode 100644 include/resourceService.hpp delete mode 100644 include/room.hpp delete mode 100644 include/sol/abort.hpp delete mode 100644 include/sol/as_args.hpp delete mode 100644 include/sol/as_returns.hpp delete mode 100644 include/sol/assert.hpp delete mode 100644 include/sol/base_traits.hpp delete mode 100644 include/sol/bind_traits.hpp delete mode 100644 include/sol/bytecode.hpp delete mode 100644 include/sol/call.hpp delete mode 100644 include/sol/compatibility.hpp delete mode 100644 include/sol/compatibility/compat-5.3.c.h delete mode 100644 include/sol/compatibility/compat-5.3.h delete mode 100644 include/sol/compatibility/compat-5.4.h delete mode 100644 include/sol/compatibility/lua_version.hpp delete mode 100644 include/sol/config.hpp delete mode 100644 include/sol/coroutine.hpp delete mode 100644 include/sol/debug.hpp delete mode 100644 include/sol/demangle.hpp delete mode 100644 include/sol/deprecate.hpp delete mode 100644 include/sol/detail/build_version.hpp delete mode 100644 include/sol/dump_handler.hpp delete mode 100644 include/sol/ebco.hpp delete mode 100644 include/sol/environment.hpp delete mode 100644 include/sol/epilogue.hpp delete mode 100644 include/sol/error.hpp delete mode 100644 include/sol/error_handler.hpp delete mode 100644 include/sol/forward.hpp delete mode 100644 include/sol/forward_as.hpp delete mode 100644 include/sol/forward_detail.hpp delete mode 100644 include/sol/function.hpp delete mode 100644 include/sol/function_result.hpp delete mode 100644 include/sol/function_types.hpp delete mode 100644 include/sol/function_types_core.hpp delete mode 100644 include/sol/function_types_overloaded.hpp delete mode 100644 include/sol/function_types_stateful.hpp delete mode 100644 include/sol/function_types_stateless.hpp delete mode 100644 include/sol/function_types_templated.hpp delete mode 100644 include/sol/in_place.hpp delete mode 100644 include/sol/inheritance.hpp delete mode 100644 include/sol/load_result.hpp delete mode 100644 include/sol/lua_table.hpp delete mode 100644 include/sol/lua_value.hpp delete mode 100644 include/sol/make_reference.hpp delete mode 100644 include/sol/metatable.hpp delete mode 100644 include/sol/object.hpp delete mode 100644 include/sol/object_base.hpp delete mode 100644 include/sol/optional.hpp delete mode 100644 include/sol/optional_implementation.hpp delete mode 100644 include/sol/overload.hpp delete mode 100644 include/sol/packaged_coroutine.hpp delete mode 100644 include/sol/pairs_iterator.hpp delete mode 100644 include/sol/pointer_like.hpp delete mode 100644 include/sol/policies.hpp delete mode 100644 include/sol/prologue.hpp delete mode 100644 include/sol/property.hpp delete mode 100644 include/sol/protect.hpp delete mode 100644 include/sol/protected_function.hpp delete mode 100644 include/sol/protected_function_result.hpp delete mode 100644 include/sol/protected_handler.hpp delete mode 100644 include/sol/proxy_base.hpp delete mode 100644 include/sol/raii.hpp delete mode 100644 include/sol/reference.hpp delete mode 100644 include/sol/resolve.hpp delete mode 100644 include/sol/sol.hpp delete mode 100644 include/sol/stack.hpp delete mode 100644 include/sol/stack/detail/pairs.hpp delete mode 100644 include/sol/stack_check.hpp delete mode 100644 include/sol/stack_check_get.hpp delete mode 100644 include/sol/stack_check_get_qualified.hpp delete mode 100644 include/sol/stack_check_get_unqualified.hpp delete mode 100644 include/sol/stack_check_qualified.hpp delete mode 100644 include/sol/stack_check_unqualified.hpp delete mode 100644 include/sol/stack_core.hpp delete mode 100644 include/sol/stack_field.hpp delete mode 100644 include/sol/stack_get.hpp delete mode 100644 include/sol/stack_get_qualified.hpp delete mode 100644 include/sol/stack_get_unqualified.hpp delete mode 100644 include/sol/stack_guard.hpp delete mode 100644 include/sol/stack_iterator.hpp delete mode 100644 include/sol/stack_pop.hpp delete mode 100644 include/sol/stack_probe.hpp delete mode 100644 include/sol/stack_proxy.hpp delete mode 100644 include/sol/stack_proxy_base.hpp delete mode 100644 include/sol/stack_push.hpp delete mode 100644 include/sol/stack_reference.hpp delete mode 100644 include/sol/state.hpp delete mode 100644 include/sol/state_handling.hpp delete mode 100644 include/sol/state_view.hpp delete mode 100644 include/sol/string_view.hpp delete mode 100644 include/sol/table.hpp delete mode 100644 include/sol/table_core.hpp delete mode 100644 include/sol/table_iterator.hpp delete mode 100644 include/sol/table_proxy.hpp delete mode 100644 include/sol/thread.hpp delete mode 100644 include/sol/tie.hpp delete mode 100644 include/sol/traits.hpp delete mode 100644 include/sol/trampoline.hpp delete mode 100644 include/sol/tuple.hpp delete mode 100644 include/sol/types.hpp delete mode 100644 include/sol/unicode.hpp delete mode 100644 include/sol/unique_usertype_traits.hpp delete mode 100644 include/sol/unreachable.hpp delete mode 100644 include/sol/unsafe_function.hpp delete mode 100644 include/sol/unsafe_function_result.hpp delete mode 100644 include/sol/userdata.hpp delete mode 100644 include/sol/usertype.hpp delete mode 100644 include/sol/usertype_container.hpp delete mode 100644 include/sol/usertype_container_launch.hpp delete mode 100644 include/sol/usertype_core.hpp delete mode 100644 include/sol/usertype_proxy.hpp delete mode 100644 include/sol/usertype_storage.hpp delete mode 100644 include/sol/usertype_traits.hpp delete mode 100644 include/sol/utility/is_integer.hpp delete mode 100644 include/sol/utility/to_string.hpp delete mode 100644 include/sol/variadic_args.hpp delete mode 100644 include/sol/variadic_results.hpp delete mode 100644 include/sol/version.hpp delete mode 100644 include/sol/wrapper.hpp delete mode 100644 include/soundService.hpp delete mode 100644 include/stateService.hpp delete mode 100644 include/textArea.hpp delete mode 100644 include/tile.hpp delete mode 100644 include/tilemap.hpp delete mode 100644 include/tileset.hpp delete mode 100644 include/uiElement.hpp delete mode 100644 include/winapi.hpp delete mode 100644 include/worldService.hpp delete mode 100644 libs/SDL2/include/SDL.h delete mode 100644 libs/SDL2/include/SDL_assert.h delete mode 100644 libs/SDL2/include/SDL_atomic.h delete mode 100644 libs/SDL2/include/SDL_audio.h delete mode 100644 libs/SDL2/include/SDL_bits.h delete mode 100644 libs/SDL2/include/SDL_blendmode.h delete mode 100644 libs/SDL2/include/SDL_clipboard.h delete mode 100644 libs/SDL2/include/SDL_config.h delete mode 100644 libs/SDL2/include/SDL_config.h.cmake delete mode 100644 libs/SDL2/include/SDL_config.h.in delete mode 100644 libs/SDL2/include/SDL_config_android.h delete mode 100644 libs/SDL2/include/SDL_config_emscripten.h delete mode 100644 libs/SDL2/include/SDL_config_iphoneos.h delete mode 100644 libs/SDL2/include/SDL_config_macosx.h delete mode 100644 libs/SDL2/include/SDL_config_minimal.h delete mode 100644 libs/SDL2/include/SDL_config_ngage.h delete mode 100644 libs/SDL2/include/SDL_config_os2.h delete mode 100644 libs/SDL2/include/SDL_config_pandora.h delete mode 100644 libs/SDL2/include/SDL_config_windows.h delete mode 100644 libs/SDL2/include/SDL_config_wingdk.h delete mode 100644 libs/SDL2/include/SDL_config_winrt.h delete mode 100644 libs/SDL2/include/SDL_config_xbox.h delete mode 100644 libs/SDL2/include/SDL_copying.h delete mode 100644 libs/SDL2/include/SDL_cpuinfo.h delete mode 100644 libs/SDL2/include/SDL_egl.h delete mode 100644 libs/SDL2/include/SDL_endian.h delete mode 100644 libs/SDL2/include/SDL_error.h delete mode 100644 libs/SDL2/include/SDL_events.h delete mode 100644 libs/SDL2/include/SDL_filesystem.h delete mode 100644 libs/SDL2/include/SDL_gamecontroller.h delete mode 100644 libs/SDL2/include/SDL_gesture.h delete mode 100644 libs/SDL2/include/SDL_guid.h delete mode 100644 libs/SDL2/include/SDL_haptic.h delete mode 100644 libs/SDL2/include/SDL_hidapi.h delete mode 100644 libs/SDL2/include/SDL_hints.h delete mode 100644 libs/SDL2/include/SDL_joystick.h delete mode 100644 libs/SDL2/include/SDL_keyboard.h delete mode 100644 libs/SDL2/include/SDL_keycode.h delete mode 100644 libs/SDL2/include/SDL_loadso.h delete mode 100644 libs/SDL2/include/SDL_locale.h delete mode 100644 libs/SDL2/include/SDL_log.h delete mode 100644 libs/SDL2/include/SDL_main.h delete mode 100644 libs/SDL2/include/SDL_messagebox.h delete mode 100644 libs/SDL2/include/SDL_metal.h delete mode 100644 libs/SDL2/include/SDL_misc.h delete mode 100644 libs/SDL2/include/SDL_mouse.h delete mode 100644 libs/SDL2/include/SDL_mutex.h delete mode 100644 libs/SDL2/include/SDL_name.h delete mode 100644 libs/SDL2/include/SDL_opengl.h delete mode 100644 libs/SDL2/include/SDL_opengl_glext.h delete mode 100644 libs/SDL2/include/SDL_opengles.h delete mode 100644 libs/SDL2/include/SDL_opengles2.h delete mode 100644 libs/SDL2/include/SDL_opengles2_gl2.h delete mode 100644 libs/SDL2/include/SDL_opengles2_gl2ext.h delete mode 100644 libs/SDL2/include/SDL_opengles2_gl2platform.h delete mode 100644 libs/SDL2/include/SDL_opengles2_khrplatform.h delete mode 100644 libs/SDL2/include/SDL_pixels.h delete mode 100644 libs/SDL2/include/SDL_platform.h delete mode 100644 libs/SDL2/include/SDL_power.h delete mode 100644 libs/SDL2/include/SDL_quit.h delete mode 100644 libs/SDL2/include/SDL_rect.h delete mode 100644 libs/SDL2/include/SDL_render.h delete mode 100644 libs/SDL2/include/SDL_revision.h delete mode 100644 libs/SDL2/include/SDL_revision.h.cmake delete mode 100644 libs/SDL2/include/SDL_rwops.h delete mode 100644 libs/SDL2/include/SDL_scancode.h delete mode 100644 libs/SDL2/include/SDL_sensor.h delete mode 100644 libs/SDL2/include/SDL_shape.h delete mode 100644 libs/SDL2/include/SDL_stdinc.h delete mode 100644 libs/SDL2/include/SDL_surface.h delete mode 100644 libs/SDL2/include/SDL_system.h delete mode 100644 libs/SDL2/include/SDL_syswm.h delete mode 100644 libs/SDL2/include/SDL_test.h delete mode 100644 libs/SDL2/include/SDL_test_assert.h delete mode 100644 libs/SDL2/include/SDL_test_common.h delete mode 100644 libs/SDL2/include/SDL_test_compare.h delete mode 100644 libs/SDL2/include/SDL_test_crc32.h delete mode 100644 libs/SDL2/include/SDL_test_font.h delete mode 100644 libs/SDL2/include/SDL_test_fuzzer.h delete mode 100644 libs/SDL2/include/SDL_test_harness.h delete mode 100644 libs/SDL2/include/SDL_test_images.h delete mode 100644 libs/SDL2/include/SDL_test_log.h delete mode 100644 libs/SDL2/include/SDL_test_md5.h delete mode 100644 libs/SDL2/include/SDL_test_memory.h delete mode 100644 libs/SDL2/include/SDL_test_random.h delete mode 100644 libs/SDL2/include/SDL_thread.h delete mode 100644 libs/SDL2/include/SDL_timer.h delete mode 100644 libs/SDL2/include/SDL_touch.h delete mode 100644 libs/SDL2/include/SDL_types.h delete mode 100644 libs/SDL2/include/SDL_version.h delete mode 100644 libs/SDL2/include/SDL_video.h delete mode 100644 libs/SDL2/include/SDL_vulkan.h delete mode 100644 libs/SDL2/include/begin_code.h delete mode 100644 libs/SDL2/include/close_code.h delete mode 160000 libs/luajit delete mode 160000 libs/raylib delete mode 100644 licenses/Kenney-license.txt delete mode 100644 licenses/lua-LICENSE delete mode 100644 licenses/nlohmann_json-LICENSE.MIT delete mode 100644 licenses/raylib-LICENSE delete mode 100644 licenses/vswhere-LICENSE delete mode 100644 mkdocs.yaml delete mode 100644 resources/Kenney-Icon-Font.ttf delete mode 100644 resources/LanaPixel.ttf delete mode 100644 resources/LanaPixel_OpenFontLicense.txt delete mode 100644 resources/app-icon.png delete mode 100644 resources/close.png delete mode 100644 resources/cross.png delete mode 100644 resources/dialog.png delete mode 100644 resources/figurine.png delete mode 100644 resources/logo-ups.png delete mode 100644 resources/logo.png delete mode 160000 rlImGui delete mode 100644 src/actor.cpp delete mode 100644 src/atlasTile.cpp delete mode 100644 src/collisionsContainer.cpp delete mode 100644 src/colorRect.cpp delete mode 100644 src/dialogueBalloon.cpp delete mode 100644 src/editor/aboutWindow.cpp delete mode 100644 src/editor/actorInfoPanel.cpp delete mode 100644 src/editor/actorInitWindow.cpp delete mode 100644 src/editor/actorPanelView.cpp delete mode 100644 src/editor/actorPropertiesBox.cpp delete mode 100644 src/editor/actorView.cpp delete mode 100644 src/editor/animationsView.cpp delete mode 100644 src/editor/collisionInfoPanel.cpp delete mode 100644 src/editor/collisionbox.cpp delete mode 100644 src/editor/deleteConfirmWindow.cpp delete mode 100644 src/editor/dialogueInitWindow.cpp delete mode 100644 src/editor/dialogueLineWindow.cpp delete mode 100644 src/editor/dialoguePanelView.cpp delete mode 100644 src/editor/dialogueParser.cpp delete mode 100644 src/editor/dialogueViewer.cpp delete mode 100644 src/editor/editor.cpp delete mode 100644 src/editor/editorInterfaceService.cpp delete mode 100644 src/editor/errorWindow.cpp delete mode 100644 src/editor/fileSystemService.cpp delete mode 100644 src/editor/imgui_stdlib.cpp delete mode 100644 src/editor/interactableInfoPanel.cpp delete mode 100644 src/editor/interactablePropsState.cpp delete mode 100644 src/editor/layoutContainer.cpp delete mode 100644 src/editor/main.cpp delete mode 100644 src/editor/mainView.cpp delete mode 100644 src/editor/mainViewPanel.cpp delete mode 100644 src/editor/mapInitWindow.cpp delete mode 100644 src/editor/mapPanelView.cpp delete mode 100644 src/editor/mapPropertiesBox.cpp delete mode 100644 src/editor/mapToolsBox.cpp delete mode 100644 src/editor/mapViewBox.cpp delete mode 100644 src/editor/mouseInput.cpp delete mode 100644 src/editor/panelView.cpp delete mode 100644 src/editor/project.cpp delete mode 100644 src/editor/projectBinaryViewWindow.cpp delete mode 100644 src/editor/projectCompiler.cpp delete mode 100644 src/editor/projectFile.cpp delete mode 100644 src/editor/projectGenerator.cpp delete mode 100644 src/editor/projectInitWindow.cpp delete mode 100644 src/editor/projectMenuBox.cpp delete mode 100644 src/editor/propInfoPanel.cpp delete mode 100644 src/editor/propInitWindow.cpp delete mode 100644 src/editor/propPanelView.cpp delete mode 100644 src/editor/propPropertiesBox.cpp delete mode 100644 src/editor/propView.cpp delete mode 100644 src/editor/propertiesBox.cpp delete mode 100644 src/editor/resourceViewerBox.cpp delete mode 100644 src/editor/tabList.cpp delete mode 100644 src/editor/tileSetDialogWindow.cpp delete mode 100644 src/editor/tileSetInitWindow.cpp delete mode 100644 src/editor/tileSetPanelView.cpp delete mode 100644 src/editor/tileSetPropertiesBox.cpp delete mode 100644 src/editor/tileSetViewBox.cpp delete mode 100644 src/editor/windowContainer.cpp delete mode 100644 src/editor/windowPopup.cpp delete mode 100644 src/editor/worldViewBox.cpp delete mode 100644 src/game.cpp delete mode 100644 src/game/main.cpp delete mode 100644 src/gamedata.cpp delete mode 100644 src/imageRect.cpp delete mode 100644 src/interactable.cpp delete mode 100644 src/interactablesContainer.cpp delete mode 100644 src/interfaceService.cpp delete mode 100644 src/interfaceView.cpp delete mode 100644 src/main.cpp delete mode 100644 src/player.cpp delete mode 100644 src/prop.cpp delete mode 100644 src/resourceService.cpp delete mode 100644 src/room.cpp delete mode 100644 src/rpgpplua/rpgpplua.cpp delete mode 100644 src/soundService.cpp delete mode 100644 src/stateService.cpp delete mode 100644 src/textArea.cpp delete mode 100644 src/tile.cpp delete mode 100644 src/tilemap.cpp delete mode 100644 src/tileset.cpp delete mode 100644 src/uiElement.cpp delete mode 100644 src/winapi.cpp delete mode 100644 src/worldService.cpp delete mode 100644 xmake.lua diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 61a4a25027cf822ee400fdfd1c0d8097982283d4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 10244 zcmeHM&u`pB6n>Kgc9%^Wr%h;Sg|uQXNG)NbCPWCKZa0Y_;zy!v6cXC9cz2zRiFd}b zz4_57C|BUb9{_hw96{nA;KG#~;!l8UPw>r*o!VZ)rBYQ@Gm+=LvETRn=Cl1KZa|y{-?-kguC(pWelL*WE(uQr4R7Gw>jiGN>DwKb z_qHSFC~CS7otAYuXS(5ZKYM&?^Vo;Y^y3rC-Ft!KaOH1pcQhW*{hM$U*)?3cRT>mYreb`ZaF~+IfU8Xv4g%1%KHmTH>E!4r(1)~2OSD2CQfhzw#Jo)d&jq&9F47AZe_C&^g`H;TBh zG-a(6Q(vZ-img&F+s{c}dTPn`+R4dWZ4TMCR#Vyb_5!l);(RXK%4~{uVYZdaNj#g} zyEXyVTr6}PJla^iI0BV|Esy-iS0p#b`RifMLKe zU>GnA7zUnwlp$9x{{8>SZeq}e0mHyE%>Wx)ZZ0 { - MathJax.typesetPromise() -}) diff --git a/docs/javascripts/tablesort.js b/docs/javascripts/tablesort.js deleted file mode 100644 index 6a5afcf..0000000 --- a/docs/javascripts/tablesort.js +++ /dev/null @@ -1,6 +0,0 @@ -document$.subscribe(function() { - var tables = document.querySelectorAll("article table:not([class])") - tables.forEach(function(table) { - new Tablesort(table) - }) -}) diff --git a/docs/logo.png b/docs/logo.png deleted file mode 100644 index c0b3c87d8a515ce06859eb1f2a5751994636c167..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 467 zcmV;^0WAKBP)r001Be1^@s6%>dx+00001b5ch_0Itp) z=>Px$jY&j7RCt{2+d)plFc5`d2UX$>6%xuCI7b!{$39EEj+RB;AYuyWOc6VKR= z6I=hcqLA7_c^W&@rg>|he$0kmr;ldK`5|++^$DO12m3?UPuV6tpN{7J^FG^rh<6Yi zlhpZibpBqu1p1b&)Z^tIe{X_=G7jy{>zow{`Kf|(9ggS6Z)1!x4=-Q;{zho(;|+={ z94^=4AT;%v4T` - {% if config.copyright %} - - {% endif %} - {% if not config.extra.generator == false %} - Made with - - Doxide - - and - - Material for MkDocs - - {% endif %} - diff --git a/docs/stylesheets/doxide.css b/docs/stylesheets/doxide.css deleted file mode 100644 index e6a9ccf..0000000 --- a/docs/stylesheets/doxide.css +++ /dev/null @@ -1,58 +0,0 @@ -:root { - --md-admonition-icon--variable: url('data:image/svg+xml;charset=utf-8,'); - --md-admonition-icon--function: url('data:image/svg+xml;charset=utf-8,'); - --md-admonition-icon--typedef: url('data:image/svg+xml;charset=utf-8,'); - --md-admonition-icon--concept: url('data:image/svg+xml;charset=utf-8,'); - --md-admonition-icon--macro: url('data:image/svg+xml;charset=utf-8,'); -} - -.md-typeset .admonition.variable, .md-typeset details.variable, -.md-typeset .admonition.function, .md-typeset details.function, -.md-typeset .admonition.typedef, .md-typeset details.typedef, -.md-typeset .admonition.concept, .md-typeset details.concept, -.md-typeset .admonition.macro, .md-typeset details.macro { - border-color: var(--md-default-fg-color--lighter); -} - -.md-typeset .variable > .admonition-title, .md-typeset .variable > summary, -.md-typeset .function > .admonition-title, .md-typeset .function > summary, -.md-typeset .typedef > .admonition-title, .md-typeset .typedef > summary, -.md-typeset .concept > .admonition-title, .md-typeset .concept > summary, -.md-typeset .macro > .admonition-title, .md-typeset .macro > summary { - background-color: var(--md-default-bg-color); -} - -.md-typeset .variable > .admonition-title::before, -.md-typeset .variable > summary::before { - background-color: var(--md-default-fg-color--light); - -webkit-mask-image: var(--md-admonition-icon--variable); - mask-image: var(--md-admonition-icon--variable); -} - -.md-typeset .function > .admonition-title::before, -.md-typeset .function > summary::before { - background-color: var(--md-default-fg-color--light); - -webkit-mask-image: var(--md-admonition-icon--function); - mask-image: var(--md-admonition-icon--function); -} - -.md-typeset .typedef > .admonition-title::before, -.md-typeset .typedef > summary::before { - background-color: var(--md-default-fg-color--light); - -webkit-mask-image: var(--md-admonition-icon--typedef); - mask-image: var(--md-admonition-icon--typedef); -} - -.md-typeset .concept > .admonition-title::before, -.md-typeset .concept > summary::before { - background-color: var(--md-default-fg-color--light); - -webkit-mask-image: var(--md-admonition-icon--concept); - mask-image: var(--md-admonition-icon--concept); -} - -.md-typeset .macro > .admonition-title::before, -.md-typeset .macro > summary::before { - background-color: var(--md-default-fg-color--light); - -webkit-mask-image: var(--md-admonition-icon--macro); - mask-image: var(--md-admonition-icon--macro); -} diff --git a/doxide.yaml b/doxide.yaml deleted file mode 100644 index e16432a..0000000 --- a/doxide.yaml +++ /dev/null @@ -1,5 +0,0 @@ -title: RPG++ Library -description: A C++ Library for building RPG games with the power of raylib. -files: - - "include/*.hpp" -output: 'docs/C++ API' diff --git a/include/.DS_Store b/include/.DS_Store deleted file mode 100644 index c7f7fd79d00f18d1de832273e0eeff1861637fc5..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 10244 zcmeHMOK;Oa5S~q6P9G=;5E2rSB`ydMw1R>Vmk`=RuML6&kCKPm8XP-H90Dpux$^h} zT;LBNapcI6f55+hJ16*NY|5_Vl!yZYu`8`-ZO=D5`|Wr(yCEV~={1*#Tq1H%S(fH; z$tnDv>rg4APfkH9;E6hPmbR%)?X_S?+di-iSOzQumI2FvW#DgM0BbfEXD*TUY8kK$ zSO)eO;QZjCvMi@^kVr`#xX2a&auScFppAWiVBA!eQ#nYaKw&f4J*X6_(k+Hc;CSz{ zI%GMOgG459QVE^CWB5iI}_Q-Euiu9J_J_jBiOAm3$>N6}LR{Q#&gYD6LAHIXsw`MCE+`Js+y ztSzM0*zJy29^kjb8^o)u;vQxqc9{s_W11={JF69&>TRpN?CA?=5I=p{HN-rz58X z$;|oYSQK-lYnGrH!Y7{9B+hD7A008mn~py=5 zcsJ}E%&~I=&phgno&m$cG??hYgZn_m!%PSUAXy9iA5h;{ek^AMN~+3g=HX@26${AEO_i>ZU)1w}_d~iEdCv z+t97|yX`a=y|1?ezZ)+ueo}>r$*JiXXU3Ux?o_v6w}xy5(aqbR8VXxHjD ze6PPzI(#h(nK`V*Jchl7vOd z^i2Z#ix$u&(dyw-YmVcUu$RSis^-)<&ZwA69X~HfUQ(_KOQVuLbE@MUAof|Zg*{z= zZcm@*dBo=~9Ok3C7~hCxnK?C5+yXBsw2CC*$@0ewM{YV|HVxz~QZ6qv?4h5J;pNZ3 zlz`!%4#9Xc$kA!wwa?c!Ed!PT%YbFTGVrf3Fp)Uw&Oxq@{{R198IJYSGGH0_4F=TY zN_C|I;E(-l)&`%oyQue2xv<_KkpjU*j^iQaI372A9Dfp(br)H3LA#vFK_c-4<&Xav TVE6yYF^t{+^YQk7x&QwTL%&6} diff --git a/include/actor.hpp b/include/actor.hpp deleted file mode 100644 index de71831..0000000 --- a/include/actor.hpp +++ /dev/null @@ -1,121 +0,0 @@ -#ifndef _RPGPP_ACTOR_H -#define _RPGPP_ACTOR_H - -#include "atlasTile.hpp" -#include "gamedata.hpp" -#include "tileset.hpp" -#include -#include -#include -#include -#include - -using json = nlohmann::json; - -/** Direction enum, representing an animation state. */ -enum Direction { - RPGPP_DOWN_IDLE = 0, ///< Down Idle state. - RPGPP_DOWN = 1, ///< Down state. - RPGPP_UP_IDLE = 2, ///< Up Idle state. - RPGPP_UP = 3, ///< Up state. - RPGPP_LEFT_IDLE = 4, ///< Left Idle state. - RPGPP_LEFT = 5, ///< Left state. - RPGPP_RIGHT_IDLE = 6, ///< Right Idle state. - RPGPP_RIGHT = 7 ///< Right state. -}; - -/** The Actor class represents an Actor in the game's world. - * @see [Direction](Direction.md) - */ -class Actor { -private: - std::string sourcePath; - /** The used TileSet for this Actor's sprites. */ - std::unique_ptr tileSet; - /** The path to the TileSet file. */ - std::string tileSetSource; - /** The currently shown tile from the TileSet. */ - AtlasTile tile; - /** Current position in the world of this Actor. */ - Vector2 position{}; - /** Current tile position of this Actor if such is set. */ - Vector2 tilePosition{}; - int frameCounter{}; - int frameSpeed{}; - int currentFrame{}; - /** Rectangle, representing the collision of this Actor. */ - Rectangle collisionRect{}; - /** An array of the animations. Each std::vector represents the - * frames of an animation. */ - std::array>, 8> animations; - /** A Direction enum, showing the current animation that is being played. */ - Direction currentAnimation; - -public: - /** Empty constructor. */ - Actor() = default; - /** Constructor that takes a path to the .ractor file. */ - Actor(const std::string &fileName); - /** Constructor that takes a TileSet, the atlas position of the tile to use, - * and the path to the TileSet. */ - Actor(std::unique_ptr tileSet, Vector2 atlasPos, - std::string tileSetSource); - /** Constructor that takes an ActorBin binary structure */ - Actor(ActorBin bin); - /** Dump this Actor's data to a nlohmann::json object. */ - json dumpJson(); - /** Unload routine. The UnloadTexture function will called here. */ - void unload() const; - /** Update routine. */ - void update(); - /** Draw routine. */ - void draw() const; - /** Get the source file's path for this Actor. */ - std::string getSourcePath() const; - /** Get this actor's position in the world. */ - Vector2 getPosition() const; - /** Set this Actor's position. */ - void setPosition(Vector2 newPosition); - /** Set Actor position relative to a tile in the world. */ - void setTilePosition(Vector2 newPosition, Vector2 tileSize); - /** Get this Actor's tile position. */ - Vector2 getTilePosition() const; - /** Move the Actor using a velocity vector. */ - void moveByVelocity(Vector2 velocity); - /** Get the bounding box of this Actor. */ - Rectangle getRect() const; - /** Get a reference to this Actor's TileSet. */ - TileSet &getTileSet() const; - /** Set this Actor's TileSet using a path to the tileset file. */ - void setTileSet(const std::string &newTileSetSource); - /** Get the collision rectangle of this Actor if it was moved by the velocity - * vector */ - Rectangle getCollisionRect(Vector2 velocity) const; - /** Get collision center point. */ - Vector2 getCollisionCenter() const; - /** Add a frame in the chosen animation. The frame represents an atlas tile - * from this Actor's TileSet. */ - void addAnimationFrame(Direction id, Vector2 atlasPos) const; - /** Remove a frame in the chosen animation, specified by an index. */ - void removeAnimationFrame(Direction id, int frameIndex); - /** Change a frame in the chosen animation to another atlas tile from the - * TileSet. */ - void setAnimationFrame(Direction id, int frameIndex, Vector2 atlasTile) const; - /** Add multiple frames to the chosen animation. */ - void addAnimationFrames(Direction id, - const std::vector> &frames) const; - /** Change the Actor's current animation and play it. */ - void changeAnimation(Direction id); - /** Get the path of the used TileSet. */ - std::string getTileSetSource() const; - /** Get an array of this Actor's animations */ - std::array, 8> getAnimationsRaw() const; - /** Get a specific animation */ - std::vector getAnimationRaw(Direction id) const; - /** Get the collision Rectangle of this Actor */ - Rectangle getCollisionRect() const; - /** Set the Actor's collision Rectangle */ - void setCollisionRect(Rectangle rect); -}; - -#endif diff --git a/include/atlasTile.hpp b/include/atlasTile.hpp deleted file mode 100644 index fb66302..0000000 --- a/include/atlasTile.hpp +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef _RPGPP_ATLASTILE_H -#define _RPGPP_ATLASTILE_H - -#include - -/** - * Represents a source atlas tile from a TileSet. - */ -class AtlasTile { -private: - /** Pointer to the used Texture */ - Texture *texture; - /** The atlas (source) coordinates from the TileSet. */ - Vector2 atlasCoords; -public: - /** - * Empty constructor - */ - AtlasTile(); - - /** - * Constructor that takes in a texture and coordinates on the atlas (the tileset) - */ - AtlasTile(Texture *texture, Vector2 atlasCoords); - - /** - * Get the atlas coordinates - * @returns A Vector2 which represents the atlas coordinates - */ - Vector2 getAtlasCoords() const; -}; - -#endif diff --git a/include/cereal/access.hpp b/include/cereal/access.hpp deleted file mode 100644 index 87d386c..0000000 --- a/include/cereal/access.hpp +++ /dev/null @@ -1,351 +0,0 @@ -/*! \file access.hpp - \brief Access control and default construction */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_ACCESS_HPP_ -#define CEREAL_ACCESS_HPP_ - -#include -#include -#include -#include - -#include "cereal/macros.hpp" -#include "cereal/specialize.hpp" -#include "cereal/details/helpers.hpp" - -namespace cereal -{ - // ###################################################################### - //! A class that allows cereal to load smart pointers to types that have no default constructor - /*! If your class does not have a default constructor, cereal will not be able - to load any smart pointers to it unless you overload LoadAndConstruct - for your class, and provide an appropriate load_and_construct method. You can also - choose to define a member static function instead of specializing this class. - - The specialization of LoadAndConstruct must be placed within the cereal namespace: - - @code{.cpp} - struct MyType - { - MyType( int x ); // note: no default ctor - int myX; - - // Define a serialize or load/save pair as you normally would - template - void serialize( Archive & ar ) - { - ar( myX ); - } - }; - - // Provide a specialization for LoadAndConstruct for your type - namespace cereal - { - template <> struct LoadAndConstruct - { - // load_and_construct will be passed the archive that you will be loading - // from as well as a construct object which you can use as if it were the - // constructor for your type. cereal will handle all memory management for you. - template - static void load_and_construct( Archive & ar, cereal::construct & construct ) - { - int x; - ar( x ); - construct( x ); - } - - // if you require versioning, simply add a const std::uint32_t as the final parameter, e.g.: - // load_and_construct( Archive & ar, cereal::construct & construct, std::uint32_t const version ) - }; - } // end namespace cereal - @endcode - - Please note that just as in using external serialization functions, you cannot get - access to non-public members of your class by befriending cereal::access. If you - have the ability to modify the class you wish to serialize, it is recommended that you - use member serialize functions and a static member load_and_construct function. - - load_and_construct functions, regardless of whether they are static members of your class or - whether you create one in the LoadAndConstruct specialization, have the following signature: - - @code{.cpp} - // generally Archive will be templated, but it can be specific if desired - template - static void load_and_construct( Archive & ar, cereal::construct & construct ); - // with an optional last parameter specifying the version: const std::uint32_t version - @endcode - - Versioning behaves the same way as it does for standard serialization functions. - - @tparam T The type to specialize for - @ingroup Access */ - template - struct LoadAndConstruct - { }; - - // forward decl for construct - //! @cond PRIVATE_NEVERDEFINED - namespace memory_detail{ template struct LoadAndConstructLoadWrapper; } - namespace boost_variant_detail{ template struct LoadAndConstructLoadWrapper; } - //! @endcond - - //! Used to construct types with no default constructor - /*! When serializing a type that has no default constructor, cereal - will attempt to call either the class static function load_and_construct - or the appropriate template specialization of LoadAndConstruct. cereal - will pass that function a reference to the archive as well as a reference - to a construct object which should be used to perform the allocation once - data has been appropriately loaded. - - @code{.cpp} - struct MyType - { - // note the lack of default constructor - MyType( int xx, int yy ); - - int x, y; - double notInConstructor; - - template - void serialize( Archive & ar ) - { - ar( x, y ); - ar( notInConstructor ); - } - - template - static void load_and_construct( Archive & ar, cereal::construct & construct ) - { - int x, y; - ar( x, y ); - - // use construct object to initialize with loaded data - construct( x, y ); - - // access to member variables and functions via -> operator - ar( construct->notInConstructor ); - - // could also do the above section by: - double z; - ar( z ); - construct->notInConstructor = z; - } - }; - @endcode - - @tparam T The class type being serialized - */ - template - class construct - { - public: - //! Construct and initialize the type T with the given arguments - /*! This will forward all arguments to the underlying type T, - calling an appropriate constructor. - - Calling this function more than once will result in an exception - being thrown. - - @param args The arguments to the constructor for T - @throw Exception If called more than once */ - template - void operator()( Args && ... args ); - // implementation deferred due to reliance on cereal::access - - //! Get a reference to the initialized underlying object - /*! This must be called after the object has been initialized. - - @return A reference to the initialized object - @throw Exception If called before initialization */ - T * operator->() - { - if( !itsValid ) - throw Exception("Object must be initialized prior to accessing members"); - - return itsPtr; - } - - //! Returns a raw pointer to the initialized underlying object - /*! This is mainly intended for use with passing an instance of - a constructed object to cereal::base_class. - - It is strongly recommended to avoid using this function in - any other circumstance. - - @return A raw pointer to the initialized type */ - T * ptr() - { - return operator->(); - } - - private: - template friend struct ::cereal::memory_detail::LoadAndConstructLoadWrapper; - template friend struct ::cereal::boost_variant_detail::LoadAndConstructLoadWrapper; - - construct( T * p ) : itsPtr( p ), itsEnableSharedRestoreFunction( [](){} ), itsValid( false ) {} - construct( T * p, std::function enableSharedFunc ) : // g++4.7 ice with default lambda to std func - itsPtr( p ), itsEnableSharedRestoreFunction( enableSharedFunc ), itsValid( false ) {} - construct( construct const & ) = delete; - construct & operator=( construct const & ) = delete; - - T * itsPtr; - std::function itsEnableSharedRestoreFunction; - bool itsValid; - }; - - // ###################################################################### - //! A class that can be made a friend to give cereal access to non public functions - /*! If you desire non-public serialization functions within a class, cereal can only - access these if you declare cereal::access a friend. - - @code{.cpp} - class MyClass - { - private: - friend class cereal::access; // gives access to the private serialize - - template - void serialize( Archive & ar ) - { - // some code - } - }; - @endcode - @ingroup Access */ - class access - { - public: - // ####### Standard Serialization ######################################## - template inline - static auto member_serialize(Archive & ar, T & t) -> decltype(t.CEREAL_SERIALIZE_FUNCTION_NAME(ar)) - { return t.CEREAL_SERIALIZE_FUNCTION_NAME(ar); } - - template inline - static auto member_save(Archive & ar, T const & t) -> decltype(t.CEREAL_SAVE_FUNCTION_NAME(ar)) - { return t.CEREAL_SAVE_FUNCTION_NAME(ar); } - - template inline - static auto member_save_non_const(Archive & ar, T & t) -> decltype(t.CEREAL_SAVE_FUNCTION_NAME(ar)) - { return t.CEREAL_SAVE_FUNCTION_NAME(ar); } - - template inline - static auto member_load(Archive & ar, T & t) -> decltype(t.CEREAL_LOAD_FUNCTION_NAME(ar)) - { return t.CEREAL_LOAD_FUNCTION_NAME(ar); } - - template inline - static auto member_save_minimal(Archive const & ar, T const & t) -> decltype(t.CEREAL_SAVE_MINIMAL_FUNCTION_NAME(ar)) - { return t.CEREAL_SAVE_MINIMAL_FUNCTION_NAME(ar); } - - template inline - static auto member_save_minimal_non_const(Archive const & ar, T & t) -> decltype(t.CEREAL_SAVE_MINIMAL_FUNCTION_NAME(ar)) - { return t.CEREAL_SAVE_MINIMAL_FUNCTION_NAME(ar); } - - template inline - static auto member_load_minimal(Archive const & ar, T & t, U && u) -> decltype(t.CEREAL_LOAD_MINIMAL_FUNCTION_NAME(ar, std::forward(u))) - { return t.CEREAL_LOAD_MINIMAL_FUNCTION_NAME(ar, std::forward(u)); } - - // ####### Versioned Serialization ####################################### - template inline - static auto member_serialize(Archive & ar, T & t, const std::uint32_t version ) -> decltype(t.CEREAL_SERIALIZE_FUNCTION_NAME(ar, version)) - { return t.CEREAL_SERIALIZE_FUNCTION_NAME(ar, version); } - - template inline - static auto member_save(Archive & ar, T const & t, const std::uint32_t version ) -> decltype(t.CEREAL_SAVE_FUNCTION_NAME(ar, version)) - { return t.CEREAL_SAVE_FUNCTION_NAME(ar, version); } - - template inline - static auto member_save_non_const(Archive & ar, T & t, const std::uint32_t version ) -> decltype(t.CEREAL_SAVE_FUNCTION_NAME(ar, version)) - { return t.CEREAL_SAVE_FUNCTION_NAME(ar, version); } - - template inline - static auto member_load(Archive & ar, T & t, const std::uint32_t version ) -> decltype(t.CEREAL_LOAD_FUNCTION_NAME(ar, version)) - { return t.CEREAL_LOAD_FUNCTION_NAME(ar, version); } - - template inline - static auto member_save_minimal(Archive const & ar, T const & t, const std::uint32_t version) -> decltype(t.CEREAL_SAVE_MINIMAL_FUNCTION_NAME(ar, version)) - { return t.CEREAL_SAVE_MINIMAL_FUNCTION_NAME(ar, version); } - - template inline - static auto member_save_minimal_non_const(Archive const & ar, T & t, const std::uint32_t version) -> decltype(t.CEREAL_SAVE_MINIMAL_FUNCTION_NAME(ar, version)) - { return t.CEREAL_SAVE_MINIMAL_FUNCTION_NAME(ar, version); } - - template inline - static auto member_load_minimal(Archive const & ar, T & t, U && u, const std::uint32_t version) -> decltype(t.CEREAL_LOAD_MINIMAL_FUNCTION_NAME(ar, std::forward(u), version)) - { return t.CEREAL_LOAD_MINIMAL_FUNCTION_NAME(ar, std::forward(u), version); } - - // ####### Other Functionality ########################################## - // for detecting inheritance from enable_shared_from_this - template inline - static auto shared_from_this(T & t) -> decltype(t.shared_from_this()); - - // for placement new - template inline - static void construct( T *& ptr, Args && ... args ) - { - new (ptr) T( std::forward( args )... ); - } - - // for non-placement new with a default constructor - template inline - static T * construct() - { - return new T(); - } - - template inline - static std::false_type load_and_construct(...) - { return std::false_type(); } - - template inline - static auto load_and_construct(Archive & ar, ::cereal::construct & construct) -> decltype(T::load_and_construct(ar, construct)) - { - T::load_and_construct( ar, construct ); - } - - template inline - static auto load_and_construct(Archive & ar, ::cereal::construct & construct, const std::uint32_t version) -> decltype(T::load_and_construct(ar, construct, version)) - { - T::load_and_construct( ar, construct, version ); - } - }; // end class access - - // ###################################################################### - // Deferred Implementation, see construct for more information - template template inline - void construct::operator()( Args && ... args ) - { - if( itsValid ) - throw Exception("Attempting to construct an already initialized object"); - - ::cereal::access::construct( itsPtr, std::forward( args )... ); - itsEnableSharedRestoreFunction(); - itsValid = true; - } -} // namespace cereal - -#endif // CEREAL_ACCESS_HPP_ diff --git a/include/cereal/archives/adapters.hpp b/include/cereal/archives/adapters.hpp deleted file mode 100644 index e2fb57d..0000000 --- a/include/cereal/archives/adapters.hpp +++ /dev/null @@ -1,163 +0,0 @@ -/*! \file adapters.hpp - \brief Archive adapters that provide additional functionality - on top of an existing archive */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_ARCHIVES_ADAPTERS_HPP_ -#define CEREAL_ARCHIVES_ADAPTERS_HPP_ - -#include "cereal/details/helpers.hpp" -#include - -namespace cereal -{ - #ifdef CEREAL_FUTURE_EXPERIMENTAL - - // Forward declaration for friend access - template U & get_user_data( A & ); - - //! Wraps an archive and gives access to user data - /*! This adapter is useful if you require access to - either raw pointers or references within your - serialization functions. - - While cereal does not directly support serialization - raw pointers or references, it is sometimes the case - that you may want to supply something such as a raw - pointer or global reference to some constructor. - In this situation this adapter would likely be used - with the construct class to allow for non-default - constructors. - - @note This feature is experimental and may be altered or removed in a future release. See issue #46. - - @code{.cpp} - struct MyUserData - { - int * myRawPointer; - std::reference_wrapper myReference; - }; - - struct MyClass - { - // Note the raw pointer parameter - MyClass( int xx, int * rawP ); - - int x; - - template - void serialize( Archive & ar ) - { ar( x ); } - - template - static void load_and_construct( Archive & ar, cereal::construct & construct ) - { - int xx; - ar( xx ); - // note the need to use get_user_data to retrieve user data from the archive - construct( xx, cereal::get_user_data( ar ).myRawPointer ); - } - }; - - int main() - { - { - MyUserData md; - md.myRawPointer = &something; - md.myReference = someInstanceOfType; - - std::ifstream is( "data.xml" ); - cereal::UserDataAdapter ar( md, is ); - - std::unique_ptr sc; - ar( sc ); // use as normal - } - - return 0; - } - @endcode - - @relates get_user_data - - @tparam UserData The type to give the archive access to - @tparam Archive The archive to wrap */ - template - class UserDataAdapter : public Archive - { - public: - //! Construct the archive with some user data struct - /*! This will forward all arguments (other than the user - data) to the wrapped archive type. The UserDataAdapter - can then be used identically to the wrapped archive type - - @tparam Args The arguments to pass to the constructor of - the archive. */ - template - UserDataAdapter( UserData & ud, Args && ... args ) : - Archive( std::forward( args )... ), - userdata( ud ) - { } - - private: - //! Overload the rtti function to enable dynamic_cast - void rtti() {} - friend UserData & get_user_data( Archive & ar ); - UserData & userdata; //!< The actual user data - }; - - //! Retrieves user data from an archive wrapped by UserDataAdapter - /*! This will attempt to retrieve the user data associated with - some archive wrapped by UserDataAdapter. If this is used on - an archive that is not wrapped, a run-time exception will occur. - - @note This feature is experimental and may be altered or removed in a future release. See issue #46. - - @note The correct use of this function cannot be enforced at compile - time. - - @relates UserDataAdapter - @tparam UserData The data struct contained in the archive - @tparam Archive The archive, which should be wrapped by UserDataAdapter - @param ar The archive - @throws Exception if the archive this is used upon is not wrapped with - UserDataAdapter. */ - template - UserData & get_user_data( Archive & ar ) - { - try - { - return dynamic_cast &>( ar ).userdata; - } - catch( std::bad_cast const & ) - { - throw ::cereal::Exception("Attempting to get user data from archive not wrapped in UserDataAdapter"); - } - } - #endif // CEREAL_FUTURE_EXPERIMENTAL -} // namespace cereal - -#endif // CEREAL_ARCHIVES_ADAPTERS_HPP_ diff --git a/include/cereal/archives/binary.hpp b/include/cereal/archives/binary.hpp deleted file mode 100644 index 0bded01..0000000 --- a/include/cereal/archives/binary.hpp +++ /dev/null @@ -1,169 +0,0 @@ -/*! \file binary.hpp - \brief Binary input and output archives */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_ARCHIVES_BINARY_HPP_ -#define CEREAL_ARCHIVES_BINARY_HPP_ - -#include "cereal/cereal.hpp" -#include - -namespace cereal -{ - // ###################################################################### - //! An output archive designed to save data in a compact binary representation - /*! This archive outputs data to a stream in an extremely compact binary - representation with as little extra metadata as possible. - - This archive does nothing to ensure that the endianness of the saved - and loaded data is the same. If you need to have portability over - architectures with different endianness, use PortableBinaryOutputArchive. - - When using a binary archive and a file stream, you must use the - std::ios::binary format flag to avoid having your data altered - inadvertently. - - \ingroup Archives */ - class BinaryOutputArchive : public OutputArchive - { - public: - //! Construct, outputting to the provided stream - /*! @param stream The stream to output to. Can be a stringstream, a file stream, or - even cout! */ - BinaryOutputArchive(std::ostream & stream) : - OutputArchive(this), - itsStream(stream) - { } - - ~BinaryOutputArchive() CEREAL_NOEXCEPT = default; - - //! Writes size bytes of data to the output stream - void saveBinary( const void * data, std::streamsize size ) - { - auto const writtenSize = itsStream.rdbuf()->sputn( reinterpret_cast( data ), size ); - - if(writtenSize != size) - throw Exception("Failed to write " + std::to_string(size) + " bytes to output stream! Wrote " + std::to_string(writtenSize)); - } - - private: - std::ostream & itsStream; - }; - - // ###################################################################### - //! An input archive designed to load data saved using BinaryOutputArchive - /* This archive does nothing to ensure that the endianness of the saved - and loaded data is the same. If you need to have portability over - architectures with different endianness, use PortableBinaryOutputArchive. - - When using a binary archive and a file stream, you must use the - std::ios::binary format flag to avoid having your data altered - inadvertently. - - \ingroup Archives */ - class BinaryInputArchive : public InputArchive - { - public: - //! Construct, loading from the provided stream - BinaryInputArchive(std::istream & stream) : - InputArchive(this), - itsStream(stream) - { } - - ~BinaryInputArchive() CEREAL_NOEXCEPT = default; - - //! Reads size bytes of data from the input stream - void loadBinary( void * const data, std::streamsize size ) - { - auto const readSize = itsStream.rdbuf()->sgetn( reinterpret_cast( data ), size ); - - if(readSize != size) - throw Exception("Failed to read " + std::to_string(size) + " bytes from input stream! Read " + std::to_string(readSize)); - } - - private: - std::istream & itsStream; - }; - - // ###################################################################### - // Common BinaryArchive serialization functions - - //! Saving for POD types to binary - template inline - typename std::enable_if::value, void>::type - CEREAL_SAVE_FUNCTION_NAME(BinaryOutputArchive & ar, T const & t) - { - ar.saveBinary(std::addressof(t), sizeof(t)); - } - - //! Loading for POD types from binary - template inline - typename std::enable_if::value, void>::type - CEREAL_LOAD_FUNCTION_NAME(BinaryInputArchive & ar, T & t) - { - ar.loadBinary(std::addressof(t), sizeof(t)); - } - - //! Serializing NVP types to binary - template inline - CEREAL_ARCHIVE_RESTRICT(BinaryInputArchive, BinaryOutputArchive) - CEREAL_SERIALIZE_FUNCTION_NAME( Archive & ar, NameValuePair & t ) - { - ar( t.value ); - } - - //! Serializing SizeTags to binary - template inline - CEREAL_ARCHIVE_RESTRICT(BinaryInputArchive, BinaryOutputArchive) - CEREAL_SERIALIZE_FUNCTION_NAME( Archive & ar, SizeTag & t ) - { - ar( t.size ); - } - - //! Saving binary data - template inline - void CEREAL_SAVE_FUNCTION_NAME(BinaryOutputArchive & ar, BinaryData const & bd) - { - ar.saveBinary( bd.data, static_cast( bd.size ) ); - } - - //! Loading binary data - template inline - void CEREAL_LOAD_FUNCTION_NAME(BinaryInputArchive & ar, BinaryData & bd) - { - ar.loadBinary(bd.data, static_cast( bd.size ) ); - } -} // namespace cereal - -// register archives for polymorphic support -CEREAL_REGISTER_ARCHIVE(cereal::BinaryOutputArchive) -CEREAL_REGISTER_ARCHIVE(cereal::BinaryInputArchive) - -// tie input and output archives together -CEREAL_SETUP_ARCHIVE_TRAITS(cereal::BinaryInputArchive, cereal::BinaryOutputArchive) - -#endif // CEREAL_ARCHIVES_BINARY_HPP_ diff --git a/include/cereal/archives/json.hpp b/include/cereal/archives/json.hpp deleted file mode 100644 index 199efc9..0000000 --- a/include/cereal/archives/json.hpp +++ /dev/null @@ -1,1024 +0,0 @@ -/*! \file json.hpp - \brief JSON input and output archives */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_ARCHIVES_JSON_HPP_ -#define CEREAL_ARCHIVES_JSON_HPP_ - -#include "cereal/cereal.hpp" -#include "cereal/details/util.hpp" - -namespace cereal -{ - //! An exception thrown when rapidjson fails an internal assertion - /*! @ingroup Utility */ - struct RapidJSONException : Exception - { RapidJSONException( const char * what_ ) : Exception( what_ ) {} }; -} - -// Inform rapidjson that assert will throw -#ifndef CEREAL_RAPIDJSON_ASSERT_THROWS -#define CEREAL_RAPIDJSON_ASSERT_THROWS -#endif // CEREAL_RAPIDJSON_ASSERT_THROWS - -// Override rapidjson assertions to throw exceptions by default -#ifndef CEREAL_RAPIDJSON_ASSERT -#define CEREAL_RAPIDJSON_ASSERT(x) if(!(x)){ \ - throw ::cereal::RapidJSONException("rapidjson internal assertion failure: " #x); } -#endif // RAPIDJSON_ASSERT - -// Enable support for parsing of nan, inf, -inf -#ifndef CEREAL_RAPIDJSON_WRITE_DEFAULT_FLAGS -#define CEREAL_RAPIDJSON_WRITE_DEFAULT_FLAGS kWriteNanAndInfFlag -#endif - -// Enable support for parsing of nan, inf, -inf -#ifndef CEREAL_RAPIDJSON_PARSE_DEFAULT_FLAGS -#define CEREAL_RAPIDJSON_PARSE_DEFAULT_FLAGS kParseFullPrecisionFlag | kParseNanAndInfFlag -#endif - -#include "cereal/external/rapidjson/prettywriter.h" -#include "cereal/external/rapidjson/ostreamwrapper.h" -#include "cereal/external/rapidjson/istreamwrapper.h" -#include "cereal/external/rapidjson/document.h" -#include "cereal/external/base64.hpp" - -#include -#include -#include -#include -#include - -namespace cereal -{ - // ###################################################################### - //! An output archive designed to save data to JSON - /*! This archive uses RapidJSON to build serialize data to JSON. - - JSON archives provides a human readable output but at decreased - performance (both in time and space) compared to binary archives. - - JSON archives are only guaranteed to finish flushing their contents - upon destruction and should thus be used in an RAII fashion. - - JSON benefits greatly from name-value pairs, which if present, will - name the nodes in the output. If these are not present, each level - of the output will be given an automatically generated delimited name. - - The precision of the output archive controls the number of decimals output - for floating point numbers and should be sufficiently large (i.e. at least 20) - if there is a desire to have binary equality between the numbers output and - those read in. In general you should expect a loss of precision when going - from floating point to text and back. - - JSON archives do not output the size information for any dynamically sized structure - and instead infer it from the number of children for a node. This means that data - can be hand edited for dynamic sized structures and will still be readable. This - is accomplished through the cereal::SizeTag object, which will cause the archive - to output the data as a JSON array (e.g. marked by [] instead of {}), which indicates - that the container is variable sized and may be edited. - - \ingroup Archives */ - class JSONOutputArchive : public OutputArchive, public traits::TextArchive - { - enum class NodeType { StartObject, InObject, StartArray, InArray }; - - using WriteStream = CEREAL_RAPIDJSON_NAMESPACE::OStreamWrapper; - using JSONWriter = CEREAL_RAPIDJSON_NAMESPACE::PrettyWriter; - - public: - /*! @name Common Functionality - Common use cases for directly interacting with an JSONOutputArchive */ - //! @{ - - //! A class containing various advanced options for the JSON archive - class Options - { - public: - //! Default options - static Options Default(){ return Options(); } - - //! Default options with no indentation - static Options NoIndent(){ return Options( JSONWriter::kDefaultMaxDecimalPlaces, IndentChar::space, 0 ); } - - //! The character to use for indenting - enum class IndentChar : char - { - space = ' ', - tab = '\t', - newline = '\n', - carriage_return = '\r' - }; - - //! Specify specific options for the JSONOutputArchive - /*! @param precision The precision used for floating point numbers - @param indentChar The type of character to indent with - @param indentLength The number of indentChar to use for indentation - (0 corresponds to no indentation) */ - explicit Options( int precision = JSONWriter::kDefaultMaxDecimalPlaces, - IndentChar indentChar = IndentChar::space, - unsigned int indentLength = 4 ) : - itsPrecision( precision ), - itsIndentChar( static_cast(indentChar) ), - itsIndentLength( indentLength ) { } - - private: - friend class JSONOutputArchive; - int itsPrecision; - char itsIndentChar; - unsigned int itsIndentLength; - }; - - //! Construct, outputting to the provided stream - /*! @param stream The stream to output to. - @param options The JSON specific options to use. See the Options struct - for the values of default parameters */ - JSONOutputArchive(std::ostream & stream, Options const & options = Options::Default() ) : - OutputArchive(this), - itsWriteStream(stream), - itsWriter(itsWriteStream), - itsNextName(nullptr) - { - itsWriter.SetMaxDecimalPlaces( options.itsPrecision ); - itsWriter.SetIndent( options.itsIndentChar, options.itsIndentLength ); - itsNameCounter.push(0); - itsNodeStack.push(NodeType::StartObject); - } - - //! Destructor, flushes the JSON - ~JSONOutputArchive() CEREAL_NOEXCEPT - { - if (itsNodeStack.top() == NodeType::InObject) - itsWriter.EndObject(); - else if (itsNodeStack.top() == NodeType::InArray) - itsWriter.EndArray(); - } - - //! Saves some binary data, encoded as a base64 string, with an optional name - /*! This will create a new node, optionally named, and insert a value that consists of - the data encoded as a base64 string */ - void saveBinaryValue( const void * data, size_t size, const char * name = nullptr ) - { - setNextName( name ); - writeName(); - - auto base64string = base64::encode( reinterpret_cast( data ), size ); - saveValue( base64string ); - }; - - //! @} - /*! @name Internal Functionality - Functionality designed for use by those requiring control over the inner mechanisms of - the JSONOutputArchive */ - //! @{ - - //! Starts a new node in the JSON output - /*! The node can optionally be given a name by calling setNextName prior - to creating the node - - Nodes only need to be started for types that are themselves objects or arrays */ - void startNode() - { - writeName(); - itsNodeStack.push(NodeType::StartObject); - itsNameCounter.push(0); - } - - //! Designates the most recently added node as finished - void finishNode() - { - // if we ended up serializing an empty object or array, writeName - // will never have been called - so start and then immediately end - // the object/array. - // - // We'll also end any object/arrays we happen to be in - switch(itsNodeStack.top()) - { - case NodeType::StartArray: - itsWriter.StartArray(); - // fall through - case NodeType::InArray: - itsWriter.EndArray(); - break; - case NodeType::StartObject: - itsWriter.StartObject(); - // fall through - case NodeType::InObject: - itsWriter.EndObject(); - break; - } - - itsNodeStack.pop(); - itsNameCounter.pop(); - } - - //! Sets the name for the next node created with startNode - void setNextName( const char * name ) - { - itsNextName = name; - } - - //! Saves a bool to the current node - void saveValue(bool b) { itsWriter.Bool(b); } - //! Saves an int to the current node - void saveValue(int i) { itsWriter.Int(i); } - //! Saves a uint to the current node - void saveValue(unsigned u) { itsWriter.Uint(u); } - //! Saves an int64 to the current node - void saveValue(int64_t i64) { itsWriter.Int64(i64); } - //! Saves a uint64 to the current node - void saveValue(uint64_t u64) { itsWriter.Uint64(u64); } - //! Saves a double to the current node - void saveValue(double d) { itsWriter.Double(d); } - //! Saves a string to the current node - void saveValue(std::string const & s) { itsWriter.String(s.c_str(), static_cast( s.size() )); } - //! Saves a const char * to the current node - void saveValue(char const * s) { itsWriter.String(s); } - //! Saves a nullptr to the current node - void saveValue(std::nullptr_t) { itsWriter.Null(); } - - private: - // Some compilers/OS have difficulty disambiguating the above for various flavors of longs, so we provide - // special overloads to handle these cases. - - //! 32 bit signed long saving to current node - template ::value> = traits::sfinae> inline - void saveLong(T l){ saveValue( static_cast( l ) ); } - - //! non 32 bit signed long saving to current node - template ::value> = traits::sfinae> inline - void saveLong(T l){ saveValue( static_cast( l ) ); } - - //! 32 bit unsigned long saving to current node - template ::value> = traits::sfinae> inline - void saveLong(T lu){ saveValue( static_cast( lu ) ); } - - //! non 32 bit unsigned long saving to current node - template ::value> = traits::sfinae> inline - void saveLong(T lu){ saveValue( static_cast( lu ) ); } - - public: -#if defined(_MSC_VER) && _MSC_VER < 1916 - //! MSVC only long overload to current node - void saveValue( unsigned long lu ){ saveLong( lu ); }; -#else // _MSC_VER - //! Serialize a long if it would not be caught otherwise - template ::value, - !std::is_same::value, - !std::is_same::value> = traits::sfinae> inline - void saveValue( T t ){ saveLong( t ); } - - //! Serialize an unsigned long if it would not be caught otherwise - template ::value, - !std::is_same::value, - !std::is_same::value> = traits::sfinae> inline - void saveValue( T t ){ saveLong( t ); } -#endif // _MSC_VER - - //! Save exotic arithmetic as strings to current node - /*! Handles long long (if distinct from other types), unsigned long (if distinct), and long double */ - template ::value, - !std::is_same::value, - !std::is_same::value, - !std::is_same::value, - !std::is_same::value, - (sizeof(T) >= sizeof(long double) || sizeof(T) >= sizeof(long long))> = traits::sfinae> inline - void saveValue(T const & t) - { - std::stringstream ss; ss.precision( std::numeric_limits::max_digits10 ); - ss << t; - saveValue( ss.str() ); - } - - //! Write the name of the upcoming node and prepare object/array state - /*! Since writeName is called for every value that is output, regardless of - whether it has a name or not, it is the place where we will do a deferred - check of our node state and decide whether we are in an array or an object. - - The general workflow of saving to the JSON archive is: - - 1. (optional) Set the name for the next node to be created, usually done by an NVP - 2. Start the node - 3. (if there is data to save) Write the name of the node (this function) - 4. (if there is data to save) Save the data (with saveValue) - 5. Finish the node - */ - void writeName() - { - NodeType const & nodeType = itsNodeStack.top(); - - // Start up either an object or an array, depending on state - if(nodeType == NodeType::StartArray) - { - itsWriter.StartArray(); - itsNodeStack.top() = NodeType::InArray; - } - else if(nodeType == NodeType::StartObject) - { - itsNodeStack.top() = NodeType::InObject; - itsWriter.StartObject(); - } - - // Array types do not output names - if(nodeType == NodeType::InArray) return; - - if(itsNextName == nullptr) - { - std::string name = "value" + std::to_string( itsNameCounter.top()++ ) + "\0"; - saveValue(name); - } - else - { - saveValue(itsNextName); - itsNextName = nullptr; - } - } - - //! Designates that the current node should be output as an array, not an object - void makeArray() - { - itsNodeStack.top() = NodeType::StartArray; - } - - //! @} - - private: - WriteStream itsWriteStream; //!< Rapidjson write stream - JSONWriter itsWriter; //!< Rapidjson writer - char const * itsNextName; //!< The next name - std::stack itsNameCounter; //!< Counter for creating unique names for unnamed nodes - std::stack itsNodeStack; - }; // JSONOutputArchive - - // ###################################################################### - //! An input archive designed to load data from JSON - /*! This archive uses RapidJSON to read in a JSON archive. - - As with the output JSON archive, the preferred way to use this archive is in - an RAII fashion, ensuring its destruction after all data has been read. - - Input JSON should have been produced by the JSONOutputArchive. Data can - only be added to dynamically sized containers (marked by JSON arrays) - - the input archive will determine their size by looking at the number of child nodes. - Only JSON originating from a JSONOutputArchive is officially supported, but data - from other sources may work if properly formatted. - - The JSONInputArchive does not require that nodes are loaded in the same - order they were saved by JSONOutputArchive. Using name value pairs (NVPs), - it is possible to load in an out of order fashion or otherwise skip/select - specific nodes to load. - - The default behavior of the input archive is to read sequentially starting - with the first node and exploring its children. When a given NVP does - not match the read in name for a node, the archive will search for that - node at the current level and load it if it exists. After loading an out of - order node, the archive will then proceed back to loading sequentially from - its new position. - - Consider this simple example where loading of some data is skipped: - - @code{cpp} - // imagine the input file has someData(1-9) saved in order at the top level node - ar( someData1, someData2, someData3 ); // XML loads in the order it sees in the file - ar( cereal::make_nvp( "hello", someData6 ) ); // NVP given does not - // match expected NVP name, so we search - // for the given NVP and load that value - ar( someData7, someData8, someData9 ); // with no NVP given, loading resumes at its - // current location, proceeding sequentially - @endcode - - \ingroup Archives */ - class JSONInputArchive : public InputArchive, public traits::TextArchive - { - private: - using ReadStream = CEREAL_RAPIDJSON_NAMESPACE::IStreamWrapper; - typedef CEREAL_RAPIDJSON_NAMESPACE::GenericValue> JSONValue; - typedef JSONValue::ConstMemberIterator MemberIterator; - typedef JSONValue::ConstValueIterator ValueIterator; - typedef CEREAL_RAPIDJSON_NAMESPACE::Document::GenericValue GenericValue; - - public: - /*! @name Common Functionality - Common use cases for directly interacting with an JSONInputArchive */ - //! @{ - - //! Construct, reading from the provided stream - /*! @param stream The stream to read from */ - JSONInputArchive(std::istream & stream) : - InputArchive(this), - itsNextName( nullptr ), - itsReadStream(stream) - { - itsDocument.ParseStream<>(itsReadStream); - if (itsDocument.IsArray()) - itsIteratorStack.emplace_back(itsDocument.Begin(), itsDocument.End()); - else - itsIteratorStack.emplace_back(itsDocument.MemberBegin(), itsDocument.MemberEnd()); - } - - ~JSONInputArchive() CEREAL_NOEXCEPT = default; - - //! Loads some binary data, encoded as a base64 string - /*! This will automatically start and finish a node to load the data, and can be called directly by - users. - - Note that this follows the same ordering rules specified in the class description in regards - to loading in/out of order */ - void loadBinaryValue( void * data, size_t size, const char * name = nullptr ) - { - itsNextName = name; - - std::string encoded; - loadValue( encoded ); - auto decoded = base64::decode( encoded ); - - if( size != decoded.size() ) - throw Exception("Decoded binary data size does not match specified size"); - - std::memcpy( data, decoded.data(), decoded.size() ); - itsNextName = nullptr; - }; - - private: - //! @} - /*! @name Internal Functionality - Functionality designed for use by those requiring control over the inner mechanisms of - the JSONInputArchive */ - //! @{ - - //! An internal iterator that handles both array and object types - /*! This class is a variant and holds both types of iterators that - rapidJSON supports - one for arrays and one for objects. */ - class Iterator - { - public: - Iterator() : itsIndex( 0 ), itsType(Null_) {} - - Iterator(MemberIterator begin, MemberIterator end) : - itsMemberItBegin(begin), itsMemberItEnd(end), itsIndex(0), itsSize(std::distance(begin, end)), itsType(Member) - { - if( itsSize == 0 ) - itsType = Null_; - } - - Iterator(ValueIterator begin, ValueIterator end) : - itsValueItBegin(begin), itsIndex(0), itsSize(std::distance(begin, end)), itsType(Value) - { - if( itsSize == 0 ) - itsType = Null_; - } - - //! Advance to the next node - Iterator & operator++() - { - ++itsIndex; - return *this; - } - - //! Get the value of the current node - GenericValue const & value() - { - if( itsIndex >= itsSize ) - throw cereal::Exception("No more objects in input"); - - switch(itsType) - { - case Value : return itsValueItBegin[itsIndex]; - case Member: return itsMemberItBegin[itsIndex].value; - default: throw cereal::Exception("JSONInputArchive internal error: null or empty iterator to object or array!"); - } - } - - //! Get the name of the current node, or nullptr if it has no name - const char * name() const - { - if( itsType == Member && (itsMemberItBegin + itsIndex) != itsMemberItEnd ) - return itsMemberItBegin[itsIndex].name.GetString(); - else - return nullptr; - } - - //! Adjust our position such that we are at the node with the given name - /*! @throws Exception if no such named node exists */ - inline void search( const char * searchName ) - { - const auto len = std::strlen( searchName ); - size_t index = 0; - for( auto it = itsMemberItBegin; it != itsMemberItEnd; ++it, ++index ) - { - const auto currentName = it->name.GetString(); - if( ( std::strncmp( searchName, currentName, len ) == 0 ) && - ( std::strlen( currentName ) == len ) ) - { - itsIndex = index; - return; - } - } - - throw Exception("JSON Parsing failed - provided NVP (" + std::string(searchName) + ") not found"); - } - - private: - MemberIterator itsMemberItBegin, itsMemberItEnd; //!< The member iterator (object) - ValueIterator itsValueItBegin; //!< The value iterator (array) - size_t itsIndex, itsSize; //!< The current index of this iterator - enum Type {Value, Member, Null_} itsType; //!< Whether this holds values (array) or members (objects) or nothing - }; - - //! Searches for the expectedName node if it doesn't match the actualName - /*! This needs to be called before every load or node start occurs. This function will - check to see if an NVP has been provided (with setNextName) and if so, see if that name matches the actual - next name given. If the names do not match, it will search in the current level of the JSON for that name. - If the name is not found, an exception will be thrown. - - Resets the NVP name after called. - - @throws Exception if an expectedName is given and not found */ - inline void search() - { - // store pointer to itsNextName locally and reset to nullptr in case search() throws - auto localNextName = itsNextName; - itsNextName = nullptr; - - // The name an NVP provided with setNextName() - if( localNextName ) - { - // The actual name of the current node - auto const actualName = itsIteratorStack.back().name(); - - // Do a search if we don't see a name coming up, or if the names don't match - if( !actualName || std::strcmp( localNextName, actualName ) != 0 ) - itsIteratorStack.back().search( localNextName ); - } - } - - public: - //! Starts a new node, going into its proper iterator - /*! This places an iterator for the next node to be parsed onto the iterator stack. If the next - node is an array, this will be a value iterator, otherwise it will be a member iterator. - - By default our strategy is to start with the document root node and then recursively iterate through - all children in the order they show up in the document. - We don't need to know NVPs to do this; we'll just blindly load in the order things appear in. - - If we were given an NVP, we will search for it if it does not match our the name of the next node - that would normally be loaded. This functionality is provided by search(). */ - void startNode() - { - search(); - - if(itsIteratorStack.back().value().IsArray()) - itsIteratorStack.emplace_back(itsIteratorStack.back().value().Begin(), itsIteratorStack.back().value().End()); - else - itsIteratorStack.emplace_back(itsIteratorStack.back().value().MemberBegin(), itsIteratorStack.back().value().MemberEnd()); - } - - //! Finishes the most recently started node - void finishNode() - { - itsIteratorStack.pop_back(); - ++itsIteratorStack.back(); - } - - //! Retrieves the current node name - /*! @return nullptr if no name exists */ - const char * getNodeName() const - { - return itsIteratorStack.back().name(); - } - - //! Sets the name for the next node created with startNode - void setNextName( const char * name ) - { - itsNextName = name; - } - - //! Loads a value from the current node - small signed overload - template ::value, - sizeof(T) < sizeof(int64_t)> = traits::sfinae> inline - void loadValue(T & val) - { - search(); - - val = static_cast( itsIteratorStack.back().value().GetInt() ); - ++itsIteratorStack.back(); - } - - //! Loads a value from the current node - small unsigned overload - template ::value, - sizeof(T) < sizeof(uint64_t), - !std::is_same::value> = traits::sfinae> inline - void loadValue(T & val) - { - search(); - - val = static_cast( itsIteratorStack.back().value().GetUint() ); - ++itsIteratorStack.back(); - } - - //! Loads a value from the current node - bool overload - void loadValue(bool & val) { search(); val = itsIteratorStack.back().value().GetBool(); ++itsIteratorStack.back(); } - //! Loads a value from the current node - int64 overload - void loadValue(int64_t & val) { search(); val = itsIteratorStack.back().value().GetInt64(); ++itsIteratorStack.back(); } - //! Loads a value from the current node - uint64 overload - void loadValue(uint64_t & val) { search(); val = itsIteratorStack.back().value().GetUint64(); ++itsIteratorStack.back(); } - //! Loads a value from the current node - float overload - void loadValue(float & val) { search(); val = static_cast(itsIteratorStack.back().value().GetDouble()); ++itsIteratorStack.back(); } - //! Loads a value from the current node - double overload - void loadValue(double & val) { search(); val = itsIteratorStack.back().value().GetDouble(); ++itsIteratorStack.back(); } - //! Loads a value from the current node - string overload - void loadValue(std::string & val) { search(); val = itsIteratorStack.back().value().GetString(); ++itsIteratorStack.back(); } - //! Loads a nullptr from the current node - void loadValue(std::nullptr_t&) { search(); CEREAL_RAPIDJSON_ASSERT(itsIteratorStack.back().value().IsNull()); ++itsIteratorStack.back(); } - - // Special cases to handle various flavors of long, which tend to conflict with - // the int32_t or int64_t on various compiler/OS combinations. MSVC doesn't need any of this. - #ifndef _MSC_VER - private: - //! 32 bit signed long loading from current node - template inline - typename std::enable_if::value, void>::type - loadLong(T & l){ loadValue( reinterpret_cast( l ) ); } - - //! non 32 bit signed long loading from current node - template inline - typename std::enable_if::value, void>::type - loadLong(T & l){ loadValue( reinterpret_cast( l ) ); } - - //! 32 bit unsigned long loading from current node - template inline - typename std::enable_if::value, void>::type - loadLong(T & lu){ loadValue( reinterpret_cast( lu ) ); } - - //! non 32 bit unsigned long loading from current node - template inline - typename std::enable_if::value, void>::type - loadLong(T & lu){ loadValue( reinterpret_cast( lu ) ); } - - public: - //! Serialize a long if it would not be caught otherwise - template inline - typename std::enable_if::value && - sizeof(T) >= sizeof(std::int64_t) && - !std::is_same::value, void>::type - loadValue( T & t ){ loadLong(t); } - - //! Serialize an unsigned long if it would not be caught otherwise - template inline - typename std::enable_if::value && - sizeof(T) >= sizeof(std::uint64_t) && - !std::is_same::value, void>::type - loadValue( T & t ){ loadLong(t); } - #endif // _MSC_VER - - private: - //! Convert a string to a long long - void stringToNumber( std::string const & str, long long & val ) { val = std::stoll( str ); } - //! Convert a string to an unsigned long long - void stringToNumber( std::string const & str, unsigned long long & val ) { val = std::stoull( str ); } - //! Convert a string to a long double - void stringToNumber( std::string const & str, long double & val ) { val = std::stold( str ); } - - public: - //! Loads a value from the current node - long double and long long overloads - template ::value, - !std::is_same::value, - !std::is_same::value, - !std::is_same::value, - !std::is_same::value, - (sizeof(T) >= sizeof(long double) || sizeof(T) >= sizeof(long long))> = traits::sfinae> - inline void loadValue(T & val) - { - std::string encoded; - loadValue( encoded ); - stringToNumber( encoded, val ); - } - - //! Loads the size for a SizeTag - void loadSize(size_type & size) - { - if (itsIteratorStack.size() == 1) - size = itsDocument.Size(); - else - size = (itsIteratorStack.rbegin() + 1)->value().Size(); - } - - //! @} - - private: - const char * itsNextName; //!< Next name set by NVP - ReadStream itsReadStream; //!< Rapidjson write stream - std::vector itsIteratorStack; //!< 'Stack' of rapidJSON iterators - CEREAL_RAPIDJSON_NAMESPACE::Document itsDocument; //!< Rapidjson document - }; - - // ###################################################################### - // JSONArchive prologue and epilogue functions - // ###################################################################### - - // ###################################################################### - //! Prologue for NVPs for JSON archives - /*! NVPs do not start or finish nodes - they just set up the names */ - template inline - void prologue( JSONOutputArchive &, NameValuePair const & ) - { } - - //! Prologue for NVPs for JSON archives - template inline - void prologue( JSONInputArchive &, NameValuePair const & ) - { } - - // ###################################################################### - //! Epilogue for NVPs for JSON archives - /*! NVPs do not start or finish nodes - they just set up the names */ - template inline - void epilogue( JSONOutputArchive &, NameValuePair const & ) - { } - - //! Epilogue for NVPs for JSON archives - /*! NVPs do not start or finish nodes - they just set up the names */ - template inline - void epilogue( JSONInputArchive &, NameValuePair const & ) - { } - - // ###################################################################### - //! Prologue for deferred data for JSON archives - /*! Do nothing for the defer wrapper */ - template inline - void prologue( JSONOutputArchive &, DeferredData const & ) - { } - - //! Prologue for deferred data for JSON archives - template inline - void prologue( JSONInputArchive &, DeferredData const & ) - { } - - // ###################################################################### - //! Epilogue for deferred for JSON archives - /*! NVPs do not start or finish nodes - they just set up the names */ - template inline - void epilogue( JSONOutputArchive &, DeferredData const & ) - { } - - //! Epilogue for deferred for JSON archives - /*! Do nothing for the defer wrapper */ - template inline - void epilogue( JSONInputArchive &, DeferredData const & ) - { } - - // ###################################################################### - //! Prologue for SizeTags for JSON archives - /*! SizeTags are strictly ignored for JSON, they just indicate - that the current node should be made into an array */ - template inline - void prologue( JSONOutputArchive & ar, SizeTag const & ) - { - ar.makeArray(); - } - - //! Prologue for SizeTags for JSON archives - template inline - void prologue( JSONInputArchive &, SizeTag const & ) - { } - - // ###################################################################### - //! Epilogue for SizeTags for JSON archives - /*! SizeTags are strictly ignored for JSON */ - template inline - void epilogue( JSONOutputArchive &, SizeTag const & ) - { } - - //! Epilogue for SizeTags for JSON archives - template inline - void epilogue( JSONInputArchive &, SizeTag const & ) - { } - - // ###################################################################### - //! Prologue for all other types for JSON archives (except minimal types) - /*! Starts a new node, named either automatically or by some NVP, - that may be given data by the type about to be archived - - Minimal types do not start or finish nodes */ - template ::value, - !traits::has_minimal_base_class_serialization::value, - !traits::has_minimal_output_serialization::value> = traits::sfinae> - inline void prologue( JSONOutputArchive & ar, T const & ) - { - ar.startNode(); - } - - //! Prologue for all other types for JSON archives - template ::value, - !traits::has_minimal_base_class_serialization::value, - !traits::has_minimal_input_serialization::value> = traits::sfinae> - inline void prologue( JSONInputArchive & ar, T const & ) - { - ar.startNode(); - } - - // ###################################################################### - //! Epilogue for all other types other for JSON archives (except minimal types) - /*! Finishes the node created in the prologue - - Minimal types do not start or finish nodes */ - template ::value, - !traits::has_minimal_base_class_serialization::value, - !traits::has_minimal_output_serialization::value> = traits::sfinae> - inline void epilogue( JSONOutputArchive & ar, T const & ) - { - ar.finishNode(); - } - - //! Epilogue for all other types other for JSON archives - template ::value, - !traits::has_minimal_base_class_serialization::value, - !traits::has_minimal_input_serialization::value> = traits::sfinae> - inline void epilogue( JSONInputArchive & ar, T const & ) - { - ar.finishNode(); - } - - // ###################################################################### - //! Prologue for arithmetic types for JSON archives - inline - void prologue( JSONOutputArchive & ar, std::nullptr_t const & ) - { - ar.writeName(); - } - - //! Prologue for arithmetic types for JSON archives - inline - void prologue( JSONInputArchive &, std::nullptr_t const & ) - { } - - // ###################################################################### - //! Epilogue for arithmetic types for JSON archives - inline - void epilogue( JSONOutputArchive &, std::nullptr_t const & ) - { } - - //! Epilogue for arithmetic types for JSON archives - inline - void epilogue( JSONInputArchive &, std::nullptr_t const & ) - { } - - // ###################################################################### - //! Prologue for arithmetic types for JSON archives - template ::value> = traits::sfinae> inline - void prologue( JSONOutputArchive & ar, T const & ) - { - ar.writeName(); - } - - //! Prologue for arithmetic types for JSON archives - template ::value> = traits::sfinae> inline - void prologue( JSONInputArchive &, T const & ) - { } - - // ###################################################################### - //! Epilogue for arithmetic types for JSON archives - template ::value> = traits::sfinae> inline - void epilogue( JSONOutputArchive &, T const & ) - { } - - //! Epilogue for arithmetic types for JSON archives - template ::value> = traits::sfinae> inline - void epilogue( JSONInputArchive &, T const & ) - { } - - // ###################################################################### - //! Prologue for strings for JSON archives - template inline - void prologue(JSONOutputArchive & ar, std::basic_string const &) - { - ar.writeName(); - } - - //! Prologue for strings for JSON archives - template inline - void prologue(JSONInputArchive &, std::basic_string const &) - { } - - // ###################################################################### - //! Epilogue for strings for JSON archives - template inline - void epilogue(JSONOutputArchive &, std::basic_string const &) - { } - - //! Epilogue for strings for JSON archives - template inline - void epilogue(JSONInputArchive &, std::basic_string const &) - { } - - // ###################################################################### - // Common JSONArchive serialization functions - // ###################################################################### - //! Serializing NVP types to JSON - template inline - void CEREAL_SAVE_FUNCTION_NAME( JSONOutputArchive & ar, NameValuePair const & t ) - { - ar.setNextName( t.name ); - ar( t.value ); - } - - template inline - void CEREAL_LOAD_FUNCTION_NAME( JSONInputArchive & ar, NameValuePair & t ) - { - ar.setNextName( t.name ); - ar( t.value ); - } - - //! Saving for nullptr to JSON - inline - void CEREAL_SAVE_FUNCTION_NAME(JSONOutputArchive & ar, std::nullptr_t const & t) - { - ar.saveValue( t ); - } - - //! Loading arithmetic from JSON - inline - void CEREAL_LOAD_FUNCTION_NAME(JSONInputArchive & ar, std::nullptr_t & t) - { - ar.loadValue( t ); - } - - //! Saving for arithmetic to JSON - template ::value> = traits::sfinae> inline - void CEREAL_SAVE_FUNCTION_NAME(JSONOutputArchive & ar, T const & t) - { - ar.saveValue( t ); - } - - //! Loading arithmetic from JSON - template ::value> = traits::sfinae> inline - void CEREAL_LOAD_FUNCTION_NAME(JSONInputArchive & ar, T & t) - { - ar.loadValue( t ); - } - - //! saving string to JSON - template inline - void CEREAL_SAVE_FUNCTION_NAME(JSONOutputArchive & ar, std::basic_string const & str) - { - ar.saveValue( str ); - } - - //! loading string from JSON - template inline - void CEREAL_LOAD_FUNCTION_NAME(JSONInputArchive & ar, std::basic_string & str) - { - ar.loadValue( str ); - } - - // ###################################################################### - //! Saving SizeTags to JSON - template inline - void CEREAL_SAVE_FUNCTION_NAME( JSONOutputArchive &, SizeTag const & ) - { - // nothing to do here, we don't explicitly save the size - } - - //! Loading SizeTags from JSON - template inline - void CEREAL_LOAD_FUNCTION_NAME( JSONInputArchive & ar, SizeTag & st ) - { - ar.loadSize( st.size ); - } -} // namespace cereal - -// register archives for polymorphic support -CEREAL_REGISTER_ARCHIVE(cereal::JSONInputArchive) -CEREAL_REGISTER_ARCHIVE(cereal::JSONOutputArchive) - -// tie input and output archives together -CEREAL_SETUP_ARCHIVE_TRAITS(cereal::JSONInputArchive, cereal::JSONOutputArchive) - -#endif // CEREAL_ARCHIVES_JSON_HPP_ diff --git a/include/cereal/archives/portable_binary.hpp b/include/cereal/archives/portable_binary.hpp deleted file mode 100644 index 4288321..0000000 --- a/include/cereal/archives/portable_binary.hpp +++ /dev/null @@ -1,334 +0,0 @@ -/*! \file binary.hpp - \brief Binary input and output archives */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_ARCHIVES_PORTABLE_BINARY_HPP_ -#define CEREAL_ARCHIVES_PORTABLE_BINARY_HPP_ - -#include "cereal/cereal.hpp" -#include -#include - -namespace cereal -{ - namespace portable_binary_detail - { - //! Returns true if the current machine is little endian - /*! @ingroup Internal */ - inline std::uint8_t is_little_endian() - { - static std::int32_t test = 1; - return *reinterpret_cast( &test ) == 1; - } - - //! Swaps the order of bytes for some chunk of memory - /*! @param data The data as a uint8_t pointer - @tparam DataSize The true size of the data - @ingroup Internal */ - template - inline void swap_bytes( std::uint8_t * data ) - { - for( std::size_t i = 0, end = DataSize / 2; i < end; ++i ) - std::swap( data[i], data[DataSize - i - 1] ); - } - } // end namespace portable_binary_detail - - // ###################################################################### - //! An output archive designed to save data in a compact binary representation portable over different architectures - /*! This archive outputs data to a stream in an extremely compact binary - representation with as little extra metadata as possible. - - This archive will record the endianness of the data as well as the desired in/out endianness - and assuming that the user takes care of ensuring serialized types are the same size - across machines, is portable over different architectures. - - When using a binary archive and a file stream, you must use the - std::ios::binary format flag to avoid having your data altered - inadvertently. - - \warning This archive has not been thoroughly tested across different architectures. - Please report any issues, optimizations, or feature requests at - the project github. - - \ingroup Archives */ - class PortableBinaryOutputArchive : public OutputArchive - { - public: - //! A class containing various advanced options for the PortableBinaryOutput archive - class Options - { - public: - //! Represents desired endianness - enum class Endianness : std::uint8_t - { big, little }; - - //! Default options, preserve system endianness - static Options Default(){ return Options(); } - - //! Save as little endian - static Options LittleEndian(){ return Options( Endianness::little ); } - - //! Save as big endian - static Options BigEndian(){ return Options( Endianness::big ); } - - //! Specify specific options for the PortableBinaryOutputArchive - /*! @param outputEndian The desired endianness of saved (output) data */ - explicit Options( Endianness outputEndian = getEndianness() ) : - itsOutputEndianness( outputEndian ) { } - - private: - //! Gets the endianness of the system - inline static Endianness getEndianness() - { return portable_binary_detail::is_little_endian() ? Endianness::little : Endianness::big; } - - //! Checks if Options is set for little endian - inline std::uint8_t is_little_endian() const - { return itsOutputEndianness == Endianness::little; } - - friend class PortableBinaryOutputArchive; - Endianness itsOutputEndianness; - }; - - //! Construct, outputting to the provided stream - /*! @param stream The stream to output to. Should be opened with std::ios::binary flag. - @param options The PortableBinary specific options to use. See the Options struct - for the values of default parameters */ - PortableBinaryOutputArchive(std::ostream & stream, Options const & options = Options::Default()) : - OutputArchive(this), - itsStream(stream), - itsConvertEndianness( portable_binary_detail::is_little_endian() ^ options.is_little_endian() ) - { - this->operator()( options.is_little_endian() ); - } - - ~PortableBinaryOutputArchive() CEREAL_NOEXCEPT = default; - - //! Writes size bytes of data to the output stream - template inline - void saveBinary( const void * data, std::streamsize size ) - { - std::streamsize writtenSize = 0; - - if( itsConvertEndianness ) - { - for( std::streamsize i = 0; i < size; i += DataSize ) - for( std::streamsize j = 0; j < DataSize; ++j ) - writtenSize += itsStream.rdbuf()->sputn( reinterpret_cast( data ) + DataSize - j - 1 + i, 1 ); - } - else - writtenSize = itsStream.rdbuf()->sputn( reinterpret_cast( data ), size ); - - if(writtenSize != size) - throw Exception("Failed to write " + std::to_string(size) + " bytes to output stream! Wrote " + std::to_string(writtenSize)); - } - - private: - std::ostream & itsStream; - const uint8_t itsConvertEndianness; //!< If set to true, we will need to swap bytes upon saving - }; - - // ###################################################################### - //! An input archive designed to load data saved using PortableBinaryOutputArchive - /*! This archive outputs data to a stream in an extremely compact binary - representation with as little extra metadata as possible. - - This archive will load the endianness of the serialized data and - if necessary transform it to match that of the local machine. This comes - at a significant performance cost compared to non portable archives if - the transformation is necessary, and also causes a small performance hit - even if it is not necessary. - - It is recommended to use portable archives only if you know that you will - be sending binary data to machines with different endianness. - - The archive will do nothing to ensure types are the same size - that is - the responsibility of the user. - - When using a binary archive and a file stream, you must use the - std::ios::binary format flag to avoid having your data altered - inadvertently. - - \warning This archive has not been thoroughly tested across different architectures. - Please report any issues, optimizations, or feature requests at - the project github. - - \ingroup Archives */ - class PortableBinaryInputArchive : public InputArchive - { - public: - //! A class containing various advanced options for the PortableBinaryInput archive - class Options - { - public: - //! Represents desired endianness - enum class Endianness : std::uint8_t - { big, little }; - - //! Default options, preserve system endianness - static Options Default(){ return Options(); } - - //! Load into little endian - static Options LittleEndian(){ return Options( Endianness::little ); } - - //! Load into big endian - static Options BigEndian(){ return Options( Endianness::big ); } - - //! Specify specific options for the PortableBinaryInputArchive - /*! @param inputEndian The desired endianness of loaded (input) data */ - explicit Options( Endianness inputEndian = getEndianness() ) : - itsInputEndianness( inputEndian ) { } - - private: - //! Gets the endianness of the system - inline static Endianness getEndianness() - { return portable_binary_detail::is_little_endian() ? Endianness::little : Endianness::big; } - - //! Checks if Options is set for little endian - inline std::uint8_t is_little_endian() const - { return itsInputEndianness == Endianness::little; } - - friend class PortableBinaryInputArchive; - Endianness itsInputEndianness; - }; - - //! Construct, loading from the provided stream - /*! @param stream The stream to read from. Should be opened with std::ios::binary flag. - @param options The PortableBinary specific options to use. See the Options struct - for the values of default parameters */ - PortableBinaryInputArchive(std::istream & stream, Options const & options = Options::Default()) : - InputArchive(this), - itsStream(stream), - itsConvertEndianness( false ) - { - uint8_t streamLittleEndian; - this->operator()( streamLittleEndian ); - itsConvertEndianness = options.is_little_endian() ^ streamLittleEndian; - } - - ~PortableBinaryInputArchive() CEREAL_NOEXCEPT = default; - - //! Reads size bytes of data from the input stream - /*! @param data The data to save - @param size The number of bytes in the data - @tparam DataSize T The size of the actual type of the data elements being loaded */ - template inline - void loadBinary( void * const data, std::streamsize size ) - { - // load data - auto const readSize = itsStream.rdbuf()->sgetn( reinterpret_cast( data ), size ); - - if(readSize != size) - throw Exception("Failed to read " + std::to_string(size) + " bytes from input stream! Read " + std::to_string(readSize)); - - // flip bits if needed - if( itsConvertEndianness ) - { - std::uint8_t * ptr = reinterpret_cast( data ); - for( std::streamsize i = 0; i < size; i += DataSize ) - portable_binary_detail::swap_bytes( ptr + i ); - } - } - - private: - std::istream & itsStream; - uint8_t itsConvertEndianness; //!< If set to true, we will need to swap bytes upon loading - }; - - // ###################################################################### - // Common BinaryArchive serialization functions - - //! Saving for POD types to portable binary - template inline - typename std::enable_if::value, void>::type - CEREAL_SAVE_FUNCTION_NAME(PortableBinaryOutputArchive & ar, T const & t) - { - static_assert( !std::is_floating_point::value || - (std::is_floating_point::value && std::numeric_limits::is_iec559), - "Portable binary only supports IEEE 754 standardized floating point" ); - ar.template saveBinary(std::addressof(t), sizeof(t)); - } - - //! Loading for POD types from portable binary - template inline - typename std::enable_if::value, void>::type - CEREAL_LOAD_FUNCTION_NAME(PortableBinaryInputArchive & ar, T & t) - { - static_assert( !std::is_floating_point::value || - (std::is_floating_point::value && std::numeric_limits::is_iec559), - "Portable binary only supports IEEE 754 standardized floating point" ); - ar.template loadBinary(std::addressof(t), sizeof(t)); - } - - //! Serializing NVP types to portable binary - template inline - CEREAL_ARCHIVE_RESTRICT(PortableBinaryInputArchive, PortableBinaryOutputArchive) - CEREAL_SERIALIZE_FUNCTION_NAME( Archive & ar, NameValuePair & t ) - { - ar( t.value ); - } - - //! Serializing SizeTags to portable binary - template inline - CEREAL_ARCHIVE_RESTRICT(PortableBinaryInputArchive, PortableBinaryOutputArchive) - CEREAL_SERIALIZE_FUNCTION_NAME( Archive & ar, SizeTag & t ) - { - ar( t.size ); - } - - //! Saving binary data to portable binary - template inline - void CEREAL_SAVE_FUNCTION_NAME(PortableBinaryOutputArchive & ar, BinaryData const & bd) - { - typedef typename std::remove_pointer::type TT; - static_assert( !std::is_floating_point::value || - (std::is_floating_point::value && std::numeric_limits::is_iec559), - "Portable binary only supports IEEE 754 standardized floating point" ); - - ar.template saveBinary( bd.data, static_cast( bd.size ) ); - } - - //! Loading binary data from portable binary - template inline - void CEREAL_LOAD_FUNCTION_NAME(PortableBinaryInputArchive & ar, BinaryData & bd) - { - typedef typename std::remove_pointer::type TT; - static_assert( !std::is_floating_point::value || - (std::is_floating_point::value && std::numeric_limits::is_iec559), - "Portable binary only supports IEEE 754 standardized floating point" ); - - ar.template loadBinary( bd.data, static_cast( bd.size ) ); - } -} // namespace cereal - -// register archives for polymorphic support -CEREAL_REGISTER_ARCHIVE(cereal::PortableBinaryOutputArchive) -CEREAL_REGISTER_ARCHIVE(cereal::PortableBinaryInputArchive) - -// tie input and output archives together -CEREAL_SETUP_ARCHIVE_TRAITS(cereal::PortableBinaryInputArchive, cereal::PortableBinaryOutputArchive) - -#endif // CEREAL_ARCHIVES_PORTABLE_BINARY_HPP_ diff --git a/include/cereal/archives/xml.hpp b/include/cereal/archives/xml.hpp deleted file mode 100644 index 18e8f45..0000000 --- a/include/cereal/archives/xml.hpp +++ /dev/null @@ -1,956 +0,0 @@ -/*! \file xml.hpp - \brief XML input and output archives */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_ARCHIVES_XML_HPP_ -#define CEREAL_ARCHIVES_XML_HPP_ -#include "cereal/cereal.hpp" -#include "cereal/details/util.hpp" - -#include "cereal/external/rapidxml/rapidxml.hpp" -#include "cereal/external/rapidxml/rapidxml_print.hpp" -#include "cereal/external/base64.hpp" - -#include -#include -#include -#include -#include -#include -#include - -namespace cereal -{ - namespace xml_detail - { - #ifndef CEREAL_XML_STRING_VALUE - //! The default name for the root node in a cereal xml archive. - /*! You can define CEREAL_XML_STRING_VALUE to be different assuming you do so - before this file is included. */ - #define CEREAL_XML_STRING_VALUE "cereal" - #endif // CEREAL_XML_STRING_VALUE - - //! The name given to the root node in a cereal xml archive - static const char * CEREAL_XML_STRING = CEREAL_XML_STRING_VALUE; - - //! Returns true if the character is whitespace - inline bool isWhitespace( char c ) - { - return c == ' ' || c == '\t' || c == '\n' || c == '\r'; - } - } - - // ###################################################################### - //! An output archive designed to save data to XML - /*! This archive uses RapidXML to build an in memory XML tree of the - data it serializes before outputting it to its stream upon destruction. - This archive should be used in an RAII fashion, letting - the automatic destruction of the object cause the flush to its stream. - - XML archives provides a human readable output but at decreased - performance (both in time and space) compared to binary archives. - - XML benefits greatly from name-value pairs, which if present, will - name the nodes in the output. If these are not present, each level - of the output tree will be given an automatically generated delimited name. - - The precision of the output archive controls the number of decimals output - for floating point numbers and should be sufficiently large (i.e. at least 20) - if there is a desire to have binary equality between the numbers output and - those read in. In general you should expect a loss of precision when going - from floating point to text and back. - - XML archives can optionally print the type of everything they serialize, which - adds an attribute to each node. - - XML archives do not output the size information for any dynamically sized structure - and instead infer it from the number of children for a node. This means that data - can be hand edited for dynamic sized structures and will still be readable. This - is accomplished through the cereal::SizeTag object, which will also add an attribute - to its parent field. - \ingroup Archives */ - class XMLOutputArchive : public OutputArchive, public traits::TextArchive - { - public: - /*! @name Common Functionality - Common use cases for directly interacting with an XMLOutputArchive */ - //! @{ - - //! A class containing various advanced options for the XML archive - /*! Options can either be directly passed to the constructor, or chained using the - modifier functions for an interface analogous to named parameters */ - class Options - { - public: - //! Default options - static Options Default(){ return Options(); } - - //! Specify specific options for the XMLOutputArchive - /*! @param precision_ The precision used for floating point numbers - @param indent_ Whether to indent each line of XML - @param outputType_ Whether to output the type of each serialized object as an attribute - @param sizeAttributes_ Whether dynamically sized containers output the size=dynamic attribute */ - explicit Options( int precision_ = std::numeric_limits::max_digits10, - bool indent_ = true, - bool outputType_ = false, - bool sizeAttributes_ = true ) : - itsPrecision( precision_ ), - itsIndent( indent_ ), - itsOutputType( outputType_ ), - itsSizeAttributes( sizeAttributes_ ) - { } - - /*! @name Option Modifiers - An interface for setting option settings analogous to named parameters. - - @code{cpp} - cereal::XMLOutputArchive ar( myStream, - cereal::XMLOutputArchive::Options() - .indent(true) - .sizeAttributes(false) ); - @endcode - */ - //! @{ - - //! Sets the precision used for floaing point numbers - Options & precision( int value ){ itsPrecision = value; return * this; } - //! Whether to indent each line of XML - Options & indent( bool enable ){ itsIndent = enable; return *this; } - //! Whether to output the type of each serialized object as an attribute - Options & outputType( bool enable ){ itsOutputType = enable; return *this; } - //! Whether dynamically sized containers (e.g. vector) output the size=dynamic attribute - Options & sizeAttributes( bool enable ){ itsSizeAttributes = enable; return *this; } - - //! @} - - private: - friend class XMLOutputArchive; - int itsPrecision; - bool itsIndent; - bool itsOutputType; - bool itsSizeAttributes; - }; - - //! Construct, outputting to the provided stream upon destruction - /*! @param stream The stream to output to. Note that XML is only guaranteed to flush - its output to the stream upon destruction. - @param options The XML specific options to use. See the Options struct - for the values of default parameters */ - XMLOutputArchive( std::ostream & stream, Options const & options = Options::Default() ) : - OutputArchive(this), - itsStream(stream), - itsOutputType( options.itsOutputType ), - itsIndent( options.itsIndent ), - itsSizeAttributes(options.itsSizeAttributes) - { - // rapidxml will delete all allocations when xml_document is cleared - auto node = itsXML.allocate_node( rapidxml::node_declaration ); - node->append_attribute( itsXML.allocate_attribute( "version", "1.0" ) ); - node->append_attribute( itsXML.allocate_attribute( "encoding", "utf-8" ) ); - itsXML.append_node( node ); - - // allocate root node - auto root = itsXML.allocate_node( rapidxml::node_element, xml_detail::CEREAL_XML_STRING ); - itsXML.append_node( root ); - itsNodes.emplace( root ); - - // set attributes on the streams - itsStream << std::boolalpha; - itsStream.precision( options.itsPrecision ); - itsOS << std::boolalpha; - itsOS.precision( options.itsPrecision ); - } - - //! Destructor, flushes the XML - ~XMLOutputArchive() CEREAL_NOEXCEPT - { - const int flags = itsIndent ? 0x0 : rapidxml::print_no_indenting; - rapidxml::print( itsStream, itsXML, flags ); - itsXML.clear(); - } - - //! Saves some binary data, encoded as a base64 string, with an optional name - /*! This can be called directly by users and it will automatically create a child node for - the current XML node, populate it with a base64 encoded string, and optionally name - it. The node will be finished after it has been populated. */ - void saveBinaryValue( const void * data, size_t size, const char * name = nullptr ) - { - itsNodes.top().name = name; - - startNode(); - - auto base64string = base64::encode( reinterpret_cast( data ), size ); - saveValue( base64string ); - - if( itsOutputType ) - itsNodes.top().node->append_attribute( itsXML.allocate_attribute( "type", "cereal binary data" ) ); - - finishNode(); - } - - //! @} - /*! @name Internal Functionality - Functionality designed for use by those requiring control over the inner mechanisms of - the XMLOutputArchive */ - //! @{ - - //! Creates a new node that is a child of the node at the top of the stack - /*! Nodes will be given a name that has either been pre-set by a name value pair, - or generated based upon a counter unique to the parent node. If you want to - give a node a specific name, use setNextName prior to calling startNode. - - The node will then be pushed onto the node stack. */ - void startNode() - { - // generate a name for this new node - const auto nameString = itsNodes.top().getValueName(); - - // allocate strings for all of the data in the XML object - auto namePtr = itsXML.allocate_string( nameString.data(), nameString.length() + 1 ); - - // insert into the XML - auto node = itsXML.allocate_node( rapidxml::node_element, namePtr, nullptr, nameString.size() ); - itsNodes.top().node->append_node( node ); - itsNodes.emplace( node ); - } - - //! Designates the most recently added node as finished - void finishNode() - { - itsNodes.pop(); - } - - //! Sets the name for the next node created with startNode - void setNextName( const char * name ) - { - itsNodes.top().name = name; - } - - //! Saves some data, encoded as a string, into the current top level node - /*! The data will be be named with the most recent name if one exists, - otherwise it will be given some default delimited value that depends upon - the parent node */ - template inline - void saveValue( T const & value ) - { - itsOS.clear(); itsOS.seekp( 0, std::ios::beg ); - itsOS << value << std::ends; - - auto strValue = itsOS.str(); - - // itsOS.str() may contain data from previous calls after the first '\0' that was just inserted - // and this data is counted in the length call. We make sure to remove that section so that the - // whitespace validation is done properly - strValue.resize(std::strlen(strValue.c_str())); - - // If the first or last character is a whitespace, add xml:space attribute - const auto len = strValue.length(); - if ( len > 0 && ( xml_detail::isWhitespace( strValue[0] ) || xml_detail::isWhitespace( strValue[len - 1] ) ) ) - { - itsNodes.top().node->append_attribute( itsXML.allocate_attribute( "xml:space", "preserve" ) ); - } - - // allocate strings for all of the data in the XML object - auto dataPtr = itsXML.allocate_string(strValue.c_str(), strValue.length() + 1 ); - - // insert into the XML - itsNodes.top().node->append_node( itsXML.allocate_node( rapidxml::node_data, nullptr, dataPtr ) ); - } - - //! Overload for uint8_t prevents them from being serialized as characters - void saveValue( uint8_t const & value ) - { - saveValue( static_cast( value ) ); - } - - //! Overload for int8_t prevents them from being serialized as characters - void saveValue( int8_t const & value ) - { - saveValue( static_cast( value ) ); - } - - //! Causes the type to be appended as an attribute to the most recently made node if output type is set to true - template inline - void insertType() - { - if( !itsOutputType ) - return; - - // generate a name for this new node - const auto nameString = util::demangledName(); - - // allocate strings for all of the data in the XML object - auto namePtr = itsXML.allocate_string( nameString.data(), nameString.length() + 1 ); - - itsNodes.top().node->append_attribute( itsXML.allocate_attribute( "type", namePtr ) ); - } - - //! Appends an attribute to the current top level node - void appendAttribute( const char * name, const char * value ) - { - auto namePtr = itsXML.allocate_string( name ); - auto valuePtr = itsXML.allocate_string( value ); - itsNodes.top().node->append_attribute( itsXML.allocate_attribute( namePtr, valuePtr ) ); - } - - bool hasSizeAttributes() const { return itsSizeAttributes; } - - protected: - //! A struct that contains metadata about a node - struct NodeInfo - { - NodeInfo( rapidxml::xml_node<> * n = nullptr, - const char * nm = nullptr ) : - node( n ), - counter( 0 ), - name( nm ) - { } - - rapidxml::xml_node<> * node; //!< A pointer to this node - size_t counter; //!< The counter for naming child nodes - const char * name; //!< The name for the next child node - - //! Gets the name for the next child node created from this node - /*! The name will be automatically generated using the counter if - a name has not been previously set. If a name has been previously - set, that name will be returned only once */ - std::string getValueName() - { - if( name ) - { - auto n = name; - name = nullptr; - return {n}; - } - else - return "value" + std::to_string( counter++ ) + "\0"; - } - }; // NodeInfo - - //! @} - - private: - std::ostream & itsStream; //!< The output stream - rapidxml::xml_document<> itsXML; //!< The XML document - std::stack itsNodes; //!< A stack of nodes added to the document - std::ostringstream itsOS; //!< Used to format strings internally - bool itsOutputType; //!< Controls whether type information is printed - bool itsIndent; //!< Controls whether indenting is used - bool itsSizeAttributes; //!< Controls whether lists have a size attribute - }; // XMLOutputArchive - - // ###################################################################### - //! An output archive designed to load data from XML - /*! This archive uses RapidXML to build an in memory XML tree of the - data in the stream it is given before loading any types serialized. - - As with the output XML archive, the preferred way to use this archive is in - an RAII fashion, ensuring its destruction after all data has been read. - - Input XML should have been produced by the XMLOutputArchive. Data can - only be added to dynamically sized containers - the input archive will - determine their size by looking at the number of child nodes. Data that - did not originate from an XMLOutputArchive is not officially supported, - but may be possible to use if properly formatted. - - The XMLInputArchive does not require that nodes are loaded in the same - order they were saved by XMLOutputArchive. Using name value pairs (NVPs), - it is possible to load in an out of order fashion or otherwise skip/select - specific nodes to load. - - The default behavior of the input archive is to read sequentially starting - with the first node and exploring its children. When a given NVP does - not match the read in name for a node, the archive will search for that - node at the current level and load it if it exists. After loading an out of - order node, the archive will then proceed back to loading sequentially from - its new position. - - Consider this simple example where loading of some data is skipped: - - @code{cpp} - // imagine the input file has someData(1-9) saved in order at the top level node - ar( someData1, someData2, someData3 ); // XML loads in the order it sees in the file - ar( cereal::make_nvp( "hello", someData6 ) ); // NVP given does not - // match expected NVP name, so we search - // for the given NVP and load that value - ar( someData7, someData8, someData9 ); // with no NVP given, loading resumes at its - // current location, proceeding sequentially - @endcode - - \ingroup Archives */ - class XMLInputArchive : public InputArchive, public traits::TextArchive - { - public: - /*! @name Common Functionality - Common use cases for directly interacting with an XMLInputArchive */ - //! @{ - - //! Construct, reading in from the provided stream - /*! Reads in an entire XML document from some stream and parses it as soon - as serialization starts - - @param stream The stream to read from. Can be a stringstream or a file. */ - XMLInputArchive( std::istream & stream ) : - InputArchive( this ), - itsData( std::istreambuf_iterator( stream ), std::istreambuf_iterator() ) - { - try - { - itsData.push_back('\0'); // rapidxml will do terrible things without the data being null terminated - itsXML.parse( reinterpret_cast( itsData.data() ) ); - } - catch( rapidxml::parse_error const & ) - { - //std::cerr << "-----Original-----" << std::endl; - //stream.seekg(0); - //std::cout << std::string( std::istreambuf_iterator( stream ), std::istreambuf_iterator() ) << std::endl; - - //std::cerr << "-----Error-----" << std::endl; - //std::cerr << e.what() << std::endl; - //std::cerr << e.where() << std::endl; - throw Exception("XML Parsing failed - likely due to invalid characters or invalid naming"); - } - - // Parse the root - auto root = itsXML.first_node( xml_detail::CEREAL_XML_STRING ); - if( root == nullptr ) - throw Exception("Could not detect cereal root node - likely due to empty or invalid input"); - else - itsNodes.emplace( root ); - } - - ~XMLInputArchive() CEREAL_NOEXCEPT = default; - - //! Loads some binary data, encoded as a base64 string, optionally specified by some name - /*! This will automatically start and finish a node to load the data, and can be called directly by - users. - - Note that this follows the same ordering rules specified in the class description in regards - to loading in/out of order */ - void loadBinaryValue( void * data, size_t size, const char * name = nullptr ) - { - setNextName( name ); - startNode(); - - std::string encoded; - loadValue( encoded ); - - auto decoded = base64::decode( encoded ); - - if( size != decoded.size() ) - throw Exception("Decoded binary data size does not match specified size"); - - std::memcpy( data, decoded.data(), decoded.size() ); - - finishNode(); - } - - //! @} - /*! @name Internal Functionality - Functionality designed for use by those requiring control over the inner mechanisms of - the XMLInputArchive */ - //! @{ - - //! Prepares to start reading the next node - /*! This places the next node to be parsed onto the nodes stack. - - By default our strategy is to start with the document root node and then - recursively iterate through all children in the order they show up in the document. - We don't need to know NVPs do to this; we'll just blindly load in the order things appear in. - - We check to see if the specified NVP matches what the next automatically loaded node is. If they - match, we just continue as normal, going in order. If they don't match, we attempt to find a node - named after the NVP that is being loaded. If that NVP does not exist, we throw an exception. */ - void startNode() - { - auto next = itsNodes.top().child; // By default we would move to the next child node - auto const expectedName = itsNodes.top().name; // this is the expected name from the NVP, if provided - - // If we were given an NVP name, look for it in the current level of the document. - // We only need to do this if either we have exhausted the siblings of the current level or - // the NVP name does not match the name of the node we would normally read next - if( expectedName && ( next == nullptr || std::strcmp( next->name(), expectedName ) != 0 ) ) - { - next = itsNodes.top().search( expectedName ); - - if( next == nullptr ) - throw Exception("XML Parsing failed - provided NVP (" + std::string(expectedName) + ") not found"); - } - - itsNodes.emplace( next ); - } - - //! Finishes reading the current node - void finishNode() - { - // remove current - itsNodes.pop(); - - // advance parent - itsNodes.top().advance(); - - // Reset name - itsNodes.top().name = nullptr; - } - - //! Retrieves the current node name - //! will return @c nullptr if the node does not have a name - const char * getNodeName() const - { - return itsNodes.top().getChildName(); - } - - //! Sets the name for the next node created with startNode - void setNextName( const char * name ) - { - itsNodes.top().name = name; - } - - //! Loads a bool from the current top node - template ::value, - std::is_same::value> = traits::sfinae> inline - void loadValue( T & value ) - { - std::istringstream is( itsNodes.top().node->value() ); - is.setf( std::ios::boolalpha ); - is >> value; - } - - //! Loads a char (signed or unsigned) from the current top node - template ::value, - !std::is_same::value, - sizeof(T) == sizeof(char)> = traits::sfinae> inline - void loadValue( T & value ) - { - value = *reinterpret_cast( itsNodes.top().node->value() ); - } - - //! Load an int8_t from the current top node (ensures we parse entire number) - void loadValue( int8_t & value ) - { - int32_t val; loadValue( val ); value = static_cast( val ); - } - - //! Load a uint8_t from the current top node (ensures we parse entire number) - void loadValue( uint8_t & value ) - { - uint32_t val; loadValue( val ); value = static_cast( val ); - } - - //! Loads a type best represented as an unsigned long from the current top node - template ::value, - !std::is_same::value, - !std::is_same::value, - !std::is_same::value, - sizeof(T) < sizeof(long long)> = traits::sfinae> inline - void loadValue( T & value ) - { - value = static_cast( std::stoul( itsNodes.top().node->value() ) ); - } - - //! Loads a type best represented as an unsigned long long from the current top node - template ::value, - !std::is_same::value, - sizeof(T) >= sizeof(long long)> = traits::sfinae> inline - void loadValue( T & value ) - { - value = static_cast( std::stoull( itsNodes.top().node->value() ) ); - } - - //! Loads a type best represented as an int from the current top node - template ::value, - !std::is_same::value, - sizeof(T) <= sizeof(int)> = traits::sfinae> inline - void loadValue( T & value ) - { - value = static_cast( std::stoi( itsNodes.top().node->value() ) ); - } - - //! Loads a type best represented as a long from the current top node - template ::value, - (sizeof(T) > sizeof(int)), - sizeof(T) <= sizeof(long)> = traits::sfinae> inline - void loadValue( T & value ) - { - value = static_cast( std::stol( itsNodes.top().node->value() ) ); - } - - //! Loads a type best represented as a long long from the current top node - template ::value, - (sizeof(T) > sizeof(long)), - sizeof(T) <= sizeof(long long)> = traits::sfinae> inline - void loadValue( T & value ) - { - value = static_cast( std::stoll( itsNodes.top().node->value() ) ); - } - - //! Loads a type best represented as a float from the current top node - void loadValue( float & value ) - { - try - { - value = std::stof( itsNodes.top().node->value() ); - } - catch( std::out_of_range const & ) - { - // special case for denormalized values - std::istringstream is( itsNodes.top().node->value() ); - is >> value; - if( std::fpclassify( value ) != FP_SUBNORMAL ) - throw; - } - } - - //! Loads a type best represented as a double from the current top node - void loadValue( double & value ) - { - try - { - value = std::stod( itsNodes.top().node->value() ); - } - catch( std::out_of_range const & ) - { - // special case for denormalized values - std::istringstream is( itsNodes.top().node->value() ); - is >> value; - if( std::fpclassify( value ) != FP_SUBNORMAL ) - throw; - } - } - - //! Loads a type best represented as a long double from the current top node - void loadValue( long double & value ) - { - try - { - value = std::stold( itsNodes.top().node->value() ); - } - catch( std::out_of_range const & ) - { - // special case for denormalized values - std::istringstream is( itsNodes.top().node->value() ); - is >> value; - if( std::fpclassify( value ) != FP_SUBNORMAL ) - throw; - } - } - - //! Loads a string from the current node from the current top node - template inline - void loadValue( std::basic_string & str ) - { - std::basic_istringstream is( itsNodes.top().node->value() ); - - str.assign( std::istreambuf_iterator( is ), - std::istreambuf_iterator() ); - } - - //! Loads the size of the current top node - template inline - void loadSize( T & value ) - { - value = getNumChildren( itsNodes.top().node ); - } - - protected: - //! Gets the number of children (usually interpreted as size) for the specified node - static size_t getNumChildren( rapidxml::xml_node<> * node ) - { - size_t size = 0; - node = node->first_node(); // get first child - - while( node != nullptr ) - { - ++size; - node = node->next_sibling(); - } - - return size; - } - - //! A struct that contains metadata about a node - /*! Keeps track of some top level node, its number of - remaining children, and the current active child node */ - struct NodeInfo - { - NodeInfo( rapidxml::xml_node<> * n = nullptr ) : - node( n ), - child( n->first_node() ), - size( XMLInputArchive::getNumChildren( n ) ), - name( nullptr ) - { } - - //! Advances to the next sibling node of the child - /*! If this is the last sibling child will be null after calling */ - void advance() - { - if( size > 0 ) - { - --size; - child = child->next_sibling(); - } - } - - //! Searches for a child with the given name in this node - /*! @param searchName The name to search for (must be null terminated) - @return The node if found, nullptr otherwise */ - rapidxml::xml_node<> * search( const char * searchName ) - { - if( searchName ) - { - size_t new_size = XMLInputArchive::getNumChildren( node ); - const size_t name_size = rapidxml::internal::measure( searchName ); - - for( auto new_child = node->first_node(); new_child != nullptr; new_child = new_child->next_sibling() ) - { - if( rapidxml::internal::compare( new_child->name(), new_child->name_size(), searchName, name_size, true ) ) - { - size = new_size; - child = new_child; - - return new_child; - } - --new_size; - } - } - - return nullptr; - } - - //! Returns the actual name of the next child node, if it exists - const char * getChildName() const - { - return child ? child->name() : nullptr; - } - - rapidxml::xml_node<> * node; //!< A pointer to this node - rapidxml::xml_node<> * child; //!< A pointer to its current child - size_t size; //!< The remaining number of children for this node - const char * name; //!< The NVP name for next child node - }; // NodeInfo - - //! @} - - private: - std::vector itsData; //!< The raw data loaded - rapidxml::xml_document<> itsXML; //!< The XML document - std::stack itsNodes; //!< A stack of nodes read from the document - }; - - // ###################################################################### - // XMLArchive prologue and epilogue functions - // ###################################################################### - - // ###################################################################### - //! Prologue for NVPs for XML output archives - /*! NVPs do not start or finish nodes - they just set up the names */ - template inline - void prologue( XMLOutputArchive &, NameValuePair const & ) - { } - - //! Prologue for NVPs for XML input archives - template inline - void prologue( XMLInputArchive &, NameValuePair const & ) - { } - - // ###################################################################### - //! Epilogue for NVPs for XML output archives - /*! NVPs do not start or finish nodes - they just set up the names */ - template inline - void epilogue( XMLOutputArchive &, NameValuePair const & ) - { } - - //! Epilogue for NVPs for XML input archives - template inline - void epilogue( XMLInputArchive &, NameValuePair const & ) - { } - - // ###################################################################### - //! Prologue for deferred data for XML archives - /*! Do nothing for the defer wrapper */ - template inline - void prologue( XMLOutputArchive &, DeferredData const & ) - { } - - //! Prologue for deferred data for XML archives - template inline - void prologue( XMLInputArchive &, DeferredData const & ) - { } - - // ###################################################################### - //! Epilogue for deferred for XML archives - /*! NVPs do not start or finish nodes - they just set up the names */ - template inline - void epilogue( XMLOutputArchive &, DeferredData const & ) - { } - - //! Epilogue for deferred for XML archives - /*! Do nothing for the defer wrapper */ - template inline - void epilogue( XMLInputArchive &, DeferredData const & ) - { } - - // ###################################################################### - //! Prologue for SizeTags for XML output archives - /*! SizeTags do not start or finish nodes */ - template inline - void prologue( XMLOutputArchive & ar, SizeTag const & ) - { - if (ar.hasSizeAttributes()) - { - ar.appendAttribute("size", "dynamic"); - } - } - - template inline - void prologue( XMLInputArchive &, SizeTag const & ) - { } - - //! Epilogue for SizeTags for XML output archives - /*! SizeTags do not start or finish nodes */ - template inline - void epilogue( XMLOutputArchive &, SizeTag const & ) - { } - - template inline - void epilogue( XMLInputArchive &, SizeTag const & ) - { } - - // ###################################################################### - //! Prologue for all other types for XML output archives (except minimal types) - /*! Starts a new node, named either automatically or by some NVP, - that may be given data by the type about to be archived - - Minimal types do not start or end nodes */ - template ::value || - traits::has_minimal_output_serialization::value> = traits::sfinae> inline - void prologue( XMLOutputArchive & ar, T const & ) - { - ar.startNode(); - ar.insertType(); - } - - //! Prologue for all other types for XML input archives (except minimal types) - template ::value || - traits::has_minimal_input_serialization::value> = traits::sfinae> inline - void prologue( XMLInputArchive & ar, T const & ) - { - ar.startNode(); - } - - // ###################################################################### - //! Epilogue for all other types other for XML output archives (except minimal types) - /*! Finishes the node created in the prologue - - Minimal types do not start or end nodes */ - template ::value || - traits::has_minimal_output_serialization::value> = traits::sfinae> inline - void epilogue( XMLOutputArchive & ar, T const & ) - { - ar.finishNode(); - } - - //! Epilogue for all other types other for XML output archives (except minimal types) - template ::value || - traits::has_minimal_input_serialization::value> = traits::sfinae> inline - void epilogue( XMLInputArchive & ar, T const & ) - { - ar.finishNode(); - } - - // ###################################################################### - // Common XMLArchive serialization functions - // ###################################################################### - - //! Saving NVP types to XML - template inline - void CEREAL_SAVE_FUNCTION_NAME( XMLOutputArchive & ar, NameValuePair const & t ) - { - ar.setNextName( t.name ); - ar( t.value ); - } - - //! Loading NVP types from XML - template inline - void CEREAL_LOAD_FUNCTION_NAME( XMLInputArchive & ar, NameValuePair & t ) - { - ar.setNextName( t.name ); - ar( t.value ); - } - - // ###################################################################### - //! Saving SizeTags to XML - template inline - void CEREAL_SAVE_FUNCTION_NAME( XMLOutputArchive &, SizeTag const & ) - { } - - //! Loading SizeTags from XML - template inline - void CEREAL_LOAD_FUNCTION_NAME( XMLInputArchive & ar, SizeTag & st ) - { - ar.loadSize( st.size ); - } - - // ###################################################################### - //! Saving for POD types to xml - template ::value> = traits::sfinae> inline - void CEREAL_SAVE_FUNCTION_NAME(XMLOutputArchive & ar, T const & t) - { - ar.saveValue( t ); - } - - //! Loading for POD types from xml - template ::value> = traits::sfinae> inline - void CEREAL_LOAD_FUNCTION_NAME(XMLInputArchive & ar, T & t) - { - ar.loadValue( t ); - } - - // ###################################################################### - //! saving string to xml - template inline - void CEREAL_SAVE_FUNCTION_NAME(XMLOutputArchive & ar, std::basic_string const & str) - { - ar.saveValue( str ); - } - - //! loading string from xml - template inline - void CEREAL_LOAD_FUNCTION_NAME(XMLInputArchive & ar, std::basic_string & str) - { - ar.loadValue( str ); - } -} // namespace cereal - -// register archives for polymorphic support -CEREAL_REGISTER_ARCHIVE(cereal::XMLOutputArchive) -CEREAL_REGISTER_ARCHIVE(cereal::XMLInputArchive) - -// tie input and output archives together -CEREAL_SETUP_ARCHIVE_TRAITS(cereal::XMLInputArchive, cereal::XMLOutputArchive) - -#endif // CEREAL_ARCHIVES_XML_HPP_ diff --git a/include/cereal/cereal.hpp b/include/cereal/cereal.hpp deleted file mode 100644 index 764380b..0000000 --- a/include/cereal/cereal.hpp +++ /dev/null @@ -1,1120 +0,0 @@ -/*! \file cereal.hpp - \brief Main cereal functionality */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_CEREAL_HPP_ -#define CEREAL_CEREAL_HPP_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "cereal/macros.hpp" -#include "cereal/details/traits.hpp" -#include "cereal/details/helpers.hpp" -#include "cereal/types/base_class.hpp" - -namespace cereal -{ - // ###################################################################### - //! Creates a name value pair - /*! @relates NameValuePair - @ingroup Utility */ - template inline - NameValuePair make_nvp( std::string const & name, T && value ) - { - return {name.c_str(), std::forward(value)}; - } - - //! Creates a name value pair - /*! @relates NameValuePair - @ingroup Utility */ - template inline - NameValuePair make_nvp( const char * name, T && value ) - { - return {name, std::forward(value)}; - } - - //! Creates a name value pair for the variable T with the same name as the variable - /*! @relates NameValuePair - @ingroup Utility */ - #define CEREAL_NVP(T) ::cereal::make_nvp(#T, T) - - // ###################################################################### - //! Convenience function to create binary data for both const and non const pointers - /*! @param data Pointer to beginning of the data - @param size The size in bytes of the data - @relates BinaryData - @ingroup Utility */ - template inline - BinaryData binary_data( T && data, size_t size ) - { - return {std::forward(data), size}; - } - - // ###################################################################### - //! Creates a size tag from some variable. - /*! Will normally be used to serialize size (e.g. size()) information for - variable size containers. If you have a variable sized container, - the very first thing it serializes should be its size, wrapped in - a SizeTag. - - @relates SizeTag - @ingroup Utility */ - template inline - SizeTag make_size_tag( T && sz ) - { - return {std::forward(sz)}; - } - - // ###################################################################### - //! Marks data for deferred serialization - /*! cereal performs a recursive depth-first traversal of data it serializes. When - serializing smart pointers to large, nested, or cyclical data structures, it - is possible to encounter a stack overflow from excessive recursion when following - a chain of pointers. - - Deferment can help in these situations if the data can be serialized separately from - the pointers used to traverse the structure. For example, a graph structure can have its - nodes serialized before its edges: - - @code{.cpp} - struct MyEdge - { - std::shared_ptr connection; - int some_value; - - template - void serialize(Archive & archive) - { - // when we serialize an edge, we'll defer serializing the associated node - archive( cereal::defer( connection ), - some_value ); - } - }; - - struct MyGraphStructure - { - std::vector edges; - std::vector nodes; - - template - void serialize(Archive & archive) - { - // because of the deferment, we ensure all nodes are fully serialized - // before any connection pointers to those nodes are serialized - archive( edges, nodes ); - - // we have to explicitly inform the archive when it is safe to serialize - // the deferred data - archive.serializeDeferments(); - } - }; - @endcode - - @relates DeferredData - @ingroup Utility */ - template inline - DeferredData defer( T && value ) - { - return {std::forward(value)}; - } - - // ###################################################################### - //! Called before a type is serialized to set up any special archive state - //! for processing some type - /*! If designing a serializer that needs to set up any kind of special - state or output extra information for a type, specialize this function - for the archive type and the types that require the extra information. - @ingroup Internal */ - template inline - void prologue( Archive & /* archive */, T const & /* data */) - { } - - //! Called after a type is serialized to tear down any special archive state - //! for processing some type - /*! @ingroup Internal */ - template inline - void epilogue( Archive & /* archive */, T const & /* data */) - { } - - // ###################################################################### - //! Special flags for archives - /*! AllowEmptyClassElision - This allows for empty classes to be serialized even if they do not provide - a serialization function. Classes with no data members are considered to be - empty. Be warned that if this is enabled and you attempt to serialize an - empty class with improperly formed serialize or load/save functions, no - static error will occur - the error will propogate silently and your - intended serialization functions may not be called. You can manually - ensure that your classes that have custom serialization are correct - by using the traits is_output_serializable and is_input_serializable - in cereal/details/traits.hpp. - @ingroup Internal */ - enum Flags { AllowEmptyClassElision = 1 }; - - // ###################################################################### - //! Registers a specific Archive type with cereal - /*! This registration should be done once per archive. A good place to - put this is immediately following the definition of your archive. - Archive registration is only strictly necessary if you wish to - support pointers to polymorphic data types. All archives that - come with cereal are already registered. - @ingroup Internal */ - #define CEREAL_REGISTER_ARCHIVE(Archive) \ - namespace cereal { namespace detail { \ - template \ - typename polymorphic_serialization_support::type \ - instantiate_polymorphic_binding( T*, Archive*, BindingTag, adl_tag ); \ - } } /* end namespaces */ - - //! Helper macro to omit unused warning - #if defined(__GNUC__) - // GCC / clang don't want the function - #define CEREAL_UNUSED_FUNCTION - #else - #define CEREAL_UNUSED_FUNCTION static void unused() { (void)version; } - #endif - - // ###################################################################### - //! Defines a class version for some type - /*! Versioning information is optional and adds some small amount of - overhead to serialization. This overhead will occur both in terms of - space in the archive (the version information for each class will be - stored exactly once) as well as runtime (versioned serialization functions - must check to see if they need to load or store version information). - - Versioning is useful if you plan on fundamentally changing the way some - type is serialized in the future. Versioned serialization functions - cannot be used to load non-versioned data. - - By default, all types have an assumed version value of zero. By - using this macro, you may change the version number associated with - some type. cereal will then use this value as a second parameter - to your serialization functions. - - The interface for the serialization functions is nearly identical - to non-versioned serialization with the addition of a second parameter, - const std::uint32_t version, which will be supplied with the correct - version number. Serializing the version number on a save happens - automatically. - - Versioning cannot be mixed with non-versioned serialization functions. - Having both types will result result in a compile time error. Data - serialized without versioning cannot be loaded by a serialization - function with added versioning support. - - Example interface for versioning on a non-member serialize function: - - @code{cpp} - CEREAL_CLASS_VERSION( Mytype, 77 ); // register class version - - template - void serialize( Archive & ar, Mytype & t, const std::uint32_t version ) - { - // When performing a load, the version associated with the class - // is whatever it was when that data was originally serialized - // - // When we save, we'll use the version that is defined in the macro - - if( version >= some_number ) - // do this - else - // do that - } - @endcode - - Interfaces for other forms of serialization functions is similar. This - macro should be placed at global scope. - @ingroup Utility */ - - //! On C++17, define the StaticObject as inline to merge the definitions across TUs - //! This prevents multiple definition errors when this macro appears in a header file - //! included in multiple TUs. - #ifdef CEREAL_HAS_CPP17 - #define CEREAL_CLASS_VERSION(TYPE, VERSION_NUMBER) \ - namespace cereal { namespace detail { \ - template <> struct Version \ - { \ - static std::uint32_t registerVersion() \ - { \ - ::cereal::detail::StaticObject::getInstance().mapping.emplace( \ - std::type_index(typeid(TYPE)).hash_code(), VERSION_NUMBER ); \ - return VERSION_NUMBER; \ - } \ - static inline const std::uint32_t version = registerVersion(); \ - CEREAL_UNUSED_FUNCTION \ - }; /* end Version */ \ - } } // end namespaces - #else - #define CEREAL_CLASS_VERSION(TYPE, VERSION_NUMBER) \ - namespace cereal { namespace detail { \ - template <> struct Version \ - { \ - static const std::uint32_t version; \ - static std::uint32_t registerVersion() \ - { \ - ::cereal::detail::StaticObject::getInstance().mapping.emplace( \ - std::type_index(typeid(TYPE)).hash_code(), VERSION_NUMBER ); \ - return VERSION_NUMBER; \ - } \ - CEREAL_UNUSED_FUNCTION \ - }; /* end Version */ \ - const std::uint32_t Version::version = \ - Version::registerVersion(); \ - } } // end namespaces - - #endif - - // ###################################################################### - //! The base output archive class - /*! This is the base output archive for all output archives. If you create - a custom archive class, it should derive from this, passing itself as - a template parameter for the ArchiveType. - - The base class provides all of the functionality necessary to - properly forward data to the correct serialization functions. - - Individual archives should use a combination of prologue and - epilogue functions together with specializations of serialize, save, - and load to alter the functionality of their serialization. - - @tparam ArchiveType The archive type that derives from OutputArchive - @tparam Flags Flags to control advanced functionality. See the Flags - enum for more information. - @ingroup Internal */ - template - class OutputArchive : public detail::OutputArchiveBase - { - public: - //! Construct the output archive - /*! @param derived A pointer to the derived ArchiveType (pass this from the derived archive) */ - OutputArchive(ArchiveType * const derived) : self(derived), itsCurrentPointerId(1), itsCurrentPolymorphicTypeId(1) - { } - - OutputArchive & operator=( OutputArchive const & ) = delete; - - //! Serializes all passed in data - /*! This is the primary interface for serializing data with an archive */ - template inline - ArchiveType & operator()( Types && ... args ) - { - self->process( std::forward( args )... ); - return *self; - } - - //! Serializes any data marked for deferment using defer - /*! This will cause any data wrapped in DeferredData to be immediately serialized */ - void serializeDeferments() - { - for( auto & deferment : itsDeferments ) - deferment(); - } - - /*! @name Boost Transition Layer - Functionality that mirrors the syntax for Boost. This is useful if you are transitioning - a large project from Boost to cereal. The preferred interface for cereal is using operator(). */ - //! @{ - - //! Indicates this archive is not intended for loading - /*! This ensures compatibility with boost archive types. If you are transitioning - from boost, you can check this value within a member or external serialize function - (i.e., Archive::is_loading::value) to disable behavior specific to loading, until - you can transition to split save/load or save_minimal/load_minimal functions */ - using is_loading = std::false_type; - - //! Indicates this archive is intended for saving - /*! This ensures compatibility with boost archive types. If you are transitioning - from boost, you can check this value within a member or external serialize function - (i.e., Archive::is_saving::value) to enable behavior specific to loading, until - you can transition to split save/load or save_minimal/load_minimal functions */ - using is_saving = std::true_type; - - //! Serializes passed in data - /*! This is a boost compatability layer and is not the preferred way of using - cereal. If you are transitioning from boost, use this until you can - transition to the operator() overload */ - template inline - ArchiveType & operator&( T && arg ) - { - self->process( std::forward( arg ) ); - return *self; - } - - //! Serializes passed in data - /*! This is a boost compatability layer and is not the preferred way of using - cereal. If you are transitioning from boost, use this until you can - transition to the operator() overload */ - template inline - ArchiveType & operator<<( T && arg ) - { - self->process( std::forward( arg ) ); - return *self; - } - - //! @} - - //! Registers a shared pointer with the archive - /*! This function is used to track shared pointer targets to prevent - unnecessary saves from taking place if multiple shared pointers - point to the same data. - - @internal - @param sharedPointer The shared pointer itself (the adress is taked via get()). - The archive takes a copy to prevent the memory location to be freed - as long as the address is used as id. This is needed to prevent CVE-2020-11105. - @return A key that uniquely identifies the pointer */ - inline std::uint32_t registerSharedPointer(const std::shared_ptr& sharedPointer) - { - void const * addr = sharedPointer.get(); - - // Handle null pointers by just returning 0 - if(addr == 0) return 0; - itsSharedPointerStorage.push_back(sharedPointer); - - auto id = itsSharedPointerMap.find( addr ); - if( id == itsSharedPointerMap.end() ) - { - auto ptrId = itsCurrentPointerId++; - itsSharedPointerMap.insert( {addr, ptrId} ); - return ptrId | detail::msb_32bit; // mask MSB to be 1 - } - else - return id->second; - } - - //! Registers a polymorphic type name with the archive - /*! This function is used to track polymorphic types to prevent - unnecessary saves of identifying strings used by the polymorphic - support functionality. - - @internal - @param name The name to associate with a polymorphic type - @return A key that uniquely identifies the polymorphic type name */ - inline std::uint32_t registerPolymorphicType( char const * name ) - { - auto id = itsPolymorphicTypeMap.find( name ); - if( id == itsPolymorphicTypeMap.end() ) - { - auto polyId = itsCurrentPolymorphicTypeId++; - itsPolymorphicTypeMap.insert( {name, polyId} ); - return polyId | detail::msb_32bit; // mask MSB to be 1 - } - else - return id->second; - } - - private: - //! Serializes data after calling prologue, then calls epilogue - template inline - void process( T && head ) - { - prologue( *self, head ); - self->processImpl( head ); - epilogue( *self, head ); - } - - //! Unwinds to process all data - template inline - void process( T && head, Other && ... tail ) - { - self->process( std::forward( head ) ); - self->process( std::forward( tail )... ); - } - - //! Serialization of a virtual_base_class wrapper - /*! \sa virtual_base_class */ - template inline - ArchiveType & processImpl(virtual_base_class const & b) - { - traits::detail::base_class_id id(b.base_ptr); - if(itsBaseClassSet.count(id) == 0) - { - itsBaseClassSet.insert(id); - self->processImpl( *b.base_ptr ); - } - return *self; - } - - //! Serialization of a base_class wrapper - /*! \sa base_class */ - template inline - ArchiveType & processImpl(base_class const & b) - { - self->processImpl( *b.base_ptr ); - return *self; - } - - std::vector> itsDeferments; - - template inline - ArchiveType & processImpl(DeferredData const & d) - { - std::function deferment( [this, d](){ self->process( d.value ); } ); - itsDeferments.emplace_back( std::move(deferment) ); - - return *self; - } - - //! Helper macro that expands the requirements for activating an overload - /*! Requirements: - Has the requested serialization function - Does not have version and unversioned at the same time - Is output serializable AND - is specialized for this type of function OR - has no specialization at all */ - #define PROCESS_IF(name) \ - traits::EnableIf::value, \ - !traits::has_invalid_output_versioning::value, \ - (traits::is_output_serializable::value && \ - (traits::is_specialized_##name::value || \ - !traits::is_specialized::value))> = traits::sfinae - - //! Member serialization - template inline - ArchiveType & processImpl(T const & t) - { - access::member_serialize(*self, const_cast(t)); - return *self; - } - - //! Non member serialization - template inline - ArchiveType & processImpl(T const & t) - { - CEREAL_SERIALIZE_FUNCTION_NAME(*self, const_cast(t)); - return *self; - } - - //! Member split (save) - template inline - ArchiveType & processImpl(T const & t) - { - access::member_save(*self, t); - return *self; - } - - //! Non member split (save) - template inline - ArchiveType & processImpl(T const & t) - { - CEREAL_SAVE_FUNCTION_NAME(*self, t); - return *self; - } - - //! Member split (save_minimal) - template inline - ArchiveType & processImpl(T const & t) - { - self->process( access::member_save_minimal(*self, t) ); - return *self; - } - - //! Non member split (save_minimal) - template inline - ArchiveType & processImpl(T const & t) - { - self->process( CEREAL_SAVE_MINIMAL_FUNCTION_NAME(*self, t) ); - return *self; - } - - //! Empty class specialization - template ::value, - std::is_empty::value> = traits::sfinae> inline - ArchiveType & processImpl(T const &) - { - return *self; - } - - //! No matching serialization - /*! Invalid if we have invalid output versioning or - we are not output serializable, and either - don't allow empty class ellision or allow it but are not serializing an empty class */ - template ::value || - (!traits::is_output_serializable::value && - (!(Flags & AllowEmptyClassElision) || ((Flags & AllowEmptyClassElision) && !std::is_empty::value)))> = traits::sfinae> inline - ArchiveType & processImpl(T const &) - { - static_assert(traits::detail::count_output_serializers::value != 0, - "cereal could not find any output serialization functions for the provided type and archive combination. \n\n " - "Types must either have a serialize function, load/save pair, or load_minimal/save_minimal pair (you may not mix these). \n " - "Serialize functions generally have the following signature: \n\n " - "template \n " - " void serialize(Archive & ar) \n " - " { \n " - " ar( member1, member2, member3 ); \n " - " } \n\n " ); - - static_assert(traits::detail::count_output_serializers::value < 2, - "cereal found more than one compatible output serialization function for the provided type and archive combination. \n\n " - "Types must either have a serialize function, load/save pair, or load_minimal/save_minimal pair (you may not mix these). \n " - "Use specialization (see access.hpp) if you need to disambiguate between serialize vs load/save functions. \n " - "Note that serialization functions can be inherited which may lead to the aforementioned ambiguities. \n " - "In addition, you may not mix versioned with non-versioned serialization functions. \n\n "); - - return *self; - } - - //! Registers a class version with the archive and serializes it if necessary - /*! If this is the first time this class has been serialized, we will record its - version number and serialize that. - - @tparam T The type of the class being serialized */ - template inline - std::uint32_t registerClassVersion() - { - static const auto hash = std::type_index(typeid(T)).hash_code(); - const auto insertResult = itsVersionedTypes.insert( hash ); - const auto lock = detail::StaticObject::lock(); - const auto version = - detail::StaticObject::getInstance().find( hash, detail::Version::version ); - - if( insertResult.second ) // insertion took place, serialize the version number - process( make_nvp("cereal_class_version", version) ); - - return version; - } - - //! Member serialization - /*! Versioning implementation */ - template inline - ArchiveType & processImpl(T const & t) - { - access::member_serialize(*self, const_cast(t), registerClassVersion()); - return *self; - } - - //! Non member serialization - /*! Versioning implementation */ - template inline - ArchiveType & processImpl(T const & t) - { - CEREAL_SERIALIZE_FUNCTION_NAME(*self, const_cast(t), registerClassVersion()); - return *self; - } - - //! Member split (save) - /*! Versioning implementation */ - template inline - ArchiveType & processImpl(T const & t) - { - access::member_save(*self, t, registerClassVersion()); - return *self; - } - - //! Non member split (save) - /*! Versioning implementation */ - template inline - ArchiveType & processImpl(T const & t) - { - CEREAL_SAVE_FUNCTION_NAME(*self, t, registerClassVersion()); - return *self; - } - - //! Member split (save_minimal) - /*! Versioning implementation */ - template inline - ArchiveType & processImpl(T const & t) - { - self->process( access::member_save_minimal(*self, t, registerClassVersion()) ); - return *self; - } - - //! Non member split (save_minimal) - /*! Versioning implementation */ - template inline - ArchiveType & processImpl(T const & t) - { - self->process( CEREAL_SAVE_MINIMAL_FUNCTION_NAME(*self, t, registerClassVersion()) ); - return *self; - } - - #undef PROCESS_IF - - private: - ArchiveType * const self; - - //! A set of all base classes that have been serialized - std::unordered_set itsBaseClassSet; - - //! Maps from addresses to pointer ids - std::unordered_map itsSharedPointerMap; - - //! Copy of shared pointers used in #itsSharedPointerMap to make sure they are kept alive - // during lifetime of itsSharedPointerMap to prevent CVE-2020-11105. - std::vector> itsSharedPointerStorage; - - //! The id to be given to the next pointer - std::uint32_t itsCurrentPointerId; - - //! Maps from polymorphic type name strings to ids - std::unordered_map itsPolymorphicTypeMap; - - //! The id to be given to the next polymorphic type name - std::uint32_t itsCurrentPolymorphicTypeId; - - //! Keeps track of classes that have versioning information associated with them - std::unordered_set itsVersionedTypes; - }; // class OutputArchive - - // ###################################################################### - //! The base input archive class - /*! This is the base input archive for all input archives. If you create - a custom archive class, it should derive from this, passing itself as - a template parameter for the ArchiveType. - - The base class provides all of the functionality necessary to - properly forward data to the correct serialization functions. - - Individual archives should use a combination of prologue and - epilogue functions together with specializations of serialize, save, - and load to alter the functionality of their serialization. - - @tparam ArchiveType The archive type that derives from InputArchive - @tparam Flags Flags to control advanced functionality. See the Flags - enum for more information. - @ingroup Internal */ - template - class InputArchive : public detail::InputArchiveBase - { - public: - //! Construct the output archive - /*! @param derived A pointer to the derived ArchiveType (pass this from the derived archive) */ - InputArchive(ArchiveType * const derived) : - self(derived), - itsBaseClassSet(), - itsSharedPointerMap(), - itsPolymorphicTypeMap(), - itsVersionedTypes() - { } - - InputArchive & operator=( InputArchive const & ) = delete; - - //! Serializes all passed in data - /*! This is the primary interface for serializing data with an archive */ - template inline - ArchiveType & operator()( Types && ... args ) - { - process( std::forward( args )... ); - return *self; - } - - //! Serializes any data marked for deferment using defer - /*! This will cause any data wrapped in DeferredData to be immediately serialized */ - void serializeDeferments() - { - for( auto & deferment : itsDeferments ) - deferment(); - } - - /*! @name Boost Transition Layer - Functionality that mirrors the syntax for Boost. This is useful if you are transitioning - a large project from Boost to cereal. The preferred interface for cereal is using operator(). */ - //! @{ - - //! Indicates this archive is intended for loading - /*! This ensures compatibility with boost archive types. If you are transitioning - from boost, you can check this value within a member or external serialize function - (i.e., Archive::is_loading::value) to enable behavior specific to loading, until - you can transition to split save/load or save_minimal/load_minimal functions */ - using is_loading = std::true_type; - - //! Indicates this archive is not intended for saving - /*! This ensures compatibility with boost archive types. If you are transitioning - from boost, you can check this value within a member or external serialize function - (i.e., Archive::is_saving::value) to disable behavior specific to loading, until - you can transition to split save/load or save_minimal/load_minimal functions */ - using is_saving = std::false_type; - - //! Serializes passed in data - /*! This is a boost compatability layer and is not the preferred way of using - cereal. If you are transitioning from boost, use this until you can - transition to the operator() overload */ - template inline - ArchiveType & operator&( T && arg ) - { - self->process( std::forward( arg ) ); - return *self; - } - - //! Serializes passed in data - /*! This is a boost compatability layer and is not the preferred way of using - cereal. If you are transitioning from boost, use this until you can - transition to the operator() overload */ - template inline - ArchiveType & operator>>( T && arg ) - { - self->process( std::forward( arg ) ); - return *self; - } - - //! @} - - //! Retrieves a shared pointer given a unique key for it - /*! This is used to retrieve a previously registered shared_ptr - which has already been loaded. - - @internal - @param id The unique id that was serialized for the pointer - @return A shared pointer to the data - @throw Exception if the id does not exist */ - inline std::shared_ptr getSharedPointer(std::uint32_t const id) - { - if(id == 0) return std::shared_ptr(nullptr); - - auto iter = itsSharedPointerMap.find( id ); - if(iter == itsSharedPointerMap.end()) - throw Exception("Error while trying to deserialize a smart pointer. Could not find id " + std::to_string(id)); - - return iter->second; - } - - //! Registers a shared pointer to its unique identifier - /*! After a shared pointer has been allocated for the first time, it should - be registered with its loaded id for future references to it. - - @internal - @param id The unique identifier for the shared pointer - @param ptr The actual shared pointer */ - inline void registerSharedPointer(std::uint32_t const id, std::shared_ptr ptr) - { - std::uint32_t const stripped_id = id & ~detail::msb_32bit; - itsSharedPointerMap[stripped_id] = ptr; - } - - //! Retrieves the string for a polymorphic type given a unique key for it - /*! This is used to retrieve a string previously registered during - a polymorphic load. - - @internal - @param id The unique id that was serialized for the polymorphic type - @return The string identifier for the tyep */ - inline std::string getPolymorphicName(std::uint32_t const id) - { - auto name = itsPolymorphicTypeMap.find( id ); - if(name == itsPolymorphicTypeMap.end()) - { - throw Exception("Error while trying to deserialize a polymorphic pointer. Could not find type id " + std::to_string(id)); - } - return name->second; - } - - //! Registers a polymorphic name string to its unique identifier - /*! After a polymorphic type has been loaded for the first time, it should - be registered with its loaded id for future references to it. - - @internal - @param id The unique identifier for the polymorphic type - @param name The name associated with the tyep */ - inline void registerPolymorphicName(std::uint32_t const id, std::string const & name) - { - std::uint32_t const stripped_id = id & ~detail::msb_32bit; - itsPolymorphicTypeMap.insert( {stripped_id, name} ); - } - - private: - //! Serializes data after calling prologue, then calls epilogue - template inline - void process( T && head ) - { - prologue( *self, head ); - self->processImpl( head ); - epilogue( *self, head ); - } - - //! Unwinds to process all data - template inline - void process( T && head, Other && ... tail ) - { - process( std::forward( head ) ); - process( std::forward( tail )... ); - } - - //! Serialization of a virtual_base_class wrapper - /*! \sa virtual_base_class */ - template inline - ArchiveType & processImpl(virtual_base_class & b) - { - traits::detail::base_class_id id(b.base_ptr); - if(itsBaseClassSet.count(id) == 0) - { - itsBaseClassSet.insert(id); - self->processImpl( *b.base_ptr ); - } - return *self; - } - - //! Serialization of a base_class wrapper - /*! \sa base_class */ - template inline - ArchiveType & processImpl(base_class & b) - { - self->processImpl( *b.base_ptr ); - return *self; - } - - std::vector> itsDeferments; - - template inline - ArchiveType & processImpl(DeferredData const & d) - { - std::function deferment( [this, d](){ self->process( d.value ); } ); - itsDeferments.emplace_back( std::move(deferment) ); - - return *self; - } - - //! Helper macro that expands the requirements for activating an overload - /*! Requirements: - Has the requested serialization function - Does not have version and unversioned at the same time - Is input serializable AND - is specialized for this type of function OR - has no specialization at all */ - #define PROCESS_IF(name) \ - traits::EnableIf::value, \ - !traits::has_invalid_input_versioning::value, \ - (traits::is_input_serializable::value && \ - (traits::is_specialized_##name::value || \ - !traits::is_specialized::value))> = traits::sfinae - - //! Member serialization - template inline - ArchiveType & processImpl(T & t) - { - access::member_serialize(*self, t); - return *self; - } - - //! Non member serialization - template inline - ArchiveType & processImpl(T & t) - { - CEREAL_SERIALIZE_FUNCTION_NAME(*self, t); - return *self; - } - - //! Member split (load) - template inline - ArchiveType & processImpl(T & t) - { - access::member_load(*self, t); - return *self; - } - - //! Non member split (load) - template inline - ArchiveType & processImpl(T & t) - { - CEREAL_LOAD_FUNCTION_NAME(*self, t); - return *self; - } - - //! Member split (load_minimal) - template inline - ArchiveType & processImpl(T & t) - { - using OutArchiveType = typename traits::detail::get_output_from_input::type; - typename traits::has_member_save_minimal::type value; - self->process( value ); - access::member_load_minimal(*self, t, value); - return *self; - } - - //! Non member split (load_minimal) - template inline - ArchiveType & processImpl(T & t) - { - using OutArchiveType = typename traits::detail::get_output_from_input::type; - typename traits::has_non_member_save_minimal::type value; - self->process( value ); - CEREAL_LOAD_MINIMAL_FUNCTION_NAME(*self, t, value); - return *self; - } - - //! Empty class specialization - template ::value, - std::is_empty::value> = traits::sfinae> inline - ArchiveType & processImpl(T const &) - { - return *self; - } - - //! No matching serialization - /*! Invalid if we have invalid input versioning or - we are not input serializable, and either - don't allow empty class ellision or allow it but are not serializing an empty class */ - template ::value || - (!traits::is_input_serializable::value && - (!(Flags & AllowEmptyClassElision) || ((Flags & AllowEmptyClassElision) && !std::is_empty::value)))> = traits::sfinae> inline - ArchiveType & processImpl(T const &) - { - static_assert(traits::detail::count_input_serializers::value != 0, - "cereal could not find any input serialization functions for the provided type and archive combination. \n\n " - "Types must either have a serialize function, load/save pair, or load_minimal/save_minimal pair (you may not mix these). \n " - "Serialize functions generally have the following signature: \n\n " - "template \n " - " void serialize(Archive & ar) \n " - " { \n " - " ar( member1, member2, member3 ); \n " - " } \n\n " ); - - static_assert(traits::detail::count_input_serializers::value < 2, - "cereal found more than one compatible input serialization function for the provided type and archive combination. \n\n " - "Types must either have a serialize function, load/save pair, or load_minimal/save_minimal pair (you may not mix these). \n " - "Use specialization (see access.hpp) if you need to disambiguate between serialize vs load/save functions. \n " - "Note that serialization functions can be inherited which may lead to the aforementioned ambiguities. \n " - "In addition, you may not mix versioned with non-versioned serialization functions. \n\n "); - - return *self; - } - - //! Befriend for versioning in load_and_construct - template friend struct detail::Construct; - - //! Registers a class version with the archive and serializes it if necessary - /*! If this is the first time this class has been serialized, we will record its - version number and serialize that. - - @tparam T The type of the class being serialized */ - template inline - std::uint32_t loadClassVersion() - { - static const auto hash = std::type_index(typeid(T)).hash_code(); - auto lookupResult = itsVersionedTypes.find( hash ); - - if( lookupResult != itsVersionedTypes.end() ) // already exists - return lookupResult->second; - else // need to load - { - std::uint32_t version; - - process( make_nvp("cereal_class_version", version) ); - itsVersionedTypes.emplace_hint( lookupResult, hash, version ); - - return version; - } - } - - //! Member serialization - /*! Versioning implementation */ - template inline - ArchiveType & processImpl(T & t) - { - const auto version = loadClassVersion(); - access::member_serialize(*self, t, version); - return *self; - } - - //! Non member serialization - /*! Versioning implementation */ - template inline - ArchiveType & processImpl(T & t) - { - const auto version = loadClassVersion(); - CEREAL_SERIALIZE_FUNCTION_NAME(*self, t, version); - return *self; - } - - //! Member split (load) - /*! Versioning implementation */ - template inline - ArchiveType & processImpl(T & t) - { - const auto version = loadClassVersion(); - access::member_load(*self, t, version); - return *self; - } - - //! Non member split (load) - /*! Versioning implementation */ - template inline - ArchiveType & processImpl(T & t) - { - const auto version = loadClassVersion(); - CEREAL_LOAD_FUNCTION_NAME(*self, t, version); - return *self; - } - - //! Member split (load_minimal) - /*! Versioning implementation */ - template inline - ArchiveType & processImpl(T & t) - { - using OutArchiveType = typename traits::detail::get_output_from_input::type; - const auto version = loadClassVersion(); - typename traits::has_member_versioned_save_minimal::type value; - self->process(value); - access::member_load_minimal(*self, t, value, version); - return *self; - } - - //! Non member split (load_minimal) - /*! Versioning implementation */ - template inline - ArchiveType & processImpl(T & t) - { - using OutArchiveType = typename traits::detail::get_output_from_input::type; - const auto version = loadClassVersion(); - typename traits::has_non_member_versioned_save_minimal::type value; - self->process(value); - CEREAL_LOAD_MINIMAL_FUNCTION_NAME(*self, t, value, version); - return *self; - } - - #undef PROCESS_IF - - private: - ArchiveType * const self; - - //! A set of all base classes that have been serialized - std::unordered_set itsBaseClassSet; - - //! Maps from pointer ids to metadata - std::unordered_map> itsSharedPointerMap; - - //! Maps from name ids to names - std::unordered_map itsPolymorphicTypeMap; - - //! Maps from type hash codes to version numbers - std::unordered_map itsVersionedTypes; - }; // class InputArchive -} // namespace cereal - -// This include needs to come after things such as binary_data, make_nvp, etc -#include "cereal/types/common.hpp" - -#endif // CEREAL_CEREAL_HPP_ diff --git a/include/cereal/details/helpers.hpp b/include/cereal/details/helpers.hpp deleted file mode 100644 index 8dafb8e..0000000 --- a/include/cereal/details/helpers.hpp +++ /dev/null @@ -1,422 +0,0 @@ -/*! \file helpers.hpp - \brief Internal helper functionality - \ingroup Internal */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_DETAILS_HELPERS_HPP_ -#define CEREAL_DETAILS_HELPERS_HPP_ - -#include -#include -#include -#include -#include -#include - -#include "cereal/macros.hpp" -#include "cereal/details/static_object.hpp" - -namespace cereal -{ - // ###################################################################### - //! An exception class thrown when things go wrong at runtime - /*! @ingroup Utility */ - struct Exception : public std::runtime_error - { - explicit Exception( const std::string & what_ ) : std::runtime_error(what_) {} - explicit Exception( const char * what_ ) : std::runtime_error(what_) {} - }; - - // ###################################################################### - //! The size type used by cereal - /*! To ensure compatability between 32, 64, etc bit machines, we need to use - a fixed size type instead of size_t, which may vary from machine to - machine. - - The default value for CEREAL_SIZE_TYPE is specified in cereal/macros.hpp */ - using size_type = CEREAL_SIZE_TYPE; - - // forward decls - class BinaryOutputArchive; - class BinaryInputArchive; - - // ###################################################################### - namespace detail - { - struct NameValuePairCore {}; //!< Traits struct for NVPs - struct DeferredDataCore {}; //!< Traits struct for DeferredData - } - - // ###################################################################### - //! For holding name value pairs - /*! This pairs a name (some string) with some value such that an archive - can potentially take advantage of the pairing. - - In serialization functions, NameValuePairs are usually created like so: - @code{.cpp} - struct MyStruct - { - int a, b, c, d, e; - - template - void serialize(Archive & archive) - { - archive( CEREAL_NVP(a), - CEREAL_NVP(b), - CEREAL_NVP(c), - CEREAL_NVP(d), - CEREAL_NVP(e) ); - } - }; - @endcode - - Alternatively, you can give you data members custom names like so: - @code{.cpp} - struct MyStruct - { - int a, b, my_embarrassing_variable_name, d, e; - - template - void serialize(Archive & archive) - { - archive( CEREAL_NVP(a), - CEREAL_NVP(b), - cereal::make_nvp("var", my_embarrassing_variable_name) ); - CEREAL_NVP(d), - CEREAL_NVP(e) ); - } - }; - @endcode - - There is a slight amount of overhead to creating NameValuePairs, so there - is a third method which will elide the names when they are not used by - the Archive: - - @code{.cpp} - struct MyStruct - { - int a, b; - - template - void serialize(Archive & archive) - { - archive( cereal::make_nvp(a), - cereal::make_nvp(b) ); - } - }; - @endcode - - This third method is generally only used when providing generic type - support. Users writing their own serialize functions will normally - explicitly control whether they want to use NVPs or not. - - @internal */ - template - class NameValuePair : detail::NameValuePairCore - { - private: - // If we get passed an array, keep the type as is, otherwise store - // a reference if we were passed an l value reference, else copy the value - using Type = typename std::conditional::type>::value, - typename std::remove_cv::type, - typename std::conditional::value, - T, - typename std::decay::type>::type>::type; - - // prevent nested nvps - static_assert( !std::is_base_of::value, - "Cannot pair a name to a NameValuePair" ); - - NameValuePair & operator=( NameValuePair const & ) = delete; - - public: - //! Constructs a new NameValuePair - /*! @param n The name of the pair - @param v The value to pair. Ideally this should be an l-value reference so that - the value can be both loaded and saved to. If you pass an r-value reference, - the NameValuePair will store a copy of it instead of a reference. Thus you should - only pass r-values in cases where this makes sense, such as the result of some - size() call. - @internal */ - NameValuePair( char const * n, T && v ) : name(n), value(std::forward(v)) {} - - char const * name; - Type value; - }; - - //! A specialization of make_nvp<> that simply forwards the value for binary archives - /*! @relates NameValuePair - @internal */ - template inline - typename - std::enable_if::value || - std::is_same::value, - T && >::type - make_nvp( const char *, T && value ) - { - return std::forward(value); - } - - //! A specialization of make_nvp<> that actually creates an nvp for non-binary archives - /*! @relates NameValuePair - @internal */ - template inline - typename - std::enable_if::value && - !std::is_same::value, - NameValuePair >::type - make_nvp( const char * name, T && value) - { - return {name, std::forward(value)}; - } - - //! Convenience for creating a templated NVP - /*! For use in internal generic typing functions which have an - Archive type declared - @internal */ - #define CEREAL_NVP_(name, value) ::cereal::make_nvp(name, value) - - // ###################################################################### - //! A wrapper around data that can be serialized in a binary fashion - /*! This class is used to demarcate data that can safely be serialized - as a binary chunk of data. Individual archives can then choose how - best represent this during serialization. - - @internal */ - template - struct BinaryData - { - //! Internally store the pointer as a void *, keeping const if created with - //! a const pointer - using PT = typename std::conditional::type>::type>::value, - const void *, - void *>::type; - - BinaryData( T && d, uint64_t s ) : data(std::forward(d)), size(s) {} - - PT data; //!< pointer to beginning of data - uint64_t size; //!< size in bytes - }; - - // ###################################################################### - //! A wrapper around data that should be serialized after all non-deferred data - /*! This class is used to demarcate data that can only be safely serialized after - any data not wrapped in this class. - - @internal */ - template - class DeferredData : detail::DeferredDataCore - { - private: - // If we get passed an array, keep the type as is, otherwise store - // a reference if we were passed an l value reference, else copy the value - using Type = typename std::conditional::type>::value, - typename std::remove_cv::type, - typename std::conditional::value, - T, - typename std::decay::type>::type>::type; - - // prevent nested nvps - static_assert( !std::is_base_of::value, - "Cannot defer DeferredData" ); - - DeferredData & operator=( DeferredData const & ) = delete; - - public: - //! Constructs a new NameValuePair - /*! @param v The value to defer. Ideally this should be an l-value reference so that - the value can be both loaded and saved to. If you pass an r-value reference, - the DeferredData will store a copy of it instead of a reference. Thus you should - only pass r-values in cases where this makes sense, such as the result of some - size() call. - @internal */ - DeferredData( T && v ) : value(std::forward(v)) {} - - Type value; - }; - - // ###################################################################### - namespace detail - { - // base classes for type checking - /* The rtti virtual function only exists to enable an archive to - be used in a polymorphic fashion, if necessary. See the - archive adapters for an example of this */ - class OutputArchiveBase - { - public: - OutputArchiveBase() = default; - OutputArchiveBase( OutputArchiveBase && ) CEREAL_NOEXCEPT {} - OutputArchiveBase & operator=( OutputArchiveBase && ) CEREAL_NOEXCEPT { return *this; } - virtual ~OutputArchiveBase() CEREAL_NOEXCEPT = default; - - private: - virtual void rtti() {} - }; - - class InputArchiveBase - { - public: - InputArchiveBase() = default; - InputArchiveBase( InputArchiveBase && ) CEREAL_NOEXCEPT {} - InputArchiveBase & operator=( InputArchiveBase && ) CEREAL_NOEXCEPT { return *this; } - virtual ~InputArchiveBase() CEREAL_NOEXCEPT = default; - - private: - virtual void rtti() {} - }; - - // forward decls for polymorphic support - template struct polymorphic_serialization_support; - struct adl_tag; - - // used during saving pointers - static const uint32_t msb_32bit = 0x80000000; - static const int32_t msb2_32bit = 0x40000000; - } - - // ###################################################################### - //! A wrapper around size metadata - /*! This class provides a way for archives to have more flexibility over how - they choose to serialize size metadata for containers. For some archive - types, the size may be implicitly encoded in the output (e.g. JSON) and - not need an explicit entry. Specializing serialize or load/save for - your archive and SizeTags allows you to choose what happens. - - @internal */ - template - class SizeTag - { - private: - // Store a reference if passed an lvalue reference, otherwise - // make a copy of the data - using Type = typename std::conditional::value, - T, - typename std::decay::type>::type; - - SizeTag & operator=( SizeTag const & ) = delete; - - public: - SizeTag( T && sz ) : size(std::forward(sz)) {} - - Type size; - }; - - // ###################################################################### - //! A wrapper around a key and value for serializing data into maps. - /*! This class just provides a grouping of keys and values into a struct for - human readable archives. For example, XML archives will use this wrapper - to write maps like so: - - @code{.xml} - - - MyFirstKey - MyFirstValue - - - MySecondKey - MySecondValue - - - @endcode - - \sa make_map_item - @internal */ - template - struct MapItem - { - using KeyType = typename std::conditional< - std::is_lvalue_reference::value, - Key, - typename std::decay::type>::type; - - using ValueType = typename std::conditional< - std::is_lvalue_reference::value, - Value, - typename std::decay::type>::type; - - //! Construct a MapItem from a key and a value - /*! @internal */ - MapItem( Key && key_, Value && value_ ) : key(std::forward(key_)), value(std::forward(value_)) {} - - MapItem & operator=( MapItem const & ) = delete; - - KeyType key; - ValueType value; - - //! Serialize the MapItem with the NVPs "key" and "value" - template inline - void CEREAL_SERIALIZE_FUNCTION_NAME(Archive & archive) - { - archive( make_nvp("key", key), - make_nvp("value", value) ); - } - }; - - //! Create a MapItem so that human readable archives will group keys and values together - /*! @internal - @relates MapItem */ - template inline - MapItem make_map_item(KeyType && key, ValueType && value) - { - return {std::forward(key), std::forward(value)}; - } - - namespace detail - { - //! Tag for Version, which due to its anonymous namespace, becomes a different - //! type in each translation unit - /*! This allows CEREAL_CLASS_VERSION to be safely called in a header file */ - namespace{ struct version_binding_tag {}; } - - // ###################################################################### - //! Version information class - /*! This is the base case for classes that have not been explicitly - registered */ - template struct Version - { - static const std::uint32_t version = 0; - // we don't need to explicitly register these types since they - // always get a version number of 0 - }; - - //! Holds all registered version information - struct Versions - { - std::unordered_map mapping; - - std::uint32_t find( std::size_t hash, std::uint32_t version ) - { - const auto result = mapping.emplace( hash, version ); - return result.first->second; - } - }; // struct Versions - } // namespace detail -} // namespace cereal - -#endif // CEREAL_DETAILS_HELPERS_HPP_ diff --git a/include/cereal/details/polymorphic_impl.hpp b/include/cereal/details/polymorphic_impl.hpp deleted file mode 100644 index deb3440..0000000 --- a/include/cereal/details/polymorphic_impl.hpp +++ /dev/null @@ -1,825 +0,0 @@ -/*! \file polymorphic_impl.hpp - \brief Internal polymorphism support - \ingroup Internal */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* This code is heavily inspired by the boost serialization implementation by the following authors - - (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . - Use, modification and distribution is subject to the Boost Software - License, Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt) - - See http://www.boost.org for updates, documentation, and revision history. - - (C) Copyright 2006 David Abrahams - http://www.boost.org. - - See /boost/serialization/export.hpp, /boost/archive/detail/register_archive.hpp, - and /boost/serialization/void_cast.hpp for their implementation. Additional details - found in other files split across serialization and archive. -*/ -#ifndef CEREAL_DETAILS_POLYMORPHIC_IMPL_HPP_ -#define CEREAL_DETAILS_POLYMORPHIC_IMPL_HPP_ - -#include "cereal/details/polymorphic_impl_fwd.hpp" -#include "cereal/details/static_object.hpp" -#include "cereal/types/memory.hpp" -#include "cereal/types/string.hpp" -#include -#include -#include -#include -#include -#include - -//! Helper macro to omit unused warning -#if defined(__GNUC__) - // GCC / clang don't want the function - #define CEREAL_BIND_TO_ARCHIVES_UNUSED_FUNCTION -#else - #define CEREAL_BIND_TO_ARCHIVES_UNUSED_FUNCTION static void unused() { (void)b; } -#endif - -//! Binds a polymorhic type to all registered archives -/*! This binds a polymorphic type to all compatible registered archives that - have been registered with CEREAL_REGISTER_ARCHIVE. This must be called - after all archives are registered (usually after the archives themselves - have been included). */ -#ifdef CEREAL_HAS_CPP17 -#define CEREAL_BIND_TO_ARCHIVES(...) \ - namespace cereal { \ - namespace detail { \ - template<> \ - struct init_binding<__VA_ARGS__> { \ - static inline bind_to_archives<__VA_ARGS__> const & b= \ - ::cereal::detail::StaticObject< \ - bind_to_archives<__VA_ARGS__> \ - >::getInstance().bind(); \ - CEREAL_BIND_TO_ARCHIVES_UNUSED_FUNCTION \ - }; \ - }} /* end namespaces */ -#else -#define CEREAL_BIND_TO_ARCHIVES(...) \ - namespace cereal { \ - namespace detail { \ - template<> \ - struct init_binding<__VA_ARGS__> { \ - static bind_to_archives<__VA_ARGS__> const& b; \ - CEREAL_BIND_TO_ARCHIVES_UNUSED_FUNCTION \ - }; \ - bind_to_archives<__VA_ARGS__> const & init_binding<__VA_ARGS__>::b = \ - ::cereal::detail::StaticObject< \ - bind_to_archives<__VA_ARGS__> \ - >::getInstance().bind(); \ - }} /* end namespaces */ -#endif - -namespace cereal -{ - /* Polymorphic casting support */ - namespace detail - { - //! Base type for polymorphic void casting - /*! Contains functions for casting between registered base and derived types. - - This is necessary so that cereal can properly cast between polymorphic types - even though void pointers are used, which normally have no type information. - Runtime type information is used instead to index a compile-time made mapping - that can perform the proper cast. In the case of multiple levels of inheritance, - cereal will attempt to find the shortest path by using registered relationships to - perform the cast. - - This class will be allocated as a StaticObject and only referenced by pointer, - allowing a templated derived version of it to define strongly typed functions - that cast between registered base and derived types. */ - struct PolymorphicCaster - { - PolymorphicCaster() = default; - PolymorphicCaster( const PolymorphicCaster & ) = default; - PolymorphicCaster & operator=( const PolymorphicCaster & ) = default; - PolymorphicCaster( PolymorphicCaster && ) CEREAL_NOEXCEPT {} - PolymorphicCaster & operator=( PolymorphicCaster && ) CEREAL_NOEXCEPT { return *this; } - virtual ~PolymorphicCaster() CEREAL_NOEXCEPT = default; - - //! Downcasts to the proper derived type - virtual void const * downcast( void const * const ptr ) const = 0; - //! Upcast to proper base type - virtual void * upcast( void * const ptr ) const = 0; - //! Upcast to proper base type, shared_ptr version - virtual std::shared_ptr upcast( std::shared_ptr const & ptr ) const = 0; - }; - - //! Holds registered mappings between base and derived types for casting - /*! This will be allocated as a StaticObject and holds a map containing - all registered mappings between base and derived types. */ - struct PolymorphicCasters - { - //! Maps from a derived type index to a set of chainable casters - using DerivedCasterMap = std::unordered_map>; - //! Maps from base type index to a map from derived type index to caster - std::unordered_map map; - - std::multimap reverseMap; - - //! Error message used for unregistered polymorphic casts - #define UNREGISTERED_POLYMORPHIC_CAST_EXCEPTION(LoadSave) \ - throw cereal::Exception("Trying to " #LoadSave " a registered polymorphic type with an unregistered polymorphic cast.\n" \ - "Could not find a path to a base class (" + util::demangle(baseInfo.name()) + ") for type: " + ::cereal::util::demangledName() + "\n" \ - "Make sure you either serialize the base class at some point via cereal::base_class or cereal::virtual_base_class.\n" \ - "Alternatively, manually register the association with CEREAL_REGISTER_POLYMORPHIC_RELATION."); - - //! Checks if the mapping object that can perform the upcast or downcast exists, and returns it if so - /*! Uses the type index from the base and derived class to find the matching - registered caster. If no matching caster exists, the bool in the pair will be false and the vector - reference should not be used. */ - static std::pair const &> - lookup_if_exists( std::type_index const & baseIndex, std::type_index const & derivedIndex ) - { - // First phase of lookup - match base type index - auto const & baseMap = StaticObject::getInstance().map; - auto baseIter = baseMap.find( baseIndex ); - if (baseIter == baseMap.end()) - return {false, {}}; - - // Second phase - find a match from base to derived - auto const & derivedMap = baseIter->second; - auto derivedIter = derivedMap.find( derivedIndex ); - if (derivedIter == derivedMap.end()) - return {false, {}}; - - return {true, derivedIter->second}; - } - - //! Gets the mapping object that can perform the upcast or downcast - /*! Uses the type index from the base and derived class to find the matching - registered caster. If no matching caster exists, calls the exception function. - - The returned PolymorphicCaster is capable of upcasting or downcasting between the two types. */ - template inline - static std::vector const & lookup( std::type_index const & baseIndex, std::type_index const & derivedIndex, F && exceptionFunc ) - { - // First phase of lookup - match base type index - auto const & baseMap = StaticObject::getInstance().map; - auto baseIter = baseMap.find( baseIndex ); - if( baseIter == baseMap.end() ) - exceptionFunc(); - - // Second phase - find a match from base to derived - auto const & derivedMap = baseIter->second; - auto derivedIter = derivedMap.find( derivedIndex ); - if( derivedIter == derivedMap.end() ) - exceptionFunc(); - - return derivedIter->second; - } - - //! Performs a downcast to the derived type using a registered mapping - template inline - static const Derived * downcast( const void * dptr, std::type_info const & baseInfo ) - { - auto const & mapping = lookup( baseInfo, typeid(Derived), [&](){ UNREGISTERED_POLYMORPHIC_CAST_EXCEPTION(save) } ); - - for( auto const * dmap : mapping ) - dptr = dmap->downcast( dptr ); - - return static_cast( dptr ); - } - - //! Performs an upcast to the registered base type using the given a derived type - /*! The return is untyped because the final casting to the base type must happen in the polymorphic - serialization function, where the type is known at compile time */ - template inline - static void * upcast( Derived * const dptr, std::type_info const & baseInfo ) - { - auto const & mapping = lookup( baseInfo, typeid(Derived), [&](){ UNREGISTERED_POLYMORPHIC_CAST_EXCEPTION(load) } ); - - void * uptr = dptr; - for( auto mIter = mapping.rbegin(), mEnd = mapping.rend(); mIter != mEnd; ++mIter ) - uptr = (*mIter)->upcast( uptr ); - - return uptr; - } - - //! Upcasts for shared pointers - template inline - static std::shared_ptr upcast( std::shared_ptr const & dptr, std::type_info const & baseInfo ) - { - auto const & mapping = lookup( baseInfo, typeid(Derived), [&](){ UNREGISTERED_POLYMORPHIC_CAST_EXCEPTION(load) } ); - - std::shared_ptr uptr = dptr; - for( auto mIter = mapping.rbegin(), mEnd = mapping.rend(); mIter != mEnd; ++mIter ) - uptr = (*mIter)->upcast( uptr ); - - return uptr; - } - - #undef UNREGISTERED_POLYMORPHIC_CAST_EXCEPTION - }; - - #ifdef CEREAL_OLDER_GCC - #define CEREAL_EMPLACE_MAP(map, key, value) \ - map.insert( std::make_pair(std::move(key), std::move(value)) ); - #else // NOT CEREAL_OLDER_GCC - #define CEREAL_EMPLACE_MAP(map, key, value) \ - map.emplace( key, value ); - #endif // NOT_CEREAL_OLDER_GCC - - //! Strongly typed derivation of PolymorphicCaster - template - struct PolymorphicVirtualCaster : PolymorphicCaster - { - //! Inserts an entry in the polymorphic casting map for this pairing - /*! Creates an explicit mapping between Base and Derived in both upwards and - downwards directions, allowing void pointers to either to be properly cast - assuming dynamic type information is available */ - PolymorphicVirtualCaster() - { - const auto baseKey = std::type_index(typeid(Base)); - const auto derivedKey = std::type_index(typeid(Derived)); - - // First insert the relation Base->Derived - const auto lock = StaticObject::lock(); - auto & baseMap = StaticObject::getInstance().map; - - { - auto & derivedMap = baseMap.insert( {baseKey, PolymorphicCasters::DerivedCasterMap{}} ).first->second; - auto & derivedVec = derivedMap.insert( {derivedKey, {}} ).first->second; - derivedVec.push_back( this ); - } - - // Insert reverse relation Derived->Base - auto & reverseMap = StaticObject::getInstance().reverseMap; - CEREAL_EMPLACE_MAP(reverseMap, derivedKey, baseKey); - - // Find all chainable unregistered relations - /* The strategy here is to process only the nodes in the class hierarchy graph that have been - affected by the new insertion. The aglorithm iteratively processes a node an ensures that it - is updated with all new shortest length paths. It then rocesses the parents of the active node, - with the knowledge that all children have already been processed. - - Note that for the following, we'll use the nomenclature of parent and child to not confuse with - the inserted base derived relationship */ - { - // Checks whether there is a path from parent->child and returns a pair - // dist is set to MAX if the path does not exist - auto checkRelation = [](std::type_index const & parentInfo, std::type_index const & childInfo) -> - std::pair const &> - { - auto result = PolymorphicCasters::lookup_if_exists( parentInfo, childInfo ); - if( result.first ) - { - auto const & path = result.second; - return {path.size(), path}; - } - else - return {(std::numeric_limits::max)(), {}}; - }; - - std::stack parentStack; // Holds the parent nodes to be processed - std::vector dirtySet; // Marks child nodes that have been changed - std::unordered_set processedParents; // Marks parent nodes that have been processed - - // Checks if a child has been marked dirty - auto isDirty = [&](std::type_index const & c) - { - auto const dirtySetSize = dirtySet.size(); - for( size_t i = 0; i < dirtySetSize; ++i ) - if( dirtySet[i] == c ) - return true; - - return false; - }; - - // Begin processing the base key and mark derived as dirty - parentStack.push( baseKey ); - dirtySet.emplace_back( derivedKey ); - - while( !parentStack.empty() ) - { - using Relations = std::unordered_multimap>>; - Relations unregisteredRelations; // Defer insertions until after main loop to prevent iterator invalidation - - const auto parent = parentStack.top(); - parentStack.pop(); - - // Update paths to all children marked dirty - for( auto const & childPair : baseMap[parent] ) - { - const auto child = childPair.first; - if( isDirty( child ) && baseMap.count( child ) ) - { - auto parentChildPath = checkRelation( parent, child ); - - // Search all paths from the child to its own children (finalChild), - // looking for a shorter parth from parent to finalChild - for( auto const & finalChildPair : baseMap[child] ) - { - const auto finalChild = finalChildPair.first; - - auto parentFinalChildPath = checkRelation( parent, finalChild ); - auto childFinalChildPath = checkRelation( child, finalChild ); - - const size_t newLength = 1u + parentChildPath.first; - - if( newLength < parentFinalChildPath.first ) - { - std::vector path = parentChildPath.second; - path.insert( path.end(), childFinalChildPath.second.begin(), childFinalChildPath.second.end() ); - - // Check to see if we have a previous uncommitted path in unregisteredRelations - // that is shorter. If so, ignore this path - auto hintRange = unregisteredRelations.equal_range( parent ); - auto hint = hintRange.first; - for( ; hint != hintRange.second; ++hint ) - if( hint->second.first == finalChild ) - break; - - const bool uncommittedExists = hint != unregisteredRelations.end(); - if( uncommittedExists && (hint->second.second.size() <= newLength) ) - continue; - - auto newPath = std::pair>{finalChild, std::move(path)}; - - // Insert the new path if it doesn't exist, otherwise this will just lookup where to do the - // replacement - #ifdef CEREAL_OLDER_GCC - auto old = unregisteredRelations.insert( hint, std::make_pair(parent, newPath) ); - #else // NOT CEREAL_OLDER_GCC - auto old = unregisteredRelations.emplace_hint( hint, parent, newPath ); - #endif // NOT CEREAL_OLDER_GCC - - // If there was an uncommitted path, we need to perform a replacement - if( uncommittedExists ) - old->second = newPath; - } - } // end loop over child's children - } // end if dirty and child has children - } // end loop over children - - // Insert chained relations - for( auto const & it : unregisteredRelations ) - { - auto & derivedMap = baseMap.find( it.first )->second; - derivedMap[it.second.first] = it.second.second; - CEREAL_EMPLACE_MAP(reverseMap, it.second.first, it.first ); - } - - // Mark current parent as modified - dirtySet.emplace_back( parent ); - - // Insert all parents of the current parent node that haven't yet been processed - auto parentRange = reverseMap.equal_range( parent ); - for( auto pIter = parentRange.first; pIter != parentRange.second; ++pIter ) - { - const auto pParent = pIter->second; - if( !processedParents.count( pParent ) ) - { - parentStack.push( pParent ); - processedParents.insert( pParent ); - } - } - } // end loop over parent stack - } // end chainable relations - } // end PolymorphicVirtualCaster() - - #undef CEREAL_EMPLACE_MAP - - //! Performs the proper downcast with the templated types - void const * downcast( void const * const ptr ) const override - { - return dynamic_cast( static_cast( ptr ) ); - } - - //! Performs the proper upcast with the templated types - void * upcast( void * const ptr ) const override - { - return dynamic_cast( static_cast( ptr ) ); - } - - //! Performs the proper upcast with the templated types (shared_ptr version) - std::shared_ptr upcast( std::shared_ptr const & ptr ) const override - { - return std::dynamic_pointer_cast( std::static_pointer_cast( ptr ) ); - } - }; - - //! Registers a polymorphic casting relation between a Base and Derived type - /*! Registering a relation allows cereal to properly cast between the two types - given runtime type information and void pointers. - - Registration happens automatically via cereal::base_class and cereal::virtual_base_class - instantiations. For cases where neither is called, see the CEREAL_REGISTER_POLYMORPHIC_RELATION - macro */ - template - struct RegisterPolymorphicCaster - { - static PolymorphicCaster const * bind( std::true_type /* is_polymorphic */) - { - return &StaticObject>::getInstance(); - } - - static PolymorphicCaster const * bind( std::false_type /* is_polymorphic */ ) - { return nullptr; } - - //! Performs registration (binding) between Base and Derived - /*! If the type is not polymorphic, nothing will happen */ - static PolymorphicCaster const * bind() - { return bind( typename std::is_polymorphic::type() ); } - }; - } - - /* General polymorphism support */ - namespace detail - { - //! Binds a compile time type with a user defined string - template - struct binding_name {}; - - //! A structure holding a map from type_indices to output serializer functions - /*! A static object of this map should be created for each registered archive - type, containing entries for every registered type that describe how to - properly cast the type to its real type in polymorphic scenarios for - shared_ptr, weak_ptr, and unique_ptr. */ - template - struct OutputBindingMap - { - //! A serializer function - /*! Serializer functions return nothing and take an archive as - their first parameter (will be cast properly inside the function, - a pointer to actual data (contents of smart_ptr's get() function) - as their second parameter, and the type info of the owning smart_ptr - as their final parameter */ - typedef std::function Serializer; - - //! Struct containing the serializer functions for all pointer types - struct Serializers - { - Serializer shared_ptr, //!< Serializer function for shared/weak pointers - unique_ptr; //!< Serializer function for unique pointers - }; - - //! A map of serializers for pointers of all registered types - std::map map; - }; - - //! An empty noop deleter - template struct EmptyDeleter { void operator()(T *) const {} }; - - //! A structure holding a map from type name strings to input serializer functions - /*! A static object of this map should be created for each registered archive - type, containing entries for every registered type that describe how to - properly cast the type to its real type in polymorphic scenarios for - shared_ptr, weak_ptr, and unique_ptr. */ - template - struct InputBindingMap - { - //! Shared ptr serializer function - /*! Serializer functions return nothing and take an archive as - their first parameter (will be cast properly inside the function, - a shared_ptr (or unique_ptr for the unique case) of any base - type, and the type id of said base type as the third parameter. - Internally it will properly be loaded and cast to the correct type. */ - typedef std::function &, std::type_info const &)> SharedSerializer; - //! Unique ptr serializer function - typedef std::function> &, std::type_info const &)> UniqueSerializer; - - //! Struct containing the serializer functions for all pointer types - struct Serializers - { - SharedSerializer shared_ptr; //!< Serializer function for shared/weak pointers - UniqueSerializer unique_ptr; //!< Serializer function for unique pointers - }; - - //! A map of serializers for pointers of all registered types - std::map map; - }; - - // forward decls for archives from cereal.hpp - class InputArchiveBase; - class OutputArchiveBase; - - //! Creates a binding (map entry) between an input archive type and a polymorphic type - /*! Bindings are made when types are registered, assuming that at least one - archive has already been registered. When this struct is created, - it will insert (at run time) an entry into a map that properly handles - casting for serializing polymorphic objects */ - template struct InputBindingCreator - { - //! Initialize the binding - InputBindingCreator() - { - auto & map = StaticObject>::getInstance().map; - auto lock = StaticObject>::lock(); - auto key = std::string(binding_name::name()); - auto lb = map.lower_bound(key); - - if (lb != map.end() && lb->first == key) - return; - - typename InputBindingMap::Serializers serializers; - - serializers.shared_ptr = - [](void * arptr, std::shared_ptr & dptr, std::type_info const & baseInfo) - { - Archive & ar = *static_cast(arptr); - std::shared_ptr ptr; - - ar( CEREAL_NVP_("ptr_wrapper", ::cereal::memory_detail::make_ptr_wrapper(ptr)) ); - - dptr = PolymorphicCasters::template upcast( ptr, baseInfo ); - }; - - serializers.unique_ptr = - [](void * arptr, std::unique_ptr> & dptr, std::type_info const & baseInfo) - { - Archive & ar = *static_cast(arptr); - std::unique_ptr ptr; - - ar( CEREAL_NVP_("ptr_wrapper", ::cereal::memory_detail::make_ptr_wrapper(ptr)) ); - - dptr.reset( PolymorphicCasters::template upcast( ptr.release(), baseInfo )); - }; - - map.insert( lb, { std::move(key), std::move(serializers) } ); - } - }; - - //! Creates a binding (map entry) between an output archive type and a polymorphic type - /*! Bindings are made when types are registered, assuming that at least one - archive has already been registered. When this struct is created, - it will insert (at run time) an entry into a map that properly handles - casting for serializing polymorphic objects */ - template struct OutputBindingCreator - { - //! Writes appropriate metadata to the archive for this polymorphic type - static void writeMetadata(Archive & ar) - { - // Register the polymorphic type name with the archive, and get the id - char const * name = binding_name::name(); - std::uint32_t id = ar.registerPolymorphicType(name); - - // Serialize the id - ar( CEREAL_NVP_("polymorphic_id", id) ); - - // If the msb of the id is 1, then the type name is new, and we should serialize it - if( id & detail::msb_32bit ) - { - std::string namestring(name); - ar( CEREAL_NVP_("polymorphic_name", namestring) ); - } - } - - //! Holds a properly typed shared_ptr to the polymorphic type - class PolymorphicSharedPointerWrapper - { - public: - /*! Wrap a raw polymorphic pointer in a shared_ptr to its true type - - The wrapped pointer will not be responsible for ownership of the held pointer - so it will not attempt to destroy it; instead the refcount of the wrapped - pointer will be tied to a fake 'ownership pointer' that will do nothing - when it ultimately goes out of scope. - - The main reason for doing this, other than not to destroy the true object - with our wrapper pointer, is to avoid meddling with the internal reference - count in a polymorphic type that inherits from std::enable_shared_from_this. - - @param dptr A void pointer to the contents of the shared_ptr to serialize */ - PolymorphicSharedPointerWrapper( T const * dptr ) : refCount(), wrappedPtr( refCount, dptr ) - { } - - //! Get the wrapped shared_ptr */ - inline std::shared_ptr const & operator()() const { return wrappedPtr; } - - private: - std::shared_ptr refCount; //!< The ownership pointer - std::shared_ptr wrappedPtr; //!< The wrapped pointer - }; - - //! Does the actual work of saving a polymorphic shared_ptr - /*! This function will properly create a shared_ptr from the void * that is passed in - before passing it to the archive for serialization. - - In addition, this will also preserve the state of any internal enable_shared_from_this mechanisms - - @param ar The archive to serialize to - @param dptr Pointer to the actual data held by the shared_ptr */ - static inline void savePolymorphicSharedPtr( Archive & ar, T const * dptr, std::true_type /* has_shared_from_this */ ) - { - ::cereal::memory_detail::EnableSharedStateHelper state( const_cast(dptr) ); - PolymorphicSharedPointerWrapper psptr( dptr ); - ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper( psptr() ) ) ); - } - - //! Does the actual work of saving a polymorphic shared_ptr - /*! This function will properly create a shared_ptr from the void * that is passed in - before passing it to the archive for serialization. - - This version is for types that do not inherit from std::enable_shared_from_this. - - @param ar The archive to serialize to - @param dptr Pointer to the actual data held by the shared_ptr */ - static inline void savePolymorphicSharedPtr( Archive & ar, T const * dptr, std::false_type /* has_shared_from_this */ ) - { - PolymorphicSharedPointerWrapper psptr( dptr ); - ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper( psptr() ) ) ); - } - - //! Initialize the binding - OutputBindingCreator() - { - auto & map = StaticObject>::getInstance().map; - auto key = std::type_index(typeid(T)); - auto lb = map.lower_bound(key); - - if (lb != map.end() && lb->first == key) - return; - - typename OutputBindingMap::Serializers serializers; - - serializers.shared_ptr = - [&](void * arptr, void const * dptr, std::type_info const & baseInfo) - { - Archive & ar = *static_cast(arptr); - writeMetadata(ar); - - auto ptr = PolymorphicCasters::template downcast( dptr, baseInfo ); - - #if defined(_MSC_VER) && _MSC_VER < 1916 && !defined(__clang__) - savePolymorphicSharedPtr( ar, ptr, ::cereal::traits::has_shared_from_this::type() ); // MSVC doesn't like typename here - #else // not _MSC_VER - savePolymorphicSharedPtr( ar, ptr, typename ::cereal::traits::has_shared_from_this::type() ); - #endif // _MSC_VER - }; - - serializers.unique_ptr = - [&](void * arptr, void const * dptr, std::type_info const & baseInfo) - { - Archive & ar = *static_cast(arptr); - writeMetadata(ar); - - std::unique_ptr> const ptr( PolymorphicCasters::template downcast( dptr, baseInfo ) ); - - ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper(ptr)) ); - }; - - map.insert( { std::move(key), std::move(serializers) } ); - } - }; - - //! Used to help out argument dependent lookup for finding potential overloads - //! of instantiate_polymorphic_binding - struct adl_tag {}; - - //! Tag for init_binding, bind_to_archives and instantiate_polymorphic_binding. - //! For C++14 and below, we must instantiate a unique StaticObject per TU that is - //! otherwise identical -- otherwise we get multiple definition problems (ODR violations). - //! To achieve this, put a tag in an anonymous namespace and use it as a template argument. - //! - //! For C++17, we can use static inline global variables to unify these definitions across - //! all TUs in the same shared object (DLL). The tag is therefore not necessary. - //! For convenience, keep it to not complicate other code, but don't put it in - //! an anonymous namespace. Now the template instantiations will correspond - //! to the same type, and since they are marked inline with C++17, they will be merged - //! across all TUs. -#ifdef CEREAL_HAS_CPP17 - struct polymorphic_binding_tag {}; -#else - namespace { struct polymorphic_binding_tag {}; } -#endif - - - //! Causes the static object bindings between an archive type and a serializable type T - template - struct create_bindings - { - static const InputBindingCreator & - load(std::true_type) - { - return cereal::detail::StaticObject>::getInstance(); - } - - static const OutputBindingCreator & - save(std::true_type) - { - return cereal::detail::StaticObject>::getInstance(); - } - - inline static void load(std::false_type) {} - inline static void save(std::false_type) {} - }; - - //! When specialized, causes the compiler to instantiate its parameter - template - struct instantiate_function {}; - - /*! This struct is used as the return type of instantiate_polymorphic_binding - for specific Archive types. When the compiler looks for overloads of - instantiate_polymorphic_binding, it will be forced to instantiate this - struct during overload resolution, even though it will not be part of a valid - overload */ - template - struct polymorphic_serialization_support - { - #if defined(_MSC_VER) && !defined(__INTEL_COMPILER) - //! Creates the appropriate bindings depending on whether the archive supports - //! saving or loading - virtual CEREAL_DLL_EXPORT void instantiate() CEREAL_USED; - #else // NOT _MSC_VER - //! Creates the appropriate bindings depending on whether the archive supports - //! saving or loading - static CEREAL_DLL_EXPORT void instantiate() CEREAL_USED; - //! This typedef causes the compiler to instantiate this static function - typedef instantiate_function unused; - #endif // _MSC_VER - }; - - // instantiate implementation - template - CEREAL_DLL_EXPORT void polymorphic_serialization_support::instantiate() - { - create_bindings::save( std::integral_constant::value && - traits::is_output_serializable::value>{} ); - - create_bindings::load( std::integral_constant::value && - traits::is_input_serializable::value>{} ); - } - - //! Begins the binding process of a type to all registered archives - /*! Archives need to be registered prior to this struct being instantiated via - the CEREAL_REGISTER_ARCHIVE macro. Overload resolution will then force - several static objects to be made that allow us to bind together all - registered archive types with the parameter type T. */ - template - struct bind_to_archives - { - //! Binding for non abstract types - void bind(std::false_type) const - { - instantiate_polymorphic_binding(static_cast(nullptr), 0, Tag{}, adl_tag{}); - } - - //! Binding for abstract types - void bind(std::true_type) const - { } - - //! Binds the type T to all registered archives - /*! If T is abstract, we will not serialize it and thus - do not need to make a binding */ - bind_to_archives const & bind() const - { - static_assert( std::is_polymorphic::value, - "Attempting to register non polymorphic type" ); - bind( std::is_abstract() ); - return *this; - } - }; - - //! Used to hide the static object used to bind T to registered archives - template - struct init_binding; - - //! Base case overload for instantiation - /*! This will end up always being the best overload due to the second - parameter always being passed as an int. All other overloads will - accept pointers to archive types and have lower precedence than int. - - Since the compiler needs to check all possible overloads, the - other overloads created via CEREAL_REGISTER_ARCHIVE, which will have - lower precedence due to requring a conversion from int to (Archive*), - will cause their return types to be instantiated through the static object - mechanisms even though they are never called. - - See the documentation for the other functions to try and understand this */ - template - void instantiate_polymorphic_binding( T*, int, BindingTag, adl_tag ) {} - } // namespace detail -} // namespace cereal - -#endif // CEREAL_DETAILS_POLYMORPHIC_IMPL_HPP_ diff --git a/include/cereal/details/polymorphic_impl_fwd.hpp b/include/cereal/details/polymorphic_impl_fwd.hpp deleted file mode 100644 index 83ae7fa..0000000 --- a/include/cereal/details/polymorphic_impl_fwd.hpp +++ /dev/null @@ -1,65 +0,0 @@ -/*! \file polymorphic_impl_fwd.hpp - \brief Internal polymorphism support forward declarations - \ingroup Internal */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* This code is heavily inspired by the boost serialization implementation by the following authors - - (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . - Use, modification and distribution is subject to the Boost Software - License, Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt) - - See http://www.boost.org for updates, documentation, and revision history. - - (C) Copyright 2006 David Abrahams - http://www.boost.org. - - See /boost/serialization/export.hpp and /boost/archive/detail/register_archive.hpp for their - implementation. -*/ - -#ifndef CEREAL_DETAILS_POLYMORPHIC_IMPL_FWD_HPP_ -#define CEREAL_DETAILS_POLYMORPHIC_IMPL_FWD_HPP_ - -namespace cereal -{ - namespace detail - { - //! Forward declaration, see polymorphic_impl.hpp for more information - template - struct RegisterPolymorphicCaster; - - //! Forward declaration, see polymorphic_impl.hpp for more information - struct PolymorphicCasters; - - //! Forward declaration, see polymorphic_impl.hpp for more information - template - struct PolymorphicRelation; - } // namespace detail -} // namespace cereal - -#endif // CEREAL_DETAILS_POLYMORPHIC_IMPL_FWD_HPP_ diff --git a/include/cereal/details/static_object.hpp b/include/cereal/details/static_object.hpp deleted file mode 100644 index 10f7273..0000000 --- a/include/cereal/details/static_object.hpp +++ /dev/null @@ -1,128 +0,0 @@ -/*! \file static_object.hpp - \brief Internal polymorphism static object support - \ingroup Internal */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_DETAILS_STATIC_OBJECT_HPP_ -#define CEREAL_DETAILS_STATIC_OBJECT_HPP_ - -#include "cereal/macros.hpp" - -#if CEREAL_THREAD_SAFE -#include -#endif - -//! Prevent link optimization from removing non-referenced static objects -/*! Especially for polymorphic support, we create static objects which - may not ever be explicitly referenced. Most linkers will detect this - and remove the code causing various unpleasant runtime errors. These - macros, adopted from Boost (see force_include.hpp) prevent this - (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . - Use, modification and distribution is subject to the Boost Software - License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at - http://www.boost.org/LICENSE_1_0.txt) */ - -#if defined(_MSC_VER) && !defined(__clang__) -# define CEREAL_DLL_EXPORT __declspec(dllexport) -# define CEREAL_USED -#else // clang or gcc -# define CEREAL_DLL_EXPORT __attribute__ ((visibility("default"))) -# define CEREAL_USED __attribute__ ((__used__)) -#endif - -namespace cereal -{ - namespace detail - { - //! A static, pre-execution object - /*! This class will create a single copy (singleton) of some - type and ensures that merely referencing this type will - cause it to be instantiated and initialized pre-execution. - For example, this is used heavily in the polymorphic pointer - serialization mechanisms to bind various archive types with - different polymorphic classes */ - template - class CEREAL_DLL_EXPORT StaticObject - { - private: - - static T & create() - { - static T t; - //! Forces instantiation at pre-execution time - (void)instance; - return t; - } - - StaticObject( StaticObject const & /*other*/ ) {} - - public: - static T & getInstance() - { - return create(); - } - - //! A class that acts like std::lock_guard - class LockGuard - { - #if CEREAL_THREAD_SAFE - public: - LockGuard(std::mutex & m) : lock(m) {} - private: - std::unique_lock lock; - #else - public: - LockGuard() = default; - LockGuard(LockGuard const &) = default; // prevents implicit copy ctor warning - ~LockGuard() CEREAL_NOEXCEPT {} // prevents variable not used - #endif - }; - - //! Attempts to lock this static object for the current scope - /*! @note This function is a no-op if cereal is not compiled with - thread safety enabled (CEREAL_THREAD_SAFE = 1). - - This function returns an object that holds a lock for - this StaticObject that will release its lock upon destruction. This - call will block until the lock is available. */ - static LockGuard lock() - { - #if CEREAL_THREAD_SAFE - static std::mutex instanceMutex; - return LockGuard{instanceMutex}; - #else - return LockGuard{}; - #endif - } - - private: - static T & instance; - }; - - template T & StaticObject::instance = StaticObject::create(); - } // namespace detail -} // namespace cereal - -#endif // CEREAL_DETAILS_STATIC_OBJECT_HPP_ diff --git a/include/cereal/details/traits.hpp b/include/cereal/details/traits.hpp deleted file mode 100644 index e1fda1d..0000000 --- a/include/cereal/details/traits.hpp +++ /dev/null @@ -1,1411 +0,0 @@ -/*! \file traits.hpp - \brief Internal type trait support - \ingroup Internal */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_DETAILS_TRAITS_HPP_ -#define CEREAL_DETAILS_TRAITS_HPP_ - -#ifndef __clang__ -#if (__GNUC__ == 4 && __GNUC_MINOR__ <= 7) -#define CEREAL_OLDER_GCC -#endif // gcc 4.7 or earlier -#endif // __clang__ - -#include -#include - -#include "cereal/macros.hpp" -#include "cereal/access.hpp" - -namespace cereal -{ - namespace traits - { - using yes = std::true_type; - using no = std::false_type; - - namespace detail - { - // ###################################################################### - //! Used to delay a static_assert until template instantiation - template - struct delay_static_assert : std::false_type {}; - - // ###################################################################### - // SFINAE Helpers - #ifdef CEREAL_OLDER_GCC // when VS supports better SFINAE, we can use this as the default - template struct Void { typedef void type; }; - #endif // CEREAL_OLDER_GCC - - //! Return type for SFINAE Enablers - enum class sfinae {}; - - // ###################################################################### - // Helper functionality for boolean integral constants and Enable/DisableIf - template struct meta_bool_and : std::integral_constant::value> {}; - template struct meta_bool_and : std::integral_constant {}; - - template struct meta_bool_or : std::integral_constant::value> {}; - template struct meta_bool_or : std::integral_constant {}; - - // workaround needed due to bug in MSVC 2013, see - // http://connect.microsoft.com/VisualStudio/feedback/details/800231/c-11-alias-template-issue - template - struct EnableIfHelper : std::enable_if::value, sfinae> {}; - - template - struct DisableIfHelper : std::enable_if::value, sfinae> {}; - } // namespace detail - - //! Used as the default value for EnableIf and DisableIf template parameters - /*! @relates EnableIf - @relates DisableIf */ - static const detail::sfinae sfinae = {}; - - // ###################################################################### - //! Provides a way to enable a function if conditions are met - /*! This is intended to be used in a near identical fashion to std::enable_if - while being significantly easier to read at the cost of not allowing for as - complicated of a condition. - - This will compile (allow the function) if every condition evaluates to true. - at compile time. This should be used with SFINAE to ensure that at least - one other candidate function works when one fails due to an EnableIf. - - This should be used as the las template parameter to a function as - an unnamed parameter with a default value of cereal::traits::sfinae: - - @code{cpp} - // using by making the last template argument variadic - template ::value> = sfinae> - void func(T t ); - @endcode - - Note that this performs a logical AND of all conditions, so you will need - to construct more complicated requirements with this fact in mind. - - @relates DisableIf - @relates sfinae - @tparam Conditions The conditions which will be logically ANDed to enable the function. */ - template - using EnableIf = typename detail::EnableIfHelper::type; - - // ###################################################################### - //! Provides a way to disable a function if conditions are met - /*! This is intended to be used in a near identical fashion to std::enable_if - while being significantly easier to read at the cost of not allowing for as - complicated of a condition. - - This will compile (allow the function) if every condition evaluates to false. - This should be used with SFINAE to ensure that at least one other candidate - function works when one fails due to a DisableIf. - - This should be used as the las template parameter to a function as - an unnamed parameter with a default value of cereal::traits::sfinae: - - @code{cpp} - // using by making the last template argument variadic - template ::value> = sfinae> - void func(T t ); - @endcode - - This is often used in conjunction with EnableIf to form an enable/disable pair of - overloads. - - Note that this performs a logical AND of all conditions, so you will need - to construct more complicated requirements with this fact in mind. If all conditions - hold, the function will be disabled. - - @relates EnableIf - @relates sfinae - @tparam Conditions The conditions which will be logically ANDed to disable the function. */ - template - using DisableIf = typename detail::DisableIfHelper::type; - - // ###################################################################### - namespace detail - { - template - struct get_output_from_input : no - { - static_assert( detail::delay_static_assert::value, - "Could not find an associated output archive for input archive." ); - }; - - template - struct get_input_from_output : no - { - static_assert( detail::delay_static_assert::value, - "Could not find an associated input archive for output archive." ); - }; - } - - //! Sets up traits that relate an input archive to an output archive - #define CEREAL_SETUP_ARCHIVE_TRAITS(InputArchive, OutputArchive) \ - namespace cereal { namespace traits { namespace detail { \ - template <> struct get_output_from_input \ - { using type = OutputArchive; }; \ - template <> struct get_input_from_output \ - { using type = InputArchive; }; } } } /* end namespaces */ - - // ###################################################################### - //! Used to convert a MAKE_HAS_XXX macro into a versioned variant - #define CEREAL_MAKE_VERSIONED_TEST ,0 - - // ###################################################################### - //! Creates a test for whether a non const member function exists - /*! This creates a class derived from std::integral_constant that will be true if - the type has the proper member function for the given archive. - - @param name The name of the function to test for (e.g. serialize, load, save) - @param test_name The name to give the test for the function being tested for (e.g. serialize, versioned_serialize) - @param versioned Either blank or the macro CEREAL_MAKE_VERSIONED_TEST */ - #ifdef CEREAL_OLDER_GCC - #define CEREAL_MAKE_HAS_MEMBER_TEST(name, test_name, versioned) \ - template \ - struct has_member_##test_name : no {}; \ - template \ - struct has_member_##test_name(), std::declval() versioned ) ) >::type> : yes {} - #else // NOT CEREAL_OLDER_GCC - #define CEREAL_MAKE_HAS_MEMBER_TEST(name, test_name, versioned) \ - namespace detail \ - { \ - template \ - struct has_member_##name##_##versioned##_impl \ - { \ - template \ - static auto test(int) -> decltype( cereal::access::member_##name( std::declval(), std::declval() versioned ), yes()); \ - template \ - static no test(...); \ - static const bool value = std::is_same(0)), yes>::value; \ - }; \ - } /* end namespace detail */ \ - template \ - struct has_member_##test_name : std::integral_constant::value> {} - #endif // NOT CEREAL_OLDER_GCC - - // ###################################################################### - //! Creates a test for whether a non const non-member function exists - /*! This creates a class derived from std::integral_constant that will be true if - the type has the proper non-member function for the given archive. */ - #define CEREAL_MAKE_HAS_NON_MEMBER_TEST(test_name, func, versioned) \ - namespace detail \ - { \ - template \ - struct has_non_member_##test_name##_impl \ - { \ - template \ - static auto test(int) -> decltype( func( std::declval(), std::declval() versioned ), yes()); \ - template \ - static no test( ... ); \ - static const bool value = std::is_same( 0 ) ), yes>::value; \ - }; \ - } /* end namespace detail */ \ - template \ - struct has_non_member_##test_name : std::integral_constant::value> {} - - // ###################################################################### - // Member Serialize - CEREAL_MAKE_HAS_MEMBER_TEST(serialize, serialize,); - - // ###################################################################### - // Member Serialize (versioned) - CEREAL_MAKE_HAS_MEMBER_TEST(serialize, versioned_serialize, CEREAL_MAKE_VERSIONED_TEST); - - // ###################################################################### - // Non Member Serialize - CEREAL_MAKE_HAS_NON_MEMBER_TEST(serialize, CEREAL_SERIALIZE_FUNCTION_NAME,); - - // ###################################################################### - // Non Member Serialize (versioned) - CEREAL_MAKE_HAS_NON_MEMBER_TEST(versioned_serialize, CEREAL_SERIALIZE_FUNCTION_NAME, CEREAL_MAKE_VERSIONED_TEST); - - // ###################################################################### - // Member Load - CEREAL_MAKE_HAS_MEMBER_TEST(load, load,); - - // ###################################################################### - // Member Load (versioned) - CEREAL_MAKE_HAS_MEMBER_TEST(load, versioned_load, CEREAL_MAKE_VERSIONED_TEST); - - // ###################################################################### - // Non Member Load - CEREAL_MAKE_HAS_NON_MEMBER_TEST(load, CEREAL_LOAD_FUNCTION_NAME,); - - // ###################################################################### - // Non Member Load (versioned) - CEREAL_MAKE_HAS_NON_MEMBER_TEST(versioned_load, CEREAL_LOAD_FUNCTION_NAME, CEREAL_MAKE_VERSIONED_TEST); - - // ###################################################################### - #undef CEREAL_MAKE_HAS_NON_MEMBER_TEST - #undef CEREAL_MAKE_HAS_MEMBER_TEST - - // ###################################################################### - //! Creates a test for whether a member save function exists - /*! This creates a class derived from std::integral_constant that will be true if - the type has the proper member function for the given archive. - - @param test_name The name to give the test (e.g. save or versioned_save) - @param versioned Either blank or the macro CEREAL_MAKE_VERSIONED_TEST */ - #ifdef CEREAL_OLDER_GCC - #define CEREAL_MAKE_HAS_MEMBER_SAVE_IMPL(test_name, versioned) \ - namespace detail \ - { \ - template \ - struct has_member_##test_name##_impl \ - { \ - template struct test : no {}; \ - template \ - struct test(), \ - std::declval() versioned ) ) >::type> : yes {}; \ - static const bool value = test(); \ - \ - template struct test2 : no {}; \ - template \ - struct test2(), \ - std::declval::type&>() versioned ) ) >::type> : yes {}; \ - static const bool not_const_type = test2(); \ - }; \ - } /* end namespace detail */ - #else /* NOT CEREAL_OLDER_GCC =================================== */ - #define CEREAL_MAKE_HAS_MEMBER_SAVE_IMPL(test_name, versioned) \ - namespace detail \ - { \ - template \ - struct has_member_##test_name##_impl \ - { \ - template \ - static auto test(int) -> decltype( cereal::access::member_save( std::declval(), \ - std::declval() versioned ), yes()); \ - template static no test(...); \ - static const bool value = std::is_same(0)), yes>::value; \ - \ - template \ - static auto test2(int) -> decltype( cereal::access::member_save_non_const( \ - std::declval(), \ - std::declval::type&>() versioned ), yes()); \ - template static no test2(...); \ - static const bool not_const_type = std::is_same(0)), yes>::value; \ - }; \ - } /* end namespace detail */ - #endif /* NOT CEREAL_OLDER_GCC */ - - // ###################################################################### - // Member Save - CEREAL_MAKE_HAS_MEMBER_SAVE_IMPL(save, ) - - template - struct has_member_save : std::integral_constant::value> - { - typedef typename detail::has_member_save_impl check; - static_assert( check::value || !check::not_const_type, - "cereal detected a non-const save. \n " - "save member functions must always be const" ); - }; - - // ###################################################################### - // Member Save (versioned) - CEREAL_MAKE_HAS_MEMBER_SAVE_IMPL(versioned_save, CEREAL_MAKE_VERSIONED_TEST) - - template - struct has_member_versioned_save : std::integral_constant::value> - { - typedef typename detail::has_member_versioned_save_impl check; - static_assert( check::value || !check::not_const_type, - "cereal detected a versioned non-const save. \n " - "save member functions must always be const" ); - }; - - // ###################################################################### - #undef CEREAL_MAKE_HAS_MEMBER_SAVE_IMPL - - // ###################################################################### - //! Creates a test for whether a non-member save function exists - /*! This creates a class derived from std::integral_constant that will be true if - the type has the proper non-member function for the given archive. - - @param test_name The name to give the test (e.g. save or versioned_save) - @param versioned Either blank or the macro CEREAL_MAKE_VERSIONED_TEST */ - #define CEREAL_MAKE_HAS_NON_MEMBER_SAVE_TEST(test_name, versioned) \ - namespace detail \ - { \ - template \ - struct has_non_member_##test_name##_impl \ - { \ - template \ - static auto test(int) -> decltype( CEREAL_SAVE_FUNCTION_NAME( \ - std::declval(), \ - std::declval() versioned ), yes()); \ - template static no test(...); \ - static const bool value = std::is_same(0)), yes>::value; \ - \ - template \ - static auto test2(int) -> decltype( CEREAL_SAVE_FUNCTION_NAME( \ - std::declval(), \ - std::declval::type&>() versioned ), yes()); \ - template static no test2(...); \ - static const bool not_const_type = std::is_same(0)), yes>::value; \ - }; \ - } /* end namespace detail */ \ - \ - template \ - struct has_non_member_##test_name : std::integral_constant::value> \ - { \ - using check = typename detail::has_non_member_##test_name##_impl; \ - static_assert( check::value || !check::not_const_type, \ - "cereal detected a non-const type parameter in non-member " #test_name ". \n " \ - #test_name " non-member functions must always pass their types as const" ); \ - }; - - // ###################################################################### - // Non Member Save - CEREAL_MAKE_HAS_NON_MEMBER_SAVE_TEST(save, ) - - // ###################################################################### - // Non Member Save (versioned) - CEREAL_MAKE_HAS_NON_MEMBER_SAVE_TEST(versioned_save, CEREAL_MAKE_VERSIONED_TEST) - - // ###################################################################### - #undef CEREAL_MAKE_HAS_NON_MEMBER_SAVE_TEST - - // ###################################################################### - // Minimal Utilities - namespace detail - { - // Determines if the provided type is an std::string - template struct is_string : std::false_type {}; - - template - struct is_string> : std::true_type {}; - } - - // Determines if the type is valid for use with a minimal serialize function - template - struct is_minimal_type : std::integral_constant::value || std::is_arithmetic::value> {}; - - // ###################################################################### - //! Creates implementation details for whether a member save_minimal function exists - /*! This creates a class derived from std::integral_constant that will be true if - the type has the proper member function for the given archive. - - @param test_name The name to give the test (e.g. save_minimal or versioned_save_minimal) - @param versioned Either blank or the macro CEREAL_MAKE_VERSIONED_TEST */ - #ifdef CEREAL_OLDER_GCC - #define CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_IMPL(test_name, versioned) \ - namespace detail \ - { \ - template \ - struct has_member_##test_name##_impl \ - { \ - template struct test : no {}; \ - template \ - struct test(), \ - std::declval() versioned ) ) >::type> : yes {}; \ - \ - static const bool value = test(); \ - \ - template struct test2 : no {}; \ - template \ - struct test2(), \ - std::declval::type&>() versioned ) ) >::type> : yes {}; \ - static const bool not_const_type = test2(); \ - \ - static const bool valid = value || !not_const_type; \ - }; \ - } /* end namespace detail */ - #else /* NOT CEREAL_OLDER_GCC =================================== */ - #define CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_IMPL(test_name, versioned) \ - namespace detail \ - { \ - template \ - struct has_member_##test_name##_impl \ - { \ - template \ - static auto test(int) -> decltype( cereal::access::member_save_minimal( \ - std::declval(), \ - std::declval() versioned ), yes()); \ - template static no test(...); \ - static const bool value = std::is_same(0)), yes>::value; \ - \ - template \ - static auto test2(int) -> decltype( cereal::access::member_save_minimal_non_const( \ - std::declval(), \ - std::declval::type&>() versioned ), yes()); \ - template static no test2(...); \ - static const bool not_const_type = std::is_same(0)), yes>::value; \ - \ - static const bool valid = value || !not_const_type; \ - }; \ - } /* end namespace detail */ - #endif // NOT CEREAL_OLDER_GCC - - // ###################################################################### - //! Creates helpers for minimal save functions - /*! The get_member_*_type structs allow access to the return type of a save_minimal, - assuming that the function actually exists. If the function does not - exist, the type will be void. - - @param test_name The name to give the test (e.g. save_minimal or versioned_save_minimal) - @param versioned Either blank or the macro CEREAL_MAKE_VERSIONED_TEST */ - #define CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_HELPERS_IMPL(test_name, versioned) \ - namespace detail \ - { \ - template \ - struct get_member_##test_name##_type { using type = void; }; \ - \ - template \ - struct get_member_##test_name##_type \ - { \ - using type = decltype( cereal::access::member_save_minimal( std::declval(), \ - std::declval() versioned ) ); \ - }; \ - } /* end namespace detail */ - - // ###################################################################### - //! Creates a test for whether a member save_minimal function exists - /*! This creates a class derived from std::integral_constant that will be true if - the type has the proper member function for the given archive. - - @param test_name The name to give the test (e.g. save_minimal or versioned_save_minimal) */ - #define CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_TEST(test_name) \ - template \ - struct has_member_##test_name : std::integral_constant::value> \ - { \ - using check = typename detail::has_member_##test_name##_impl; \ - static_assert( check::valid, \ - "cereal detected a non-const member " #test_name ". \n " \ - #test_name " member functions must always be const" ); \ - \ - using type = typename detail::get_member_##test_name##_type::type; \ - static_assert( (check::value && is_minimal_type::value) || !check::value, \ - "cereal detected a member " #test_name " with an invalid return type. \n " \ - "return type must be arithmetic or string" ); \ - }; - - // ###################################################################### - // Member Save Minimal - CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_IMPL(save_minimal, ) - CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_HELPERS_IMPL(save_minimal, ) - CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_TEST(save_minimal) - - // ###################################################################### - // Member Save Minimal (versioned) - CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_IMPL(versioned_save_minimal, CEREAL_MAKE_VERSIONED_TEST) - CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_HELPERS_IMPL(versioned_save_minimal, CEREAL_MAKE_VERSIONED_TEST) - CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_TEST(versioned_save_minimal) - - // ###################################################################### - #undef CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_IMPL - #undef CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_HELPERS_IMPL - #undef CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_TEST - - // ###################################################################### - //! Creates a test for whether a non-member save_minimal function exists - /*! This creates a class derived from std::integral_constant that will be true if - the type has the proper member function for the given archive. - - @param test_name The name to give the test (e.g. save_minimal or versioned_save_minimal) - @param versioned Either blank or the macro CEREAL_MAKE_VERSIONED_TEST */ - #define CEREAL_MAKE_HAS_NON_MEMBER_SAVE_MINIMAL_TEST(test_name, versioned) \ - namespace detail \ - { \ - template \ - struct has_non_member_##test_name##_impl \ - { \ - template \ - static auto test(int) -> decltype( CEREAL_SAVE_MINIMAL_FUNCTION_NAME( \ - std::declval(), \ - std::declval() versioned ), yes()); \ - template static no test(...); \ - static const bool value = std::is_same(0)), yes>::value; \ - \ - template \ - static auto test2(int) -> decltype( CEREAL_SAVE_MINIMAL_FUNCTION_NAME( \ - std::declval(), \ - std::declval::type&>() versioned ), yes()); \ - template static no test2(...); \ - static const bool not_const_type = std::is_same(0)), yes>::value; \ - \ - static const bool valid = value || !not_const_type; \ - }; \ - \ - template \ - struct get_non_member_##test_name##_type { using type = void; }; \ - \ - template \ - struct get_non_member_##test_name##_type \ - { \ - using type = decltype( CEREAL_SAVE_MINIMAL_FUNCTION_NAME( std::declval(), \ - std::declval() versioned ) ); \ - }; \ - } /* end namespace detail */ \ - \ - template \ - struct has_non_member_##test_name : std::integral_constant::value> \ - { \ - using check = typename detail::has_non_member_##test_name##_impl; \ - static_assert( check::valid, \ - "cereal detected a non-const type parameter in non-member " #test_name ". \n " \ - #test_name " non-member functions must always pass their types as const" ); \ - \ - using type = typename detail::get_non_member_##test_name##_type::type; \ - static_assert( (check::value && is_minimal_type::value) || !check::value, \ - "cereal detected a non-member " #test_name " with an invalid return type. \n " \ - "return type must be arithmetic or string" ); \ - }; - - // ###################################################################### - // Non-Member Save Minimal - CEREAL_MAKE_HAS_NON_MEMBER_SAVE_MINIMAL_TEST(save_minimal, ) - - // ###################################################################### - // Non-Member Save Minimal (versioned) - CEREAL_MAKE_HAS_NON_MEMBER_SAVE_MINIMAL_TEST(versioned_save_minimal, CEREAL_MAKE_VERSIONED_TEST) - - // ###################################################################### - #undef CEREAL_MAKE_HAS_NON_MEMBER_SAVE_MINIMAL_TEST - - // ###################################################################### - // Load Minimal Utilities - namespace detail - { - //! Used to help strip away conversion wrappers - /*! If someone writes a non-member load/save minimal function that accepts its - parameter as some generic template type and needs to perform trait checks - on that type, our NoConvert wrappers will interfere with this. Using - the struct strip_minmal, users can strip away our wrappers to get to - the underlying type, allowing traits to work properly */ - struct NoConvertBase {}; - - //! A struct that prevents implicit conversion - /*! Any type instantiated with this struct will be unable to implicitly convert - to another type. Is designed to only allow conversion to Source const &. - - @tparam Source the type of the original source */ - template - struct NoConvertConstRef : NoConvertBase - { - using type = Source; //!< Used to get underlying type easily - - template ::value>::type> - operator Dest () = delete; - - //! only allow conversion if the types are the same and we are converting into a const reference - template ::value>::type> - operator Dest const & (); - }; - - //! A struct that prevents implicit conversion - /*! Any type instantiated with this struct will be unable to implicitly convert - to another type. Is designed to only allow conversion to Source &. - - @tparam Source the type of the original source */ - template - struct NoConvertRef : NoConvertBase - { - using type = Source; //!< Used to get underlying type easily - - template ::value>::type> - operator Dest () = delete; - - #ifdef __clang__ - template ::value>::type> - operator Dest const & () = delete; - #endif // __clang__ - - //! only allow conversion if the types are the same and we are converting into a const reference - template ::value>::type> - operator Dest & (); - }; - - //! A type that can implicitly convert to anything else - struct AnyConvert - { - template - operator Dest & (); - - template - operator Dest const & () const; - }; - } // namespace detail - - // ###################################################################### - //! Creates a test for whether a member load_minimal function exists - /*! This creates a class derived from std::integral_constant that will be true if - the type has the proper member function for the given archive. - - Our strategy here is to first check if a function matching the signature more or less exists - (allow anything like load_minimal(xxx) using AnyConvert, and then secondly enforce - that it has the correct signature using NoConvertConstRef - - @param test_name The name to give the test (e.g. load_minimal or versioned_load_minimal) - @param versioned Either blank or the macro CEREAL_MAKE_VERSIONED_TEST */ - #ifdef CEREAL_OLDER_GCC - #define CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_IMPL(test_name, versioned) \ - namespace detail \ - { \ - template struct has_member_##test_name##_impl : no {}; \ - template \ - struct has_member_##test_name##_impl(), \ - std::declval(), AnyConvert() versioned ) ) >::type> : yes {}; \ - \ - template struct has_member_##test_name##_type_impl : no {}; \ - template \ - struct has_member_##test_name##_type_impl(), \ - std::declval(), NoConvertConstRef() versioned ) ) >::type> : yes {}; \ - } /* end namespace detail */ - #else /* NOT CEREAL_OLDER_GCC =================================== */ - #define CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_IMPL(test_name, versioned) \ - namespace detail \ - { \ - template \ - struct has_member_##test_name##_impl \ - { \ - template \ - static auto test(int) -> decltype( cereal::access::member_load_minimal( \ - std::declval(), \ - std::declval(), AnyConvert() versioned ), yes()); \ - template static no test(...); \ - static const bool value = std::is_same(0)), yes>::value; \ - }; \ - template \ - struct has_member_##test_name##_type_impl \ - { \ - template \ - static auto test(int) -> decltype( cereal::access::member_load_minimal( \ - std::declval(), \ - std::declval(), NoConvertConstRef() versioned ), yes()); \ - template static no test(...); \ - static const bool value = std::is_same(0)), yes>::value; \ - \ - }; \ - } /* end namespace detail */ - #endif // NOT CEREAL_OLDER_GCC - - // ###################################################################### - //! Creates helpers for minimal load functions - /*! The has_member_*_wrapper structs ensure that the load and save types for the - requested function type match appropriately. - - @param load_test_name The name to give the test (e.g. load_minimal or versioned_load_minimal) - @param save_test_name The name to give the test (e.g. save_minimal or versioned_save_minimal, - should match the load name. - @param save_test_prefix The name to give the test (e.g. save_minimal or versioned_save_minimal, - should match the load name, without the trailing "_minimal" (e.g. - save or versioned_save). Needed because the preprocessor is an abomination. - @param versioned Either blank or the macro CEREAL_MAKE_VERSIONED_TEST */ - #define CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_HELPERS_IMPL(load_test_name, save_test_name, save_test_prefix, versioned) \ - namespace detail \ - { \ - template \ - struct has_member_##load_test_name##_wrapper : std::false_type {}; \ - \ - template \ - struct has_member_##load_test_name##_wrapper \ - { \ - using AOut = typename detail::get_output_from_input::type; \ - \ - static_assert( has_member_##save_test_prefix##_minimal::value, \ - "cereal detected member " #load_test_name " but no valid member " #save_test_name ". \n " \ - "cannot evaluate correctness of " #load_test_name " without valid " #save_test_name "." ); \ - \ - using SaveType = typename detail::get_member_##save_test_prefix##_minimal_type::type; \ - const static bool value = has_member_##load_test_name##_impl::value; \ - const static bool valid = has_member_##load_test_name##_type_impl::value; \ - \ - static_assert( valid || !value, "cereal detected different or invalid types in corresponding member " \ - #load_test_name " and " #save_test_name " functions. \n " \ - "the paramater to " #load_test_name " must be a constant reference to the type that " \ - #save_test_name " returns." ); \ - }; \ - } /* end namespace detail */ - - // ###################################################################### - //! Creates a test for whether a member load_minimal function exists - /*! This creates a class derived from std::integral_constant that will be true if - the type has the proper member function for the given archive. - - @param load_test_name The name to give the test (e.g. load_minimal or versioned_load_minimal) - @param load_test_prefix The above parameter minus the trailing "_minimal" */ - #define CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_TEST(load_test_name, load_test_prefix) \ - template \ - struct has_member_##load_test_prefix##_minimal : std::integral_constant::value>::value> {}; - - // ###################################################################### - // Member Load Minimal - CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_IMPL(load_minimal, ) - CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_HELPERS_IMPL(load_minimal, save_minimal, save, ) - CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_TEST(load_minimal, load) - - // ###################################################################### - // Member Load Minimal (versioned) - CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_IMPL(versioned_load_minimal, CEREAL_MAKE_VERSIONED_TEST) - CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_HELPERS_IMPL(versioned_load_minimal, versioned_save_minimal, versioned_save, CEREAL_MAKE_VERSIONED_TEST) - CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_TEST(versioned_load_minimal, versioned_load) - - // ###################################################################### - #undef CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_IMPL - #undef CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_HELPERS_IMPL - #undef CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_TEST - - // ###################################################################### - // Non-Member Load Minimal - namespace detail - { - #ifdef CEREAL_OLDER_GCC - void CEREAL_LOAD_MINIMAL_FUNCTION_NAME(); // prevents nonsense complaining about not finding this - void CEREAL_SAVE_MINIMAL_FUNCTION_NAME(); - #endif // CEREAL_OLDER_GCC - } // namespace detail - - // ###################################################################### - //! Creates a test for whether a non-member load_minimal function exists - /*! This creates a class derived from std::integral_constant that will be true if - the type has the proper member function for the given archive. - - See notes from member load_minimal implementation. - - Note that there should be an additional const check on load_minimal after the valid check, - but this currently interferes with many valid uses of minimal serialization. It has been - removed (see #565 on github) and previously was: - - @code - static_assert( check::const_valid || !check::exists, - "cereal detected an invalid serialization type parameter in non-member " #test_name ". " - #test_name " non-member functions must accept their serialization type by non-const reference" ); - @endcode - - See #132, #436, #263, and #565 on https://github.com/USCiLab/cereal for more details. - - @param test_name The name to give the test (e.g. load_minimal or versioned_load_minimal) - @param save_name The corresponding name the save test would have (e.g. save_minimal or versioned_save_minimal) - @param versioned Either blank or the macro CEREAL_MAKE_VERSIONED_TEST */ - #define CEREAL_MAKE_HAS_NON_MEMBER_LOAD_MINIMAL_TEST(test_name, save_name, versioned) \ - namespace detail \ - { \ - template \ - struct has_non_member_##test_name##_impl \ - { \ - template \ - static auto test(int) -> decltype( CEREAL_LOAD_MINIMAL_FUNCTION_NAME( \ - std::declval(), std::declval(), AnyConvert() versioned ), yes() ); \ - template static no test( ... ); \ - static const bool exists = std::is_same( 0 ) ), yes>::value; \ - \ - template \ - static auto test2(int) -> decltype( CEREAL_LOAD_MINIMAL_FUNCTION_NAME( \ - std::declval(), std::declval(), NoConvertConstRef() versioned ), yes() ); \ - template static no test2( ... ); \ - static const bool valid = std::is_same( 0 ) ), yes>::value; \ - \ - template \ - static auto test3(int) -> decltype( CEREAL_LOAD_MINIMAL_FUNCTION_NAME( \ - std::declval(), NoConvertRef(), AnyConvert() versioned ), yes() ); \ - template static no test3( ... ); \ - static const bool const_valid = std::is_same( 0 ) ), yes>::value; \ - }; \ - \ - template \ - struct has_non_member_##test_name##_wrapper : std::false_type {}; \ - \ - template \ - struct has_non_member_##test_name##_wrapper \ - { \ - using AOut = typename detail::get_output_from_input::type; \ - \ - static_assert( detail::has_non_member_##save_name##_impl::valid, \ - "cereal detected non-member " #test_name " but no valid non-member " #save_name ". \n " \ - "cannot evaluate correctness of " #test_name " without valid " #save_name "." ); \ - \ - using SaveType = typename detail::get_non_member_##save_name##_type::type; \ - using check = has_non_member_##test_name##_impl; \ - static const bool value = check::exists; \ - \ - static_assert( check::valid || !check::exists, "cereal detected different types in corresponding non-member " \ - #test_name " and " #save_name " functions. \n " \ - "the paramater to " #test_name " must be a constant reference to the type that " #save_name " returns." ); \ - }; \ - } /* namespace detail */ \ - \ - template \ - struct has_non_member_##test_name : std::integral_constant::exists>::value> {}; - - // ###################################################################### - // Non-Member Load Minimal - CEREAL_MAKE_HAS_NON_MEMBER_LOAD_MINIMAL_TEST(load_minimal, save_minimal, ) - - // ###################################################################### - // Non-Member Load Minimal (versioned) - CEREAL_MAKE_HAS_NON_MEMBER_LOAD_MINIMAL_TEST(versioned_load_minimal, versioned_save_minimal, CEREAL_MAKE_VERSIONED_TEST) - - // ###################################################################### - #undef CEREAL_MAKE_HAS_NON_MEMBER_LOAD_MINIMAL_TEST - - // ###################################################################### - namespace detail - { - // const stripped away before reaching here, prevents errors on conversion from - // construct to construct - template - struct has_member_load_and_construct_impl : std::integral_constant( std::declval(), std::declval< ::cereal::construct&>() ) ), void>::value> - { }; - - template - struct has_member_versioned_load_and_construct_impl : std::integral_constant( std::declval(), std::declval< ::cereal::construct&>(), 0 ) ), void>::value> - { }; - } // namespace detail - - //! Member load and construct check - template - struct has_member_load_and_construct : detail::has_member_load_and_construct_impl::type, A> - { }; - - //! Member load and construct check (versioned) - template - struct has_member_versioned_load_and_construct : detail::has_member_versioned_load_and_construct_impl::type, A> - { }; - - // ###################################################################### - //! Creates a test for whether a non-member load_and_construct specialization exists - /*! This creates a class derived from std::integral_constant that will be true if - the type has the proper non-member function for the given archive. */ - #define CEREAL_MAKE_HAS_NON_MEMBER_LOAD_AND_CONSTRUCT_TEST(test_name, versioned) \ - namespace detail \ - { \ - template \ - struct has_non_member_##test_name##_impl \ - { \ - template \ - static auto test(int) -> decltype( LoadAndConstruct::load_and_construct( \ - std::declval(), std::declval< ::cereal::construct&>() versioned ), yes()); \ - template \ - static no test( ... ); \ - static const bool value = std::is_same( 0 ) ), yes>::value; \ - }; \ - } /* end namespace detail */ \ - template \ - struct has_non_member_##test_name : \ - std::integral_constant::type, A>::value> {}; - - // ###################################################################### - //! Non member load and construct check - CEREAL_MAKE_HAS_NON_MEMBER_LOAD_AND_CONSTRUCT_TEST(load_and_construct, ) - - // ###################################################################### - //! Non member load and construct check (versioned) - CEREAL_MAKE_HAS_NON_MEMBER_LOAD_AND_CONSTRUCT_TEST(versioned_load_and_construct, CEREAL_MAKE_VERSIONED_TEST) - - // ###################################################################### - //! Has either a member or non member load and construct - template - struct has_load_and_construct : std::integral_constant::value || has_non_member_load_and_construct::value || - has_member_versioned_load_and_construct::value || has_non_member_versioned_load_and_construct::value> - { }; - - // ###################################################################### - #undef CEREAL_MAKE_HAS_NON_MEMBER_LOAD_AND_CONSTRUCT_TEST - - // ###################################################################### - // End of serialization existence tests - #undef CEREAL_MAKE_VERSIONED_TEST - - // ###################################################################### - template - struct has_member_split : std::integral_constant::value && has_member_save::value) || - (has_member_versioned_load::value && has_member_versioned_save::value)> {}; - - // ###################################################################### - template - struct has_non_member_split : std::integral_constant::value && has_non_member_save::value) || - (has_non_member_versioned_load::value && has_non_member_versioned_save::value)> {}; - - // ###################################################################### - template - struct has_invalid_output_versioning : std::integral_constant::value && has_member_save::value) || - (has_non_member_versioned_save::value && has_non_member_save::value) || - (has_member_versioned_serialize::value && has_member_serialize::value) || - (has_non_member_versioned_serialize::value && has_non_member_serialize::value) || - (has_member_versioned_save_minimal::value && has_member_save_minimal::value) || - (has_non_member_versioned_save_minimal::value && has_non_member_save_minimal::value)> {}; - - // ###################################################################### - template - struct has_invalid_input_versioning : std::integral_constant::value && has_member_load::value) || - (has_non_member_versioned_load::value && has_non_member_load::value) || - (has_member_versioned_serialize::value && has_member_serialize::value) || - (has_non_member_versioned_serialize::value && has_non_member_serialize::value) || - (has_member_versioned_load_minimal::value && has_member_load_minimal::value) || - (has_non_member_versioned_load_minimal::value && has_non_member_load_minimal::value)> {}; - - // ###################################################################### - namespace detail - { - //! Create a test for a cereal::specialization entry - #define CEREAL_MAKE_IS_SPECIALIZED_IMPL(name) \ - template \ - struct is_specialized_##name : std::integral_constant>::value> {} - - CEREAL_MAKE_IS_SPECIALIZED_IMPL(member_serialize); - CEREAL_MAKE_IS_SPECIALIZED_IMPL(member_load_save); - CEREAL_MAKE_IS_SPECIALIZED_IMPL(member_load_save_minimal); - CEREAL_MAKE_IS_SPECIALIZED_IMPL(non_member_serialize); - CEREAL_MAKE_IS_SPECIALIZED_IMPL(non_member_load_save); - CEREAL_MAKE_IS_SPECIALIZED_IMPL(non_member_load_save_minimal); - - #undef CEREAL_MAKE_IS_SPECIALIZED_IMPL - - //! Number of specializations detected - template - struct count_specializations : std::integral_constant::value + - is_specialized_member_load_save::value + - is_specialized_member_load_save_minimal::value + - is_specialized_non_member_serialize::value + - is_specialized_non_member_load_save::value + - is_specialized_non_member_load_save_minimal::value> {}; - } // namespace detail - - //! Check if any specialization exists for a type - template - struct is_specialized : std::integral_constant::value || - detail::is_specialized_member_load_save::value || - detail::is_specialized_member_load_save_minimal::value || - detail::is_specialized_non_member_serialize::value || - detail::is_specialized_non_member_load_save::value || - detail::is_specialized_non_member_load_save_minimal::value> - { - static_assert(detail::count_specializations::value <= 1, "More than one explicit specialization detected for type."); - }; - - //! Create the static assertion for some specialization - /*! This assertion will fail if the type is indeed specialized and does not have the appropriate - type of serialization functions */ - #define CEREAL_MAKE_IS_SPECIALIZED_ASSERT(name, versioned_name, print_name, spec_name) \ - static_assert( (is_specialized::value && detail::is_specialized_##spec_name::value && \ - (has_##name::value || has_##versioned_name::value)) \ - || !(is_specialized::value && detail::is_specialized_##spec_name::value), \ - "cereal detected " #print_name " specialization but no " #print_name " serialize function" ) - - //! Generates a test for specialization for versioned and unversioned functions - /*! This creates checks that can be queried to see if a given type of serialization function - has been specialized for this type */ - #define CEREAL_MAKE_IS_SPECIALIZED(name, versioned_name, spec_name) \ - template \ - struct is_specialized_##name : std::integral_constant::value && detail::is_specialized_##spec_name::value> \ - { CEREAL_MAKE_IS_SPECIALIZED_ASSERT(name, versioned_name, name, spec_name); }; \ - template \ - struct is_specialized_##versioned_name : std::integral_constant::value && detail::is_specialized_##spec_name::value> \ - { CEREAL_MAKE_IS_SPECIALIZED_ASSERT(name, versioned_name, versioned_name, spec_name); } - - CEREAL_MAKE_IS_SPECIALIZED(member_serialize, member_versioned_serialize, member_serialize); - CEREAL_MAKE_IS_SPECIALIZED(non_member_serialize, non_member_versioned_serialize, non_member_serialize); - - CEREAL_MAKE_IS_SPECIALIZED(member_save, member_versioned_save, member_load_save); - CEREAL_MAKE_IS_SPECIALIZED(non_member_save, non_member_versioned_save, non_member_load_save); - CEREAL_MAKE_IS_SPECIALIZED(member_load, member_versioned_load, member_load_save); - CEREAL_MAKE_IS_SPECIALIZED(non_member_load, non_member_versioned_load, non_member_load_save); - - CEREAL_MAKE_IS_SPECIALIZED(member_save_minimal, member_versioned_save_minimal, member_load_save_minimal); - CEREAL_MAKE_IS_SPECIALIZED(non_member_save_minimal, non_member_versioned_save_minimal, non_member_load_save_minimal); - CEREAL_MAKE_IS_SPECIALIZED(member_load_minimal, member_versioned_load_minimal, member_load_save_minimal); - CEREAL_MAKE_IS_SPECIALIZED(non_member_load_minimal, non_member_versioned_load_minimal, non_member_load_save_minimal); - - #undef CEREAL_MAKE_IS_SPECIALIZED_ASSERT - #undef CEREAL_MAKE_IS_SPECIALIZED - - // ###################################################################### - // detects if a type has any active minimal output serialization - template - struct has_minimal_output_serialization : std::integral_constant::value || - ((has_member_save_minimal::value || - has_non_member_save_minimal::value || - has_member_versioned_save_minimal::value || - has_non_member_versioned_save_minimal::value) && - !(is_specialized_member_serialize::value || - is_specialized_member_save::value))> {}; - - // ###################################################################### - // detects if a type has any active minimal input serialization - template - struct has_minimal_input_serialization : std::integral_constant::value || - ((has_member_load_minimal::value || - has_non_member_load_minimal::value || - has_member_versioned_load_minimal::value || - has_non_member_versioned_load_minimal::value) && - !(is_specialized_member_serialize::value || - is_specialized_member_load::value))> {}; - - // ###################################################################### - namespace detail - { - //! The number of output serialization functions available - /*! If specialization is being used, we'll count only those; otherwise we'll count everything */ - template - struct count_output_serializers : std::integral_constant::value ? count_specializations::value : - has_member_save::value + - has_non_member_save::value + - has_member_serialize::value + - has_non_member_serialize::value + - has_member_save_minimal::value + - has_non_member_save_minimal::value + - /*-versioned---------------------------------------------------------*/ - has_member_versioned_save::value + - has_non_member_versioned_save::value + - has_member_versioned_serialize::value + - has_non_member_versioned_serialize::value + - has_member_versioned_save_minimal::value + - has_non_member_versioned_save_minimal::value> {}; - } - - template - struct is_output_serializable : std::integral_constant::value == 1> {}; - - // ###################################################################### - namespace detail - { - //! The number of input serialization functions available - /*! If specialization is being used, we'll count only those; otherwise we'll count everything */ - template - struct count_input_serializers : std::integral_constant::value ? count_specializations::value : - has_member_load::value + - has_non_member_load::value + - has_member_serialize::value + - has_non_member_serialize::value + - has_member_load_minimal::value + - has_non_member_load_minimal::value + - /*-versioned---------------------------------------------------------*/ - has_member_versioned_load::value + - has_non_member_versioned_load::value + - has_member_versioned_serialize::value + - has_non_member_versioned_serialize::value + - has_member_versioned_load_minimal::value + - has_non_member_versioned_load_minimal::value> {}; - } - - template - struct is_input_serializable : std::integral_constant::value == 1> {}; - - // ###################################################################### - // Base Class Support - namespace detail - { - struct base_class_id - { - template - base_class_id(T const * const t) : - type(typeid(T)), - ptr(t), - hash(std::hash()(typeid(T)) ^ (std::hash()(t) << 1)) - { } - - bool operator==(base_class_id const & other) const - { return (type == other.type) && (ptr == other.ptr); } - - std::type_index type; - void const * ptr; - size_t hash; - }; - struct base_class_id_hash { size_t operator()(base_class_id const & id) const { return id.hash; } }; - } // namespace detail - - namespace detail - { - //! Common base type for base class casting - struct BaseCastBase {}; - - template - struct get_base_class; - - template class Cast, class Base> - struct get_base_class> - { - using type = Base; - }; - - //! Base class cast, behave as the test - template class Test, class Archive, - bool IsBaseCast = std::is_base_of::value> - struct has_minimal_base_class_serialization_impl : Test::type, Archive> - { }; - - //! Not a base class cast - template class Test, class Archive> - struct has_minimal_base_class_serialization_impl : std::false_type - { }; - } - - //! Checks to see if the base class used in a cast has a minimal serialization - /*! @tparam Cast Either base_class or virtual_base_class wrapped type - @tparam Test A has_minimal test (for either input or output) - @tparam Archive The archive to use with the test */ - template class Test, class Archive> - struct has_minimal_base_class_serialization : detail::has_minimal_base_class_serialization_impl - { }; - - - // ###################################################################### - namespace detail - { - struct shared_from_this_wrapper - { - template - static auto (check)( U const & t ) -> decltype( ::cereal::access::shared_from_this(t), std::true_type() ); - - static auto (check)( ... ) -> decltype( std::false_type() ); - - template - static auto get( U const & t ) -> decltype( t.shared_from_this() ); - }; - } - - //! Determine if T or any base class of T has inherited from std::enable_shared_from_this - template - struct has_shared_from_this : decltype((detail::shared_from_this_wrapper::check)(std::declval())) - { }; - - //! Get the type of the base class of T which inherited from std::enable_shared_from_this - template - struct get_shared_from_this_base - { - private: - using PtrType = decltype(detail::shared_from_this_wrapper::get(std::declval())); - public: - //! The type of the base of T that inherited from std::enable_shared_from_this - using type = typename std::decay::type; - }; - - // ###################################################################### - //! Extracts the true type from something possibly wrapped in a cereal NoConvert - /*! Internally cereal uses some wrapper classes to test the validity of non-member - minimal load and save functions. This can interfere with user type traits on - templated load and save minimal functions. To get to the correct underlying type, - users should use strip_minimal when performing any enable_if type type trait checks. - - See the enum serialization in types/common.hpp for an example of using this */ - template ::value> - struct strip_minimal - { - using type = T; - }; - - //! Specialization for types wrapped in a NoConvert - template - struct strip_minimal - { - using type = typename T::type; - }; - - // ###################################################################### - //! Determines whether the class T can be default constructed by cereal::access - template - struct is_default_constructible - { - #ifdef CEREAL_OLDER_GCC - template - struct test : no {}; - template - struct test() ) >::type> : yes {}; - static const bool value = test(); - #else // NOT CEREAL_OLDER_GCC ========================================= - template - static auto test(int) -> decltype( cereal::access::construct(), yes()); - template - static no test(...); - static const bool value = std::is_same(0)), yes>::value; - #endif // NOT CEREAL_OLDER_GCC - }; - - // ###################################################################### - namespace detail - { - //! Removes all qualifiers and minimal wrappers from an archive - template - using decay_archive = typename std::decay::type>::type; - } - - //! Checks if the provided archive type is equal to some cereal archive type - /*! This automatically does things such as std::decay and removing any other wrappers that may be - on the Archive template parameter. - - Example use: - @code{cpp} - // example use to disable a serialization function - template ::value> = sfinae> - void save( Archive & ar, MyType const & mt ); - @endcode */ - template - struct is_same_archive : std::integral_constant, CerealArchiveT>::value> - { }; - - // ###################################################################### - //! A macro to use to restrict which types of archives your function will work for. - /*! This requires you to have a template class parameter named Archive and replaces the void return - type for your function. - - INTYPE refers to the input archive type you wish to restrict on. - OUTTYPE refers to the output archive type you wish to restrict on. - - For example, if we want to limit a serialize to only work with binary serialization: - - @code{.cpp} - template - CEREAL_ARCHIVE_RESTRICT(BinaryInputArchive, BinaryOutputArchive) - serialize( Archive & ar, MyCoolType & m ) - { - ar & m; - } - @endcode - - If you need to do more restrictions in your enable_if, you will need to do this by hand. - */ - #define CEREAL_ARCHIVE_RESTRICT(INTYPE, OUTTYPE) \ - typename std::enable_if::value || cereal::traits::is_same_archive::value, void>::type - - //! Type traits only struct used to mark an archive as human readable (text based) - /*! Archives that wish to identify as text based/human readable should inherit from - this struct */ - struct TextArchive {}; - - //! Checks if an archive is a text archive (human readable) - template - struct is_text_archive : std::integral_constant>::value> - { }; - } // namespace traits - - // ###################################################################### - namespace detail - { - template ::value, - bool MemberVersioned = traits::has_member_versioned_load_and_construct::value, - bool NonMember = traits::has_non_member_load_and_construct::value, - bool NonMemberVersioned = traits::has_non_member_versioned_load_and_construct::value> - struct Construct - { - static_assert( cereal::traits::detail::delay_static_assert::value, - "cereal found more than one compatible load_and_construct function for the provided type and archive combination. \n\n " - "Types must either have a member load_and_construct function or a non-member specialization of LoadAndConstruct (you may not mix these). \n " - "In addition, you may not mix versioned with non-versioned load_and_construct functions. \n\n " ); - static T * load_andor_construct( A & /*ar*/, construct & /*construct*/ ) - { return nullptr; } - }; - - // no load and construct case - template - struct Construct - { - static_assert( ::cereal::traits::is_default_constructible::value, - "Trying to serialize a an object with no default constructor. \n\n " - "Types must either be default constructible or define either a member or non member Construct function. \n " - "Construct functions generally have the signature: \n\n " - "template \n " - "static void load_and_construct(Archive & ar, cereal::construct & construct) \n " - "{ \n " - " var a; \n " - " ar( a ) \n " - " construct( a ); \n " - "} \n\n" ); - static T * load_andor_construct() - { return ::cereal::access::construct(); } - }; - - // member non-versioned - template - struct Construct - { - static void load_andor_construct( A & ar, construct & construct ) - { - access::load_and_construct( ar, construct ); - } - }; - - // member versioned - template - struct Construct - { - static void load_andor_construct( A & ar, construct & construct ) - { - const auto version = ar.template loadClassVersion(); - access::load_and_construct( ar, construct, version ); - } - }; - - // non-member non-versioned - template - struct Construct - { - static void load_andor_construct( A & ar, construct & construct ) - { - LoadAndConstruct::load_and_construct( ar, construct ); - } - }; - - // non-member versioned - template - struct Construct - { - static void load_andor_construct( A & ar, construct & construct ) - { - const auto version = ar.template loadClassVersion(); - LoadAndConstruct::load_and_construct( ar, construct, version ); - } - }; - } // namespace detail -} // namespace cereal - -#endif // CEREAL_DETAILS_TRAITS_HPP_ diff --git a/include/cereal/details/util.hpp b/include/cereal/details/util.hpp deleted file mode 100644 index e4aebe9..0000000 --- a/include/cereal/details/util.hpp +++ /dev/null @@ -1,84 +0,0 @@ -/*! \file util.hpp - \brief Internal misc utilities - \ingroup Internal */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_DETAILS_UTIL_HPP_ -#define CEREAL_DETAILS_UTIL_HPP_ - -#include -#include - -#ifdef _MSC_VER -namespace cereal -{ - namespace util - { - //! Demangles the type encoded in a string - /*! @internal */ - inline std::string demangle( std::string const & name ) - { return name; } - - //! Gets the demangled name of a type - /*! @internal */ - template inline - std::string demangledName() - { return typeid( T ).name(); } - } // namespace util -} // namespace cereal -#else // clang or gcc -#include -#include -namespace cereal -{ - namespace util - { - //! Demangles the type encoded in a string - /*! @internal */ - inline std::string demangle(std::string mangledName) - { - int status = 0; - char *demangledName = nullptr; - std::size_t len; - - demangledName = abi::__cxa_demangle(mangledName.c_str(), 0, &len, &status); - - std::string retName(demangledName); - free(demangledName); - - return retName; - } - - //! Gets the demangled name of a type - /*! @internal */ - template inline - std::string demangledName() - { return demangle(typeid(T).name()); } - } -} // namespace cereal -#endif // clang or gcc branch of _MSC_VER -#endif // CEREAL_DETAILS_UTIL_HPP_ diff --git a/include/cereal/external/LICENSE b/include/cereal/external/LICENSE deleted file mode 100644 index 66300b6..0000000 --- a/include/cereal/external/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (C) 2004-2008 René Nyffenegger - -This source code is provided 'as-is', without any express or implied -warranty. In no event will the author be held liable for any damages -arising from the use of this software. - -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it -freely, subject to the following restrictions: - -1. The origin of this source code must not be misrepresented; you must not - claim that you wrote the original source code. If you use this source code - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - -2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original source code. - -3. This notice may not be removed or altered from any source distribution. - -René Nyffenegger rene.nyffenegger@adp-gmbh.ch diff --git a/include/cereal/external/base64.hpp b/include/cereal/external/base64.hpp deleted file mode 100644 index ce32324..0000000 --- a/include/cereal/external/base64.hpp +++ /dev/null @@ -1,134 +0,0 @@ -/* - Copyright (C) 2004-2008 René Nyffenegger - - This source code is provided 'as-is', without any express or implied - warranty. In no event will the author be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this source code must not be misrepresented; you must not - claim that you wrote the original source code. If you use this source code - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original source code. - - 3. This notice may not be removed or altered from any source distribution. - - René Nyffenegger rene.nyffenegger@adp-gmbh.ch -*/ - -#ifndef CEREAL_EXTERNAL_BASE64_HPP_ -#define CEREAL_EXTERNAL_BASE64_HPP_ - -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - -#include - -namespace cereal -{ - namespace base64 - { - static const std::string chars = - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; - - static inline bool is_base64(unsigned char c) { - return (isalnum(c) || (c == '+') || (c == '/')); - } - - inline std::string encode(unsigned char const* bytes_to_encode, size_t in_len) { - std::string ret; - int i = 0; - int j = 0; - unsigned char char_array_3[3]; - unsigned char char_array_4[4]; - - while (in_len--) { - char_array_3[i++] = *(bytes_to_encode++); - if (i == 3) { - char_array_4[0] = static_cast((char_array_3[0] & 0xfc) >> 2); - char_array_4[1] = static_cast( ( ( char_array_3[0] & 0x03 ) << 4 ) + ( ( char_array_3[1] & 0xf0 ) >> 4 ) ); - char_array_4[2] = static_cast( ( ( char_array_3[1] & 0x0f ) << 2 ) + ( ( char_array_3[2] & 0xc0 ) >> 6 ) ); - char_array_4[3] = static_cast( char_array_3[2] & 0x3f ); - - for(i = 0; (i <4) ; i++) - ret += chars[char_array_4[i]]; - i = 0; - } - } - - if (i) - { - for(j = i; j < 3; j++) - char_array_3[j] = '\0'; - - char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; - char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); - char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); - char_array_4[3] = char_array_3[2] & 0x3f; - - for (j = 0; (j < i + 1); j++) - ret += chars[char_array_4[j]]; - - while((i++ < 3)) - ret += '='; - } - - return ret; - } - - inline std::string decode(std::string const& encoded_string) { - size_t in_len = encoded_string.size(); - size_t i = 0; - size_t j = 0; - int in_ = 0; - unsigned char char_array_4[4], char_array_3[3]; - std::string ret; - - while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { - char_array_4[i++] = encoded_string[in_]; in_++; - if (i ==4) { - for (i = 0; i <4; i++) - char_array_4[i] = static_cast(chars.find( char_array_4[i] )); - - char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); - char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); - char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; - - for (i = 0; (i < 3); i++) - ret += char_array_3[i]; - i = 0; - } - } - - if (i) { - for (j = i; j <4; j++) - char_array_4[j] = 0; - - for (j = 0; j <4; j++) - char_array_4[j] = static_cast(chars.find( char_array_4[j] )); - - char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); - char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); - char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; - - for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; - } - - return ret; - } - } // namespace base64 -} // namespace cereal -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif -#endif // CEREAL_EXTERNAL_BASE64_HPP_ diff --git a/include/cereal/external/rapidjson/LICENSE b/include/cereal/external/rapidjson/LICENSE deleted file mode 100644 index 4546f15..0000000 --- a/include/cereal/external/rapidjson/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Tencent is pleased to support the open source community by making RapidJSON available. - -Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. - -Licensed under the MIT License (the "License"); you may not use this file except -in compliance with the License. You may obtain a copy of the License at - -http://opensource.org/licenses/MIT - -Unless required by applicable law or agreed to in writing, software distributed -under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -CONDITIONS OF ANY KIND, either express or implied. See the License for the -specific language governing permissions and limitations under the License. diff --git a/include/cereal/external/rapidjson/allocators.h b/include/cereal/external/rapidjson/allocators.h deleted file mode 100644 index d375e28..0000000 --- a/include/cereal/external/rapidjson/allocators.h +++ /dev/null @@ -1,284 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_ALLOCATORS_H_ -#define CEREAL_RAPIDJSON_ALLOCATORS_H_ - -#include "rapidjson.h" - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -/////////////////////////////////////////////////////////////////////////////// -// Allocator - -/*! \class rapidjson::Allocator - \brief Concept for allocating, resizing and freeing memory block. - - Note that Malloc() and Realloc() are non-static but Free() is static. - - So if an allocator need to support Free(), it needs to put its pointer in - the header of memory block. - -\code -concept Allocator { - static const bool kNeedFree; //!< Whether this allocator needs to call Free(). - - // Allocate a memory block. - // \param size of the memory block in bytes. - // \returns pointer to the memory block. - void* Malloc(size_t size); - - // Resize a memory block. - // \param originalPtr The pointer to current memory block. Null pointer is permitted. - // \param originalSize The current size in bytes. (Design issue: since some allocator may not book-keep this, explicitly pass to it can save memory.) - // \param newSize the new size in bytes. - void* Realloc(void* originalPtr, size_t originalSize, size_t newSize); - - // Free a memory block. - // \param pointer to the memory block. Null pointer is permitted. - static void Free(void *ptr); -}; -\endcode -*/ - - -/*! \def CEREAL_RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY - \ingroup CEREAL_RAPIDJSON_CONFIG - \brief User-defined kDefaultChunkCapacity definition. - - User can define this as any \c size that is a power of 2. -*/ - -#ifndef CEREAL_RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY -#define CEREAL_RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY (64 * 1024) -#endif - - -/////////////////////////////////////////////////////////////////////////////// -// CrtAllocator - -//! C-runtime library allocator. -/*! This class is just wrapper for standard C library memory routines. - \note implements Allocator concept -*/ -class CrtAllocator { -public: - static const bool kNeedFree = true; - void* Malloc(size_t size) { - if (size) // behavior of malloc(0) is implementation defined. - return std::malloc(size); - else - return NULL; // standardize to returning NULL. - } - void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) { - (void)originalSize; - if (newSize == 0) { - std::free(originalPtr); - return NULL; - } - return std::realloc(originalPtr, newSize); - } - static void Free(void *ptr) { std::free(ptr); } -}; - -/////////////////////////////////////////////////////////////////////////////// -// MemoryPoolAllocator - -//! Default memory allocator used by the parser and DOM. -/*! This allocator allocate memory blocks from pre-allocated memory chunks. - - It does not free memory blocks. And Realloc() only allocate new memory. - - The memory chunks are allocated by BaseAllocator, which is CrtAllocator by default. - - User may also supply a buffer as the first chunk. - - If the user-buffer is full then additional chunks are allocated by BaseAllocator. - - The user-buffer is not deallocated by this allocator. - - \tparam BaseAllocator the allocator type for allocating memory chunks. Default is CrtAllocator. - \note implements Allocator concept -*/ -template -class MemoryPoolAllocator { -public: - static const bool kNeedFree = false; //!< Tell users that no need to call Free() with this allocator. (concept Allocator) - - //! Constructor with chunkSize. - /*! \param chunkSize The size of memory chunk. The default is kDefaultChunkSize. - \param baseAllocator The allocator for allocating memory chunks. - */ - MemoryPoolAllocator(size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) : - chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(0), baseAllocator_(baseAllocator), ownBaseAllocator_(0) - { - } - - //! Constructor with user-supplied buffer. - /*! The user buffer will be used firstly. When it is full, memory pool allocates new chunk with chunk size. - - The user buffer will not be deallocated when this allocator is destructed. - - \param buffer User supplied buffer. - \param size Size of the buffer in bytes. It must at least larger than sizeof(ChunkHeader). - \param chunkSize The size of memory chunk. The default is kDefaultChunkSize. - \param baseAllocator The allocator for allocating memory chunks. - */ - MemoryPoolAllocator(void *buffer, size_t size, size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) : - chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(buffer), baseAllocator_(baseAllocator), ownBaseAllocator_(0) - { - CEREAL_RAPIDJSON_ASSERT(buffer != 0); - CEREAL_RAPIDJSON_ASSERT(size > sizeof(ChunkHeader)); - chunkHead_ = reinterpret_cast(buffer); - chunkHead_->capacity = size - sizeof(ChunkHeader); - chunkHead_->size = 0; - chunkHead_->next = 0; - } - - //! Destructor. - /*! This deallocates all memory chunks, excluding the user-supplied buffer. - */ - ~MemoryPoolAllocator() { - Clear(); - CEREAL_RAPIDJSON_DELETE(ownBaseAllocator_); - } - - //! Deallocates all memory chunks, excluding the user-supplied buffer. - void Clear() { - while (chunkHead_ && chunkHead_ != userBuffer_) { - ChunkHeader* next = chunkHead_->next; - baseAllocator_->Free(chunkHead_); - chunkHead_ = next; - } - if (chunkHead_ && chunkHead_ == userBuffer_) - chunkHead_->size = 0; // Clear user buffer - } - - //! Computes the total capacity of allocated memory chunks. - /*! \return total capacity in bytes. - */ - size_t Capacity() const { - size_t capacity = 0; - for (ChunkHeader* c = chunkHead_; c != 0; c = c->next) - capacity += c->capacity; - return capacity; - } - - //! Computes the memory blocks allocated. - /*! \return total used bytes. - */ - size_t Size() const { - size_t size = 0; - for (ChunkHeader* c = chunkHead_; c != 0; c = c->next) - size += c->size; - return size; - } - - //! Allocates a memory block. (concept Allocator) - void* Malloc(size_t size) { - if (!size) - return NULL; - - size = CEREAL_RAPIDJSON_ALIGN(size); - if (chunkHead_ == 0 || chunkHead_->size + size > chunkHead_->capacity) - if (!AddChunk(chunk_capacity_ > size ? chunk_capacity_ : size)) - return NULL; - - void *buffer = reinterpret_cast(chunkHead_) + CEREAL_RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size; - chunkHead_->size += size; - return buffer; - } - - //! Resizes a memory block (concept Allocator) - void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) { - if (originalPtr == 0) - return Malloc(newSize); - - if (newSize == 0) - return NULL; - - originalSize = CEREAL_RAPIDJSON_ALIGN(originalSize); - newSize = CEREAL_RAPIDJSON_ALIGN(newSize); - - // Do not shrink if new size is smaller than original - if (originalSize >= newSize) - return originalPtr; - - // Simply expand it if it is the last allocation and there is sufficient space - if (originalPtr == reinterpret_cast(chunkHead_) + CEREAL_RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size - originalSize) { - size_t increment = static_cast(newSize - originalSize); - if (chunkHead_->size + increment <= chunkHead_->capacity) { - chunkHead_->size += increment; - return originalPtr; - } - } - - // Realloc process: allocate and copy memory, do not free original buffer. - if (void* newBuffer = Malloc(newSize)) { - if (originalSize) - std::memcpy(newBuffer, originalPtr, originalSize); - return newBuffer; - } - else - return NULL; - } - - //! Frees a memory block (concept Allocator) - static void Free(void *ptr) { (void)ptr; } // Do nothing - -private: - //! Copy constructor is not permitted. - MemoryPoolAllocator(const MemoryPoolAllocator& rhs) /* = delete */; - //! Copy assignment operator is not permitted. - MemoryPoolAllocator& operator=(const MemoryPoolAllocator& rhs) /* = delete */; - - //! Creates a new chunk. - /*! \param capacity Capacity of the chunk in bytes. - \return true if success. - */ - bool AddChunk(size_t capacity) { - if (!baseAllocator_) - ownBaseAllocator_ = baseAllocator_ = CEREAL_RAPIDJSON_NEW(BaseAllocator)(); - if (ChunkHeader* chunk = reinterpret_cast(baseAllocator_->Malloc(CEREAL_RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + capacity))) { - chunk->capacity = capacity; - chunk->size = 0; - chunk->next = chunkHead_; - chunkHead_ = chunk; - return true; - } - else - return false; - } - - static const int kDefaultChunkCapacity = CEREAL_RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY; //!< Default chunk capacity. - - //! Chunk header for perpending to each chunk. - /*! Chunks are stored as a singly linked list. - */ - struct ChunkHeader { - size_t capacity; //!< Capacity of the chunk in bytes (excluding the header itself). - size_t size; //!< Current size of allocated memory in bytes. - ChunkHeader *next; //!< Next chunk in the linked list. - }; - - ChunkHeader *chunkHead_; //!< Head of the chunk linked-list. Only the head chunk serves allocation. - size_t chunk_capacity_; //!< The minimum capacity of chunk when they are allocated. - void *userBuffer_; //!< User supplied buffer. - BaseAllocator* baseAllocator_; //!< base allocator for allocating memory chunks. - BaseAllocator* ownBaseAllocator_; //!< base allocator created by this object. -}; - -CEREAL_RAPIDJSON_NAMESPACE_END - -#endif // CEREAL_RAPIDJSON_ENCODINGS_H_ diff --git a/include/cereal/external/rapidjson/cursorstreamwrapper.h b/include/cereal/external/rapidjson/cursorstreamwrapper.h deleted file mode 100644 index f3d20f7..0000000 --- a/include/cereal/external/rapidjson/cursorstreamwrapper.h +++ /dev/null @@ -1,78 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_CURSORSTREAMWRAPPER_H_ -#define CEREAL_RAPIDJSON_CURSORSTREAMWRAPPER_H_ - -#include "stream.h" - -#if defined(__GNUC__) -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(effc++) -#endif - -#if defined(_MSC_VER) && _MSC_VER <= 1800 -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(4702) // unreachable code -CEREAL_RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - - -//! Cursor stream wrapper for counting line and column number if error exists. -/*! - \tparam InputStream Any stream that implements Stream Concept -*/ -template > -class CursorStreamWrapper : public GenericStreamWrapper { -public: - typedef typename Encoding::Ch Ch; - - CursorStreamWrapper(InputStream& is): - GenericStreamWrapper(is), line_(1), col_(0) {} - - // counting line and column number - Ch Take() { - Ch ch = this->is_.Take(); - if(ch == '\n') { - line_ ++; - col_ = 0; - } else { - col_ ++; - } - return ch; - } - - //! Get the error line number, if error exists. - size_t GetLine() const { return line_; } - //! Get the error column number, if error exists. - size_t GetColumn() const { return col_; } - -private: - size_t line_; //!< Current Line - size_t col_; //!< Current Column -}; - -#if defined(_MSC_VER) && _MSC_VER <= 1800 -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#if defined(__GNUC__) -CEREAL_RAPIDJSON_DIAG_POP -#endif - -CEREAL_RAPIDJSON_NAMESPACE_END - -#endif // CEREAL_RAPIDJSON_CURSORSTREAMWRAPPER_H_ diff --git a/include/cereal/external/rapidjson/document.h b/include/cereal/external/rapidjson/document.h deleted file mode 100644 index 91c4be8..0000000 --- a/include/cereal/external/rapidjson/document.h +++ /dev/null @@ -1,2659 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_DOCUMENT_H_ -#define CEREAL_RAPIDJSON_DOCUMENT_H_ - -/*! \file document.h */ - -#include "reader.h" -#include "internal/meta.h" -#include "internal/strfunc.h" -#include "memorystream.h" -#include "encodedstream.h" -#include // placement new -#include -#ifdef __cpp_lib_three_way_comparison -#include -#endif - -CEREAL_RAPIDJSON_DIAG_PUSH -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_OFF(padded) -CEREAL_RAPIDJSON_DIAG_OFF(switch-enum) -CEREAL_RAPIDJSON_DIAG_OFF(c++98-compat) -#elif defined(_MSC_VER) -CEREAL_RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant -CEREAL_RAPIDJSON_DIAG_OFF(4244) // conversion from kXxxFlags to 'uint16_t', possible loss of data -#endif - -#ifdef __GNUC__ -CEREAL_RAPIDJSON_DIAG_OFF(effc++) -#endif // __GNUC__ - -#ifndef CEREAL_RAPIDJSON_NOMEMBERITERATORCLASS -#include // std::random_access_iterator_tag -#endif - -#if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS -#include // std::move -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -// Forward declaration. -template -class GenericValue; - -template -class GenericDocument; - -//! Name-value pair in a JSON object value. -/*! - This class was internal to GenericValue. It used to be a inner struct. - But a compiler (IBM XL C/C++ for AIX) have reported to have problem with that so it moved as a namespace scope struct. - https://code.google.com/p/rapidjson/issues/detail?id=64 -*/ -template -struct GenericMember { - GenericValue name; //!< name of member (must be a string) - GenericValue value; //!< value of member. - - // swap() for std::sort() and other potential use in STL. - friend inline void swap(GenericMember& a, GenericMember& b) CEREAL_RAPIDJSON_NOEXCEPT { - a.name.Swap(b.name); - a.value.Swap(b.value); - } -}; - -/////////////////////////////////////////////////////////////////////////////// -// GenericMemberIterator - -#ifndef CEREAL_RAPIDJSON_NOMEMBERITERATORCLASS - -//! (Constant) member iterator for a JSON object value -/*! - \tparam Const Is this a constant iterator? - \tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document) - \tparam Allocator Allocator type for allocating memory of object, array and string. - - This class implements a Random Access Iterator for GenericMember elements - of a GenericValue, see ISO/IEC 14882:2003(E) C++ standard, 24.1 [lib.iterator.requirements]. - - \note This iterator implementation is mainly intended to avoid implicit - conversions from iterator values to \c NULL, - e.g. from GenericValue::FindMember. - - \note Define \c CEREAL_RAPIDJSON_NOMEMBERITERATORCLASS to fall back to a - pointer-based implementation, if your platform doesn't provide - the C++ header. - - \see GenericMember, GenericValue::MemberIterator, GenericValue::ConstMemberIterator - */ -template -class GenericMemberIterator { - - friend class GenericValue; - template friend class GenericMemberIterator; - - typedef GenericMember PlainType; - typedef typename internal::MaybeAddConst::Type ValueType; - -public: - //! Iterator type itself - typedef GenericMemberIterator Iterator; - //! Constant iterator type - typedef GenericMemberIterator ConstIterator; - //! Non-constant iterator type - typedef GenericMemberIterator NonConstIterator; - - /** \name std::iterator_traits support */ - //@{ - typedef ValueType value_type; - typedef ValueType * pointer; - typedef ValueType & reference; - typedef std::ptrdiff_t difference_type; - typedef std::random_access_iterator_tag iterator_category; - //@} - - //! Pointer to (const) GenericMember - typedef pointer Pointer; - //! Reference to (const) GenericMember - typedef reference Reference; - //! Signed integer type (e.g. \c ptrdiff_t) - typedef difference_type DifferenceType; - - //! Default constructor (singular value) - /*! Creates an iterator pointing to no element. - \note All operations, except for comparisons, are undefined on such values. - */ - GenericMemberIterator() : ptr_() {} - - //! Iterator conversions to more const - /*! - \param it (Non-const) iterator to copy from - - Allows the creation of an iterator from another GenericMemberIterator - that is "less const". Especially, creating a non-constant iterator - from a constant iterator are disabled: - \li const -> non-const (not ok) - \li const -> const (ok) - \li non-const -> const (ok) - \li non-const -> non-const (ok) - - \note If the \c Const template parameter is already \c false, this - constructor effectively defines a regular copy-constructor. - Otherwise, the copy constructor is implicitly defined. - */ - GenericMemberIterator(const NonConstIterator & it) : ptr_(it.ptr_) {} - Iterator& operator=(const NonConstIterator & it) { ptr_ = it.ptr_; return *this; } - - //! @name stepping - //@{ - Iterator& operator++(){ ++ptr_; return *this; } - Iterator& operator--(){ --ptr_; return *this; } - Iterator operator++(int){ Iterator old(*this); ++ptr_; return old; } - Iterator operator--(int){ Iterator old(*this); --ptr_; return old; } - //@} - - //! @name increment/decrement - //@{ - Iterator operator+(DifferenceType n) const { return Iterator(ptr_+n); } - Iterator operator-(DifferenceType n) const { return Iterator(ptr_-n); } - - Iterator& operator+=(DifferenceType n) { ptr_+=n; return *this; } - Iterator& operator-=(DifferenceType n) { ptr_-=n; return *this; } - //@} - - //! @name relations - //@{ - template bool operator==(const GenericMemberIterator& that) const { return ptr_ == that.ptr_; } - template bool operator!=(const GenericMemberIterator& that) const { return ptr_ != that.ptr_; } - template bool operator<=(const GenericMemberIterator& that) const { return ptr_ <= that.ptr_; } - template bool operator>=(const GenericMemberIterator& that) const { return ptr_ >= that.ptr_; } - template bool operator< (const GenericMemberIterator& that) const { return ptr_ < that.ptr_; } - template bool operator> (const GenericMemberIterator& that) const { return ptr_ > that.ptr_; } - -#ifdef __cpp_lib_three_way_comparison - template std::strong_ordering operator<=>(const GenericMemberIterator& that) const { return ptr_ <=> that.ptr_; } -#endif - //@} - - //! @name dereference - //@{ - Reference operator*() const { return *ptr_; } - Pointer operator->() const { return ptr_; } - Reference operator[](DifferenceType n) const { return ptr_[n]; } - //@} - - //! Distance - DifferenceType operator-(ConstIterator that) const { return ptr_-that.ptr_; } - -private: - //! Internal constructor from plain pointer - explicit GenericMemberIterator(Pointer p) : ptr_(p) {} - - Pointer ptr_; //!< raw pointer -}; - -#else // CEREAL_RAPIDJSON_NOMEMBERITERATORCLASS - -// class-based member iterator implementation disabled, use plain pointers - -template -class GenericMemberIterator; - -//! non-const GenericMemberIterator -template -class GenericMemberIterator { - //! use plain pointer as iterator type - typedef GenericMember* Iterator; -}; -//! const GenericMemberIterator -template -class GenericMemberIterator { - //! use plain const pointer as iterator type - typedef const GenericMember* Iterator; -}; - -#endif // CEREAL_RAPIDJSON_NOMEMBERITERATORCLASS - -/////////////////////////////////////////////////////////////////////////////// -// GenericStringRef - -//! Reference to a constant string (not taking a copy) -/*! - \tparam CharType character type of the string - - This helper class is used to automatically infer constant string - references for string literals, especially from \c const \b (!) - character arrays. - - The main use is for creating JSON string values without copying the - source string via an \ref Allocator. This requires that the referenced - string pointers have a sufficient lifetime, which exceeds the lifetime - of the associated GenericValue. - - \b Example - \code - Value v("foo"); // ok, no need to copy & calculate length - const char foo[] = "foo"; - v.SetString(foo); // ok - - const char* bar = foo; - // Value x(bar); // not ok, can't rely on bar's lifetime - Value x(StringRef(bar)); // lifetime explicitly guaranteed by user - Value y(StringRef(bar, 3)); // ok, explicitly pass length - \endcode - - \see StringRef, GenericValue::SetString -*/ -template -struct GenericStringRef { - typedef CharType Ch; //!< character type of the string - - //! Create string reference from \c const character array -#ifndef __clang__ // -Wdocumentation - /*! - This constructor implicitly creates a constant string reference from - a \c const character array. It has better performance than - \ref StringRef(const CharType*) by inferring the string \ref length - from the array length, and also supports strings containing null - characters. - - \tparam N length of the string, automatically inferred - - \param str Constant character array, lifetime assumed to be longer - than the use of the string in e.g. a GenericValue - - \post \ref s == str - - \note Constant complexity. - \note There is a hidden, private overload to disallow references to - non-const character arrays to be created via this constructor. - By this, e.g. function-scope arrays used to be filled via - \c snprintf are excluded from consideration. - In such cases, the referenced string should be \b copied to the - GenericValue instead. - */ -#endif - template - GenericStringRef(const CharType (&str)[N]) CEREAL_RAPIDJSON_NOEXCEPT - : s(str), length(N-1) {} - - //! Explicitly create string reference from \c const character pointer -#ifndef __clang__ // -Wdocumentation - /*! - This constructor can be used to \b explicitly create a reference to - a constant string pointer. - - \see StringRef(const CharType*) - - \param str Constant character pointer, lifetime assumed to be longer - than the use of the string in e.g. a GenericValue - - \post \ref s == str - - \note There is a hidden, private overload to disallow references to - non-const character arrays to be created via this constructor. - By this, e.g. function-scope arrays used to be filled via - \c snprintf are excluded from consideration. - In such cases, the referenced string should be \b copied to the - GenericValue instead. - */ -#endif - explicit GenericStringRef(const CharType* str) - : s(str), length(NotNullStrLen(str)) {} - - //! Create constant string reference from pointer and length -#ifndef __clang__ // -Wdocumentation - /*! \param str constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue - \param len length of the string, excluding the trailing NULL terminator - - \post \ref s == str && \ref length == len - \note Constant complexity. - */ -#endif - GenericStringRef(const CharType* str, SizeType len) - : s(CEREAL_RAPIDJSON_LIKELY(str) ? str : emptyString), length(len) { CEREAL_RAPIDJSON_ASSERT(str != 0 || len == 0u); } - - GenericStringRef(const GenericStringRef& rhs) : s(rhs.s), length(rhs.length) {} - - //! implicit conversion to plain CharType pointer - operator const Ch *() const { return s; } - - const Ch* const s; //!< plain CharType pointer - const SizeType length; //!< length of the string (excluding the trailing NULL terminator) - -private: - SizeType NotNullStrLen(const CharType* str) { - CEREAL_RAPIDJSON_ASSERT(str != 0); - return internal::StrLen(str); - } - - /// Empty string - used when passing in a NULL pointer - static const Ch emptyString[]; - - //! Disallow construction from non-const array - template - GenericStringRef(CharType (&str)[N]) /* = delete */; - //! Copy assignment operator not permitted - immutable type - GenericStringRef& operator=(const GenericStringRef& rhs) /* = delete */; -}; - -template -const CharType GenericStringRef::emptyString[] = { CharType() }; - -//! Mark a character pointer as constant string -/*! Mark a plain character pointer as a "string literal". This function - can be used to avoid copying a character string to be referenced as a - value in a JSON GenericValue object, if the string's lifetime is known - to be valid long enough. - \tparam CharType Character type of the string - \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue - \return GenericStringRef string reference object - \relatesalso GenericStringRef - - \see GenericValue::GenericValue(StringRefType), GenericValue::operator=(StringRefType), GenericValue::SetString(StringRefType), GenericValue::PushBack(StringRefType, Allocator&), GenericValue::AddMember -*/ -template -inline GenericStringRef StringRef(const CharType* str) { - return GenericStringRef(str); -} - -//! Mark a character pointer as constant string -/*! Mark a plain character pointer as a "string literal". This function - can be used to avoid copying a character string to be referenced as a - value in a JSON GenericValue object, if the string's lifetime is known - to be valid long enough. - - This version has better performance with supplied length, and also - supports string containing null characters. - - \tparam CharType character type of the string - \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue - \param length The length of source string. - \return GenericStringRef string reference object - \relatesalso GenericStringRef -*/ -template -inline GenericStringRef StringRef(const CharType* str, size_t length) { - return GenericStringRef(str, SizeType(length)); -} - -#if CEREAL_RAPIDJSON_HAS_STDSTRING -//! Mark a string object as constant string -/*! Mark a string object (e.g. \c std::string) as a "string literal". - This function can be used to avoid copying a string to be referenced as a - value in a JSON GenericValue object, if the string's lifetime is known - to be valid long enough. - - \tparam CharType character type of the string - \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue - \return GenericStringRef string reference object - \relatesalso GenericStringRef - \note Requires the definition of the preprocessor symbol \ref CEREAL_RAPIDJSON_HAS_STDSTRING. -*/ -template -inline GenericStringRef StringRef(const std::basic_string& str) { - return GenericStringRef(str.data(), SizeType(str.size())); -} -#endif - -/////////////////////////////////////////////////////////////////////////////// -// GenericValue type traits -namespace internal { - -template -struct IsGenericValueImpl : FalseType {}; - -// select candidates according to nested encoding and allocator types -template struct IsGenericValueImpl::Type, typename Void::Type> - : IsBaseOf, T>::Type {}; - -// helper to match arbitrary GenericValue instantiations, including derived classes -template struct IsGenericValue : IsGenericValueImpl::Type {}; - -} // namespace internal - -/////////////////////////////////////////////////////////////////////////////// -// TypeHelper - -namespace internal { - -template -struct TypeHelper {}; - -template -struct TypeHelper { - static bool Is(const ValueType& v) { return v.IsBool(); } - static bool Get(const ValueType& v) { return v.GetBool(); } - static ValueType& Set(ValueType& v, bool data) { return v.SetBool(data); } - static ValueType& Set(ValueType& v, bool data, typename ValueType::AllocatorType&) { return v.SetBool(data); } -}; - -template -struct TypeHelper { - static bool Is(const ValueType& v) { return v.IsInt(); } - static int Get(const ValueType& v) { return v.GetInt(); } - static ValueType& Set(ValueType& v, int data) { return v.SetInt(data); } - static ValueType& Set(ValueType& v, int data, typename ValueType::AllocatorType&) { return v.SetInt(data); } -}; - -template -struct TypeHelper { - static bool Is(const ValueType& v) { return v.IsUint(); } - static unsigned Get(const ValueType& v) { return v.GetUint(); } - static ValueType& Set(ValueType& v, unsigned data) { return v.SetUint(data); } - static ValueType& Set(ValueType& v, unsigned data, typename ValueType::AllocatorType&) { return v.SetUint(data); } -}; - -#ifdef _MSC_VER -CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(long) == sizeof(int)); -template -struct TypeHelper { - static bool Is(const ValueType& v) { return v.IsInt(); } - static long Get(const ValueType& v) { return v.GetInt(); } - static ValueType& Set(ValueType& v, long data) { return v.SetInt(data); } - static ValueType& Set(ValueType& v, long data, typename ValueType::AllocatorType&) { return v.SetInt(data); } -}; - -CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(unsigned long) == sizeof(unsigned)); -template -struct TypeHelper { - static bool Is(const ValueType& v) { return v.IsUint(); } - static unsigned long Get(const ValueType& v) { return v.GetUint(); } - static ValueType& Set(ValueType& v, unsigned long data) { return v.SetUint(data); } - static ValueType& Set(ValueType& v, unsigned long data, typename ValueType::AllocatorType&) { return v.SetUint(data); } -}; -#endif - -template -struct TypeHelper { - static bool Is(const ValueType& v) { return v.IsInt64(); } - static int64_t Get(const ValueType& v) { return v.GetInt64(); } - static ValueType& Set(ValueType& v, int64_t data) { return v.SetInt64(data); } - static ValueType& Set(ValueType& v, int64_t data, typename ValueType::AllocatorType&) { return v.SetInt64(data); } -}; - -template -struct TypeHelper { - static bool Is(const ValueType& v) { return v.IsUint64(); } - static uint64_t Get(const ValueType& v) { return v.GetUint64(); } - static ValueType& Set(ValueType& v, uint64_t data) { return v.SetUint64(data); } - static ValueType& Set(ValueType& v, uint64_t data, typename ValueType::AllocatorType&) { return v.SetUint64(data); } -}; - -template -struct TypeHelper { - static bool Is(const ValueType& v) { return v.IsDouble(); } - static double Get(const ValueType& v) { return v.GetDouble(); } - static ValueType& Set(ValueType& v, double data) { return v.SetDouble(data); } - static ValueType& Set(ValueType& v, double data, typename ValueType::AllocatorType&) { return v.SetDouble(data); } -}; - -template -struct TypeHelper { - static bool Is(const ValueType& v) { return v.IsFloat(); } - static float Get(const ValueType& v) { return v.GetFloat(); } - static ValueType& Set(ValueType& v, float data) { return v.SetFloat(data); } - static ValueType& Set(ValueType& v, float data, typename ValueType::AllocatorType&) { return v.SetFloat(data); } -}; - -template -struct TypeHelper { - typedef const typename ValueType::Ch* StringType; - static bool Is(const ValueType& v) { return v.IsString(); } - static StringType Get(const ValueType& v) { return v.GetString(); } - static ValueType& Set(ValueType& v, const StringType data) { return v.SetString(typename ValueType::StringRefType(data)); } - static ValueType& Set(ValueType& v, const StringType data, typename ValueType::AllocatorType& a) { return v.SetString(data, a); } -}; - -#if CEREAL_RAPIDJSON_HAS_STDSTRING -template -struct TypeHelper > { - typedef std::basic_string StringType; - static bool Is(const ValueType& v) { return v.IsString(); } - static StringType Get(const ValueType& v) { return StringType(v.GetString(), v.GetStringLength()); } - static ValueType& Set(ValueType& v, const StringType& data, typename ValueType::AllocatorType& a) { return v.SetString(data, a); } -}; -#endif - -template -struct TypeHelper { - typedef typename ValueType::Array ArrayType; - static bool Is(const ValueType& v) { return v.IsArray(); } - static ArrayType Get(ValueType& v) { return v.GetArray(); } - static ValueType& Set(ValueType& v, ArrayType data) { return v = data; } - static ValueType& Set(ValueType& v, ArrayType data, typename ValueType::AllocatorType&) { return v = data; } -}; - -template -struct TypeHelper { - typedef typename ValueType::ConstArray ArrayType; - static bool Is(const ValueType& v) { return v.IsArray(); } - static ArrayType Get(const ValueType& v) { return v.GetArray(); } -}; - -template -struct TypeHelper { - typedef typename ValueType::Object ObjectType; - static bool Is(const ValueType& v) { return v.IsObject(); } - static ObjectType Get(ValueType& v) { return v.GetObject(); } - static ValueType& Set(ValueType& v, ObjectType data) { return v = data; } - static ValueType& Set(ValueType& v, ObjectType data, typename ValueType::AllocatorType&) { return v = data; } -}; - -template -struct TypeHelper { - typedef typename ValueType::ConstObject ObjectType; - static bool Is(const ValueType& v) { return v.IsObject(); } - static ObjectType Get(const ValueType& v) { return v.GetObject(); } -}; - -} // namespace internal - -// Forward declarations -template class GenericArray; -template class GenericObject; - -/////////////////////////////////////////////////////////////////////////////// -// GenericValue - -//! Represents a JSON value. Use Value for UTF8 encoding and default allocator. -/*! - A JSON value can be one of 7 types. This class is a variant type supporting - these types. - - Use the Value if UTF8 and default allocator - - \tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document) - \tparam Allocator Allocator type for allocating memory of object, array and string. -*/ -template > -class GenericValue { -public: - //! Name-value pair in an object. - typedef GenericMember Member; - typedef Encoding EncodingType; //!< Encoding type from template parameter. - typedef Allocator AllocatorType; //!< Allocator type from template parameter. - typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding. - typedef GenericStringRef StringRefType; //!< Reference to a constant string - typedef typename GenericMemberIterator::Iterator MemberIterator; //!< Member iterator for iterating in object. - typedef typename GenericMemberIterator::Iterator ConstMemberIterator; //!< Constant member iterator for iterating in object. - typedef GenericValue* ValueIterator; //!< Value iterator for iterating in array. - typedef const GenericValue* ConstValueIterator; //!< Constant value iterator for iterating in array. - typedef GenericValue ValueType; //!< Value type of itself. - typedef GenericArray Array; - typedef GenericArray ConstArray; - typedef GenericObject Object; - typedef GenericObject ConstObject; - - //!@name Constructors and destructor. - //@{ - - //! Default constructor creates a null value. - GenericValue() CEREAL_RAPIDJSON_NOEXCEPT : data_() { data_.f.flags = kNullFlag; } - -#if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - //! Move constructor in C++11 - GenericValue(GenericValue&& rhs) CEREAL_RAPIDJSON_NOEXCEPT : data_(rhs.data_) { - rhs.data_.f.flags = kNullFlag; // give up contents - } -#endif - -private: - //! Copy constructor is not permitted. - GenericValue(const GenericValue& rhs); - -#if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - //! Moving from a GenericDocument is not permitted. - template - GenericValue(GenericDocument&& rhs); - - //! Move assignment from a GenericDocument is not permitted. - template - GenericValue& operator=(GenericDocument&& rhs); -#endif - -public: - - //! Constructor with JSON value type. - /*! This creates a Value of specified type with default content. - \param type Type of the value. - \note Default content for number is zero. - */ - explicit GenericValue(Type type) CEREAL_RAPIDJSON_NOEXCEPT : data_() { - static const uint16_t defaultFlags[] = { - kNullFlag, kFalseFlag, kTrueFlag, kObjectFlag, kArrayFlag, kShortStringFlag, - kNumberAnyFlag - }; - CEREAL_RAPIDJSON_NOEXCEPT_ASSERT(type >= kNullType && type <= kNumberType); - data_.f.flags = defaultFlags[type]; - - // Use ShortString to store empty string. - if (type == kStringType) - data_.ss.SetLength(0); - } - - //! Explicit copy constructor (with allocator) - /*! Creates a copy of a Value by using the given Allocator - \tparam SourceAllocator allocator of \c rhs - \param rhs Value to copy from (read-only) - \param allocator Allocator for allocating copied elements and buffers. Commonly use GenericDocument::GetAllocator(). - \param copyConstStrings Force copying of constant strings (e.g. referencing an in-situ buffer) - \see CopyFrom() - */ - template - GenericValue(const GenericValue& rhs, Allocator& allocator, bool copyConstStrings = false) { - switch (rhs.GetType()) { - case kObjectType: { - SizeType count = rhs.data_.o.size; - Member* lm = reinterpret_cast(allocator.Malloc(count * sizeof(Member))); - const typename GenericValue::Member* rm = rhs.GetMembersPointer(); - for (SizeType i = 0; i < count; i++) { - new (&lm[i].name) GenericValue(rm[i].name, allocator, copyConstStrings); - new (&lm[i].value) GenericValue(rm[i].value, allocator, copyConstStrings); - } - data_.f.flags = kObjectFlag; - data_.o.size = data_.o.capacity = count; - SetMembersPointer(lm); - } - break; - case kArrayType: { - SizeType count = rhs.data_.a.size; - GenericValue* le = reinterpret_cast(allocator.Malloc(count * sizeof(GenericValue))); - const GenericValue* re = rhs.GetElementsPointer(); - for (SizeType i = 0; i < count; i++) - new (&le[i]) GenericValue(re[i], allocator, copyConstStrings); - data_.f.flags = kArrayFlag; - data_.a.size = data_.a.capacity = count; - SetElementsPointer(le); - } - break; - case kStringType: - if (rhs.data_.f.flags == kConstStringFlag && !copyConstStrings) { - data_.f.flags = rhs.data_.f.flags; - data_ = *reinterpret_cast(&rhs.data_); - } - else - SetStringRaw(StringRef(rhs.GetString(), rhs.GetStringLength()), allocator); - break; - default: - data_.f.flags = rhs.data_.f.flags; - data_ = *reinterpret_cast(&rhs.data_); - break; - } - } - - //! Constructor for boolean value. - /*! \param b Boolean value - \note This constructor is limited to \em real boolean values and rejects - implicitly converted types like arbitrary pointers. Use an explicit cast - to \c bool, if you want to construct a boolean JSON value in such cases. - */ -#ifndef CEREAL_RAPIDJSON_DOXYGEN_RUNNING // hide SFINAE from Doxygen - template - explicit GenericValue(T b, CEREAL_RAPIDJSON_ENABLEIF((internal::IsSame))) CEREAL_RAPIDJSON_NOEXCEPT // See #472 -#else - explicit GenericValue(bool b) CEREAL_RAPIDJSON_NOEXCEPT -#endif - : data_() { - // safe-guard against failing SFINAE - CEREAL_RAPIDJSON_STATIC_ASSERT((internal::IsSame::Value)); - data_.f.flags = b ? kTrueFlag : kFalseFlag; - } - - //! Constructor for int value. - explicit GenericValue(int i) CEREAL_RAPIDJSON_NOEXCEPT : data_() { - data_.n.i64 = i; - data_.f.flags = (i >= 0) ? (kNumberIntFlag | kUintFlag | kUint64Flag) : kNumberIntFlag; - } - - //! Constructor for unsigned value. - explicit GenericValue(unsigned u) CEREAL_RAPIDJSON_NOEXCEPT : data_() { - data_.n.u64 = u; - data_.f.flags = (u & 0x80000000) ? kNumberUintFlag : (kNumberUintFlag | kIntFlag | kInt64Flag); - } - - //! Constructor for int64_t value. - explicit GenericValue(int64_t i64) CEREAL_RAPIDJSON_NOEXCEPT : data_() { - data_.n.i64 = i64; - data_.f.flags = kNumberInt64Flag; - if (i64 >= 0) { - data_.f.flags |= kNumberUint64Flag; - if (!(static_cast(i64) & CEREAL_RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x00000000))) - data_.f.flags |= kUintFlag; - if (!(static_cast(i64) & CEREAL_RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000))) - data_.f.flags |= kIntFlag; - } - else if (i64 >= static_cast(CEREAL_RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000))) - data_.f.flags |= kIntFlag; - } - - //! Constructor for uint64_t value. - explicit GenericValue(uint64_t u64) CEREAL_RAPIDJSON_NOEXCEPT : data_() { - data_.n.u64 = u64; - data_.f.flags = kNumberUint64Flag; - if (!(u64 & CEREAL_RAPIDJSON_UINT64_C2(0x80000000, 0x00000000))) - data_.f.flags |= kInt64Flag; - if (!(u64 & CEREAL_RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x00000000))) - data_.f.flags |= kUintFlag; - if (!(u64 & CEREAL_RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000))) - data_.f.flags |= kIntFlag; - } - - //! Constructor for double value. - explicit GenericValue(double d) CEREAL_RAPIDJSON_NOEXCEPT : data_() { data_.n.d = d; data_.f.flags = kNumberDoubleFlag; } - - //! Constructor for float value. - explicit GenericValue(float f) CEREAL_RAPIDJSON_NOEXCEPT : data_() { data_.n.d = static_cast(f); data_.f.flags = kNumberDoubleFlag; } - - //! Constructor for constant string (i.e. do not make a copy of string) - GenericValue(const Ch* s, SizeType length) CEREAL_RAPIDJSON_NOEXCEPT : data_() { SetStringRaw(StringRef(s, length)); } - - //! Constructor for constant string (i.e. do not make a copy of string) - explicit GenericValue(StringRefType s) CEREAL_RAPIDJSON_NOEXCEPT : data_() { SetStringRaw(s); } - - //! Constructor for copy-string (i.e. do make a copy of string) - GenericValue(const Ch* s, SizeType length, Allocator& allocator) : data_() { SetStringRaw(StringRef(s, length), allocator); } - - //! Constructor for copy-string (i.e. do make a copy of string) - GenericValue(const Ch*s, Allocator& allocator) : data_() { SetStringRaw(StringRef(s), allocator); } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - //! Constructor for copy-string from a string object (i.e. do make a copy of string) - /*! \note Requires the definition of the preprocessor symbol \ref CEREAL_RAPIDJSON_HAS_STDSTRING. - */ - GenericValue(const std::basic_string& s, Allocator& allocator) : data_() { SetStringRaw(StringRef(s), allocator); } -#endif - - //! Constructor for Array. - /*! - \param a An array obtained by \c GetArray(). - \note \c Array is always pass-by-value. - \note the source array is moved into this value and the sourec array becomes empty. - */ - GenericValue(Array a) CEREAL_RAPIDJSON_NOEXCEPT : data_(a.value_.data_) { - a.value_.data_ = Data(); - a.value_.data_.f.flags = kArrayFlag; - } - - //! Constructor for Object. - /*! - \param o An object obtained by \c GetObject(). - \note \c Object is always pass-by-value. - \note the source object is moved into this value and the sourec object becomes empty. - */ - GenericValue(Object o) CEREAL_RAPIDJSON_NOEXCEPT : data_(o.value_.data_) { - o.value_.data_ = Data(); - o.value_.data_.f.flags = kObjectFlag; - } - - //! Destructor. - /*! Need to destruct elements of array, members of object, or copy-string. - */ - ~GenericValue() { - if (Allocator::kNeedFree) { // Shortcut by Allocator's trait - switch(data_.f.flags) { - case kArrayFlag: - { - GenericValue* e = GetElementsPointer(); - for (GenericValue* v = e; v != e + data_.a.size; ++v) - v->~GenericValue(); - Allocator::Free(e); - } - break; - - case kObjectFlag: - for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m) - m->~Member(); - Allocator::Free(GetMembersPointer()); - break; - - case kCopyStringFlag: - Allocator::Free(const_cast(GetStringPointer())); - break; - - default: - break; // Do nothing for other types. - } - } - } - - //@} - - //!@name Assignment operators - //@{ - - //! Assignment with move semantics. - /*! \param rhs Source of the assignment. It will become a null value after assignment. - */ - GenericValue& operator=(GenericValue& rhs) CEREAL_RAPIDJSON_NOEXCEPT { - if (CEREAL_RAPIDJSON_LIKELY(this != &rhs)) { - this->~GenericValue(); - RawAssign(rhs); - } - return *this; - } - -#if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - //! Move assignment in C++11 - GenericValue& operator=(GenericValue&& rhs) CEREAL_RAPIDJSON_NOEXCEPT { - return *this = rhs.Move(); - } -#endif - - //! Assignment of constant string reference (no copy) - /*! \param str Constant string reference to be assigned - \note This overload is needed to avoid clashes with the generic primitive type assignment overload below. - \see GenericStringRef, operator=(T) - */ - GenericValue& operator=(StringRefType str) CEREAL_RAPIDJSON_NOEXCEPT { - GenericValue s(str); - return *this = s; - } - - //! Assignment with primitive types. - /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t - \param value The value to be assigned. - - \note The source type \c T explicitly disallows all pointer types, - especially (\c const) \ref Ch*. This helps avoiding implicitly - referencing character strings with insufficient lifetime, use - \ref SetString(const Ch*, Allocator&) (for copying) or - \ref StringRef() (to explicitly mark the pointer as constant) instead. - All other pointer types would implicitly convert to \c bool, - use \ref SetBool() instead. - */ - template - CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::IsPointer), (GenericValue&)) - operator=(T value) { - GenericValue v(value); - return *this = v; - } - - //! Deep-copy assignment from Value - /*! Assigns a \b copy of the Value to the current Value object - \tparam SourceAllocator Allocator type of \c rhs - \param rhs Value to copy from (read-only) - \param allocator Allocator to use for copying - \param copyConstStrings Force copying of constant strings (e.g. referencing an in-situ buffer) - */ - template - GenericValue& CopyFrom(const GenericValue& rhs, Allocator& allocator, bool copyConstStrings = false) { - CEREAL_RAPIDJSON_ASSERT(static_cast(this) != static_cast(&rhs)); - this->~GenericValue(); - new (this) GenericValue(rhs, allocator, copyConstStrings); - return *this; - } - - //! Exchange the contents of this value with those of other. - /*! - \param other Another value. - \note Constant complexity. - */ - GenericValue& Swap(GenericValue& other) CEREAL_RAPIDJSON_NOEXCEPT { - GenericValue temp; - temp.RawAssign(*this); - RawAssign(other); - other.RawAssign(temp); - return *this; - } - - //! free-standing swap function helper - /*! - Helper function to enable support for common swap implementation pattern based on \c std::swap: - \code - void swap(MyClass& a, MyClass& b) { - using std::swap; - swap(a.value, b.value); - // ... - } - \endcode - \see Swap() - */ - friend inline void swap(GenericValue& a, GenericValue& b) CEREAL_RAPIDJSON_NOEXCEPT { a.Swap(b); } - - //! Prepare Value for move semantics - /*! \return *this */ - GenericValue& Move() CEREAL_RAPIDJSON_NOEXCEPT { return *this; } - //@} - - //!@name Equal-to and not-equal-to operators - //@{ - //! Equal-to operator - /*! - \note If an object contains duplicated named member, comparing equality with any object is always \c false. - \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). - */ - template - bool operator==(const GenericValue& rhs) const { - typedef GenericValue RhsType; - if (GetType() != rhs.GetType()) - return false; - - switch (GetType()) { - case kObjectType: // Warning: O(n^2) inner-loop - if (data_.o.size != rhs.data_.o.size) - return false; - for (ConstMemberIterator lhsMemberItr = MemberBegin(); lhsMemberItr != MemberEnd(); ++lhsMemberItr) { - typename RhsType::ConstMemberIterator rhsMemberItr = rhs.FindMember(lhsMemberItr->name); - if (rhsMemberItr == rhs.MemberEnd() || lhsMemberItr->value != rhsMemberItr->value) - return false; - } - return true; - - case kArrayType: - if (data_.a.size != rhs.data_.a.size) - return false; - for (SizeType i = 0; i < data_.a.size; i++) - if ((*this)[i] != rhs[i]) - return false; - return true; - - case kStringType: - return StringEqual(rhs); - - case kNumberType: - if (IsDouble() || rhs.IsDouble()) { - double a = GetDouble(); // May convert from integer to double. - double b = rhs.GetDouble(); // Ditto - return a >= b && a <= b; // Prevent -Wfloat-equal - } - else - return data_.n.u64 == rhs.data_.n.u64; - - default: - return true; - } - } - - //! Equal-to operator with const C-string pointer - bool operator==(const Ch* rhs) const { return *this == GenericValue(StringRef(rhs)); } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - //! Equal-to operator with string object - /*! \note Requires the definition of the preprocessor symbol \ref CEREAL_RAPIDJSON_HAS_STDSTRING. - */ - bool operator==(const std::basic_string& rhs) const { return *this == GenericValue(StringRef(rhs)); } -#endif - - //! Equal-to operator with primitive types - /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c double, \c true, \c false - */ - template CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr,internal::IsGenericValue >), (bool)) operator==(const T& rhs) const { return *this == GenericValue(rhs); } - - //! Not-equal-to operator - /*! \return !(*this == rhs) - */ - template - bool operator!=(const GenericValue& rhs) const { return !(*this == rhs); } - - //! Not-equal-to operator with const C-string pointer - bool operator!=(const Ch* rhs) const { return !(*this == rhs); } - - //! Not-equal-to operator with arbitrary types - /*! \return !(*this == rhs) - */ - template CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue), (bool)) operator!=(const T& rhs) const { return !(*this == rhs); } - - //! Equal-to operator with arbitrary types (symmetric version) - /*! \return (rhs == lhs) - */ - template friend CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue), (bool)) operator==(const T& lhs, const GenericValue& rhs) { return rhs == lhs; } - - //! Not-Equal-to operator with arbitrary types (symmetric version) - /*! \return !(rhs == lhs) - */ - template friend CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue), (bool)) operator!=(const T& lhs, const GenericValue& rhs) { return !(rhs == lhs); } - //@} - - //!@name Type - //@{ - - Type GetType() const { return static_cast(data_.f.flags & kTypeMask); } - bool IsNull() const { return data_.f.flags == kNullFlag; } - bool IsFalse() const { return data_.f.flags == kFalseFlag; } - bool IsTrue() const { return data_.f.flags == kTrueFlag; } - bool IsBool() const { return (data_.f.flags & kBoolFlag) != 0; } - bool IsObject() const { return data_.f.flags == kObjectFlag; } - bool IsArray() const { return data_.f.flags == kArrayFlag; } - bool IsNumber() const { return (data_.f.flags & kNumberFlag) != 0; } - bool IsInt() const { return (data_.f.flags & kIntFlag) != 0; } - bool IsUint() const { return (data_.f.flags & kUintFlag) != 0; } - bool IsInt64() const { return (data_.f.flags & kInt64Flag) != 0; } - bool IsUint64() const { return (data_.f.flags & kUint64Flag) != 0; } - bool IsDouble() const { return (data_.f.flags & kDoubleFlag) != 0; } - bool IsString() const { return (data_.f.flags & kStringFlag) != 0; } - - // Checks whether a number can be losslessly converted to a double. - bool IsLosslessDouble() const { - if (!IsNumber()) return false; - if (IsUint64()) { - uint64_t u = GetUint64(); - volatile double d = static_cast(u); - return (d >= 0.0) - && (d < static_cast((std::numeric_limits::max)())) - && (u == static_cast(d)); - } - if (IsInt64()) { - int64_t i = GetInt64(); - volatile double d = static_cast(i); - return (d >= static_cast((std::numeric_limits::min)())) - && (d < static_cast((std::numeric_limits::max)())) - && (i == static_cast(d)); - } - return true; // double, int, uint are always lossless - } - - // Checks whether a number is a float (possible lossy). - bool IsFloat() const { - if ((data_.f.flags & kDoubleFlag) == 0) - return false; - double d = GetDouble(); - return d >= -3.4028234e38 && d <= 3.4028234e38; - } - // Checks whether a number can be losslessly converted to a float. - bool IsLosslessFloat() const { - if (!IsNumber()) return false; - double a = GetDouble(); - if (a < static_cast(-(std::numeric_limits::max)()) - || a > static_cast((std::numeric_limits::max)())) - return false; - double b = static_cast(static_cast(a)); - return a >= b && a <= b; // Prevent -Wfloat-equal - } - - //@} - - //!@name Null - //@{ - - GenericValue& SetNull() { this->~GenericValue(); new (this) GenericValue(); return *this; } - - //@} - - //!@name Bool - //@{ - - bool GetBool() const { CEREAL_RAPIDJSON_ASSERT(IsBool()); return data_.f.flags == kTrueFlag; } - //!< Set boolean value - /*! \post IsBool() == true */ - GenericValue& SetBool(bool b) { this->~GenericValue(); new (this) GenericValue(b); return *this; } - - //@} - - //!@name Object - //@{ - - //! Set this value as an empty object. - /*! \post IsObject() == true */ - GenericValue& SetObject() { this->~GenericValue(); new (this) GenericValue(kObjectType); return *this; } - - //! Get the number of members in the object. - SizeType MemberCount() const { CEREAL_RAPIDJSON_ASSERT(IsObject()); return data_.o.size; } - - //! Get the capacity of object. - SizeType MemberCapacity() const { CEREAL_RAPIDJSON_ASSERT(IsObject()); return data_.o.capacity; } - - //! Check whether the object is empty. - bool ObjectEmpty() const { CEREAL_RAPIDJSON_ASSERT(IsObject()); return data_.o.size == 0; } - - //! Get a value from an object associated with the name. - /*! \pre IsObject() == true - \tparam T Either \c Ch or \c const \c Ch (template used for disambiguation with \ref operator[](SizeType)) - \note In version 0.1x, if the member is not found, this function returns a null value. This makes issue 7. - Since 0.2, if the name is not correct, it will assert. - If user is unsure whether a member exists, user should use HasMember() first. - A better approach is to use FindMember(). - \note Linear time complexity. - */ - template - CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr::Type, Ch> >),(GenericValue&)) operator[](T* name) { - GenericValue n(StringRef(name)); - return (*this)[n]; - } - template - CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr::Type, Ch> >),(const GenericValue&)) operator[](T* name) const { return const_cast(*this)[name]; } - - //! Get a value from an object associated with the name. - /*! \pre IsObject() == true - \tparam SourceAllocator Allocator of the \c name value - - \note Compared to \ref operator[](T*), this version is faster because it does not need a StrLen(). - And it can also handle strings with embedded null characters. - - \note Linear time complexity. - */ - template - GenericValue& operator[](const GenericValue& name) { - MemberIterator member = FindMember(name); - if (member != MemberEnd()) - return member->value; - else { - CEREAL_RAPIDJSON_ASSERT(false); // see above note - - // This will generate -Wexit-time-destructors in clang - // static GenericValue NullValue; - // return NullValue; - - // Use static buffer and placement-new to prevent destruction - static char buffer[sizeof(GenericValue)]; - return *new (buffer) GenericValue(); - } - } - template - const GenericValue& operator[](const GenericValue& name) const { return const_cast(*this)[name]; } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - //! Get a value from an object associated with name (string object). - GenericValue& operator[](const std::basic_string& name) { return (*this)[GenericValue(StringRef(name))]; } - const GenericValue& operator[](const std::basic_string& name) const { return (*this)[GenericValue(StringRef(name))]; } -#endif - - //! Const member iterator - /*! \pre IsObject() == true */ - ConstMemberIterator MemberBegin() const { CEREAL_RAPIDJSON_ASSERT(IsObject()); return ConstMemberIterator(GetMembersPointer()); } - //! Const \em past-the-end member iterator - /*! \pre IsObject() == true */ - ConstMemberIterator MemberEnd() const { CEREAL_RAPIDJSON_ASSERT(IsObject()); return ConstMemberIterator(GetMembersPointer() + data_.o.size); } - //! Member iterator - /*! \pre IsObject() == true */ - MemberIterator MemberBegin() { CEREAL_RAPIDJSON_ASSERT(IsObject()); return MemberIterator(GetMembersPointer()); } - //! \em Past-the-end member iterator - /*! \pre IsObject() == true */ - MemberIterator MemberEnd() { CEREAL_RAPIDJSON_ASSERT(IsObject()); return MemberIterator(GetMembersPointer() + data_.o.size); } - - //! Request the object to have enough capacity to store members. - /*! \param newCapacity The capacity that the object at least need to have. - \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). - \return The value itself for fluent API. - \note Linear time complexity. - */ - GenericValue& MemberReserve(SizeType newCapacity, Allocator &allocator) { - CEREAL_RAPIDJSON_ASSERT(IsObject()); - if (newCapacity > data_.o.capacity) { - SetMembersPointer(reinterpret_cast(allocator.Realloc(GetMembersPointer(), data_.o.capacity * sizeof(Member), newCapacity * sizeof(Member)))); - data_.o.capacity = newCapacity; - } - return *this; - } - - //! Check whether a member exists in the object. - /*! - \param name Member name to be searched. - \pre IsObject() == true - \return Whether a member with that name exists. - \note It is better to use FindMember() directly if you need the obtain the value as well. - \note Linear time complexity. - */ - bool HasMember(const Ch* name) const { return FindMember(name) != MemberEnd(); } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - //! Check whether a member exists in the object with string object. - /*! - \param name Member name to be searched. - \pre IsObject() == true - \return Whether a member with that name exists. - \note It is better to use FindMember() directly if you need the obtain the value as well. - \note Linear time complexity. - */ - bool HasMember(const std::basic_string& name) const { return FindMember(name) != MemberEnd(); } -#endif - - //! Check whether a member exists in the object with GenericValue name. - /*! - This version is faster because it does not need a StrLen(). It can also handle string with null character. - \param name Member name to be searched. - \pre IsObject() == true - \return Whether a member with that name exists. - \note It is better to use FindMember() directly if you need the obtain the value as well. - \note Linear time complexity. - */ - template - bool HasMember(const GenericValue& name) const { return FindMember(name) != MemberEnd(); } - - //! Find member by name. - /*! - \param name Member name to be searched. - \pre IsObject() == true - \return Iterator to member, if it exists. - Otherwise returns \ref MemberEnd(). - - \note Earlier versions of Rapidjson returned a \c NULL pointer, in case - the requested member doesn't exist. For consistency with e.g. - \c std::map, this has been changed to MemberEnd() now. - \note Linear time complexity. - */ - MemberIterator FindMember(const Ch* name) { - GenericValue n(StringRef(name)); - return FindMember(n); - } - - ConstMemberIterator FindMember(const Ch* name) const { return const_cast(*this).FindMember(name); } - - //! Find member by name. - /*! - This version is faster because it does not need a StrLen(). It can also handle string with null character. - \param name Member name to be searched. - \pre IsObject() == true - \return Iterator to member, if it exists. - Otherwise returns \ref MemberEnd(). - - \note Earlier versions of Rapidjson returned a \c NULL pointer, in case - the requested member doesn't exist. For consistency with e.g. - \c std::map, this has been changed to MemberEnd() now. - \note Linear time complexity. - */ - template - MemberIterator FindMember(const GenericValue& name) { - CEREAL_RAPIDJSON_ASSERT(IsObject()); - CEREAL_RAPIDJSON_ASSERT(name.IsString()); - MemberIterator member = MemberBegin(); - for ( ; member != MemberEnd(); ++member) - if (name.StringEqual(member->name)) - break; - return member; - } - template ConstMemberIterator FindMember(const GenericValue& name) const { return const_cast(*this).FindMember(name); } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - //! Find member by string object name. - /*! - \param name Member name to be searched. - \pre IsObject() == true - \return Iterator to member, if it exists. - Otherwise returns \ref MemberEnd(). - */ - MemberIterator FindMember(const std::basic_string& name) { return FindMember(GenericValue(StringRef(name))); } - ConstMemberIterator FindMember(const std::basic_string& name) const { return FindMember(GenericValue(StringRef(name))); } -#endif - - //! Add a member (name-value pair) to the object. - /*! \param name A string value as name of member. - \param value Value of any type. - \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). - \return The value itself for fluent API. - \note The ownership of \c name and \c value will be transferred to this object on success. - \pre IsObject() && name.IsString() - \post name.IsNull() && value.IsNull() - \note Amortized Constant time complexity. - */ - GenericValue& AddMember(GenericValue& name, GenericValue& value, Allocator& allocator) { - CEREAL_RAPIDJSON_ASSERT(IsObject()); - CEREAL_RAPIDJSON_ASSERT(name.IsString()); - - ObjectData& o = data_.o; - if (o.size >= o.capacity) - MemberReserve(o.capacity == 0 ? kDefaultObjectCapacity : (o.capacity + (o.capacity + 1) / 2), allocator); - Member* members = GetMembersPointer(); - members[o.size].name.RawAssign(name); - members[o.size].value.RawAssign(value); - o.size++; - return *this; - } - - //! Add a constant string value as member (name-value pair) to the object. - /*! \param name A string value as name of member. - \param value constant string reference as value of member. - \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). - \return The value itself for fluent API. - \pre IsObject() - \note This overload is needed to avoid clashes with the generic primitive type AddMember(GenericValue&,T,Allocator&) overload below. - \note Amortized Constant time complexity. - */ - GenericValue& AddMember(GenericValue& name, StringRefType value, Allocator& allocator) { - GenericValue v(value); - return AddMember(name, v, allocator); - } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - //! Add a string object as member (name-value pair) to the object. - /*! \param name A string value as name of member. - \param value constant string reference as value of member. - \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). - \return The value itself for fluent API. - \pre IsObject() - \note This overload is needed to avoid clashes with the generic primitive type AddMember(GenericValue&,T,Allocator&) overload below. - \note Amortized Constant time complexity. - */ - GenericValue& AddMember(GenericValue& name, std::basic_string& value, Allocator& allocator) { - GenericValue v(value, allocator); - return AddMember(name, v, allocator); - } -#endif - - //! Add any primitive value as member (name-value pair) to the object. - /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t - \param name A string value as name of member. - \param value Value of primitive type \c T as value of member - \param allocator Allocator for reallocating memory. Commonly use GenericDocument::GetAllocator(). - \return The value itself for fluent API. - \pre IsObject() - - \note The source type \c T explicitly disallows all pointer types, - especially (\c const) \ref Ch*. This helps avoiding implicitly - referencing character strings with insufficient lifetime, use - \ref AddMember(StringRefType, GenericValue&, Allocator&) or \ref - AddMember(StringRefType, StringRefType, Allocator&). - All other pointer types would implicitly convert to \c bool, - use an explicit cast instead, if needed. - \note Amortized Constant time complexity. - */ - template - CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (GenericValue&)) - AddMember(GenericValue& name, T value, Allocator& allocator) { - GenericValue v(value); - return AddMember(name, v, allocator); - } - -#if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - GenericValue& AddMember(GenericValue&& name, GenericValue&& value, Allocator& allocator) { - return AddMember(name, value, allocator); - } - GenericValue& AddMember(GenericValue&& name, GenericValue& value, Allocator& allocator) { - return AddMember(name, value, allocator); - } - GenericValue& AddMember(GenericValue& name, GenericValue&& value, Allocator& allocator) { - return AddMember(name, value, allocator); - } - GenericValue& AddMember(StringRefType name, GenericValue&& value, Allocator& allocator) { - GenericValue n(name); - return AddMember(n, value, allocator); - } -#endif // CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - - - //! Add a member (name-value pair) to the object. - /*! \param name A constant string reference as name of member. - \param value Value of any type. - \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). - \return The value itself for fluent API. - \note The ownership of \c value will be transferred to this object on success. - \pre IsObject() - \post value.IsNull() - \note Amortized Constant time complexity. - */ - GenericValue& AddMember(StringRefType name, GenericValue& value, Allocator& allocator) { - GenericValue n(name); - return AddMember(n, value, allocator); - } - - //! Add a constant string value as member (name-value pair) to the object. - /*! \param name A constant string reference as name of member. - \param value constant string reference as value of member. - \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). - \return The value itself for fluent API. - \pre IsObject() - \note This overload is needed to avoid clashes with the generic primitive type AddMember(StringRefType,T,Allocator&) overload below. - \note Amortized Constant time complexity. - */ - GenericValue& AddMember(StringRefType name, StringRefType value, Allocator& allocator) { - GenericValue v(value); - return AddMember(name, v, allocator); - } - - //! Add any primitive value as member (name-value pair) to the object. - /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t - \param name A constant string reference as name of member. - \param value Value of primitive type \c T as value of member - \param allocator Allocator for reallocating memory. Commonly use GenericDocument::GetAllocator(). - \return The value itself for fluent API. - \pre IsObject() - - \note The source type \c T explicitly disallows all pointer types, - especially (\c const) \ref Ch*. This helps avoiding implicitly - referencing character strings with insufficient lifetime, use - \ref AddMember(StringRefType, GenericValue&, Allocator&) or \ref - AddMember(StringRefType, StringRefType, Allocator&). - All other pointer types would implicitly convert to \c bool, - use an explicit cast instead, if needed. - \note Amortized Constant time complexity. - */ - template - CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (GenericValue&)) - AddMember(StringRefType name, T value, Allocator& allocator) { - GenericValue n(name); - return AddMember(n, value, allocator); - } - - //! Remove all members in the object. - /*! This function do not deallocate memory in the object, i.e. the capacity is unchanged. - \note Linear time complexity. - */ - void RemoveAllMembers() { - CEREAL_RAPIDJSON_ASSERT(IsObject()); - for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m) - m->~Member(); - data_.o.size = 0; - } - - //! Remove a member in object by its name. - /*! \param name Name of member to be removed. - \return Whether the member existed. - \note This function may reorder the object members. Use \ref - EraseMember(ConstMemberIterator) if you need to preserve the - relative order of the remaining members. - \note Linear time complexity. - */ - bool RemoveMember(const Ch* name) { - GenericValue n(StringRef(name)); - return RemoveMember(n); - } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - bool RemoveMember(const std::basic_string& name) { return RemoveMember(GenericValue(StringRef(name))); } -#endif - - template - bool RemoveMember(const GenericValue& name) { - MemberIterator m = FindMember(name); - if (m != MemberEnd()) { - RemoveMember(m); - return true; - } - else - return false; - } - - //! Remove a member in object by iterator. - /*! \param m member iterator (obtained by FindMember() or MemberBegin()). - \return the new iterator after removal. - \note This function may reorder the object members. Use \ref - EraseMember(ConstMemberIterator) if you need to preserve the - relative order of the remaining members. - \note Constant time complexity. - */ - MemberIterator RemoveMember(MemberIterator m) { - CEREAL_RAPIDJSON_ASSERT(IsObject()); - CEREAL_RAPIDJSON_ASSERT(data_.o.size > 0); - CEREAL_RAPIDJSON_ASSERT(GetMembersPointer() != 0); - CEREAL_RAPIDJSON_ASSERT(m >= MemberBegin() && m < MemberEnd()); - - MemberIterator last(GetMembersPointer() + (data_.o.size - 1)); - if (data_.o.size > 1 && m != last) - *m = *last; // Move the last one to this place - else - m->~Member(); // Only one left, just destroy - --data_.o.size; - return m; - } - - //! Remove a member from an object by iterator. - /*! \param pos iterator to the member to remove - \pre IsObject() == true && \ref MemberBegin() <= \c pos < \ref MemberEnd() - \return Iterator following the removed element. - If the iterator \c pos refers to the last element, the \ref MemberEnd() iterator is returned. - \note This function preserves the relative order of the remaining object - members. If you do not need this, use the more efficient \ref RemoveMember(MemberIterator). - \note Linear time complexity. - */ - MemberIterator EraseMember(ConstMemberIterator pos) { - return EraseMember(pos, pos +1); - } - - //! Remove members in the range [first, last) from an object. - /*! \param first iterator to the first member to remove - \param last iterator following the last member to remove - \pre IsObject() == true && \ref MemberBegin() <= \c first <= \c last <= \ref MemberEnd() - \return Iterator following the last removed element. - \note This function preserves the relative order of the remaining object - members. - \note Linear time complexity. - */ - MemberIterator EraseMember(ConstMemberIterator first, ConstMemberIterator last) { - CEREAL_RAPIDJSON_ASSERT(IsObject()); - CEREAL_RAPIDJSON_ASSERT(data_.o.size > 0); - CEREAL_RAPIDJSON_ASSERT(GetMembersPointer() != 0); - CEREAL_RAPIDJSON_ASSERT(first >= MemberBegin()); - CEREAL_RAPIDJSON_ASSERT(first <= last); - CEREAL_RAPIDJSON_ASSERT(last <= MemberEnd()); - - MemberIterator pos = MemberBegin() + (first - MemberBegin()); - for (MemberIterator itr = pos; itr != last; ++itr) - itr->~Member(); - std::memmove(static_cast(&*pos), &*last, static_cast(MemberEnd() - last) * sizeof(Member)); - data_.o.size -= static_cast(last - first); - return pos; - } - - //! Erase a member in object by its name. - /*! \param name Name of member to be removed. - \return Whether the member existed. - \note Linear time complexity. - */ - bool EraseMember(const Ch* name) { - GenericValue n(StringRef(name)); - return EraseMember(n); - } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - bool EraseMember(const std::basic_string& name) { return EraseMember(GenericValue(StringRef(name))); } -#endif - - template - bool EraseMember(const GenericValue& name) { - MemberIterator m = FindMember(name); - if (m != MemberEnd()) { - EraseMember(m); - return true; - } - else - return false; - } - - Object GetObject() { CEREAL_RAPIDJSON_ASSERT(IsObject()); return Object(*this); } - ConstObject GetObject() const { CEREAL_RAPIDJSON_ASSERT(IsObject()); return ConstObject(*this); } - - //@} - - //!@name Array - //@{ - - //! Set this value as an empty array. - /*! \post IsArray == true */ - GenericValue& SetArray() { this->~GenericValue(); new (this) GenericValue(kArrayType); return *this; } - - //! Get the number of elements in array. - SizeType Size() const { CEREAL_RAPIDJSON_ASSERT(IsArray()); return data_.a.size; } - - //! Get the capacity of array. - SizeType Capacity() const { CEREAL_RAPIDJSON_ASSERT(IsArray()); return data_.a.capacity; } - - //! Check whether the array is empty. - bool Empty() const { CEREAL_RAPIDJSON_ASSERT(IsArray()); return data_.a.size == 0; } - - //! Remove all elements in the array. - /*! This function do not deallocate memory in the array, i.e. the capacity is unchanged. - \note Linear time complexity. - */ - void Clear() { - CEREAL_RAPIDJSON_ASSERT(IsArray()); - GenericValue* e = GetElementsPointer(); - for (GenericValue* v = e; v != e + data_.a.size; ++v) - v->~GenericValue(); - data_.a.size = 0; - } - - //! Get an element from array by index. - /*! \pre IsArray() == true - \param index Zero-based index of element. - \see operator[](T*) - */ - GenericValue& operator[](SizeType index) { - CEREAL_RAPIDJSON_ASSERT(IsArray()); - CEREAL_RAPIDJSON_ASSERT(index < data_.a.size); - return GetElementsPointer()[index]; - } - const GenericValue& operator[](SizeType index) const { return const_cast(*this)[index]; } - - //! Element iterator - /*! \pre IsArray() == true */ - ValueIterator Begin() { CEREAL_RAPIDJSON_ASSERT(IsArray()); return GetElementsPointer(); } - //! \em Past-the-end element iterator - /*! \pre IsArray() == true */ - ValueIterator End() { CEREAL_RAPIDJSON_ASSERT(IsArray()); return GetElementsPointer() + data_.a.size; } - //! Constant element iterator - /*! \pre IsArray() == true */ - ConstValueIterator Begin() const { return const_cast(*this).Begin(); } - //! Constant \em past-the-end element iterator - /*! \pre IsArray() == true */ - ConstValueIterator End() const { return const_cast(*this).End(); } - - //! Request the array to have enough capacity to store elements. - /*! \param newCapacity The capacity that the array at least need to have. - \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). - \return The value itself for fluent API. - \note Linear time complexity. - */ - GenericValue& Reserve(SizeType newCapacity, Allocator &allocator) { - CEREAL_RAPIDJSON_ASSERT(IsArray()); - if (newCapacity > data_.a.capacity) { - SetElementsPointer(reinterpret_cast(allocator.Realloc(GetElementsPointer(), data_.a.capacity * sizeof(GenericValue), newCapacity * sizeof(GenericValue)))); - data_.a.capacity = newCapacity; - } - return *this; - } - - //! Append a GenericValue at the end of the array. - /*! \param value Value to be appended. - \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). - \pre IsArray() == true - \post value.IsNull() == true - \return The value itself for fluent API. - \note The ownership of \c value will be transferred to this array on success. - \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient. - \note Amortized constant time complexity. - */ - GenericValue& PushBack(GenericValue& value, Allocator& allocator) { - CEREAL_RAPIDJSON_ASSERT(IsArray()); - if (data_.a.size >= data_.a.capacity) - Reserve(data_.a.capacity == 0 ? kDefaultArrayCapacity : (data_.a.capacity + (data_.a.capacity + 1) / 2), allocator); - GetElementsPointer()[data_.a.size++].RawAssign(value); - return *this; - } - -#if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - GenericValue& PushBack(GenericValue&& value, Allocator& allocator) { - return PushBack(value, allocator); - } -#endif // CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - - //! Append a constant string reference at the end of the array. - /*! \param value Constant string reference to be appended. - \param allocator Allocator for reallocating memory. It must be the same one used previously. Commonly use GenericDocument::GetAllocator(). - \pre IsArray() == true - \return The value itself for fluent API. - \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient. - \note Amortized constant time complexity. - \see GenericStringRef - */ - GenericValue& PushBack(StringRefType value, Allocator& allocator) { - return (*this).template PushBack(value, allocator); - } - - //! Append a primitive value at the end of the array. - /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t - \param value Value of primitive type T to be appended. - \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). - \pre IsArray() == true - \return The value itself for fluent API. - \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient. - - \note The source type \c T explicitly disallows all pointer types, - especially (\c const) \ref Ch*. This helps avoiding implicitly - referencing character strings with insufficient lifetime, use - \ref PushBack(GenericValue&, Allocator&) or \ref - PushBack(StringRefType, Allocator&). - All other pointer types would implicitly convert to \c bool, - use an explicit cast instead, if needed. - \note Amortized constant time complexity. - */ - template - CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (GenericValue&)) - PushBack(T value, Allocator& allocator) { - GenericValue v(value); - return PushBack(v, allocator); - } - - //! Remove the last element in the array. - /*! - \note Constant time complexity. - */ - GenericValue& PopBack() { - CEREAL_RAPIDJSON_ASSERT(IsArray()); - CEREAL_RAPIDJSON_ASSERT(!Empty()); - GetElementsPointer()[--data_.a.size].~GenericValue(); - return *this; - } - - //! Remove an element of array by iterator. - /*! - \param pos iterator to the element to remove - \pre IsArray() == true && \ref Begin() <= \c pos < \ref End() - \return Iterator following the removed element. If the iterator pos refers to the last element, the End() iterator is returned. - \note Linear time complexity. - */ - ValueIterator Erase(ConstValueIterator pos) { - return Erase(pos, pos + 1); - } - - //! Remove elements in the range [first, last) of the array. - /*! - \param first iterator to the first element to remove - \param last iterator following the last element to remove - \pre IsArray() == true && \ref Begin() <= \c first <= \c last <= \ref End() - \return Iterator following the last removed element. - \note Linear time complexity. - */ - ValueIterator Erase(ConstValueIterator first, ConstValueIterator last) { - CEREAL_RAPIDJSON_ASSERT(IsArray()); - CEREAL_RAPIDJSON_ASSERT(data_.a.size > 0); - CEREAL_RAPIDJSON_ASSERT(GetElementsPointer() != 0); - CEREAL_RAPIDJSON_ASSERT(first >= Begin()); - CEREAL_RAPIDJSON_ASSERT(first <= last); - CEREAL_RAPIDJSON_ASSERT(last <= End()); - ValueIterator pos = Begin() + (first - Begin()); - for (ValueIterator itr = pos; itr != last; ++itr) - itr->~GenericValue(); - std::memmove(static_cast(pos), last, static_cast(End() - last) * sizeof(GenericValue)); - data_.a.size -= static_cast(last - first); - return pos; - } - - Array GetArray() { CEREAL_RAPIDJSON_ASSERT(IsArray()); return Array(*this); } - ConstArray GetArray() const { CEREAL_RAPIDJSON_ASSERT(IsArray()); return ConstArray(*this); } - - //@} - - //!@name Number - //@{ - - int GetInt() const { CEREAL_RAPIDJSON_ASSERT(data_.f.flags & kIntFlag); return data_.n.i.i; } - unsigned GetUint() const { CEREAL_RAPIDJSON_ASSERT(data_.f.flags & kUintFlag); return data_.n.u.u; } - int64_t GetInt64() const { CEREAL_RAPIDJSON_ASSERT(data_.f.flags & kInt64Flag); return data_.n.i64; } - uint64_t GetUint64() const { CEREAL_RAPIDJSON_ASSERT(data_.f.flags & kUint64Flag); return data_.n.u64; } - - //! Get the value as double type. - /*! \note If the value is 64-bit integer type, it may lose precision. Use \c IsLosslessDouble() to check whether the converison is lossless. - */ - double GetDouble() const { - CEREAL_RAPIDJSON_ASSERT(IsNumber()); - if ((data_.f.flags & kDoubleFlag) != 0) return data_.n.d; // exact type, no conversion. - if ((data_.f.flags & kIntFlag) != 0) return data_.n.i.i; // int -> double - if ((data_.f.flags & kUintFlag) != 0) return data_.n.u.u; // unsigned -> double - if ((data_.f.flags & kInt64Flag) != 0) return static_cast(data_.n.i64); // int64_t -> double (may lose precision) - CEREAL_RAPIDJSON_ASSERT((data_.f.flags & kUint64Flag) != 0); return static_cast(data_.n.u64); // uint64_t -> double (may lose precision) - } - - //! Get the value as float type. - /*! \note If the value is 64-bit integer type, it may lose precision. Use \c IsLosslessFloat() to check whether the converison is lossless. - */ - float GetFloat() const { - return static_cast(GetDouble()); - } - - GenericValue& SetInt(int i) { this->~GenericValue(); new (this) GenericValue(i); return *this; } - GenericValue& SetUint(unsigned u) { this->~GenericValue(); new (this) GenericValue(u); return *this; } - GenericValue& SetInt64(int64_t i64) { this->~GenericValue(); new (this) GenericValue(i64); return *this; } - GenericValue& SetUint64(uint64_t u64) { this->~GenericValue(); new (this) GenericValue(u64); return *this; } - GenericValue& SetDouble(double d) { this->~GenericValue(); new (this) GenericValue(d); return *this; } - GenericValue& SetFloat(float f) { this->~GenericValue(); new (this) GenericValue(static_cast(f)); return *this; } - - //@} - - //!@name String - //@{ - - const Ch* GetString() const { CEREAL_RAPIDJSON_ASSERT(IsString()); return (data_.f.flags & kInlineStrFlag) ? data_.ss.str : GetStringPointer(); } - - //! Get the length of string. - /*! Since rapidjson permits "\\u0000" in the json string, strlen(v.GetString()) may not equal to v.GetStringLength(). - */ - SizeType GetStringLength() const { CEREAL_RAPIDJSON_ASSERT(IsString()); return ((data_.f.flags & kInlineStrFlag) ? (data_.ss.GetLength()) : data_.s.length); } - - //! Set this value as a string without copying source string. - /*! This version has better performance with supplied length, and also support string containing null character. - \param s source string pointer. - \param length The length of source string, excluding the trailing null terminator. - \return The value itself for fluent API. - \post IsString() == true && GetString() == s && GetStringLength() == length - \see SetString(StringRefType) - */ - GenericValue& SetString(const Ch* s, SizeType length) { return SetString(StringRef(s, length)); } - - //! Set this value as a string without copying source string. - /*! \param s source string reference - \return The value itself for fluent API. - \post IsString() == true && GetString() == s && GetStringLength() == s.length - */ - GenericValue& SetString(StringRefType s) { this->~GenericValue(); SetStringRaw(s); return *this; } - - //! Set this value as a string by copying from source string. - /*! This version has better performance with supplied length, and also support string containing null character. - \param s source string. - \param length The length of source string, excluding the trailing null terminator. - \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator(). - \return The value itself for fluent API. - \post IsString() == true && GetString() != s && strcmp(GetString(),s) == 0 && GetStringLength() == length - */ - GenericValue& SetString(const Ch* s, SizeType length, Allocator& allocator) { return SetString(StringRef(s, length), allocator); } - - //! Set this value as a string by copying from source string. - /*! \param s source string. - \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator(). - \return The value itself for fluent API. - \post IsString() == true && GetString() != s && strcmp(GetString(),s) == 0 && GetStringLength() == length - */ - GenericValue& SetString(const Ch* s, Allocator& allocator) { return SetString(StringRef(s), allocator); } - - //! Set this value as a string by copying from source string. - /*! \param s source string reference - \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator(). - \return The value itself for fluent API. - \post IsString() == true && GetString() != s.s && strcmp(GetString(),s) == 0 && GetStringLength() == length - */ - GenericValue& SetString(StringRefType s, Allocator& allocator) { this->~GenericValue(); SetStringRaw(s, allocator); return *this; } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - //! Set this value as a string by copying from source string. - /*! \param s source string. - \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator(). - \return The value itself for fluent API. - \post IsString() == true && GetString() != s.data() && strcmp(GetString(),s.data() == 0 && GetStringLength() == s.size() - \note Requires the definition of the preprocessor symbol \ref CEREAL_RAPIDJSON_HAS_STDSTRING. - */ - GenericValue& SetString(const std::basic_string& s, Allocator& allocator) { return SetString(StringRef(s), allocator); } -#endif - - //@} - - //!@name Array - //@{ - - //! Templated version for checking whether this value is type T. - /*! - \tparam T Either \c bool, \c int, \c unsigned, \c int64_t, \c uint64_t, \c double, \c float, \c const \c char*, \c std::basic_string - */ - template - bool Is() const { return internal::TypeHelper::Is(*this); } - - template - T Get() const { return internal::TypeHelper::Get(*this); } - - template - T Get() { return internal::TypeHelper::Get(*this); } - - template - ValueType& Set(const T& data) { return internal::TypeHelper::Set(*this, data); } - - template - ValueType& Set(const T& data, AllocatorType& allocator) { return internal::TypeHelper::Set(*this, data, allocator); } - - //@} - - //! Generate events of this value to a Handler. - /*! This function adopts the GoF visitor pattern. - Typical usage is to output this JSON value as JSON text via Writer, which is a Handler. - It can also be used to deep clone this value via GenericDocument, which is also a Handler. - \tparam Handler type of handler. - \param handler An object implementing concept Handler. - */ - template - bool Accept(Handler& handler) const { - switch(GetType()) { - case kNullType: return handler.Null(); - case kFalseType: return handler.Bool(false); - case kTrueType: return handler.Bool(true); - - case kObjectType: - if (CEREAL_RAPIDJSON_UNLIKELY(!handler.StartObject())) - return false; - for (ConstMemberIterator m = MemberBegin(); m != MemberEnd(); ++m) { - CEREAL_RAPIDJSON_ASSERT(m->name.IsString()); // User may change the type of name by MemberIterator. - if (CEREAL_RAPIDJSON_UNLIKELY(!handler.Key(m->name.GetString(), m->name.GetStringLength(), (m->name.data_.f.flags & kCopyFlag) != 0))) - return false; - if (CEREAL_RAPIDJSON_UNLIKELY(!m->value.Accept(handler))) - return false; - } - return handler.EndObject(data_.o.size); - - case kArrayType: - if (CEREAL_RAPIDJSON_UNLIKELY(!handler.StartArray())) - return false; - for (const GenericValue* v = Begin(); v != End(); ++v) - if (CEREAL_RAPIDJSON_UNLIKELY(!v->Accept(handler))) - return false; - return handler.EndArray(data_.a.size); - - case kStringType: - return handler.String(GetString(), GetStringLength(), (data_.f.flags & kCopyFlag) != 0); - - default: - CEREAL_RAPIDJSON_ASSERT(GetType() == kNumberType); - if (IsDouble()) return handler.Double(data_.n.d); - else if (IsInt()) return handler.Int(data_.n.i.i); - else if (IsUint()) return handler.Uint(data_.n.u.u); - else if (IsInt64()) return handler.Int64(data_.n.i64); - else return handler.Uint64(data_.n.u64); - } - } - -private: - template friend class GenericValue; - template friend class GenericDocument; - - enum { - kBoolFlag = 0x0008, - kNumberFlag = 0x0010, - kIntFlag = 0x0020, - kUintFlag = 0x0040, - kInt64Flag = 0x0080, - kUint64Flag = 0x0100, - kDoubleFlag = 0x0200, - kStringFlag = 0x0400, - kCopyFlag = 0x0800, - kInlineStrFlag = 0x1000, - - // Initial flags of different types. - kNullFlag = kNullType, - kTrueFlag = kTrueType | kBoolFlag, - kFalseFlag = kFalseType | kBoolFlag, - kNumberIntFlag = kNumberType | kNumberFlag | kIntFlag | kInt64Flag, - kNumberUintFlag = kNumberType | kNumberFlag | kUintFlag | kUint64Flag | kInt64Flag, - kNumberInt64Flag = kNumberType | kNumberFlag | kInt64Flag, - kNumberUint64Flag = kNumberType | kNumberFlag | kUint64Flag, - kNumberDoubleFlag = kNumberType | kNumberFlag | kDoubleFlag, - kNumberAnyFlag = kNumberType | kNumberFlag | kIntFlag | kInt64Flag | kUintFlag | kUint64Flag | kDoubleFlag, - kConstStringFlag = kStringType | kStringFlag, - kCopyStringFlag = kStringType | kStringFlag | kCopyFlag, - kShortStringFlag = kStringType | kStringFlag | kCopyFlag | kInlineStrFlag, - kObjectFlag = kObjectType, - kArrayFlag = kArrayType, - - kTypeMask = 0x07 - }; - - static const SizeType kDefaultArrayCapacity = 16; - static const SizeType kDefaultObjectCapacity = 16; - - struct Flag { -#if CEREAL_RAPIDJSON_48BITPOINTER_OPTIMIZATION - char payload[sizeof(SizeType) * 2 + 6]; // 2 x SizeType + lower 48-bit pointer -#elif CEREAL_RAPIDJSON_64BIT - char payload[sizeof(SizeType) * 2 + sizeof(void*) + 6]; // 6 padding bytes -#else - char payload[sizeof(SizeType) * 2 + sizeof(void*) + 2]; // 2 padding bytes -#endif - uint16_t flags; - }; - - struct String { - SizeType length; - SizeType hashcode; //!< reserved - const Ch* str; - }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode - - // implementation detail: ShortString can represent zero-terminated strings up to MaxSize chars - // (excluding the terminating zero) and store a value to determine the length of the contained - // string in the last character str[LenPos] by storing "MaxSize - length" there. If the string - // to store has the maximal length of MaxSize then str[LenPos] will be 0 and therefore act as - // the string terminator as well. For getting the string length back from that value just use - // "MaxSize - str[LenPos]". - // This allows to store 13-chars strings in 32-bit mode, 21-chars strings in 64-bit mode, - // 13-chars strings for CEREAL_RAPIDJSON_48BITPOINTER_OPTIMIZATION=1 inline (for `UTF8`-encoded strings). - struct ShortString { - enum { MaxChars = sizeof(static_cast(0)->payload) / sizeof(Ch), MaxSize = MaxChars - 1, LenPos = MaxSize }; - Ch str[MaxChars]; - - inline static bool Usable(SizeType len) { return (MaxSize >= len); } - inline void SetLength(SizeType len) { str[LenPos] = static_cast(MaxSize - len); } - inline SizeType GetLength() const { return static_cast(MaxSize - str[LenPos]); } - }; // at most as many bytes as "String" above => 12 bytes in 32-bit mode, 16 bytes in 64-bit mode - - // By using proper binary layout, retrieval of different integer types do not need conversions. - union Number { -#if CEREAL_RAPIDJSON_ENDIAN == CEREAL_RAPIDJSON_LITTLEENDIAN - struct I { - int i; - char padding[4]; - }i; - struct U { - unsigned u; - char padding2[4]; - }u; -#else - struct I { - char padding[4]; - int i; - }i; - struct U { - char padding2[4]; - unsigned u; - }u; -#endif - int64_t i64; - uint64_t u64; - double d; - }; // 8 bytes - - struct ObjectData { - SizeType size; - SizeType capacity; - Member* members; - }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode - - struct ArrayData { - SizeType size; - SizeType capacity; - GenericValue* elements; - }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode - - union Data { - String s; - ShortString ss; - Number n; - ObjectData o; - ArrayData a; - Flag f; - }; // 16 bytes in 32-bit mode, 24 bytes in 64-bit mode, 16 bytes in 64-bit with CEREAL_RAPIDJSON_48BITPOINTER_OPTIMIZATION - - CEREAL_RAPIDJSON_FORCEINLINE const Ch* GetStringPointer() const { return CEREAL_RAPIDJSON_GETPOINTER(Ch, data_.s.str); } - CEREAL_RAPIDJSON_FORCEINLINE const Ch* SetStringPointer(const Ch* str) { return CEREAL_RAPIDJSON_SETPOINTER(Ch, data_.s.str, str); } - CEREAL_RAPIDJSON_FORCEINLINE GenericValue* GetElementsPointer() const { return CEREAL_RAPIDJSON_GETPOINTER(GenericValue, data_.a.elements); } - CEREAL_RAPIDJSON_FORCEINLINE GenericValue* SetElementsPointer(GenericValue* elements) { return CEREAL_RAPIDJSON_SETPOINTER(GenericValue, data_.a.elements, elements); } - CEREAL_RAPIDJSON_FORCEINLINE Member* GetMembersPointer() const { return CEREAL_RAPIDJSON_GETPOINTER(Member, data_.o.members); } - CEREAL_RAPIDJSON_FORCEINLINE Member* SetMembersPointer(Member* members) { return CEREAL_RAPIDJSON_SETPOINTER(Member, data_.o.members, members); } - - // Initialize this value as array with initial data, without calling destructor. - void SetArrayRaw(GenericValue* values, SizeType count, Allocator& allocator) { - data_.f.flags = kArrayFlag; - if (count) { - GenericValue* e = static_cast(allocator.Malloc(count * sizeof(GenericValue))); - SetElementsPointer(e); - std::memcpy(static_cast(e), values, count * sizeof(GenericValue)); - } - else - SetElementsPointer(0); - data_.a.size = data_.a.capacity = count; - } - - //! Initialize this value as object with initial data, without calling destructor. - void SetObjectRaw(Member* members, SizeType count, Allocator& allocator) { - data_.f.flags = kObjectFlag; - if (count) { - Member* m = static_cast(allocator.Malloc(count * sizeof(Member))); - SetMembersPointer(m); - std::memcpy(static_cast(m), members, count * sizeof(Member)); - } - else - SetMembersPointer(0); - data_.o.size = data_.o.capacity = count; - } - - //! Initialize this value as constant string, without calling destructor. - void SetStringRaw(StringRefType s) CEREAL_RAPIDJSON_NOEXCEPT { - data_.f.flags = kConstStringFlag; - SetStringPointer(s); - data_.s.length = s.length; - } - - //! Initialize this value as copy string with initial data, without calling destructor. - void SetStringRaw(StringRefType s, Allocator& allocator) { - Ch* str = 0; - if (ShortString::Usable(s.length)) { - data_.f.flags = kShortStringFlag; - data_.ss.SetLength(s.length); - str = data_.ss.str; - } else { - data_.f.flags = kCopyStringFlag; - data_.s.length = s.length; - str = static_cast(allocator.Malloc((s.length + 1) * sizeof(Ch))); - SetStringPointer(str); - } - std::memcpy(str, s, s.length * sizeof(Ch)); - str[s.length] = '\0'; - } - - //! Assignment without calling destructor - void RawAssign(GenericValue& rhs) CEREAL_RAPIDJSON_NOEXCEPT { - data_ = rhs.data_; - // data_.f.flags = rhs.data_.f.flags; - rhs.data_.f.flags = kNullFlag; - } - - template - bool StringEqual(const GenericValue& rhs) const { - CEREAL_RAPIDJSON_ASSERT(IsString()); - CEREAL_RAPIDJSON_ASSERT(rhs.IsString()); - - const SizeType len1 = GetStringLength(); - const SizeType len2 = rhs.GetStringLength(); - if(len1 != len2) { return false; } - - const Ch* const str1 = GetString(); - const Ch* const str2 = rhs.GetString(); - if(str1 == str2) { return true; } // fast path for constant string - - return (std::memcmp(str1, str2, sizeof(Ch) * len1) == 0); - } - - Data data_; -}; - -//! GenericValue with UTF8 encoding -typedef GenericValue > Value; - -/////////////////////////////////////////////////////////////////////////////// -// GenericDocument - -//! A document for parsing JSON text as DOM. -/*! - \note implements Handler concept - \tparam Encoding Encoding for both parsing and string storage. - \tparam Allocator Allocator for allocating memory for the DOM - \tparam StackAllocator Allocator for allocating memory for stack during parsing. - \warning Although GenericDocument inherits from GenericValue, the API does \b not provide any virtual functions, especially no virtual destructor. To avoid memory leaks, do not \c delete a GenericDocument object via a pointer to a GenericValue. -*/ -template , typename StackAllocator = CrtAllocator> -class GenericDocument : public GenericValue { -public: - typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding. - typedef GenericValue ValueType; //!< Value type of the document. - typedef Allocator AllocatorType; //!< Allocator type from template parameter. - - //! Constructor - /*! Creates an empty document of specified type. - \param type Mandatory type of object to create. - \param allocator Optional allocator for allocating memory. - \param stackCapacity Optional initial capacity of stack in bytes. - \param stackAllocator Optional allocator for allocating memory for stack. - */ - explicit GenericDocument(Type type, Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity, StackAllocator* stackAllocator = 0) : - GenericValue(type), allocator_(allocator), ownAllocator_(0), stack_(stackAllocator, stackCapacity), parseResult_() - { - if (!allocator_) - ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator)(); - } - - //! Constructor - /*! Creates an empty document which type is Null. - \param allocator Optional allocator for allocating memory. - \param stackCapacity Optional initial capacity of stack in bytes. - \param stackAllocator Optional allocator for allocating memory for stack. - */ - GenericDocument(Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity, StackAllocator* stackAllocator = 0) : - allocator_(allocator), ownAllocator_(0), stack_(stackAllocator, stackCapacity), parseResult_() - { - if (!allocator_) - ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator)(); - } - -#if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - //! Move constructor in C++11 - GenericDocument(GenericDocument&& rhs) CEREAL_RAPIDJSON_NOEXCEPT - : ValueType(std::forward(rhs)), // explicit cast to avoid prohibited move from Document - allocator_(rhs.allocator_), - ownAllocator_(rhs.ownAllocator_), - stack_(std::move(rhs.stack_)), - parseResult_(rhs.parseResult_) - { - rhs.allocator_ = 0; - rhs.ownAllocator_ = 0; - rhs.parseResult_ = ParseResult(); - } -#endif - - ~GenericDocument() { - Destroy(); - } - -#if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - //! Move assignment in C++11 - GenericDocument& operator=(GenericDocument&& rhs) CEREAL_RAPIDJSON_NOEXCEPT - { - // The cast to ValueType is necessary here, because otherwise it would - // attempt to call GenericValue's templated assignment operator. - ValueType::operator=(std::forward(rhs)); - - // Calling the destructor here would prematurely call stack_'s destructor - Destroy(); - - allocator_ = rhs.allocator_; - ownAllocator_ = rhs.ownAllocator_; - stack_ = std::move(rhs.stack_); - parseResult_ = rhs.parseResult_; - - rhs.allocator_ = 0; - rhs.ownAllocator_ = 0; - rhs.parseResult_ = ParseResult(); - - return *this; - } -#endif - - //! Exchange the contents of this document with those of another. - /*! - \param rhs Another document. - \note Constant complexity. - \see GenericValue::Swap - */ - GenericDocument& Swap(GenericDocument& rhs) CEREAL_RAPIDJSON_NOEXCEPT { - ValueType::Swap(rhs); - stack_.Swap(rhs.stack_); - internal::Swap(allocator_, rhs.allocator_); - internal::Swap(ownAllocator_, rhs.ownAllocator_); - internal::Swap(parseResult_, rhs.parseResult_); - return *this; - } - - // Allow Swap with ValueType. - // Refer to Effective C++ 3rd Edition/Item 33: Avoid hiding inherited names. - using ValueType::Swap; - - //! free-standing swap function helper - /*! - Helper function to enable support for common swap implementation pattern based on \c std::swap: - \code - void swap(MyClass& a, MyClass& b) { - using std::swap; - swap(a.doc, b.doc); - // ... - } - \endcode - \see Swap() - */ - friend inline void swap(GenericDocument& a, GenericDocument& b) CEREAL_RAPIDJSON_NOEXCEPT { a.Swap(b); } - - //! Populate this document by a generator which produces SAX events. - /*! \tparam Generator A functor with bool f(Handler) prototype. - \param g Generator functor which sends SAX events to the parameter. - \return The document itself for fluent API. - */ - template - GenericDocument& Populate(Generator& g) { - ClearStackOnExit scope(*this); - if (g(*this)) { - CEREAL_RAPIDJSON_ASSERT(stack_.GetSize() == sizeof(ValueType)); // Got one and only one root object - ValueType::operator=(*stack_.template Pop(1));// Move value from stack to document - } - return *this; - } - - //!@name Parse from stream - //!@{ - - //! Parse JSON text from an input stream (with Encoding conversion) - /*! \tparam parseFlags Combination of \ref ParseFlag. - \tparam SourceEncoding Encoding of input stream - \tparam InputStream Type of input stream, implementing Stream concept - \param is Input stream to be parsed. - \return The document itself for fluent API. - */ - template - GenericDocument& ParseStream(InputStream& is) { - GenericReader reader( - stack_.HasAllocator() ? &stack_.GetAllocator() : 0); - ClearStackOnExit scope(*this); - parseResult_ = reader.template Parse(is, *this); - if (parseResult_) { - CEREAL_RAPIDJSON_ASSERT(stack_.GetSize() == sizeof(ValueType)); // Got one and only one root object - ValueType::operator=(*stack_.template Pop(1));// Move value from stack to document - } - return *this; - } - - //! Parse JSON text from an input stream - /*! \tparam parseFlags Combination of \ref ParseFlag. - \tparam InputStream Type of input stream, implementing Stream concept - \param is Input stream to be parsed. - \return The document itself for fluent API. - */ - template - GenericDocument& ParseStream(InputStream& is) { - return ParseStream(is); - } - - //! Parse JSON text from an input stream (with \ref kParseDefaultFlags) - /*! \tparam InputStream Type of input stream, implementing Stream concept - \param is Input stream to be parsed. - \return The document itself for fluent API. - */ - template - GenericDocument& ParseStream(InputStream& is) { - return ParseStream(is); - } - //!@} - - //!@name Parse in-place from mutable string - //!@{ - - //! Parse JSON text from a mutable string - /*! \tparam parseFlags Combination of \ref ParseFlag. - \param str Mutable zero-terminated string to be parsed. - \return The document itself for fluent API. - */ - template - GenericDocument& ParseInsitu(Ch* str) { - GenericInsituStringStream s(str); - return ParseStream(s); - } - - //! Parse JSON text from a mutable string (with \ref kParseDefaultFlags) - /*! \param str Mutable zero-terminated string to be parsed. - \return The document itself for fluent API. - */ - GenericDocument& ParseInsitu(Ch* str) { - return ParseInsitu(str); - } - //!@} - - //!@name Parse from read-only string - //!@{ - - //! Parse JSON text from a read-only string (with Encoding conversion) - /*! \tparam parseFlags Combination of \ref ParseFlag (must not contain \ref kParseInsituFlag). - \tparam SourceEncoding Transcoding from input Encoding - \param str Read-only zero-terminated string to be parsed. - */ - template - GenericDocument& Parse(const typename SourceEncoding::Ch* str) { - CEREAL_RAPIDJSON_ASSERT(!(parseFlags & kParseInsituFlag)); - GenericStringStream s(str); - return ParseStream(s); - } - - //! Parse JSON text from a read-only string - /*! \tparam parseFlags Combination of \ref ParseFlag (must not contain \ref kParseInsituFlag). - \param str Read-only zero-terminated string to be parsed. - */ - template - GenericDocument& Parse(const Ch* str) { - return Parse(str); - } - - //! Parse JSON text from a read-only string (with \ref kParseDefaultFlags) - /*! \param str Read-only zero-terminated string to be parsed. - */ - GenericDocument& Parse(const Ch* str) { - return Parse(str); - } - - template - GenericDocument& Parse(const typename SourceEncoding::Ch* str, size_t length) { - CEREAL_RAPIDJSON_ASSERT(!(parseFlags & kParseInsituFlag)); - MemoryStream ms(reinterpret_cast(str), length * sizeof(typename SourceEncoding::Ch)); - EncodedInputStream is(ms); - ParseStream(is); - return *this; - } - - template - GenericDocument& Parse(const Ch* str, size_t length) { - return Parse(str, length); - } - - GenericDocument& Parse(const Ch* str, size_t length) { - return Parse(str, length); - } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - template - GenericDocument& Parse(const std::basic_string& str) { - // c_str() is constant complexity according to standard. Should be faster than Parse(const char*, size_t) - return Parse(str.c_str()); - } - - template - GenericDocument& Parse(const std::basic_string& str) { - return Parse(str.c_str()); - } - - GenericDocument& Parse(const std::basic_string& str) { - return Parse(str); - } -#endif // CEREAL_RAPIDJSON_HAS_STDSTRING - - //!@} - - //!@name Handling parse errors - //!@{ - - //! Whether a parse error has occurred in the last parsing. - bool HasParseError() const { return parseResult_.IsError(); } - - //! Get the \ref ParseErrorCode of last parsing. - ParseErrorCode GetParseError() const { return parseResult_.Code(); } - - //! Get the position of last parsing error in input, 0 otherwise. - size_t GetErrorOffset() const { return parseResult_.Offset(); } - - //! Implicit conversion to get the last parse result -#ifndef __clang // -Wdocumentation - /*! \return \ref ParseResult of the last parse operation - - \code - Document doc; - ParseResult ok = doc.Parse(json); - if (!ok) - printf( "JSON parse error: %s (%u)\n", GetParseError_En(ok.Code()), ok.Offset()); - \endcode - */ -#endif - operator ParseResult() const { return parseResult_; } - //!@} - - //! Get the allocator of this document. - Allocator& GetAllocator() { - CEREAL_RAPIDJSON_ASSERT(allocator_); - return *allocator_; - } - - //! Get the capacity of stack in bytes. - size_t GetStackCapacity() const { return stack_.GetCapacity(); } - -private: - // clear stack on any exit from ParseStream, e.g. due to exception - struct ClearStackOnExit { - explicit ClearStackOnExit(GenericDocument& d) : d_(d) {} - ~ClearStackOnExit() { d_.ClearStack(); } - private: - ClearStackOnExit(const ClearStackOnExit&); - ClearStackOnExit& operator=(const ClearStackOnExit&); - GenericDocument& d_; - }; - - // callers of the following private Handler functions - // template friend class GenericReader; // for parsing - template friend class GenericValue; // for deep copying - -public: - // Implementation of Handler - bool Null() { new (stack_.template Push()) ValueType(); return true; } - bool Bool(bool b) { new (stack_.template Push()) ValueType(b); return true; } - bool Int(int i) { new (stack_.template Push()) ValueType(i); return true; } - bool Uint(unsigned i) { new (stack_.template Push()) ValueType(i); return true; } - bool Int64(int64_t i) { new (stack_.template Push()) ValueType(i); return true; } - bool Uint64(uint64_t i) { new (stack_.template Push()) ValueType(i); return true; } - bool Double(double d) { new (stack_.template Push()) ValueType(d); return true; } - - bool RawNumber(const Ch* str, SizeType length, bool copy) { - if (copy) - new (stack_.template Push()) ValueType(str, length, GetAllocator()); - else - new (stack_.template Push()) ValueType(str, length); - return true; - } - - bool String(const Ch* str, SizeType length, bool copy) { - if (copy) - new (stack_.template Push()) ValueType(str, length, GetAllocator()); - else - new (stack_.template Push()) ValueType(str, length); - return true; - } - - bool StartObject() { new (stack_.template Push()) ValueType(kObjectType); return true; } - - bool Key(const Ch* str, SizeType length, bool copy) { return String(str, length, copy); } - - bool EndObject(SizeType memberCount) { - typename ValueType::Member* members = stack_.template Pop(memberCount); - stack_.template Top()->SetObjectRaw(members, memberCount, GetAllocator()); - return true; - } - - bool StartArray() { new (stack_.template Push()) ValueType(kArrayType); return true; } - - bool EndArray(SizeType elementCount) { - ValueType* elements = stack_.template Pop(elementCount); - stack_.template Top()->SetArrayRaw(elements, elementCount, GetAllocator()); - return true; - } - -private: - //! Prohibit copying - GenericDocument(const GenericDocument&); - //! Prohibit assignment - GenericDocument& operator=(const GenericDocument&); - - void ClearStack() { - if (Allocator::kNeedFree) - while (stack_.GetSize() > 0) // Here assumes all elements in stack array are GenericValue (Member is actually 2 GenericValue objects) - (stack_.template Pop(1))->~ValueType(); - else - stack_.Clear(); - stack_.ShrinkToFit(); - } - - void Destroy() { - CEREAL_RAPIDJSON_DELETE(ownAllocator_); - } - - static const size_t kDefaultStackCapacity = 1024; - Allocator* allocator_; - Allocator* ownAllocator_; - internal::Stack stack_; - ParseResult parseResult_; -}; - -//! GenericDocument with UTF8 encoding -typedef GenericDocument > Document; - -//! Helper class for accessing Value of array type. -/*! - Instance of this helper class is obtained by \c GenericValue::GetArray(). - In addition to all APIs for array type, it provides range-based for loop if \c CEREAL_RAPIDJSON_HAS_CXX11_RANGE_FOR=1. -*/ -template -class GenericArray { -public: - typedef GenericArray ConstArray; - typedef GenericArray Array; - typedef ValueT PlainType; - typedef typename internal::MaybeAddConst::Type ValueType; - typedef ValueType* ValueIterator; // This may be const or non-const iterator - typedef const ValueT* ConstValueIterator; - typedef typename ValueType::AllocatorType AllocatorType; - typedef typename ValueType::StringRefType StringRefType; - - template - friend class GenericValue; - - GenericArray(const GenericArray& rhs) : value_(rhs.value_) {} - GenericArray& operator=(const GenericArray& rhs) { value_ = rhs.value_; return *this; } - ~GenericArray() {} - - SizeType Size() const { return value_.Size(); } - SizeType Capacity() const { return value_.Capacity(); } - bool Empty() const { return value_.Empty(); } - void Clear() const { value_.Clear(); } - ValueType& operator[](SizeType index) const { return value_[index]; } - ValueIterator Begin() const { return value_.Begin(); } - ValueIterator End() const { return value_.End(); } - GenericArray Reserve(SizeType newCapacity, AllocatorType &allocator) const { value_.Reserve(newCapacity, allocator); return *this; } - GenericArray PushBack(ValueType& value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; } -#if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - GenericArray PushBack(ValueType&& value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; } -#endif // CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - GenericArray PushBack(StringRefType value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; } - template CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (const GenericArray&)) PushBack(T value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; } - GenericArray PopBack() const { value_.PopBack(); return *this; } - ValueIterator Erase(ConstValueIterator pos) const { return value_.Erase(pos); } - ValueIterator Erase(ConstValueIterator first, ConstValueIterator last) const { return value_.Erase(first, last); } - -#if CEREAL_RAPIDJSON_HAS_CXX11_RANGE_FOR - ValueIterator begin() const { return value_.Begin(); } - ValueIterator end() const { return value_.End(); } -#endif - -private: - GenericArray(); - GenericArray(ValueType& value) : value_(value) {} - ValueType& value_; -}; - -//! Helper class for accessing Value of object type. -/*! - Instance of this helper class is obtained by \c GenericValue::GetObject(). - In addition to all APIs for array type, it provides range-based for loop if \c CEREAL_RAPIDJSON_HAS_CXX11_RANGE_FOR=1. -*/ -template -class GenericObject { -public: - typedef GenericObject ConstObject; - typedef GenericObject Object; - typedef ValueT PlainType; - typedef typename internal::MaybeAddConst::Type ValueType; - typedef GenericMemberIterator MemberIterator; // This may be const or non-const iterator - typedef GenericMemberIterator ConstMemberIterator; - typedef typename ValueType::AllocatorType AllocatorType; - typedef typename ValueType::StringRefType StringRefType; - typedef typename ValueType::EncodingType EncodingType; - typedef typename ValueType::Ch Ch; - - template - friend class GenericValue; - - GenericObject(const GenericObject& rhs) : value_(rhs.value_) {} - GenericObject& operator=(const GenericObject& rhs) { value_ = rhs.value_; return *this; } - ~GenericObject() {} - - SizeType MemberCount() const { return value_.MemberCount(); } - SizeType MemberCapacity() const { return value_.MemberCapacity(); } - bool ObjectEmpty() const { return value_.ObjectEmpty(); } - template ValueType& operator[](T* name) const { return value_[name]; } - template ValueType& operator[](const GenericValue& name) const { return value_[name]; } -#if CEREAL_RAPIDJSON_HAS_STDSTRING - ValueType& operator[](const std::basic_string& name) const { return value_[name]; } -#endif - MemberIterator MemberBegin() const { return value_.MemberBegin(); } - MemberIterator MemberEnd() const { return value_.MemberEnd(); } - GenericObject MemberReserve(SizeType newCapacity, AllocatorType &allocator) const { value_.MemberReserve(newCapacity, allocator); return *this; } - bool HasMember(const Ch* name) const { return value_.HasMember(name); } -#if CEREAL_RAPIDJSON_HAS_STDSTRING - bool HasMember(const std::basic_string& name) const { return value_.HasMember(name); } -#endif - template bool HasMember(const GenericValue& name) const { return value_.HasMember(name); } - MemberIterator FindMember(const Ch* name) const { return value_.FindMember(name); } - template MemberIterator FindMember(const GenericValue& name) const { return value_.FindMember(name); } -#if CEREAL_RAPIDJSON_HAS_STDSTRING - MemberIterator FindMember(const std::basic_string& name) const { return value_.FindMember(name); } -#endif - GenericObject AddMember(ValueType& name, ValueType& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } - GenericObject AddMember(ValueType& name, StringRefType value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } -#if CEREAL_RAPIDJSON_HAS_STDSTRING - GenericObject AddMember(ValueType& name, std::basic_string& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } -#endif - template CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (ValueType&)) AddMember(ValueType& name, T value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } -#if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - GenericObject AddMember(ValueType&& name, ValueType&& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } - GenericObject AddMember(ValueType&& name, ValueType& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } - GenericObject AddMember(ValueType& name, ValueType&& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } - GenericObject AddMember(StringRefType name, ValueType&& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } -#endif // CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - GenericObject AddMember(StringRefType name, ValueType& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } - GenericObject AddMember(StringRefType name, StringRefType value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } - template CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (GenericObject)) AddMember(StringRefType name, T value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } - void RemoveAllMembers() { value_.RemoveAllMembers(); } - bool RemoveMember(const Ch* name) const { return value_.RemoveMember(name); } -#if CEREAL_RAPIDJSON_HAS_STDSTRING - bool RemoveMember(const std::basic_string& name) const { return value_.RemoveMember(name); } -#endif - template bool RemoveMember(const GenericValue& name) const { return value_.RemoveMember(name); } - MemberIterator RemoveMember(MemberIterator m) const { return value_.RemoveMember(m); } - MemberIterator EraseMember(ConstMemberIterator pos) const { return value_.EraseMember(pos); } - MemberIterator EraseMember(ConstMemberIterator first, ConstMemberIterator last) const { return value_.EraseMember(first, last); } - bool EraseMember(const Ch* name) const { return value_.EraseMember(name); } -#if CEREAL_RAPIDJSON_HAS_STDSTRING - bool EraseMember(const std::basic_string& name) const { return EraseMember(ValueType(StringRef(name))); } -#endif - template bool EraseMember(const GenericValue& name) const { return value_.EraseMember(name); } - -#if CEREAL_RAPIDJSON_HAS_CXX11_RANGE_FOR - MemberIterator begin() const { return value_.MemberBegin(); } - MemberIterator end() const { return value_.MemberEnd(); } -#endif - -private: - GenericObject(); - GenericObject(ValueType& value) : value_(value) {} - ValueType& value_; -}; - -CEREAL_RAPIDJSON_NAMESPACE_END -CEREAL_RAPIDJSON_DIAG_POP - -#endif // CEREAL_RAPIDJSON_DOCUMENT_H_ diff --git a/include/cereal/external/rapidjson/encodedstream.h b/include/cereal/external/rapidjson/encodedstream.h deleted file mode 100644 index b04774b..0000000 --- a/include/cereal/external/rapidjson/encodedstream.h +++ /dev/null @@ -1,299 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_ENCODEDSTREAM_H_ -#define CEREAL_RAPIDJSON_ENCODEDSTREAM_H_ - -#include "stream.h" -#include "memorystream.h" - -#ifdef __GNUC__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(effc++) -#endif - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(padded) -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -//! Input byte stream wrapper with a statically bound encoding. -/*! - \tparam Encoding The interpretation of encoding of the stream. Either UTF8, UTF16LE, UTF16BE, UTF32LE, UTF32BE. - \tparam InputByteStream Type of input byte stream. For example, FileReadStream. -*/ -template -class EncodedInputStream { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); -public: - typedef typename Encoding::Ch Ch; - - EncodedInputStream(InputByteStream& is) : is_(is) { - current_ = Encoding::TakeBOM(is_); - } - - Ch Peek() const { return current_; } - Ch Take() { Ch c = current_; current_ = Encoding::Take(is_); return c; } - size_t Tell() const { return is_.Tell(); } - - // Not implemented - void Put(Ch) { CEREAL_RAPIDJSON_ASSERT(false); } - void Flush() { CEREAL_RAPIDJSON_ASSERT(false); } - Ch* PutBegin() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - size_t PutEnd(Ch*) { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - -private: - EncodedInputStream(const EncodedInputStream&); - EncodedInputStream& operator=(const EncodedInputStream&); - - InputByteStream& is_; - Ch current_; -}; - -//! Specialized for UTF8 MemoryStream. -template <> -class EncodedInputStream, MemoryStream> { -public: - typedef UTF8<>::Ch Ch; - - EncodedInputStream(MemoryStream& is) : is_(is) { - if (static_cast(is_.Peek()) == 0xEFu) is_.Take(); - if (static_cast(is_.Peek()) == 0xBBu) is_.Take(); - if (static_cast(is_.Peek()) == 0xBFu) is_.Take(); - } - Ch Peek() const { return is_.Peek(); } - Ch Take() { return is_.Take(); } - size_t Tell() const { return is_.Tell(); } - - // Not implemented - void Put(Ch) {} - void Flush() {} - Ch* PutBegin() { return 0; } - size_t PutEnd(Ch*) { return 0; } - - MemoryStream& is_; - -private: - EncodedInputStream(const EncodedInputStream&); - EncodedInputStream& operator=(const EncodedInputStream&); -}; - -//! Output byte stream wrapper with statically bound encoding. -/*! - \tparam Encoding The interpretation of encoding of the stream. Either UTF8, UTF16LE, UTF16BE, UTF32LE, UTF32BE. - \tparam OutputByteStream Type of input byte stream. For example, FileWriteStream. -*/ -template -class EncodedOutputStream { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); -public: - typedef typename Encoding::Ch Ch; - - EncodedOutputStream(OutputByteStream& os, bool putBOM = true) : os_(os) { - if (putBOM) - Encoding::PutBOM(os_); - } - - void Put(Ch c) { Encoding::Put(os_, c); } - void Flush() { os_.Flush(); } - - // Not implemented - Ch Peek() const { CEREAL_RAPIDJSON_ASSERT(false); return 0;} - Ch Take() { CEREAL_RAPIDJSON_ASSERT(false); return 0;} - size_t Tell() const { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - Ch* PutBegin() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - size_t PutEnd(Ch*) { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - -private: - EncodedOutputStream(const EncodedOutputStream&); - EncodedOutputStream& operator=(const EncodedOutputStream&); - - OutputByteStream& os_; -}; - -#define CEREAL_RAPIDJSON_ENCODINGS_FUNC(x) UTF8::x, UTF16LE::x, UTF16BE::x, UTF32LE::x, UTF32BE::x - -//! Input stream wrapper with dynamically bound encoding and automatic encoding detection. -/*! - \tparam CharType Type of character for reading. - \tparam InputByteStream type of input byte stream to be wrapped. -*/ -template -class AutoUTFInputStream { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); -public: - typedef CharType Ch; - - //! Constructor. - /*! - \param is input stream to be wrapped. - \param type UTF encoding type if it is not detected from the stream. - */ - AutoUTFInputStream(InputByteStream& is, UTFType type = kUTF8) : is_(&is), type_(type), hasBOM_(false) { - CEREAL_RAPIDJSON_ASSERT(type >= kUTF8 && type <= kUTF32BE); - DetectType(); - static const TakeFunc f[] = { CEREAL_RAPIDJSON_ENCODINGS_FUNC(Take) }; - takeFunc_ = f[type_]; - current_ = takeFunc_(*is_); - } - - UTFType GetType() const { return type_; } - bool HasBOM() const { return hasBOM_; } - - Ch Peek() const { return current_; } - Ch Take() { Ch c = current_; current_ = takeFunc_(*is_); return c; } - size_t Tell() const { return is_->Tell(); } - - // Not implemented - void Put(Ch) { CEREAL_RAPIDJSON_ASSERT(false); } - void Flush() { CEREAL_RAPIDJSON_ASSERT(false); } - Ch* PutBegin() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - size_t PutEnd(Ch*) { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - -private: - AutoUTFInputStream(const AutoUTFInputStream&); - AutoUTFInputStream& operator=(const AutoUTFInputStream&); - - // Detect encoding type with BOM or RFC 4627 - void DetectType() { - // BOM (Byte Order Mark): - // 00 00 FE FF UTF-32BE - // FF FE 00 00 UTF-32LE - // FE FF UTF-16BE - // FF FE UTF-16LE - // EF BB BF UTF-8 - - const unsigned char* c = reinterpret_cast(is_->Peek4()); - if (!c) - return; - - unsigned bom = static_cast(c[0] | (c[1] << 8) | (c[2] << 16) | (c[3] << 24)); - hasBOM_ = false; - if (bom == 0xFFFE0000) { type_ = kUTF32BE; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); is_->Take(); } - else if (bom == 0x0000FEFF) { type_ = kUTF32LE; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); is_->Take(); } - else if ((bom & 0xFFFF) == 0xFFFE) { type_ = kUTF16BE; hasBOM_ = true; is_->Take(); is_->Take(); } - else if ((bom & 0xFFFF) == 0xFEFF) { type_ = kUTF16LE; hasBOM_ = true; is_->Take(); is_->Take(); } - else if ((bom & 0xFFFFFF) == 0xBFBBEF) { type_ = kUTF8; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); } - - // RFC 4627: Section 3 - // "Since the first two characters of a JSON text will always be ASCII - // characters [RFC0020], it is possible to determine whether an octet - // stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking - // at the pattern of nulls in the first four octets." - // 00 00 00 xx UTF-32BE - // 00 xx 00 xx UTF-16BE - // xx 00 00 00 UTF-32LE - // xx 00 xx 00 UTF-16LE - // xx xx xx xx UTF-8 - - if (!hasBOM_) { - int pattern = (c[0] ? 1 : 0) | (c[1] ? 2 : 0) | (c[2] ? 4 : 0) | (c[3] ? 8 : 0); - switch (pattern) { - case 0x08: type_ = kUTF32BE; break; - case 0x0A: type_ = kUTF16BE; break; - case 0x01: type_ = kUTF32LE; break; - case 0x05: type_ = kUTF16LE; break; - case 0x0F: type_ = kUTF8; break; - default: break; // Use type defined by user. - } - } - - // Runtime check whether the size of character type is sufficient. It only perform checks with assertion. - if (type_ == kUTF16LE || type_ == kUTF16BE) CEREAL_RAPIDJSON_ASSERT(sizeof(Ch) >= 2); - if (type_ == kUTF32LE || type_ == kUTF32BE) CEREAL_RAPIDJSON_ASSERT(sizeof(Ch) >= 4); - } - - typedef Ch (*TakeFunc)(InputByteStream& is); - InputByteStream* is_; - UTFType type_; - Ch current_; - TakeFunc takeFunc_; - bool hasBOM_; -}; - -//! Output stream wrapper with dynamically bound encoding and automatic encoding detection. -/*! - \tparam CharType Type of character for writing. - \tparam OutputByteStream type of output byte stream to be wrapped. -*/ -template -class AutoUTFOutputStream { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); -public: - typedef CharType Ch; - - //! Constructor. - /*! - \param os output stream to be wrapped. - \param type UTF encoding type. - \param putBOM Whether to write BOM at the beginning of the stream. - */ - AutoUTFOutputStream(OutputByteStream& os, UTFType type, bool putBOM) : os_(&os), type_(type) { - CEREAL_RAPIDJSON_ASSERT(type >= kUTF8 && type <= kUTF32BE); - - // Runtime check whether the size of character type is sufficient. It only perform checks with assertion. - if (type_ == kUTF16LE || type_ == kUTF16BE) CEREAL_RAPIDJSON_ASSERT(sizeof(Ch) >= 2); - if (type_ == kUTF32LE || type_ == kUTF32BE) CEREAL_RAPIDJSON_ASSERT(sizeof(Ch) >= 4); - - static const PutFunc f[] = { CEREAL_RAPIDJSON_ENCODINGS_FUNC(Put) }; - putFunc_ = f[type_]; - - if (putBOM) - PutBOM(); - } - - UTFType GetType() const { return type_; } - - void Put(Ch c) { putFunc_(*os_, c); } - void Flush() { os_->Flush(); } - - // Not implemented - Ch Peek() const { CEREAL_RAPIDJSON_ASSERT(false); return 0;} - Ch Take() { CEREAL_RAPIDJSON_ASSERT(false); return 0;} - size_t Tell() const { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - Ch* PutBegin() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - size_t PutEnd(Ch*) { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - -private: - AutoUTFOutputStream(const AutoUTFOutputStream&); - AutoUTFOutputStream& operator=(const AutoUTFOutputStream&); - - void PutBOM() { - typedef void (*PutBOMFunc)(OutputByteStream&); - static const PutBOMFunc f[] = { CEREAL_RAPIDJSON_ENCODINGS_FUNC(PutBOM) }; - f[type_](*os_); - } - - typedef void (*PutFunc)(OutputByteStream&, Ch); - - OutputByteStream* os_; - UTFType type_; - PutFunc putFunc_; -}; - -#undef CEREAL_RAPIDJSON_ENCODINGS_FUNC - -CEREAL_RAPIDJSON_NAMESPACE_END - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#ifdef __GNUC__ -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#endif // CEREAL_RAPIDJSON_FILESTREAM_H_ diff --git a/include/cereal/external/rapidjson/encodings.h b/include/cereal/external/rapidjson/encodings.h deleted file mode 100644 index a1c27ec..0000000 --- a/include/cereal/external/rapidjson/encodings.h +++ /dev/null @@ -1,716 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_ENCODINGS_H_ -#define CEREAL_RAPIDJSON_ENCODINGS_H_ - -#include "rapidjson.h" - -#if defined(_MSC_VER) && !defined(__clang__) -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(4244) // conversion from 'type1' to 'type2', possible loss of data -CEREAL_RAPIDJSON_DIAG_OFF(4702) // unreachable code -#elif defined(__GNUC__) -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(effc++) -CEREAL_RAPIDJSON_DIAG_OFF(overflow) -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -/////////////////////////////////////////////////////////////////////////////// -// Encoding - -/*! \class rapidjson::Encoding - \brief Concept for encoding of Unicode characters. - -\code -concept Encoding { - typename Ch; //! Type of character. A "character" is actually a code unit in unicode's definition. - - enum { supportUnicode = 1 }; // or 0 if not supporting unicode - - //! \brief Encode a Unicode codepoint to an output stream. - //! \param os Output stream. - //! \param codepoint An unicode codepoint, ranging from 0x0 to 0x10FFFF inclusively. - template - static void Encode(OutputStream& os, unsigned codepoint); - - //! \brief Decode a Unicode codepoint from an input stream. - //! \param is Input stream. - //! \param codepoint Output of the unicode codepoint. - //! \return true if a valid codepoint can be decoded from the stream. - template - static bool Decode(InputStream& is, unsigned* codepoint); - - //! \brief Validate one Unicode codepoint from an encoded stream. - //! \param is Input stream to obtain codepoint. - //! \param os Output for copying one codepoint. - //! \return true if it is valid. - //! \note This function just validating and copying the codepoint without actually decode it. - template - static bool Validate(InputStream& is, OutputStream& os); - - // The following functions are deal with byte streams. - - //! Take a character from input byte stream, skip BOM if exist. - template - static CharType TakeBOM(InputByteStream& is); - - //! Take a character from input byte stream. - template - static Ch Take(InputByteStream& is); - - //! Put BOM to output byte stream. - template - static void PutBOM(OutputByteStream& os); - - //! Put a character to output byte stream. - template - static void Put(OutputByteStream& os, Ch c); -}; -\endcode -*/ - -/////////////////////////////////////////////////////////////////////////////// -// UTF8 - -//! UTF-8 encoding. -/*! http://en.wikipedia.org/wiki/UTF-8 - http://tools.ietf.org/html/rfc3629 - \tparam CharType Code unit for storing 8-bit UTF-8 data. Default is char. - \note implements Encoding concept -*/ -template -struct UTF8 { - typedef CharType Ch; - - enum { supportUnicode = 1 }; - - template - static void Encode(OutputStream& os, unsigned codepoint) { - if (codepoint <= 0x7F) - os.Put(static_cast(codepoint & 0xFF)); - else if (codepoint <= 0x7FF) { - os.Put(static_cast(0xC0 | ((codepoint >> 6) & 0xFF))); - os.Put(static_cast(0x80 | ((codepoint & 0x3F)))); - } - else if (codepoint <= 0xFFFF) { - os.Put(static_cast(0xE0 | ((codepoint >> 12) & 0xFF))); - os.Put(static_cast(0x80 | ((codepoint >> 6) & 0x3F))); - os.Put(static_cast(0x80 | (codepoint & 0x3F))); - } - else { - CEREAL_RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); - os.Put(static_cast(0xF0 | ((codepoint >> 18) & 0xFF))); - os.Put(static_cast(0x80 | ((codepoint >> 12) & 0x3F))); - os.Put(static_cast(0x80 | ((codepoint >> 6) & 0x3F))); - os.Put(static_cast(0x80 | (codepoint & 0x3F))); - } - } - - template - static void EncodeUnsafe(OutputStream& os, unsigned codepoint) { - if (codepoint <= 0x7F) - PutUnsafe(os, static_cast(codepoint & 0xFF)); - else if (codepoint <= 0x7FF) { - PutUnsafe(os, static_cast(0xC0 | ((codepoint >> 6) & 0xFF))); - PutUnsafe(os, static_cast(0x80 | ((codepoint & 0x3F)))); - } - else if (codepoint <= 0xFFFF) { - PutUnsafe(os, static_cast(0xE0 | ((codepoint >> 12) & 0xFF))); - PutUnsafe(os, static_cast(0x80 | ((codepoint >> 6) & 0x3F))); - PutUnsafe(os, static_cast(0x80 | (codepoint & 0x3F))); - } - else { - CEREAL_RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); - PutUnsafe(os, static_cast(0xF0 | ((codepoint >> 18) & 0xFF))); - PutUnsafe(os, static_cast(0x80 | ((codepoint >> 12) & 0x3F))); - PutUnsafe(os, static_cast(0x80 | ((codepoint >> 6) & 0x3F))); - PutUnsafe(os, static_cast(0x80 | (codepoint & 0x3F))); - } - } - - template - static bool Decode(InputStream& is, unsigned* codepoint) { -#define CEREAL_RAPIDJSON_COPY() c = is.Take(); *codepoint = (*codepoint << 6) | (static_cast(c) & 0x3Fu) -#define CEREAL_RAPIDJSON_TRANS(mask) result &= ((GetRange(static_cast(c)) & mask) != 0) -#define CEREAL_RAPIDJSON_TAIL() CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x70) - typename InputStream::Ch c = is.Take(); - if (!(c & 0x80)) { - *codepoint = static_cast(c); - return true; - } - - unsigned char type = GetRange(static_cast(c)); - if (type >= 32) { - *codepoint = 0; - } else { - *codepoint = (0xFFu >> type) & static_cast(c); - } - bool result = true; - switch (type) { - case 2: CEREAL_RAPIDJSON_TAIL(); return result; - case 3: CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); return result; - case 4: CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x50); CEREAL_RAPIDJSON_TAIL(); return result; - case 5: CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x10); CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); return result; - case 6: CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); return result; - case 10: CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x20); CEREAL_RAPIDJSON_TAIL(); return result; - case 11: CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x60); CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); return result; - default: return false; - } -#undef CEREAL_RAPIDJSON_COPY -#undef CEREAL_RAPIDJSON_TRANS -#undef CEREAL_RAPIDJSON_TAIL - } - - template - static bool Validate(InputStream& is, OutputStream& os) { -#define CEREAL_RAPIDJSON_COPY() os.Put(c = is.Take()) -#define CEREAL_RAPIDJSON_TRANS(mask) result &= ((GetRange(static_cast(c)) & mask) != 0) -#define CEREAL_RAPIDJSON_TAIL() CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x70) - Ch c; - CEREAL_RAPIDJSON_COPY(); - if (!(c & 0x80)) - return true; - - bool result = true; - switch (GetRange(static_cast(c))) { - case 2: CEREAL_RAPIDJSON_TAIL(); return result; - case 3: CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); return result; - case 4: CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x50); CEREAL_RAPIDJSON_TAIL(); return result; - case 5: CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x10); CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); return result; - case 6: CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); return result; - case 10: CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x20); CEREAL_RAPIDJSON_TAIL(); return result; - case 11: CEREAL_RAPIDJSON_COPY(); CEREAL_RAPIDJSON_TRANS(0x60); CEREAL_RAPIDJSON_TAIL(); CEREAL_RAPIDJSON_TAIL(); return result; - default: return false; - } -#undef CEREAL_RAPIDJSON_COPY -#undef CEREAL_RAPIDJSON_TRANS -#undef CEREAL_RAPIDJSON_TAIL - } - - static unsigned char GetRange(unsigned char c) { - // Referring to DFA of http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ - // With new mapping 1 -> 0x10, 7 -> 0x20, 9 -> 0x40, such that AND operation can test multiple types. - static const unsigned char type[] = { - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10, - 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40, - 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, - 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, - 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, - 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8, - }; - return type[c]; - } - - template - static CharType TakeBOM(InputByteStream& is) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); - typename InputByteStream::Ch c = Take(is); - if (static_cast(c) != 0xEFu) return c; - c = is.Take(); - if (static_cast(c) != 0xBBu) return c; - c = is.Take(); - if (static_cast(c) != 0xBFu) return c; - c = is.Take(); - return c; - } - - template - static Ch Take(InputByteStream& is) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); - return static_cast(is.Take()); - } - - template - static void PutBOM(OutputByteStream& os) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); - os.Put(static_cast(0xEFu)); - os.Put(static_cast(0xBBu)); - os.Put(static_cast(0xBFu)); - } - - template - static void Put(OutputByteStream& os, Ch c) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); - os.Put(static_cast(c)); - } -}; - -/////////////////////////////////////////////////////////////////////////////// -// UTF16 - -//! UTF-16 encoding. -/*! http://en.wikipedia.org/wiki/UTF-16 - http://tools.ietf.org/html/rfc2781 - \tparam CharType Type for storing 16-bit UTF-16 data. Default is wchar_t. C++11 may use char16_t instead. - \note implements Encoding concept - - \note For in-memory access, no need to concern endianness. The code units and code points are represented by CPU's endianness. - For streaming, use UTF16LE and UTF16BE, which handle endianness. -*/ -template -struct UTF16 { - typedef CharType Ch; - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(Ch) >= 2); - - enum { supportUnicode = 1 }; - - template - static void Encode(OutputStream& os, unsigned codepoint) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 2); - if (codepoint <= 0xFFFF) { - CEREAL_RAPIDJSON_ASSERT(codepoint < 0xD800 || codepoint > 0xDFFF); // Code point itself cannot be surrogate pair - os.Put(static_cast(codepoint)); - } - else { - CEREAL_RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); - unsigned v = codepoint - 0x10000; - os.Put(static_cast((v >> 10) | 0xD800)); - os.Put(static_cast((v & 0x3FF) | 0xDC00)); - } - } - - - template - static void EncodeUnsafe(OutputStream& os, unsigned codepoint) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 2); - if (codepoint <= 0xFFFF) { - CEREAL_RAPIDJSON_ASSERT(codepoint < 0xD800 || codepoint > 0xDFFF); // Code point itself cannot be surrogate pair - PutUnsafe(os, static_cast(codepoint)); - } - else { - CEREAL_RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); - unsigned v = codepoint - 0x10000; - PutUnsafe(os, static_cast((v >> 10) | 0xD800)); - PutUnsafe(os, static_cast((v & 0x3FF) | 0xDC00)); - } - } - - template - static bool Decode(InputStream& is, unsigned* codepoint) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 2); - typename InputStream::Ch c = is.Take(); - if (c < 0xD800 || c > 0xDFFF) { - *codepoint = static_cast(c); - return true; - } - else if (c <= 0xDBFF) { - *codepoint = (static_cast(c) & 0x3FF) << 10; - c = is.Take(); - *codepoint |= (static_cast(c) & 0x3FF); - *codepoint += 0x10000; - return c >= 0xDC00 && c <= 0xDFFF; - } - return false; - } - - template - static bool Validate(InputStream& is, OutputStream& os) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 2); - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 2); - typename InputStream::Ch c; - os.Put(static_cast(c = is.Take())); - if (c < 0xD800 || c > 0xDFFF) - return true; - else if (c <= 0xDBFF) { - os.Put(c = is.Take()); - return c >= 0xDC00 && c <= 0xDFFF; - } - return false; - } -}; - -//! UTF-16 little endian encoding. -template -struct UTF16LE : UTF16 { - template - static CharType TakeBOM(InputByteStream& is) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); - CharType c = Take(is); - return static_cast(c) == 0xFEFFu ? Take(is) : c; - } - - template - static CharType Take(InputByteStream& is) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); - unsigned c = static_cast(is.Take()); - c |= static_cast(static_cast(is.Take())) << 8; - return static_cast(c); - } - - template - static void PutBOM(OutputByteStream& os) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); - os.Put(static_cast(0xFFu)); - os.Put(static_cast(0xFEu)); - } - - template - static void Put(OutputByteStream& os, CharType c) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); - os.Put(static_cast(static_cast(c) & 0xFFu)); - os.Put(static_cast((static_cast(c) >> 8) & 0xFFu)); - } -}; - -//! UTF-16 big endian encoding. -template -struct UTF16BE : UTF16 { - template - static CharType TakeBOM(InputByteStream& is) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); - CharType c = Take(is); - return static_cast(c) == 0xFEFFu ? Take(is) : c; - } - - template - static CharType Take(InputByteStream& is) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); - unsigned c = static_cast(static_cast(is.Take())) << 8; - c |= static_cast(static_cast(is.Take())); - return static_cast(c); - } - - template - static void PutBOM(OutputByteStream& os) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); - os.Put(static_cast(0xFEu)); - os.Put(static_cast(0xFFu)); - } - - template - static void Put(OutputByteStream& os, CharType c) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); - os.Put(static_cast((static_cast(c) >> 8) & 0xFFu)); - os.Put(static_cast(static_cast(c) & 0xFFu)); - } -}; - -/////////////////////////////////////////////////////////////////////////////// -// UTF32 - -//! UTF-32 encoding. -/*! http://en.wikipedia.org/wiki/UTF-32 - \tparam CharType Type for storing 32-bit UTF-32 data. Default is unsigned. C++11 may use char32_t instead. - \note implements Encoding concept - - \note For in-memory access, no need to concern endianness. The code units and code points are represented by CPU's endianness. - For streaming, use UTF32LE and UTF32BE, which handle endianness. -*/ -template -struct UTF32 { - typedef CharType Ch; - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(Ch) >= 4); - - enum { supportUnicode = 1 }; - - template - static void Encode(OutputStream& os, unsigned codepoint) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 4); - CEREAL_RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); - os.Put(codepoint); - } - - template - static void EncodeUnsafe(OutputStream& os, unsigned codepoint) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 4); - CEREAL_RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); - PutUnsafe(os, codepoint); - } - - template - static bool Decode(InputStream& is, unsigned* codepoint) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 4); - Ch c = is.Take(); - *codepoint = c; - return c <= 0x10FFFF; - } - - template - static bool Validate(InputStream& is, OutputStream& os) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 4); - Ch c; - os.Put(c = is.Take()); - return c <= 0x10FFFF; - } -}; - -//! UTF-32 little endian enocoding. -template -struct UTF32LE : UTF32 { - template - static CharType TakeBOM(InputByteStream& is) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); - CharType c = Take(is); - return static_cast(c) == 0x0000FEFFu ? Take(is) : c; - } - - template - static CharType Take(InputByteStream& is) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); - unsigned c = static_cast(is.Take()); - c |= static_cast(static_cast(is.Take())) << 8; - c |= static_cast(static_cast(is.Take())) << 16; - c |= static_cast(static_cast(is.Take())) << 24; - return static_cast(c); - } - - template - static void PutBOM(OutputByteStream& os) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); - os.Put(static_cast(0xFFu)); - os.Put(static_cast(0xFEu)); - os.Put(static_cast(0x00u)); - os.Put(static_cast(0x00u)); - } - - template - static void Put(OutputByteStream& os, CharType c) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); - os.Put(static_cast(c & 0xFFu)); - os.Put(static_cast((c >> 8) & 0xFFu)); - os.Put(static_cast((c >> 16) & 0xFFu)); - os.Put(static_cast((c >> 24) & 0xFFu)); - } -}; - -//! UTF-32 big endian encoding. -template -struct UTF32BE : UTF32 { - template - static CharType TakeBOM(InputByteStream& is) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); - CharType c = Take(is); - return static_cast(c) == 0x0000FEFFu ? Take(is) : c; - } - - template - static CharType Take(InputByteStream& is) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); - unsigned c = static_cast(static_cast(is.Take())) << 24; - c |= static_cast(static_cast(is.Take())) << 16; - c |= static_cast(static_cast(is.Take())) << 8; - c |= static_cast(static_cast(is.Take())); - return static_cast(c); - } - - template - static void PutBOM(OutputByteStream& os) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); - os.Put(static_cast(0x00u)); - os.Put(static_cast(0x00u)); - os.Put(static_cast(0xFEu)); - os.Put(static_cast(0xFFu)); - } - - template - static void Put(OutputByteStream& os, CharType c) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); - os.Put(static_cast((c >> 24) & 0xFFu)); - os.Put(static_cast((c >> 16) & 0xFFu)); - os.Put(static_cast((c >> 8) & 0xFFu)); - os.Put(static_cast(c & 0xFFu)); - } -}; - -/////////////////////////////////////////////////////////////////////////////// -// ASCII - -//! ASCII encoding. -/*! http://en.wikipedia.org/wiki/ASCII - \tparam CharType Code unit for storing 7-bit ASCII data. Default is char. - \note implements Encoding concept -*/ -template -struct ASCII { - typedef CharType Ch; - - enum { supportUnicode = 0 }; - - template - static void Encode(OutputStream& os, unsigned codepoint) { - CEREAL_RAPIDJSON_ASSERT(codepoint <= 0x7F); - os.Put(static_cast(codepoint & 0xFF)); - } - - template - static void EncodeUnsafe(OutputStream& os, unsigned codepoint) { - CEREAL_RAPIDJSON_ASSERT(codepoint <= 0x7F); - PutUnsafe(os, static_cast(codepoint & 0xFF)); - } - - template - static bool Decode(InputStream& is, unsigned* codepoint) { - uint8_t c = static_cast(is.Take()); - *codepoint = c; - return c <= 0X7F; - } - - template - static bool Validate(InputStream& is, OutputStream& os) { - uint8_t c = static_cast(is.Take()); - os.Put(static_cast(c)); - return c <= 0x7F; - } - - template - static CharType TakeBOM(InputByteStream& is) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); - uint8_t c = static_cast(Take(is)); - return static_cast(c); - } - - template - static Ch Take(InputByteStream& is) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); - return static_cast(is.Take()); - } - - template - static void PutBOM(OutputByteStream& os) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); - (void)os; - } - - template - static void Put(OutputByteStream& os, Ch c) { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); - os.Put(static_cast(c)); - } -}; - -/////////////////////////////////////////////////////////////////////////////// -// AutoUTF - -//! Runtime-specified UTF encoding type of a stream. -enum UTFType { - kUTF8 = 0, //!< UTF-8. - kUTF16LE = 1, //!< UTF-16 little endian. - kUTF16BE = 2, //!< UTF-16 big endian. - kUTF32LE = 3, //!< UTF-32 little endian. - kUTF32BE = 4 //!< UTF-32 big endian. -}; - -//! Dynamically select encoding according to stream's runtime-specified UTF encoding type. -/*! \note This class can be used with AutoUTFInputtStream and AutoUTFOutputStream, which provides GetType(). -*/ -template -struct AutoUTF { - typedef CharType Ch; - - enum { supportUnicode = 1 }; - -#define CEREAL_RAPIDJSON_ENCODINGS_FUNC(x) UTF8::x, UTF16LE::x, UTF16BE::x, UTF32LE::x, UTF32BE::x - - template - static CEREAL_RAPIDJSON_FORCEINLINE void Encode(OutputStream& os, unsigned codepoint) { - typedef void (*EncodeFunc)(OutputStream&, unsigned); - static const EncodeFunc f[] = { CEREAL_RAPIDJSON_ENCODINGS_FUNC(Encode) }; - (*f[os.GetType()])(os, codepoint); - } - - template - static CEREAL_RAPIDJSON_FORCEINLINE void EncodeUnsafe(OutputStream& os, unsigned codepoint) { - typedef void (*EncodeFunc)(OutputStream&, unsigned); - static const EncodeFunc f[] = { CEREAL_RAPIDJSON_ENCODINGS_FUNC(EncodeUnsafe) }; - (*f[os.GetType()])(os, codepoint); - } - - template - static CEREAL_RAPIDJSON_FORCEINLINE bool Decode(InputStream& is, unsigned* codepoint) { - typedef bool (*DecodeFunc)(InputStream&, unsigned*); - static const DecodeFunc f[] = { CEREAL_RAPIDJSON_ENCODINGS_FUNC(Decode) }; - return (*f[is.GetType()])(is, codepoint); - } - - template - static CEREAL_RAPIDJSON_FORCEINLINE bool Validate(InputStream& is, OutputStream& os) { - typedef bool (*ValidateFunc)(InputStream&, OutputStream&); - static const ValidateFunc f[] = { CEREAL_RAPIDJSON_ENCODINGS_FUNC(Validate) }; - return (*f[is.GetType()])(is, os); - } - -#undef CEREAL_RAPIDJSON_ENCODINGS_FUNC -}; - -/////////////////////////////////////////////////////////////////////////////// -// Transcoder - -//! Encoding conversion. -template -struct Transcoder { - //! Take one Unicode codepoint from source encoding, convert it to target encoding and put it to the output stream. - template - static CEREAL_RAPIDJSON_FORCEINLINE bool Transcode(InputStream& is, OutputStream& os) { - unsigned codepoint; - if (!SourceEncoding::Decode(is, &codepoint)) - return false; - TargetEncoding::Encode(os, codepoint); - return true; - } - - template - static CEREAL_RAPIDJSON_FORCEINLINE bool TranscodeUnsafe(InputStream& is, OutputStream& os) { - unsigned codepoint; - if (!SourceEncoding::Decode(is, &codepoint)) - return false; - TargetEncoding::EncodeUnsafe(os, codepoint); - return true; - } - - //! Validate one Unicode codepoint from an encoded stream. - template - static CEREAL_RAPIDJSON_FORCEINLINE bool Validate(InputStream& is, OutputStream& os) { - return Transcode(is, os); // Since source/target encoding is different, must transcode. - } -}; - -// Forward declaration. -template -inline void PutUnsafe(Stream& stream, typename Stream::Ch c); - -//! Specialization of Transcoder with same source and target encoding. -template -struct Transcoder { - template - static CEREAL_RAPIDJSON_FORCEINLINE bool Transcode(InputStream& is, OutputStream& os) { - os.Put(is.Take()); // Just copy one code unit. This semantic is different from primary template class. - return true; - } - - template - static CEREAL_RAPIDJSON_FORCEINLINE bool TranscodeUnsafe(InputStream& is, OutputStream& os) { - PutUnsafe(os, is.Take()); // Just copy one code unit. This semantic is different from primary template class. - return true; - } - - template - static CEREAL_RAPIDJSON_FORCEINLINE bool Validate(InputStream& is, OutputStream& os) { - return Encoding::Validate(is, os); // source/target encoding are the same - } -}; - -CEREAL_RAPIDJSON_NAMESPACE_END - -#if defined(__GNUC__) || (defined(_MSC_VER) && !defined(__clang__)) -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#endif // CEREAL_RAPIDJSON_ENCODINGS_H_ diff --git a/include/cereal/external/rapidjson/error/en.h b/include/cereal/external/rapidjson/error/en.h deleted file mode 100644 index ea93bf8..0000000 --- a/include/cereal/external/rapidjson/error/en.h +++ /dev/null @@ -1,74 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_ERROR_EN_H_ -#define CEREAL_RAPIDJSON_ERROR_EN_H_ - -#include "error.h" - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(switch-enum) -CEREAL_RAPIDJSON_DIAG_OFF(covered-switch-default) -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -//! Maps error code of parsing into error message. -/*! - \ingroup CEREAL_RAPIDJSON_ERRORS - \param parseErrorCode Error code obtained in parsing. - \return the error message. - \note User can make a copy of this function for localization. - Using switch-case is safer for future modification of error codes. -*/ -inline const CEREAL_RAPIDJSON_ERROR_CHARTYPE* GetParseError_En(ParseErrorCode parseErrorCode) { - switch (parseErrorCode) { - case kParseErrorNone: return CEREAL_RAPIDJSON_ERROR_STRING("No error."); - - case kParseErrorDocumentEmpty: return CEREAL_RAPIDJSON_ERROR_STRING("The document is empty."); - case kParseErrorDocumentRootNotSingular: return CEREAL_RAPIDJSON_ERROR_STRING("The document root must not be followed by other values."); - - case kParseErrorValueInvalid: return CEREAL_RAPIDJSON_ERROR_STRING("Invalid value."); - - case kParseErrorObjectMissName: return CEREAL_RAPIDJSON_ERROR_STRING("Missing a name for object member."); - case kParseErrorObjectMissColon: return CEREAL_RAPIDJSON_ERROR_STRING("Missing a colon after a name of object member."); - case kParseErrorObjectMissCommaOrCurlyBracket: return CEREAL_RAPIDJSON_ERROR_STRING("Missing a comma or '}' after an object member."); - - case kParseErrorArrayMissCommaOrSquareBracket: return CEREAL_RAPIDJSON_ERROR_STRING("Missing a comma or ']' after an array element."); - - case kParseErrorStringUnicodeEscapeInvalidHex: return CEREAL_RAPIDJSON_ERROR_STRING("Incorrect hex digit after \\u escape in string."); - case kParseErrorStringUnicodeSurrogateInvalid: return CEREAL_RAPIDJSON_ERROR_STRING("The surrogate pair in string is invalid."); - case kParseErrorStringEscapeInvalid: return CEREAL_RAPIDJSON_ERROR_STRING("Invalid escape character in string."); - case kParseErrorStringMissQuotationMark: return CEREAL_RAPIDJSON_ERROR_STRING("Missing a closing quotation mark in string."); - case kParseErrorStringInvalidEncoding: return CEREAL_RAPIDJSON_ERROR_STRING("Invalid encoding in string."); - - case kParseErrorNumberTooBig: return CEREAL_RAPIDJSON_ERROR_STRING("Number too big to be stored in double."); - case kParseErrorNumberMissFraction: return CEREAL_RAPIDJSON_ERROR_STRING("Miss fraction part in number."); - case kParseErrorNumberMissExponent: return CEREAL_RAPIDJSON_ERROR_STRING("Miss exponent in number."); - - case kParseErrorTermination: return CEREAL_RAPIDJSON_ERROR_STRING("Terminate parsing due to Handler error."); - case kParseErrorUnspecificSyntaxError: return CEREAL_RAPIDJSON_ERROR_STRING("Unspecific syntax error."); - - default: return CEREAL_RAPIDJSON_ERROR_STRING("Unknown error."); - } -} - -CEREAL_RAPIDJSON_NAMESPACE_END - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#endif // CEREAL_RAPIDJSON_ERROR_EN_H_ diff --git a/include/cereal/external/rapidjson/error/error.h b/include/cereal/external/rapidjson/error/error.h deleted file mode 100644 index 7e7cc24..0000000 --- a/include/cereal/external/rapidjson/error/error.h +++ /dev/null @@ -1,161 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_ERROR_ERROR_H_ -#define CEREAL_RAPIDJSON_ERROR_ERROR_H_ - -#include "../rapidjson.h" - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(padded) -#endif - -/*! \file error.h */ - -/*! \defgroup CEREAL_RAPIDJSON_ERRORS RapidJSON error handling */ - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_ERROR_CHARTYPE - -//! Character type of error messages. -/*! \ingroup CEREAL_RAPIDJSON_ERRORS - The default character type is \c char. - On Windows, user can define this macro as \c TCHAR for supporting both - unicode/non-unicode settings. -*/ -#ifndef CEREAL_RAPIDJSON_ERROR_CHARTYPE -#define CEREAL_RAPIDJSON_ERROR_CHARTYPE char -#endif - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_ERROR_STRING - -//! Macro for converting string literial to \ref CEREAL_RAPIDJSON_ERROR_CHARTYPE[]. -/*! \ingroup CEREAL_RAPIDJSON_ERRORS - By default this conversion macro does nothing. - On Windows, user can define this macro as \c _T(x) for supporting both - unicode/non-unicode settings. -*/ -#ifndef CEREAL_RAPIDJSON_ERROR_STRING -#define CEREAL_RAPIDJSON_ERROR_STRING(x) x -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -/////////////////////////////////////////////////////////////////////////////// -// ParseErrorCode - -//! Error code of parsing. -/*! \ingroup CEREAL_RAPIDJSON_ERRORS - \see GenericReader::Parse, GenericReader::GetParseErrorCode -*/ -enum ParseErrorCode { - kParseErrorNone = 0, //!< No error. - - kParseErrorDocumentEmpty, //!< The document is empty. - kParseErrorDocumentRootNotSingular, //!< The document root must not follow by other values. - - kParseErrorValueInvalid, //!< Invalid value. - - kParseErrorObjectMissName, //!< Missing a name for object member. - kParseErrorObjectMissColon, //!< Missing a colon after a name of object member. - kParseErrorObjectMissCommaOrCurlyBracket, //!< Missing a comma or '}' after an object member. - - kParseErrorArrayMissCommaOrSquareBracket, //!< Missing a comma or ']' after an array element. - - kParseErrorStringUnicodeEscapeInvalidHex, //!< Incorrect hex digit after \\u escape in string. - kParseErrorStringUnicodeSurrogateInvalid, //!< The surrogate pair in string is invalid. - kParseErrorStringEscapeInvalid, //!< Invalid escape character in string. - kParseErrorStringMissQuotationMark, //!< Missing a closing quotation mark in string. - kParseErrorStringInvalidEncoding, //!< Invalid encoding in string. - - kParseErrorNumberTooBig, //!< Number too big to be stored in double. - kParseErrorNumberMissFraction, //!< Miss fraction part in number. - kParseErrorNumberMissExponent, //!< Miss exponent in number. - - kParseErrorTermination, //!< Parsing was terminated. - kParseErrorUnspecificSyntaxError //!< Unspecific syntax error. -}; - -//! Result of parsing (wraps ParseErrorCode) -/*! - \ingroup CEREAL_RAPIDJSON_ERRORS - \code - Document doc; - ParseResult ok = doc.Parse("[42]"); - if (!ok) { - fprintf(stderr, "JSON parse error: %s (%u)", - GetParseError_En(ok.Code()), ok.Offset()); - exit(EXIT_FAILURE); - } - \endcode - \see GenericReader::Parse, GenericDocument::Parse -*/ -struct ParseResult { - //!! Unspecified boolean type - typedef bool (ParseResult::*BooleanType)() const; -public: - //! Default constructor, no error. - ParseResult() : code_(kParseErrorNone), offset_(0) {} - //! Constructor to set an error. - ParseResult(ParseErrorCode code, size_t offset) : code_(code), offset_(offset) {} - - //! Get the error code. - ParseErrorCode Code() const { return code_; } - //! Get the error offset, if \ref IsError(), 0 otherwise. - size_t Offset() const { return offset_; } - - //! Explicit conversion to \c bool, returns \c true, iff !\ref IsError(). - operator BooleanType() const { return !IsError() ? &ParseResult::IsError : NULL; } - //! Whether the result is an error. - bool IsError() const { return code_ != kParseErrorNone; } - - bool operator==(const ParseResult& that) const { return code_ == that.code_; } - bool operator==(ParseErrorCode code) const { return code_ == code; } - friend bool operator==(ParseErrorCode code, const ParseResult & err) { return code == err.code_; } - - bool operator!=(const ParseResult& that) const { return !(*this == that); } - bool operator!=(ParseErrorCode code) const { return !(*this == code); } - friend bool operator!=(ParseErrorCode code, const ParseResult & err) { return err != code; } - - //! Reset error code. - void Clear() { Set(kParseErrorNone); } - //! Update error code and offset. - void Set(ParseErrorCode code, size_t offset = 0) { code_ = code; offset_ = offset; } - -private: - ParseErrorCode code_; - size_t offset_; -}; - -//! Function pointer type of GetParseError(). -/*! \ingroup CEREAL_RAPIDJSON_ERRORS - - This is the prototype for \c GetParseError_X(), where \c X is a locale. - User can dynamically change locale in runtime, e.g.: -\code - GetParseErrorFunc GetParseError = GetParseError_En; // or whatever - const CEREAL_RAPIDJSON_ERROR_CHARTYPE* s = GetParseError(document.GetParseErrorCode()); -\endcode -*/ -typedef const CEREAL_RAPIDJSON_ERROR_CHARTYPE* (*GetParseErrorFunc)(ParseErrorCode); - -CEREAL_RAPIDJSON_NAMESPACE_END - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#endif // CEREAL_RAPIDJSON_ERROR_ERROR_H_ diff --git a/include/cereal/external/rapidjson/filereadstream.h b/include/cereal/external/rapidjson/filereadstream.h deleted file mode 100644 index 253a7f9..0000000 --- a/include/cereal/external/rapidjson/filereadstream.h +++ /dev/null @@ -1,99 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_FILEREADSTREAM_H_ -#define CEREAL_RAPIDJSON_FILEREADSTREAM_H_ - -#include "stream.h" -#include - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(padded) -CEREAL_RAPIDJSON_DIAG_OFF(unreachable-code) -CEREAL_RAPIDJSON_DIAG_OFF(missing-noreturn) -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -//! File byte stream for input using fread(). -/*! - \note implements Stream concept -*/ -class FileReadStream { -public: - typedef char Ch; //!< Character type (byte). - - //! Constructor. - /*! - \param fp File pointer opened for read. - \param buffer user-supplied buffer. - \param bufferSize size of buffer in bytes. Must >=4 bytes. - */ - FileReadStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferSize_(bufferSize), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) { - CEREAL_RAPIDJSON_ASSERT(fp_ != 0); - CEREAL_RAPIDJSON_ASSERT(bufferSize >= 4); - Read(); - } - - Ch Peek() const { return *current_; } - Ch Take() { Ch c = *current_; Read(); return c; } - size_t Tell() const { return count_ + static_cast(current_ - buffer_); } - - // Not implemented - void Put(Ch) { CEREAL_RAPIDJSON_ASSERT(false); } - void Flush() { CEREAL_RAPIDJSON_ASSERT(false); } - Ch* PutBegin() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - size_t PutEnd(Ch*) { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - - // For encoding detection only. - const Ch* Peek4() const { - return (current_ + 4 - !eof_ <= bufferLast_) ? current_ : 0; - } - -private: - void Read() { - if (current_ < bufferLast_) - ++current_; - else if (!eof_) { - count_ += readCount_; - readCount_ = std::fread(buffer_, 1, bufferSize_, fp_); - bufferLast_ = buffer_ + readCount_ - 1; - current_ = buffer_; - - if (readCount_ < bufferSize_) { - buffer_[readCount_] = '\0'; - ++bufferLast_; - eof_ = true; - } - } - } - - std::FILE* fp_; - Ch *buffer_; - size_t bufferSize_; - Ch *bufferLast_; - Ch *current_; - size_t readCount_; - size_t count_; //!< Number of characters read - bool eof_; -}; - -CEREAL_RAPIDJSON_NAMESPACE_END - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#endif // CEREAL_RAPIDJSON_FILESTREAM_H_ diff --git a/include/cereal/external/rapidjson/filewritestream.h b/include/cereal/external/rapidjson/filewritestream.h deleted file mode 100644 index 44ae127..0000000 --- a/include/cereal/external/rapidjson/filewritestream.h +++ /dev/null @@ -1,104 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_FILEWRITESTREAM_H_ -#define CEREAL_RAPIDJSON_FILEWRITESTREAM_H_ - -#include "stream.h" -#include - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(unreachable-code) -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -//! Wrapper of C file stream for output using fwrite(). -/*! - \note implements Stream concept -*/ -class FileWriteStream { -public: - typedef char Ch; //!< Character type. Only support char. - - FileWriteStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferEnd_(buffer + bufferSize), current_(buffer_) { - CEREAL_RAPIDJSON_ASSERT(fp_ != 0); - } - - void Put(char c) { - if (current_ >= bufferEnd_) - Flush(); - - *current_++ = c; - } - - void PutN(char c, size_t n) { - size_t avail = static_cast(bufferEnd_ - current_); - while (n > avail) { - std::memset(current_, c, avail); - current_ += avail; - Flush(); - n -= avail; - avail = static_cast(bufferEnd_ - current_); - } - - if (n > 0) { - std::memset(current_, c, n); - current_ += n; - } - } - - void Flush() { - if (current_ != buffer_) { - size_t result = std::fwrite(buffer_, 1, static_cast(current_ - buffer_), fp_); - if (result < static_cast(current_ - buffer_)) { - // failure deliberately ignored at this time - // added to avoid warn_unused_result build errors - } - current_ = buffer_; - } - } - - // Not implemented - char Peek() const { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - char Take() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - size_t Tell() const { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - char* PutBegin() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - size_t PutEnd(char*) { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - -private: - // Prohibit copy constructor & assignment operator. - FileWriteStream(const FileWriteStream&); - FileWriteStream& operator=(const FileWriteStream&); - - std::FILE* fp_; - char *buffer_; - char *bufferEnd_; - char *current_; -}; - -//! Implement specialized version of PutN() with memset() for better performance. -template<> -inline void PutN(FileWriteStream& stream, char c, size_t n) { - stream.PutN(c, n); -} - -CEREAL_RAPIDJSON_NAMESPACE_END - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#endif // CEREAL_RAPIDJSON_FILESTREAM_H_ diff --git a/include/cereal/external/rapidjson/fwd.h b/include/cereal/external/rapidjson/fwd.h deleted file mode 100644 index 1b15c66..0000000 --- a/include/cereal/external/rapidjson/fwd.h +++ /dev/null @@ -1,151 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_FWD_H_ -#define CEREAL_RAPIDJSON_FWD_H_ - -#include "rapidjson.h" - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -// encodings.h - -template struct UTF8; -template struct UTF16; -template struct UTF16BE; -template struct UTF16LE; -template struct UTF32; -template struct UTF32BE; -template struct UTF32LE; -template struct ASCII; -template struct AutoUTF; - -template -struct Transcoder; - -// allocators.h - -class CrtAllocator; - -template -class MemoryPoolAllocator; - -// stream.h - -template -struct GenericStringStream; - -typedef GenericStringStream > StringStream; - -template -struct GenericInsituStringStream; - -typedef GenericInsituStringStream > InsituStringStream; - -// stringbuffer.h - -template -class GenericStringBuffer; - -typedef GenericStringBuffer, CrtAllocator> StringBuffer; - -// filereadstream.h - -class FileReadStream; - -// filewritestream.h - -class FileWriteStream; - -// memorybuffer.h - -template -struct GenericMemoryBuffer; - -typedef GenericMemoryBuffer MemoryBuffer; - -// memorystream.h - -struct MemoryStream; - -// reader.h - -template -struct BaseReaderHandler; - -template -class GenericReader; - -typedef GenericReader, UTF8, CrtAllocator> Reader; - -// writer.h - -template -class Writer; - -// prettywriter.h - -template -class PrettyWriter; - -// document.h - -template -struct GenericMember; - -template -class GenericMemberIterator; - -template -struct GenericStringRef; - -template -class GenericValue; - -typedef GenericValue, MemoryPoolAllocator > Value; - -template -class GenericDocument; - -typedef GenericDocument, MemoryPoolAllocator, CrtAllocator> Document; - -// pointer.h - -template -class GenericPointer; - -typedef GenericPointer Pointer; - -// schema.h - -template -class IGenericRemoteSchemaDocumentProvider; - -template -class GenericSchemaDocument; - -typedef GenericSchemaDocument SchemaDocument; -typedef IGenericRemoteSchemaDocumentProvider IRemoteSchemaDocumentProvider; - -template < - typename SchemaDocumentType, - typename OutputHandler, - typename StateAllocator> -class GenericSchemaValidator; - -typedef GenericSchemaValidator, void>, CrtAllocator> SchemaValidator; - -CEREAL_RAPIDJSON_NAMESPACE_END - -#endif // CEREAL_RAPIDJSON_RAPIDJSONFWD_H_ diff --git a/include/cereal/external/rapidjson/internal/biginteger.h b/include/cereal/external/rapidjson/internal/biginteger.h deleted file mode 100644 index 77a6519..0000000 --- a/include/cereal/external/rapidjson/internal/biginteger.h +++ /dev/null @@ -1,290 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_BIGINTEGER_H_ -#define CEREAL_RAPIDJSON_BIGINTEGER_H_ - -#include "../rapidjson.h" - -#if defined(_MSC_VER) && !__INTEL_COMPILER && defined(_M_AMD64) -#include // for _umul128 -#pragma intrinsic(_umul128) -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN -namespace internal { - -class BigInteger { -public: - typedef uint64_t Type; - - BigInteger(const BigInteger& rhs) : count_(rhs.count_) { - std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type)); - } - - explicit BigInteger(uint64_t u) : count_(1) { - digits_[0] = u; - } - - BigInteger(const char* decimals, size_t length) : count_(1) { - CEREAL_RAPIDJSON_ASSERT(length > 0); - digits_[0] = 0; - size_t i = 0; - const size_t kMaxDigitPerIteration = 19; // 2^64 = 18446744073709551616 > 10^19 - while (length >= kMaxDigitPerIteration) { - AppendDecimal64(decimals + i, decimals + i + kMaxDigitPerIteration); - length -= kMaxDigitPerIteration; - i += kMaxDigitPerIteration; - } - - if (length > 0) - AppendDecimal64(decimals + i, decimals + i + length); - } - - BigInteger& operator=(const BigInteger &rhs) - { - if (this != &rhs) { - count_ = rhs.count_; - std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type)); - } - return *this; - } - - BigInteger& operator=(uint64_t u) { - digits_[0] = u; - count_ = 1; - return *this; - } - - BigInteger& operator+=(uint64_t u) { - Type backup = digits_[0]; - digits_[0] += u; - for (size_t i = 0; i < count_ - 1; i++) { - if (digits_[i] >= backup) - return *this; // no carry - backup = digits_[i + 1]; - digits_[i + 1] += 1; - } - - // Last carry - if (digits_[count_ - 1] < backup) - PushBack(1); - - return *this; - } - - BigInteger& operator*=(uint64_t u) { - if (u == 0) return *this = 0; - if (u == 1) return *this; - if (*this == 1) return *this = u; - - uint64_t k = 0; - for (size_t i = 0; i < count_; i++) { - uint64_t hi; - digits_[i] = MulAdd64(digits_[i], u, k, &hi); - k = hi; - } - - if (k > 0) - PushBack(k); - - return *this; - } - - BigInteger& operator*=(uint32_t u) { - if (u == 0) return *this = 0; - if (u == 1) return *this; - if (*this == 1) return *this = u; - - uint64_t k = 0; - for (size_t i = 0; i < count_; i++) { - const uint64_t c = digits_[i] >> 32; - const uint64_t d = digits_[i] & 0xFFFFFFFF; - const uint64_t uc = u * c; - const uint64_t ud = u * d; - const uint64_t p0 = ud + k; - const uint64_t p1 = uc + (p0 >> 32); - digits_[i] = (p0 & 0xFFFFFFFF) | (p1 << 32); - k = p1 >> 32; - } - - if (k > 0) - PushBack(k); - - return *this; - } - - BigInteger& operator<<=(size_t shift) { - if (IsZero() || shift == 0) return *this; - - size_t offset = shift / kTypeBit; - size_t interShift = shift % kTypeBit; - CEREAL_RAPIDJSON_ASSERT(count_ + offset <= kCapacity); - - if (interShift == 0) { - std::memmove(digits_ + offset, digits_, count_ * sizeof(Type)); - count_ += offset; - } - else { - digits_[count_] = 0; - for (size_t i = count_; i > 0; i--) - digits_[i + offset] = (digits_[i] << interShift) | (digits_[i - 1] >> (kTypeBit - interShift)); - digits_[offset] = digits_[0] << interShift; - count_ += offset; - if (digits_[count_]) - count_++; - } - - std::memset(digits_, 0, offset * sizeof(Type)); - - return *this; - } - - bool operator==(const BigInteger& rhs) const { - return count_ == rhs.count_ && std::memcmp(digits_, rhs.digits_, count_ * sizeof(Type)) == 0; - } - - bool operator==(const Type rhs) const { - return count_ == 1 && digits_[0] == rhs; - } - - BigInteger& MultiplyPow5(unsigned exp) { - static const uint32_t kPow5[12] = { - 5, - 5 * 5, - 5 * 5 * 5, - 5 * 5 * 5 * 5, - 5 * 5 * 5 * 5 * 5, - 5 * 5 * 5 * 5 * 5 * 5, - 5 * 5 * 5 * 5 * 5 * 5 * 5, - 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, - 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, - 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, - 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, - 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 - }; - if (exp == 0) return *this; - for (; exp >= 27; exp -= 27) *this *= CEREAL_RAPIDJSON_UINT64_C2(0X6765C793, 0XFA10079D); // 5^27 - for (; exp >= 13; exp -= 13) *this *= static_cast(1220703125u); // 5^13 - if (exp > 0) *this *= kPow5[exp - 1]; - return *this; - } - - // Compute absolute difference of this and rhs. - // Assume this != rhs - bool Difference(const BigInteger& rhs, BigInteger* out) const { - int cmp = Compare(rhs); - CEREAL_RAPIDJSON_ASSERT(cmp != 0); - const BigInteger *a, *b; // Makes a > b - bool ret; - if (cmp < 0) { a = &rhs; b = this; ret = true; } - else { a = this; b = &rhs; ret = false; } - - Type borrow = 0; - for (size_t i = 0; i < a->count_; i++) { - Type d = a->digits_[i] - borrow; - if (i < b->count_) - d -= b->digits_[i]; - borrow = (d > a->digits_[i]) ? 1 : 0; - out->digits_[i] = d; - if (d != 0) - out->count_ = i + 1; - } - - return ret; - } - - int Compare(const BigInteger& rhs) const { - if (count_ != rhs.count_) - return count_ < rhs.count_ ? -1 : 1; - - for (size_t i = count_; i-- > 0;) - if (digits_[i] != rhs.digits_[i]) - return digits_[i] < rhs.digits_[i] ? -1 : 1; - - return 0; - } - - size_t GetCount() const { return count_; } - Type GetDigit(size_t index) const { CEREAL_RAPIDJSON_ASSERT(index < count_); return digits_[index]; } - bool IsZero() const { return count_ == 1 && digits_[0] == 0; } - -private: - void AppendDecimal64(const char* begin, const char* end) { - uint64_t u = ParseUint64(begin, end); - if (IsZero()) - *this = u; - else { - unsigned exp = static_cast(end - begin); - (MultiplyPow5(exp) <<= exp) += u; // *this = *this * 10^exp + u - } - } - - void PushBack(Type digit) { - CEREAL_RAPIDJSON_ASSERT(count_ < kCapacity); - digits_[count_++] = digit; - } - - static uint64_t ParseUint64(const char* begin, const char* end) { - uint64_t r = 0; - for (const char* p = begin; p != end; ++p) { - CEREAL_RAPIDJSON_ASSERT(*p >= '0' && *p <= '9'); - r = r * 10u + static_cast(*p - '0'); - } - return r; - } - - // Assume a * b + k < 2^128 - static uint64_t MulAdd64(uint64_t a, uint64_t b, uint64_t k, uint64_t* outHigh) { -#if defined(_MSC_VER) && defined(_M_AMD64) - uint64_t low = _umul128(a, b, outHigh) + k; - if (low < k) - (*outHigh)++; - return low; -#elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && defined(__x86_64__) - __extension__ typedef unsigned __int128 uint128; - uint128 p = static_cast(a) * static_cast(b); - p += k; - *outHigh = static_cast(p >> 64); - return static_cast(p); -#else - const uint64_t a0 = a & 0xFFFFFFFF, a1 = a >> 32, b0 = b & 0xFFFFFFFF, b1 = b >> 32; - uint64_t x0 = a0 * b0, x1 = a0 * b1, x2 = a1 * b0, x3 = a1 * b1; - x1 += (x0 >> 32); // can't give carry - x1 += x2; - if (x1 < x2) - x3 += (static_cast(1) << 32); - uint64_t lo = (x1 << 32) + (x0 & 0xFFFFFFFF); - uint64_t hi = x3 + (x1 >> 32); - - lo += k; - if (lo < k) - hi++; - *outHigh = hi; - return lo; -#endif - } - - static const size_t kBitCount = 3328; // 64bit * 54 > 10^1000 - static const size_t kCapacity = kBitCount / sizeof(Type); - static const size_t kTypeBit = sizeof(Type) * 8; - - Type digits_[kCapacity]; - size_t count_; -}; - -} // namespace internal -CEREAL_RAPIDJSON_NAMESPACE_END - -#endif // CEREAL_RAPIDJSON_BIGINTEGER_H_ diff --git a/include/cereal/external/rapidjson/internal/diyfp.h b/include/cereal/external/rapidjson/internal/diyfp.h deleted file mode 100644 index 3f92a07..0000000 --- a/include/cereal/external/rapidjson/internal/diyfp.h +++ /dev/null @@ -1,271 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -// This is a C++ header-only implementation of Grisu2 algorithm from the publication: -// Loitsch, Florian. "Printing floating-point numbers quickly and accurately with -// integers." ACM Sigplan Notices 45.6 (2010): 233-243. - -#ifndef CEREAL_RAPIDJSON_DIYFP_H_ -#define CEREAL_RAPIDJSON_DIYFP_H_ - -#include "../rapidjson.h" -#include - -#if defined(_MSC_VER) && defined(_M_AMD64) && !defined(__INTEL_COMPILER) -#include -#pragma intrinsic(_BitScanReverse64) -#pragma intrinsic(_umul128) -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN -namespace internal { - -#ifdef __GNUC__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(effc++) -#endif - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(padded) -#endif - -struct DiyFp { - DiyFp() : f(), e() {} - - DiyFp(uint64_t fp, int exp) : f(fp), e(exp) {} - - explicit DiyFp(double d) { - union { - double d; - uint64_t u64; - } u = { d }; - - int biased_e = static_cast((u.u64 & kDpExponentMask) >> kDpSignificandSize); - uint64_t significand = (u.u64 & kDpSignificandMask); - if (biased_e != 0) { - f = significand + kDpHiddenBit; - e = biased_e - kDpExponentBias; - } - else { - f = significand; - e = kDpMinExponent + 1; - } - } - - DiyFp operator-(const DiyFp& rhs) const { - return DiyFp(f - rhs.f, e); - } - - DiyFp operator*(const DiyFp& rhs) const { -#if defined(_MSC_VER) && defined(_M_AMD64) - uint64_t h; - uint64_t l = _umul128(f, rhs.f, &h); - if (l & (uint64_t(1) << 63)) // rounding - h++; - return DiyFp(h, e + rhs.e + 64); -#elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && defined(__x86_64__) - __extension__ typedef unsigned __int128 uint128; - uint128 p = static_cast(f) * static_cast(rhs.f); - uint64_t h = static_cast(p >> 64); - uint64_t l = static_cast(p); - if (l & (uint64_t(1) << 63)) // rounding - h++; - return DiyFp(h, e + rhs.e + 64); -#else - const uint64_t M32 = 0xFFFFFFFF; - const uint64_t a = f >> 32; - const uint64_t b = f & M32; - const uint64_t c = rhs.f >> 32; - const uint64_t d = rhs.f & M32; - const uint64_t ac = a * c; - const uint64_t bc = b * c; - const uint64_t ad = a * d; - const uint64_t bd = b * d; - uint64_t tmp = (bd >> 32) + (ad & M32) + (bc & M32); - tmp += 1U << 31; /// mult_round - return DiyFp(ac + (ad >> 32) + (bc >> 32) + (tmp >> 32), e + rhs.e + 64); -#endif - } - - DiyFp Normalize() const { - CEREAL_RAPIDJSON_ASSERT(f != 0); // https://stackoverflow.com/a/26809183/291737 -#if defined(_MSC_VER) && defined(_M_AMD64) - unsigned long index; - _BitScanReverse64(&index, f); - return DiyFp(f << (63 - index), e - (63 - index)); -#elif defined(__GNUC__) && __GNUC__ >= 4 - int s = __builtin_clzll(f); - return DiyFp(f << s, e - s); -#else - DiyFp res = *this; - while (!(res.f & (static_cast(1) << 63))) { - res.f <<= 1; - res.e--; - } - return res; -#endif - } - - DiyFp NormalizeBoundary() const { - DiyFp res = *this; - while (!(res.f & (kDpHiddenBit << 1))) { - res.f <<= 1; - res.e--; - } - res.f <<= (kDiySignificandSize - kDpSignificandSize - 2); - res.e = res.e - (kDiySignificandSize - kDpSignificandSize - 2); - return res; - } - - void NormalizedBoundaries(DiyFp* minus, DiyFp* plus) const { - DiyFp pl = DiyFp((f << 1) + 1, e - 1).NormalizeBoundary(); - DiyFp mi = (f == kDpHiddenBit) ? DiyFp((f << 2) - 1, e - 2) : DiyFp((f << 1) - 1, e - 1); - mi.f <<= mi.e - pl.e; - mi.e = pl.e; - *plus = pl; - *minus = mi; - } - - double ToDouble() const { - union { - double d; - uint64_t u64; - }u; - CEREAL_RAPIDJSON_ASSERT(f <= kDpHiddenBit + kDpSignificandMask); - if (e < kDpDenormalExponent) { - // Underflow. - return 0.0; - } - if (e >= kDpMaxExponent) { - // Overflow. - return std::numeric_limits::infinity(); - } - const uint64_t be = (e == kDpDenormalExponent && (f & kDpHiddenBit) == 0) ? 0 : - static_cast(e + kDpExponentBias); - u.u64 = (f & kDpSignificandMask) | (be << kDpSignificandSize); - return u.d; - } - - static const int kDiySignificandSize = 64; - static const int kDpSignificandSize = 52; - static const int kDpExponentBias = 0x3FF + kDpSignificandSize; - static const int kDpMaxExponent = 0x7FF - kDpExponentBias; - static const int kDpMinExponent = -kDpExponentBias; - static const int kDpDenormalExponent = -kDpExponentBias + 1; - static const uint64_t kDpExponentMask = CEREAL_RAPIDJSON_UINT64_C2(0x7FF00000, 0x00000000); - static const uint64_t kDpSignificandMask = CEREAL_RAPIDJSON_UINT64_C2(0x000FFFFF, 0xFFFFFFFF); - static const uint64_t kDpHiddenBit = CEREAL_RAPIDJSON_UINT64_C2(0x00100000, 0x00000000); - - uint64_t f; - int e; -}; - -inline DiyFp GetCachedPowerByIndex(size_t index) { - // 10^-348, 10^-340, ..., 10^340 - static const uint64_t kCachedPowers_F[] = { - CEREAL_RAPIDJSON_UINT64_C2(0xfa8fd5a0, 0x081c0288), CEREAL_RAPIDJSON_UINT64_C2(0xbaaee17f, 0xa23ebf76), - CEREAL_RAPIDJSON_UINT64_C2(0x8b16fb20, 0x3055ac76), CEREAL_RAPIDJSON_UINT64_C2(0xcf42894a, 0x5dce35ea), - CEREAL_RAPIDJSON_UINT64_C2(0x9a6bb0aa, 0x55653b2d), CEREAL_RAPIDJSON_UINT64_C2(0xe61acf03, 0x3d1a45df), - CEREAL_RAPIDJSON_UINT64_C2(0xab70fe17, 0xc79ac6ca), CEREAL_RAPIDJSON_UINT64_C2(0xff77b1fc, 0xbebcdc4f), - CEREAL_RAPIDJSON_UINT64_C2(0xbe5691ef, 0x416bd60c), CEREAL_RAPIDJSON_UINT64_C2(0x8dd01fad, 0x907ffc3c), - CEREAL_RAPIDJSON_UINT64_C2(0xd3515c28, 0x31559a83), CEREAL_RAPIDJSON_UINT64_C2(0x9d71ac8f, 0xada6c9b5), - CEREAL_RAPIDJSON_UINT64_C2(0xea9c2277, 0x23ee8bcb), CEREAL_RAPIDJSON_UINT64_C2(0xaecc4991, 0x4078536d), - CEREAL_RAPIDJSON_UINT64_C2(0x823c1279, 0x5db6ce57), CEREAL_RAPIDJSON_UINT64_C2(0xc2109436, 0x4dfb5637), - CEREAL_RAPIDJSON_UINT64_C2(0x9096ea6f, 0x3848984f), CEREAL_RAPIDJSON_UINT64_C2(0xd77485cb, 0x25823ac7), - CEREAL_RAPIDJSON_UINT64_C2(0xa086cfcd, 0x97bf97f4), CEREAL_RAPIDJSON_UINT64_C2(0xef340a98, 0x172aace5), - CEREAL_RAPIDJSON_UINT64_C2(0xb23867fb, 0x2a35b28e), CEREAL_RAPIDJSON_UINT64_C2(0x84c8d4df, 0xd2c63f3b), - CEREAL_RAPIDJSON_UINT64_C2(0xc5dd4427, 0x1ad3cdba), CEREAL_RAPIDJSON_UINT64_C2(0x936b9fce, 0xbb25c996), - CEREAL_RAPIDJSON_UINT64_C2(0xdbac6c24, 0x7d62a584), CEREAL_RAPIDJSON_UINT64_C2(0xa3ab6658, 0x0d5fdaf6), - CEREAL_RAPIDJSON_UINT64_C2(0xf3e2f893, 0xdec3f126), CEREAL_RAPIDJSON_UINT64_C2(0xb5b5ada8, 0xaaff80b8), - CEREAL_RAPIDJSON_UINT64_C2(0x87625f05, 0x6c7c4a8b), CEREAL_RAPIDJSON_UINT64_C2(0xc9bcff60, 0x34c13053), - CEREAL_RAPIDJSON_UINT64_C2(0x964e858c, 0x91ba2655), CEREAL_RAPIDJSON_UINT64_C2(0xdff97724, 0x70297ebd), - CEREAL_RAPIDJSON_UINT64_C2(0xa6dfbd9f, 0xb8e5b88f), CEREAL_RAPIDJSON_UINT64_C2(0xf8a95fcf, 0x88747d94), - CEREAL_RAPIDJSON_UINT64_C2(0xb9447093, 0x8fa89bcf), CEREAL_RAPIDJSON_UINT64_C2(0x8a08f0f8, 0xbf0f156b), - CEREAL_RAPIDJSON_UINT64_C2(0xcdb02555, 0x653131b6), CEREAL_RAPIDJSON_UINT64_C2(0x993fe2c6, 0xd07b7fac), - CEREAL_RAPIDJSON_UINT64_C2(0xe45c10c4, 0x2a2b3b06), CEREAL_RAPIDJSON_UINT64_C2(0xaa242499, 0x697392d3), - CEREAL_RAPIDJSON_UINT64_C2(0xfd87b5f2, 0x8300ca0e), CEREAL_RAPIDJSON_UINT64_C2(0xbce50864, 0x92111aeb), - CEREAL_RAPIDJSON_UINT64_C2(0x8cbccc09, 0x6f5088cc), CEREAL_RAPIDJSON_UINT64_C2(0xd1b71758, 0xe219652c), - CEREAL_RAPIDJSON_UINT64_C2(0x9c400000, 0x00000000), CEREAL_RAPIDJSON_UINT64_C2(0xe8d4a510, 0x00000000), - CEREAL_RAPIDJSON_UINT64_C2(0xad78ebc5, 0xac620000), CEREAL_RAPIDJSON_UINT64_C2(0x813f3978, 0xf8940984), - CEREAL_RAPIDJSON_UINT64_C2(0xc097ce7b, 0xc90715b3), CEREAL_RAPIDJSON_UINT64_C2(0x8f7e32ce, 0x7bea5c70), - CEREAL_RAPIDJSON_UINT64_C2(0xd5d238a4, 0xabe98068), CEREAL_RAPIDJSON_UINT64_C2(0x9f4f2726, 0x179a2245), - CEREAL_RAPIDJSON_UINT64_C2(0xed63a231, 0xd4c4fb27), CEREAL_RAPIDJSON_UINT64_C2(0xb0de6538, 0x8cc8ada8), - CEREAL_RAPIDJSON_UINT64_C2(0x83c7088e, 0x1aab65db), CEREAL_RAPIDJSON_UINT64_C2(0xc45d1df9, 0x42711d9a), - CEREAL_RAPIDJSON_UINT64_C2(0x924d692c, 0xa61be758), CEREAL_RAPIDJSON_UINT64_C2(0xda01ee64, 0x1a708dea), - CEREAL_RAPIDJSON_UINT64_C2(0xa26da399, 0x9aef774a), CEREAL_RAPIDJSON_UINT64_C2(0xf209787b, 0xb47d6b85), - CEREAL_RAPIDJSON_UINT64_C2(0xb454e4a1, 0x79dd1877), CEREAL_RAPIDJSON_UINT64_C2(0x865b8692, 0x5b9bc5c2), - CEREAL_RAPIDJSON_UINT64_C2(0xc83553c5, 0xc8965d3d), CEREAL_RAPIDJSON_UINT64_C2(0x952ab45c, 0xfa97a0b3), - CEREAL_RAPIDJSON_UINT64_C2(0xde469fbd, 0x99a05fe3), CEREAL_RAPIDJSON_UINT64_C2(0xa59bc234, 0xdb398c25), - CEREAL_RAPIDJSON_UINT64_C2(0xf6c69a72, 0xa3989f5c), CEREAL_RAPIDJSON_UINT64_C2(0xb7dcbf53, 0x54e9bece), - CEREAL_RAPIDJSON_UINT64_C2(0x88fcf317, 0xf22241e2), CEREAL_RAPIDJSON_UINT64_C2(0xcc20ce9b, 0xd35c78a5), - CEREAL_RAPIDJSON_UINT64_C2(0x98165af3, 0x7b2153df), CEREAL_RAPIDJSON_UINT64_C2(0xe2a0b5dc, 0x971f303a), - CEREAL_RAPIDJSON_UINT64_C2(0xa8d9d153, 0x5ce3b396), CEREAL_RAPIDJSON_UINT64_C2(0xfb9b7cd9, 0xa4a7443c), - CEREAL_RAPIDJSON_UINT64_C2(0xbb764c4c, 0xa7a44410), CEREAL_RAPIDJSON_UINT64_C2(0x8bab8eef, 0xb6409c1a), - CEREAL_RAPIDJSON_UINT64_C2(0xd01fef10, 0xa657842c), CEREAL_RAPIDJSON_UINT64_C2(0x9b10a4e5, 0xe9913129), - CEREAL_RAPIDJSON_UINT64_C2(0xe7109bfb, 0xa19c0c9d), CEREAL_RAPIDJSON_UINT64_C2(0xac2820d9, 0x623bf429), - CEREAL_RAPIDJSON_UINT64_C2(0x80444b5e, 0x7aa7cf85), CEREAL_RAPIDJSON_UINT64_C2(0xbf21e440, 0x03acdd2d), - CEREAL_RAPIDJSON_UINT64_C2(0x8e679c2f, 0x5e44ff8f), CEREAL_RAPIDJSON_UINT64_C2(0xd433179d, 0x9c8cb841), - CEREAL_RAPIDJSON_UINT64_C2(0x9e19db92, 0xb4e31ba9), CEREAL_RAPIDJSON_UINT64_C2(0xeb96bf6e, 0xbadf77d9), - CEREAL_RAPIDJSON_UINT64_C2(0xaf87023b, 0x9bf0ee6b) - }; - static const int16_t kCachedPowers_E[] = { - -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, - -954, -927, -901, -874, -847, -821, -794, -768, -741, -715, - -688, -661, -635, -608, -582, -555, -529, -502, -475, -449, - -422, -396, -369, -343, -316, -289, -263, -236, -210, -183, - -157, -130, -103, -77, -50, -24, 3, 30, 56, 83, - 109, 136, 162, 189, 216, 242, 269, 295, 322, 348, - 375, 402, 428, 455, 481, 508, 534, 561, 588, 614, - 641, 667, 694, 720, 747, 774, 800, 827, 853, 880, - 907, 933, 960, 986, 1013, 1039, 1066 - }; - CEREAL_RAPIDJSON_ASSERT(index < 87); - return DiyFp(kCachedPowers_F[index], kCachedPowers_E[index]); -} - -inline DiyFp GetCachedPower(int e, int* K) { - - //int k = static_cast(ceil((-61 - e) * 0.30102999566398114)) + 374; - double dk = (-61 - e) * 0.30102999566398114 + 347; // dk must be positive, so can do ceiling in positive - int k = static_cast(dk); - if (dk - k > 0.0) - k++; - - unsigned index = static_cast((k >> 3) + 1); - *K = -(-348 + static_cast(index << 3)); // decimal exponent no need lookup table - - return GetCachedPowerByIndex(index); -} - -inline DiyFp GetCachedPower10(int exp, int *outExp) { - CEREAL_RAPIDJSON_ASSERT(exp >= -348); - unsigned index = static_cast(exp + 348) / 8u; - *outExp = -348 + static_cast(index) * 8; - return GetCachedPowerByIndex(index); -} - -#ifdef __GNUC__ -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_POP -CEREAL_RAPIDJSON_DIAG_OFF(padded) -#endif - -} // namespace internal -CEREAL_RAPIDJSON_NAMESPACE_END - -#endif // CEREAL_RAPIDJSON_DIYFP_H_ diff --git a/include/cereal/external/rapidjson/internal/dtoa.h b/include/cereal/external/rapidjson/internal/dtoa.h deleted file mode 100644 index ea62b34..0000000 --- a/include/cereal/external/rapidjson/internal/dtoa.h +++ /dev/null @@ -1,245 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -// This is a C++ header-only implementation of Grisu2 algorithm from the publication: -// Loitsch, Florian. "Printing floating-point numbers quickly and accurately with -// integers." ACM Sigplan Notices 45.6 (2010): 233-243. - -#ifndef CEREAL_RAPIDJSON_DTOA_ -#define CEREAL_RAPIDJSON_DTOA_ - -#include "itoa.h" // GetDigitsLut() -#include "diyfp.h" -#include "ieee754.h" - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN -namespace internal { - -#ifdef __GNUC__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(effc++) -CEREAL_RAPIDJSON_DIAG_OFF(array-bounds) // some gcc versions generate wrong warnings https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59124 -#endif - -inline void GrisuRound(char* buffer, int len, uint64_t delta, uint64_t rest, uint64_t ten_kappa, uint64_t wp_w) { - while (rest < wp_w && delta - rest >= ten_kappa && - (rest + ten_kappa < wp_w || /// closer - wp_w - rest > rest + ten_kappa - wp_w)) { - buffer[len - 1]--; - rest += ten_kappa; - } -} - -inline int CountDecimalDigit32(uint32_t n) { - // Simple pure C++ implementation was faster than __builtin_clz version in this situation. - if (n < 10) return 1; - if (n < 100) return 2; - if (n < 1000) return 3; - if (n < 10000) return 4; - if (n < 100000) return 5; - if (n < 1000000) return 6; - if (n < 10000000) return 7; - if (n < 100000000) return 8; - // Will not reach 10 digits in DigitGen() - //if (n < 1000000000) return 9; - //return 10; - return 9; -} - -inline void DigitGen(const DiyFp& W, const DiyFp& Mp, uint64_t delta, char* buffer, int* len, int* K) { - static const uint32_t kPow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; - const DiyFp one(uint64_t(1) << -Mp.e, Mp.e); - const DiyFp wp_w = Mp - W; - uint32_t p1 = static_cast(Mp.f >> -one.e); - uint64_t p2 = Mp.f & (one.f - 1); - int kappa = CountDecimalDigit32(p1); // kappa in [0, 9] - *len = 0; - - while (kappa > 0) { - uint32_t d = 0; - switch (kappa) { - case 9: d = p1 / 100000000; p1 %= 100000000; break; - case 8: d = p1 / 10000000; p1 %= 10000000; break; - case 7: d = p1 / 1000000; p1 %= 1000000; break; - case 6: d = p1 / 100000; p1 %= 100000; break; - case 5: d = p1 / 10000; p1 %= 10000; break; - case 4: d = p1 / 1000; p1 %= 1000; break; - case 3: d = p1 / 100; p1 %= 100; break; - case 2: d = p1 / 10; p1 %= 10; break; - case 1: d = p1; p1 = 0; break; - default:; - } - if (d || *len) - buffer[(*len)++] = static_cast('0' + static_cast(d)); - kappa--; - uint64_t tmp = (static_cast(p1) << -one.e) + p2; - if (tmp <= delta) { - *K += kappa; - GrisuRound(buffer, *len, delta, tmp, static_cast(kPow10[kappa]) << -one.e, wp_w.f); - return; - } - } - - // kappa = 0 - for (;;) { - p2 *= 10; - delta *= 10; - char d = static_cast(p2 >> -one.e); - if (d || *len) - buffer[(*len)++] = static_cast('0' + d); - p2 &= one.f - 1; - kappa--; - if (p2 < delta) { - *K += kappa; - int index = -kappa; - GrisuRound(buffer, *len, delta, p2, one.f, wp_w.f * (index < 9 ? kPow10[index] : 0)); - return; - } - } -} - -inline void Grisu2(double value, char* buffer, int* length, int* K) { - const DiyFp v(value); - DiyFp w_m, w_p; - v.NormalizedBoundaries(&w_m, &w_p); - - const DiyFp c_mk = GetCachedPower(w_p.e, K); - const DiyFp W = v.Normalize() * c_mk; - DiyFp Wp = w_p * c_mk; - DiyFp Wm = w_m * c_mk; - Wm.f++; - Wp.f--; - DigitGen(W, Wp, Wp.f - Wm.f, buffer, length, K); -} - -inline char* WriteExponent(int K, char* buffer) { - if (K < 0) { - *buffer++ = '-'; - K = -K; - } - - if (K >= 100) { - *buffer++ = static_cast('0' + static_cast(K / 100)); - K %= 100; - const char* d = GetDigitsLut() + K * 2; - *buffer++ = d[0]; - *buffer++ = d[1]; - } - else if (K >= 10) { - const char* d = GetDigitsLut() + K * 2; - *buffer++ = d[0]; - *buffer++ = d[1]; - } - else - *buffer++ = static_cast('0' + static_cast(K)); - - return buffer; -} - -inline char* Prettify(char* buffer, int length, int k, int maxDecimalPlaces) { - const int kk = length + k; // 10^(kk-1) <= v < 10^kk - - if (0 <= k && kk <= 21) { - // 1234e7 -> 12340000000 - for (int i = length; i < kk; i++) - buffer[i] = '0'; - buffer[kk] = '.'; - buffer[kk + 1] = '0'; - return &buffer[kk + 2]; - } - else if (0 < kk && kk <= 21) { - // 1234e-2 -> 12.34 - std::memmove(&buffer[kk + 1], &buffer[kk], static_cast(length - kk)); - buffer[kk] = '.'; - if (0 > k + maxDecimalPlaces) { - // When maxDecimalPlaces = 2, 1.2345 -> 1.23, 1.102 -> 1.1 - // Remove extra trailing zeros (at least one) after truncation. - for (int i = kk + maxDecimalPlaces; i > kk + 1; i--) - if (buffer[i] != '0') - return &buffer[i + 1]; - return &buffer[kk + 2]; // Reserve one zero - } - else - return &buffer[length + 1]; - } - else if (-6 < kk && kk <= 0) { - // 1234e-6 -> 0.001234 - const int offset = 2 - kk; - std::memmove(&buffer[offset], &buffer[0], static_cast(length)); - buffer[0] = '0'; - buffer[1] = '.'; - for (int i = 2; i < offset; i++) - buffer[i] = '0'; - if (length - kk > maxDecimalPlaces) { - // When maxDecimalPlaces = 2, 0.123 -> 0.12, 0.102 -> 0.1 - // Remove extra trailing zeros (at least one) after truncation. - for (int i = maxDecimalPlaces + 1; i > 2; i--) - if (buffer[i] != '0') - return &buffer[i + 1]; - return &buffer[3]; // Reserve one zero - } - else - return &buffer[length + offset]; - } - else if (kk < -maxDecimalPlaces) { - // Truncate to zero - buffer[0] = '0'; - buffer[1] = '.'; - buffer[2] = '0'; - return &buffer[3]; - } - else if (length == 1) { - // 1e30 - buffer[1] = 'e'; - return WriteExponent(kk - 1, &buffer[2]); - } - else { - // 1234e30 -> 1.234e33 - std::memmove(&buffer[2], &buffer[1], static_cast(length - 1)); - buffer[1] = '.'; - buffer[length + 1] = 'e'; - return WriteExponent(kk - 1, &buffer[0 + length + 2]); - } -} - -inline char* dtoa(double value, char* buffer, int maxDecimalPlaces = 324) { - CEREAL_RAPIDJSON_ASSERT(maxDecimalPlaces >= 1); - Double d(value); - if (d.IsZero()) { - if (d.Sign()) - *buffer++ = '-'; // -0.0, Issue #289 - buffer[0] = '0'; - buffer[1] = '.'; - buffer[2] = '0'; - return &buffer[3]; - } - else { - if (value < 0) { - *buffer++ = '-'; - value = -value; - } - int length, K; - Grisu2(value, buffer, &length, &K); - return Prettify(buffer, length, K, maxDecimalPlaces); - } -} - -#ifdef __GNUC__ -CEREAL_RAPIDJSON_DIAG_POP -#endif - -} // namespace internal -CEREAL_RAPIDJSON_NAMESPACE_END - -#endif // CEREAL_RAPIDJSON_DTOA_ diff --git a/include/cereal/external/rapidjson/internal/ieee754.h b/include/cereal/external/rapidjson/internal/ieee754.h deleted file mode 100644 index 6730dfd..0000000 --- a/include/cereal/external/rapidjson/internal/ieee754.h +++ /dev/null @@ -1,78 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_IEEE754_ -#define CEREAL_RAPIDJSON_IEEE754_ - -#include "../rapidjson.h" - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN -namespace internal { - -class Double { -public: - Double() {} - Double(double d) : d_(d) {} - Double(uint64_t u) : u_(u) {} - - double Value() const { return d_; } - uint64_t Uint64Value() const { return u_; } - - double NextPositiveDouble() const { - CEREAL_RAPIDJSON_ASSERT(!Sign()); - return Double(u_ + 1).Value(); - } - - bool Sign() const { return (u_ & kSignMask) != 0; } - uint64_t Significand() const { return u_ & kSignificandMask; } - int Exponent() const { return static_cast(((u_ & kExponentMask) >> kSignificandSize) - kExponentBias); } - - bool IsNan() const { return (u_ & kExponentMask) == kExponentMask && Significand() != 0; } - bool IsInf() const { return (u_ & kExponentMask) == kExponentMask && Significand() == 0; } - bool IsNanOrInf() const { return (u_ & kExponentMask) == kExponentMask; } - bool IsNormal() const { return (u_ & kExponentMask) != 0 || Significand() == 0; } - bool IsZero() const { return (u_ & (kExponentMask | kSignificandMask)) == 0; } - - uint64_t IntegerSignificand() const { return IsNormal() ? Significand() | kHiddenBit : Significand(); } - int IntegerExponent() const { return (IsNormal() ? Exponent() : kDenormalExponent) - kSignificandSize; } - uint64_t ToBias() const { return (u_ & kSignMask) ? ~u_ + 1 : u_ | kSignMask; } - - static int EffectiveSignificandSize(int order) { - if (order >= -1021) - return 53; - else if (order <= -1074) - return 0; - else - return order + 1074; - } - -private: - static const int kSignificandSize = 52; - static const int kExponentBias = 0x3FF; - static const int kDenormalExponent = 1 - kExponentBias; - static const uint64_t kSignMask = CEREAL_RAPIDJSON_UINT64_C2(0x80000000, 0x00000000); - static const uint64_t kExponentMask = CEREAL_RAPIDJSON_UINT64_C2(0x7FF00000, 0x00000000); - static const uint64_t kSignificandMask = CEREAL_RAPIDJSON_UINT64_C2(0x000FFFFF, 0xFFFFFFFF); - static const uint64_t kHiddenBit = CEREAL_RAPIDJSON_UINT64_C2(0x00100000, 0x00000000); - - union { - double d_; - uint64_t u_; - }; -}; - -} // namespace internal -CEREAL_RAPIDJSON_NAMESPACE_END - -#endif // CEREAL_RAPIDJSON_IEEE754_ diff --git a/include/cereal/external/rapidjson/internal/itoa.h b/include/cereal/external/rapidjson/internal/itoa.h deleted file mode 100644 index f04e3fa..0000000 --- a/include/cereal/external/rapidjson/internal/itoa.h +++ /dev/null @@ -1,308 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_ITOA_ -#define CEREAL_RAPIDJSON_ITOA_ - -#include "../rapidjson.h" - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN -namespace internal { - -inline const char* GetDigitsLut() { - static const char cDigitsLut[200] = { - '0','0','0','1','0','2','0','3','0','4','0','5','0','6','0','7','0','8','0','9', - '1','0','1','1','1','2','1','3','1','4','1','5','1','6','1','7','1','8','1','9', - '2','0','2','1','2','2','2','3','2','4','2','5','2','6','2','7','2','8','2','9', - '3','0','3','1','3','2','3','3','3','4','3','5','3','6','3','7','3','8','3','9', - '4','0','4','1','4','2','4','3','4','4','4','5','4','6','4','7','4','8','4','9', - '5','0','5','1','5','2','5','3','5','4','5','5','5','6','5','7','5','8','5','9', - '6','0','6','1','6','2','6','3','6','4','6','5','6','6','6','7','6','8','6','9', - '7','0','7','1','7','2','7','3','7','4','7','5','7','6','7','7','7','8','7','9', - '8','0','8','1','8','2','8','3','8','4','8','5','8','6','8','7','8','8','8','9', - '9','0','9','1','9','2','9','3','9','4','9','5','9','6','9','7','9','8','9','9' - }; - return cDigitsLut; -} - -inline char* u32toa(uint32_t value, char* buffer) { - CEREAL_RAPIDJSON_ASSERT(buffer != 0); - - const char* cDigitsLut = GetDigitsLut(); - - if (value < 10000) { - const uint32_t d1 = (value / 100) << 1; - const uint32_t d2 = (value % 100) << 1; - - if (value >= 1000) - *buffer++ = cDigitsLut[d1]; - if (value >= 100) - *buffer++ = cDigitsLut[d1 + 1]; - if (value >= 10) - *buffer++ = cDigitsLut[d2]; - *buffer++ = cDigitsLut[d2 + 1]; - } - else if (value < 100000000) { - // value = bbbbcccc - const uint32_t b = value / 10000; - const uint32_t c = value % 10000; - - const uint32_t d1 = (b / 100) << 1; - const uint32_t d2 = (b % 100) << 1; - - const uint32_t d3 = (c / 100) << 1; - const uint32_t d4 = (c % 100) << 1; - - if (value >= 10000000) - *buffer++ = cDigitsLut[d1]; - if (value >= 1000000) - *buffer++ = cDigitsLut[d1 + 1]; - if (value >= 100000) - *buffer++ = cDigitsLut[d2]; - *buffer++ = cDigitsLut[d2 + 1]; - - *buffer++ = cDigitsLut[d3]; - *buffer++ = cDigitsLut[d3 + 1]; - *buffer++ = cDigitsLut[d4]; - *buffer++ = cDigitsLut[d4 + 1]; - } - else { - // value = aabbbbcccc in decimal - - const uint32_t a = value / 100000000; // 1 to 42 - value %= 100000000; - - if (a >= 10) { - const unsigned i = a << 1; - *buffer++ = cDigitsLut[i]; - *buffer++ = cDigitsLut[i + 1]; - } - else - *buffer++ = static_cast('0' + static_cast(a)); - - const uint32_t b = value / 10000; // 0 to 9999 - const uint32_t c = value % 10000; // 0 to 9999 - - const uint32_t d1 = (b / 100) << 1; - const uint32_t d2 = (b % 100) << 1; - - const uint32_t d3 = (c / 100) << 1; - const uint32_t d4 = (c % 100) << 1; - - *buffer++ = cDigitsLut[d1]; - *buffer++ = cDigitsLut[d1 + 1]; - *buffer++ = cDigitsLut[d2]; - *buffer++ = cDigitsLut[d2 + 1]; - *buffer++ = cDigitsLut[d3]; - *buffer++ = cDigitsLut[d3 + 1]; - *buffer++ = cDigitsLut[d4]; - *buffer++ = cDigitsLut[d4 + 1]; - } - return buffer; -} - -inline char* i32toa(int32_t value, char* buffer) { - CEREAL_RAPIDJSON_ASSERT(buffer != 0); - uint32_t u = static_cast(value); - if (value < 0) { - *buffer++ = '-'; - u = ~u + 1; - } - - return u32toa(u, buffer); -} - -inline char* u64toa(uint64_t value, char* buffer) { - CEREAL_RAPIDJSON_ASSERT(buffer != 0); - const char* cDigitsLut = GetDigitsLut(); - const uint64_t kTen8 = 100000000; - const uint64_t kTen9 = kTen8 * 10; - const uint64_t kTen10 = kTen8 * 100; - const uint64_t kTen11 = kTen8 * 1000; - const uint64_t kTen12 = kTen8 * 10000; - const uint64_t kTen13 = kTen8 * 100000; - const uint64_t kTen14 = kTen8 * 1000000; - const uint64_t kTen15 = kTen8 * 10000000; - const uint64_t kTen16 = kTen8 * kTen8; - - if (value < kTen8) { - uint32_t v = static_cast(value); - if (v < 10000) { - const uint32_t d1 = (v / 100) << 1; - const uint32_t d2 = (v % 100) << 1; - - if (v >= 1000) - *buffer++ = cDigitsLut[d1]; - if (v >= 100) - *buffer++ = cDigitsLut[d1 + 1]; - if (v >= 10) - *buffer++ = cDigitsLut[d2]; - *buffer++ = cDigitsLut[d2 + 1]; - } - else { - // value = bbbbcccc - const uint32_t b = v / 10000; - const uint32_t c = v % 10000; - - const uint32_t d1 = (b / 100) << 1; - const uint32_t d2 = (b % 100) << 1; - - const uint32_t d3 = (c / 100) << 1; - const uint32_t d4 = (c % 100) << 1; - - if (value >= 10000000) - *buffer++ = cDigitsLut[d1]; - if (value >= 1000000) - *buffer++ = cDigitsLut[d1 + 1]; - if (value >= 100000) - *buffer++ = cDigitsLut[d2]; - *buffer++ = cDigitsLut[d2 + 1]; - - *buffer++ = cDigitsLut[d3]; - *buffer++ = cDigitsLut[d3 + 1]; - *buffer++ = cDigitsLut[d4]; - *buffer++ = cDigitsLut[d4 + 1]; - } - } - else if (value < kTen16) { - const uint32_t v0 = static_cast(value / kTen8); - const uint32_t v1 = static_cast(value % kTen8); - - const uint32_t b0 = v0 / 10000; - const uint32_t c0 = v0 % 10000; - - const uint32_t d1 = (b0 / 100) << 1; - const uint32_t d2 = (b0 % 100) << 1; - - const uint32_t d3 = (c0 / 100) << 1; - const uint32_t d4 = (c0 % 100) << 1; - - const uint32_t b1 = v1 / 10000; - const uint32_t c1 = v1 % 10000; - - const uint32_t d5 = (b1 / 100) << 1; - const uint32_t d6 = (b1 % 100) << 1; - - const uint32_t d7 = (c1 / 100) << 1; - const uint32_t d8 = (c1 % 100) << 1; - - if (value >= kTen15) - *buffer++ = cDigitsLut[d1]; - if (value >= kTen14) - *buffer++ = cDigitsLut[d1 + 1]; - if (value >= kTen13) - *buffer++ = cDigitsLut[d2]; - if (value >= kTen12) - *buffer++ = cDigitsLut[d2 + 1]; - if (value >= kTen11) - *buffer++ = cDigitsLut[d3]; - if (value >= kTen10) - *buffer++ = cDigitsLut[d3 + 1]; - if (value >= kTen9) - *buffer++ = cDigitsLut[d4]; - - *buffer++ = cDigitsLut[d4 + 1]; - *buffer++ = cDigitsLut[d5]; - *buffer++ = cDigitsLut[d5 + 1]; - *buffer++ = cDigitsLut[d6]; - *buffer++ = cDigitsLut[d6 + 1]; - *buffer++ = cDigitsLut[d7]; - *buffer++ = cDigitsLut[d7 + 1]; - *buffer++ = cDigitsLut[d8]; - *buffer++ = cDigitsLut[d8 + 1]; - } - else { - const uint32_t a = static_cast(value / kTen16); // 1 to 1844 - value %= kTen16; - - if (a < 10) - *buffer++ = static_cast('0' + static_cast(a)); - else if (a < 100) { - const uint32_t i = a << 1; - *buffer++ = cDigitsLut[i]; - *buffer++ = cDigitsLut[i + 1]; - } - else if (a < 1000) { - *buffer++ = static_cast('0' + static_cast(a / 100)); - - const uint32_t i = (a % 100) << 1; - *buffer++ = cDigitsLut[i]; - *buffer++ = cDigitsLut[i + 1]; - } - else { - const uint32_t i = (a / 100) << 1; - const uint32_t j = (a % 100) << 1; - *buffer++ = cDigitsLut[i]; - *buffer++ = cDigitsLut[i + 1]; - *buffer++ = cDigitsLut[j]; - *buffer++ = cDigitsLut[j + 1]; - } - - const uint32_t v0 = static_cast(value / kTen8); - const uint32_t v1 = static_cast(value % kTen8); - - const uint32_t b0 = v0 / 10000; - const uint32_t c0 = v0 % 10000; - - const uint32_t d1 = (b0 / 100) << 1; - const uint32_t d2 = (b0 % 100) << 1; - - const uint32_t d3 = (c0 / 100) << 1; - const uint32_t d4 = (c0 % 100) << 1; - - const uint32_t b1 = v1 / 10000; - const uint32_t c1 = v1 % 10000; - - const uint32_t d5 = (b1 / 100) << 1; - const uint32_t d6 = (b1 % 100) << 1; - - const uint32_t d7 = (c1 / 100) << 1; - const uint32_t d8 = (c1 % 100) << 1; - - *buffer++ = cDigitsLut[d1]; - *buffer++ = cDigitsLut[d1 + 1]; - *buffer++ = cDigitsLut[d2]; - *buffer++ = cDigitsLut[d2 + 1]; - *buffer++ = cDigitsLut[d3]; - *buffer++ = cDigitsLut[d3 + 1]; - *buffer++ = cDigitsLut[d4]; - *buffer++ = cDigitsLut[d4 + 1]; - *buffer++ = cDigitsLut[d5]; - *buffer++ = cDigitsLut[d5 + 1]; - *buffer++ = cDigitsLut[d6]; - *buffer++ = cDigitsLut[d6 + 1]; - *buffer++ = cDigitsLut[d7]; - *buffer++ = cDigitsLut[d7 + 1]; - *buffer++ = cDigitsLut[d8]; - *buffer++ = cDigitsLut[d8 + 1]; - } - - return buffer; -} - -inline char* i64toa(int64_t value, char* buffer) { - CEREAL_RAPIDJSON_ASSERT(buffer != 0); - uint64_t u = static_cast(value); - if (value < 0) { - *buffer++ = '-'; - u = ~u + 1; - } - - return u64toa(u, buffer); -} - -} // namespace internal -CEREAL_RAPIDJSON_NAMESPACE_END - -#endif // CEREAL_RAPIDJSON_ITOA_ diff --git a/include/cereal/external/rapidjson/internal/meta.h b/include/cereal/external/rapidjson/internal/meta.h deleted file mode 100644 index f511ff8..0000000 --- a/include/cereal/external/rapidjson/internal/meta.h +++ /dev/null @@ -1,186 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_INTERNAL_META_H_ -#define CEREAL_RAPIDJSON_INTERNAL_META_H_ - -#include "../rapidjson.h" - -#ifdef __GNUC__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(effc++) -#endif - -#if defined(_MSC_VER) && !defined(__clang__) -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(6334) -#endif - -#if CEREAL_RAPIDJSON_HAS_CXX11_TYPETRAITS -#include -#endif - -//@cond CEREAL_RAPIDJSON_INTERNAL -CEREAL_RAPIDJSON_NAMESPACE_BEGIN -namespace internal { - -// Helper to wrap/convert arbitrary types to void, useful for arbitrary type matching -template struct Void { typedef void Type; }; - -/////////////////////////////////////////////////////////////////////////////// -// BoolType, TrueType, FalseType -// -template struct BoolType { - static const bool Value = Cond; - typedef BoolType Type; -}; -typedef BoolType TrueType; -typedef BoolType FalseType; - - -/////////////////////////////////////////////////////////////////////////////// -// SelectIf, BoolExpr, NotExpr, AndExpr, OrExpr -// - -template struct SelectIfImpl { template struct Apply { typedef T1 Type; }; }; -template <> struct SelectIfImpl { template struct Apply { typedef T2 Type; }; }; -template struct SelectIfCond : SelectIfImpl::template Apply {}; -template struct SelectIf : SelectIfCond {}; - -template struct AndExprCond : FalseType {}; -template <> struct AndExprCond : TrueType {}; -template struct OrExprCond : TrueType {}; -template <> struct OrExprCond : FalseType {}; - -template struct BoolExpr : SelectIf::Type {}; -template struct NotExpr : SelectIf::Type {}; -template struct AndExpr : AndExprCond::Type {}; -template struct OrExpr : OrExprCond::Type {}; - - -/////////////////////////////////////////////////////////////////////////////// -// AddConst, MaybeAddConst, RemoveConst -template struct AddConst { typedef const T Type; }; -template struct MaybeAddConst : SelectIfCond {}; -template struct RemoveConst { typedef T Type; }; -template struct RemoveConst { typedef T Type; }; - - -/////////////////////////////////////////////////////////////////////////////// -// IsSame, IsConst, IsMoreConst, IsPointer -// -template struct IsSame : FalseType {}; -template struct IsSame : TrueType {}; - -template struct IsConst : FalseType {}; -template struct IsConst : TrueType {}; - -template -struct IsMoreConst - : AndExpr::Type, typename RemoveConst::Type>, - BoolType::Value >= IsConst::Value> >::Type {}; - -template struct IsPointer : FalseType {}; -template struct IsPointer : TrueType {}; - -/////////////////////////////////////////////////////////////////////////////// -// IsBaseOf -// -#if CEREAL_RAPIDJSON_HAS_CXX11_TYPETRAITS - -template struct IsBaseOf - : BoolType< ::std::is_base_of::value> {}; - -#else // simplified version adopted from Boost - -template struct IsBaseOfImpl { - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(B) != 0); - CEREAL_RAPIDJSON_STATIC_ASSERT(sizeof(D) != 0); - - typedef char (&Yes)[1]; - typedef char (&No) [2]; - - template - static Yes Check(const D*, T); - static No Check(const B*, int); - - struct Host { - operator const B*() const; - operator const D*(); - }; - - enum { Value = (sizeof(Check(Host(), 0)) == sizeof(Yes)) }; -}; - -template struct IsBaseOf - : OrExpr, BoolExpr > >::Type {}; - -#endif // CEREAL_RAPIDJSON_HAS_CXX11_TYPETRAITS - - -////////////////////////////////////////////////////////////////////////// -// EnableIf / DisableIf -// -template struct EnableIfCond { typedef T Type; }; -template struct EnableIfCond { /* empty */ }; - -template struct DisableIfCond { typedef T Type; }; -template struct DisableIfCond { /* empty */ }; - -template -struct EnableIf : EnableIfCond {}; - -template -struct DisableIf : DisableIfCond {}; - -// SFINAE helpers -struct SfinaeTag {}; -template struct RemoveSfinaeTag; -template struct RemoveSfinaeTag { typedef T Type; }; - -#define CEREAL_RAPIDJSON_REMOVEFPTR_(type) \ - typename ::CEREAL_RAPIDJSON_NAMESPACE::internal::RemoveSfinaeTag \ - < ::CEREAL_RAPIDJSON_NAMESPACE::internal::SfinaeTag&(*) type>::Type - -#define CEREAL_RAPIDJSON_ENABLEIF(cond) \ - typename ::CEREAL_RAPIDJSON_NAMESPACE::internal::EnableIf \ - ::Type * = NULL - -#define CEREAL_RAPIDJSON_DISABLEIF(cond) \ - typename ::CEREAL_RAPIDJSON_NAMESPACE::internal::DisableIf \ - ::Type * = NULL - -#define CEREAL_RAPIDJSON_ENABLEIF_RETURN(cond,returntype) \ - typename ::CEREAL_RAPIDJSON_NAMESPACE::internal::EnableIf \ - ::Type - -#define CEREAL_RAPIDJSON_DISABLEIF_RETURN(cond,returntype) \ - typename ::CEREAL_RAPIDJSON_NAMESPACE::internal::DisableIf \ - ::Type - -} // namespace internal -CEREAL_RAPIDJSON_NAMESPACE_END -//@endcond - -#if defined(_MSC_VER) && !defined(__clang__) -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#ifdef __GNUC__ -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#endif // CEREAL_RAPIDJSON_INTERNAL_META_H_ diff --git a/include/cereal/external/rapidjson/internal/pow10.h b/include/cereal/external/rapidjson/internal/pow10.h deleted file mode 100644 index 7f796a1..0000000 --- a/include/cereal/external/rapidjson/internal/pow10.h +++ /dev/null @@ -1,55 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_POW10_ -#define CEREAL_RAPIDJSON_POW10_ - -#include "../rapidjson.h" - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN -namespace internal { - -//! Computes integer powers of 10 in double (10.0^n). -/*! This function uses lookup table for fast and accurate results. - \param n non-negative exponent. Must <= 308. - \return 10.0^n -*/ -inline double Pow10(int n) { - static const double e[] = { // 1e-0...1e308: 309 * 8 bytes = 2472 bytes - 1e+0, - 1e+1, 1e+2, 1e+3, 1e+4, 1e+5, 1e+6, 1e+7, 1e+8, 1e+9, 1e+10, 1e+11, 1e+12, 1e+13, 1e+14, 1e+15, 1e+16, 1e+17, 1e+18, 1e+19, 1e+20, - 1e+21, 1e+22, 1e+23, 1e+24, 1e+25, 1e+26, 1e+27, 1e+28, 1e+29, 1e+30, 1e+31, 1e+32, 1e+33, 1e+34, 1e+35, 1e+36, 1e+37, 1e+38, 1e+39, 1e+40, - 1e+41, 1e+42, 1e+43, 1e+44, 1e+45, 1e+46, 1e+47, 1e+48, 1e+49, 1e+50, 1e+51, 1e+52, 1e+53, 1e+54, 1e+55, 1e+56, 1e+57, 1e+58, 1e+59, 1e+60, - 1e+61, 1e+62, 1e+63, 1e+64, 1e+65, 1e+66, 1e+67, 1e+68, 1e+69, 1e+70, 1e+71, 1e+72, 1e+73, 1e+74, 1e+75, 1e+76, 1e+77, 1e+78, 1e+79, 1e+80, - 1e+81, 1e+82, 1e+83, 1e+84, 1e+85, 1e+86, 1e+87, 1e+88, 1e+89, 1e+90, 1e+91, 1e+92, 1e+93, 1e+94, 1e+95, 1e+96, 1e+97, 1e+98, 1e+99, 1e+100, - 1e+101,1e+102,1e+103,1e+104,1e+105,1e+106,1e+107,1e+108,1e+109,1e+110,1e+111,1e+112,1e+113,1e+114,1e+115,1e+116,1e+117,1e+118,1e+119,1e+120, - 1e+121,1e+122,1e+123,1e+124,1e+125,1e+126,1e+127,1e+128,1e+129,1e+130,1e+131,1e+132,1e+133,1e+134,1e+135,1e+136,1e+137,1e+138,1e+139,1e+140, - 1e+141,1e+142,1e+143,1e+144,1e+145,1e+146,1e+147,1e+148,1e+149,1e+150,1e+151,1e+152,1e+153,1e+154,1e+155,1e+156,1e+157,1e+158,1e+159,1e+160, - 1e+161,1e+162,1e+163,1e+164,1e+165,1e+166,1e+167,1e+168,1e+169,1e+170,1e+171,1e+172,1e+173,1e+174,1e+175,1e+176,1e+177,1e+178,1e+179,1e+180, - 1e+181,1e+182,1e+183,1e+184,1e+185,1e+186,1e+187,1e+188,1e+189,1e+190,1e+191,1e+192,1e+193,1e+194,1e+195,1e+196,1e+197,1e+198,1e+199,1e+200, - 1e+201,1e+202,1e+203,1e+204,1e+205,1e+206,1e+207,1e+208,1e+209,1e+210,1e+211,1e+212,1e+213,1e+214,1e+215,1e+216,1e+217,1e+218,1e+219,1e+220, - 1e+221,1e+222,1e+223,1e+224,1e+225,1e+226,1e+227,1e+228,1e+229,1e+230,1e+231,1e+232,1e+233,1e+234,1e+235,1e+236,1e+237,1e+238,1e+239,1e+240, - 1e+241,1e+242,1e+243,1e+244,1e+245,1e+246,1e+247,1e+248,1e+249,1e+250,1e+251,1e+252,1e+253,1e+254,1e+255,1e+256,1e+257,1e+258,1e+259,1e+260, - 1e+261,1e+262,1e+263,1e+264,1e+265,1e+266,1e+267,1e+268,1e+269,1e+270,1e+271,1e+272,1e+273,1e+274,1e+275,1e+276,1e+277,1e+278,1e+279,1e+280, - 1e+281,1e+282,1e+283,1e+284,1e+285,1e+286,1e+287,1e+288,1e+289,1e+290,1e+291,1e+292,1e+293,1e+294,1e+295,1e+296,1e+297,1e+298,1e+299,1e+300, - 1e+301,1e+302,1e+303,1e+304,1e+305,1e+306,1e+307,1e+308 - }; - CEREAL_RAPIDJSON_ASSERT(n >= 0 && n <= 308); - return e[n]; -} - -} // namespace internal -CEREAL_RAPIDJSON_NAMESPACE_END - -#endif // CEREAL_RAPIDJSON_POW10_ diff --git a/include/cereal/external/rapidjson/internal/regex.h b/include/cereal/external/rapidjson/internal/regex.h deleted file mode 100644 index 6c2ed6e..0000000 --- a/include/cereal/external/rapidjson/internal/regex.h +++ /dev/null @@ -1,740 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_INTERNAL_REGEX_H_ -#define CEREAL_RAPIDJSON_INTERNAL_REGEX_H_ - -#include "../allocators.h" -#include "../stream.h" -#include "stack.h" - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(padded) -CEREAL_RAPIDJSON_DIAG_OFF(switch-enum) -CEREAL_RAPIDJSON_DIAG_OFF(implicit-fallthrough) -#elif defined(_MSC_VER) -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated -#endif - -#ifdef __GNUC__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(effc++) -#if __GNUC__ >= 7 -CEREAL_RAPIDJSON_DIAG_OFF(implicit-fallthrough) -#endif -#endif - -#ifndef CEREAL_RAPIDJSON_REGEX_VERBOSE -#define CEREAL_RAPIDJSON_REGEX_VERBOSE 0 -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN -namespace internal { - -/////////////////////////////////////////////////////////////////////////////// -// DecodedStream - -template -class DecodedStream { -public: - DecodedStream(SourceStream& ss) : ss_(ss), codepoint_() { Decode(); } - unsigned Peek() { return codepoint_; } - unsigned Take() { - unsigned c = codepoint_; - if (c) // No further decoding when '\0' - Decode(); - return c; - } - -private: - void Decode() { - if (!Encoding::Decode(ss_, &codepoint_)) - codepoint_ = 0; - } - - SourceStream& ss_; - unsigned codepoint_; -}; - -/////////////////////////////////////////////////////////////////////////////// -// GenericRegex - -static const SizeType kRegexInvalidState = ~SizeType(0); //!< Represents an invalid index in GenericRegex::State::out, out1 -static const SizeType kRegexInvalidRange = ~SizeType(0); - -template -class GenericRegexSearch; - -//! Regular expression engine with subset of ECMAscript grammar. -/*! - Supported regular expression syntax: - - \c ab Concatenation - - \c a|b Alternation - - \c a? Zero or one - - \c a* Zero or more - - \c a+ One or more - - \c a{3} Exactly 3 times - - \c a{3,} At least 3 times - - \c a{3,5} 3 to 5 times - - \c (ab) Grouping - - \c ^a At the beginning - - \c a$ At the end - - \c . Any character - - \c [abc] Character classes - - \c [a-c] Character class range - - \c [a-z0-9_] Character class combination - - \c [^abc] Negated character classes - - \c [^a-c] Negated character class range - - \c [\b] Backspace (U+0008) - - \c \\| \\\\ ... Escape characters - - \c \\f Form feed (U+000C) - - \c \\n Line feed (U+000A) - - \c \\r Carriage return (U+000D) - - \c \\t Tab (U+0009) - - \c \\v Vertical tab (U+000B) - - \note This is a Thompson NFA engine, implemented with reference to - Cox, Russ. "Regular Expression Matching Can Be Simple And Fast (but is slow in Java, Perl, PHP, Python, Ruby,...).", - https://swtch.com/~rsc/regexp/regexp1.html -*/ -template -class GenericRegex { -public: - typedef Encoding EncodingType; - typedef typename Encoding::Ch Ch; - template friend class GenericRegexSearch; - - GenericRegex(const Ch* source, Allocator* allocator = 0) : - ownAllocator_(allocator ? 0 : CEREAL_RAPIDJSON_NEW(Allocator)()), allocator_(allocator ? allocator : ownAllocator_), - states_(allocator_, 256), ranges_(allocator_, 256), root_(kRegexInvalidState), stateCount_(), rangeCount_(), - anchorBegin_(), anchorEnd_() - { - GenericStringStream ss(source); - DecodedStream, Encoding> ds(ss); - Parse(ds); - } - - ~GenericRegex() - { - CEREAL_RAPIDJSON_DELETE(ownAllocator_); - } - - bool IsValid() const { - return root_ != kRegexInvalidState; - } - -private: - enum Operator { - kZeroOrOne, - kZeroOrMore, - kOneOrMore, - kConcatenation, - kAlternation, - kLeftParenthesis - }; - - static const unsigned kAnyCharacterClass = 0xFFFFFFFF; //!< For '.' - static const unsigned kRangeCharacterClass = 0xFFFFFFFE; - static const unsigned kRangeNegationFlag = 0x80000000; - - struct Range { - unsigned start; // - unsigned end; - SizeType next; - }; - - struct State { - SizeType out; //!< Equals to kInvalid for matching state - SizeType out1; //!< Equals to non-kInvalid for split - SizeType rangeStart; - unsigned codepoint; - }; - - struct Frag { - Frag(SizeType s, SizeType o, SizeType m) : start(s), out(o), minIndex(m) {} - SizeType start; - SizeType out; //!< link-list of all output states - SizeType minIndex; - }; - - State& GetState(SizeType index) { - CEREAL_RAPIDJSON_ASSERT(index < stateCount_); - return states_.template Bottom()[index]; - } - - const State& GetState(SizeType index) const { - CEREAL_RAPIDJSON_ASSERT(index < stateCount_); - return states_.template Bottom()[index]; - } - - Range& GetRange(SizeType index) { - CEREAL_RAPIDJSON_ASSERT(index < rangeCount_); - return ranges_.template Bottom()[index]; - } - - const Range& GetRange(SizeType index) const { - CEREAL_RAPIDJSON_ASSERT(index < rangeCount_); - return ranges_.template Bottom()[index]; - } - - template - void Parse(DecodedStream& ds) { - Stack operandStack(allocator_, 256); // Frag - Stack operatorStack(allocator_, 256); // Operator - Stack atomCountStack(allocator_, 256); // unsigned (Atom per parenthesis) - - *atomCountStack.template Push() = 0; - - unsigned codepoint; - while (ds.Peek() != 0) { - switch (codepoint = ds.Take()) { - case '^': - anchorBegin_ = true; - break; - - case '$': - anchorEnd_ = true; - break; - - case '|': - while (!operatorStack.Empty() && *operatorStack.template Top() < kAlternation) - if (!Eval(operandStack, *operatorStack.template Pop(1))) - return; - *operatorStack.template Push() = kAlternation; - *atomCountStack.template Top() = 0; - break; - - case '(': - *operatorStack.template Push() = kLeftParenthesis; - *atomCountStack.template Push() = 0; - break; - - case ')': - while (!operatorStack.Empty() && *operatorStack.template Top() != kLeftParenthesis) - if (!Eval(operandStack, *operatorStack.template Pop(1))) - return; - if (operatorStack.Empty()) - return; - operatorStack.template Pop(1); - atomCountStack.template Pop(1); - ImplicitConcatenation(atomCountStack, operatorStack); - break; - - case '?': - if (!Eval(operandStack, kZeroOrOne)) - return; - break; - - case '*': - if (!Eval(operandStack, kZeroOrMore)) - return; - break; - - case '+': - if (!Eval(operandStack, kOneOrMore)) - return; - break; - - case '{': - { - unsigned n, m; - if (!ParseUnsigned(ds, &n)) - return; - - if (ds.Peek() == ',') { - ds.Take(); - if (ds.Peek() == '}') - m = kInfinityQuantifier; - else if (!ParseUnsigned(ds, &m) || m < n) - return; - } - else - m = n; - - if (!EvalQuantifier(operandStack, n, m) || ds.Peek() != '}') - return; - ds.Take(); - } - break; - - case '.': - PushOperand(operandStack, kAnyCharacterClass); - ImplicitConcatenation(atomCountStack, operatorStack); - break; - - case '[': - { - SizeType range; - if (!ParseRange(ds, &range)) - return; - SizeType s = NewState(kRegexInvalidState, kRegexInvalidState, kRangeCharacterClass); - GetState(s).rangeStart = range; - *operandStack.template Push() = Frag(s, s, s); - } - ImplicitConcatenation(atomCountStack, operatorStack); - break; - - case '\\': // Escape character - if (!CharacterEscape(ds, &codepoint)) - return; // Unsupported escape character - // fall through to default - - default: // Pattern character - PushOperand(operandStack, codepoint); - ImplicitConcatenation(atomCountStack, operatorStack); - } - } - - while (!operatorStack.Empty()) - if (!Eval(operandStack, *operatorStack.template Pop(1))) - return; - - // Link the operand to matching state. - if (operandStack.GetSize() == sizeof(Frag)) { - Frag* e = operandStack.template Pop(1); - Patch(e->out, NewState(kRegexInvalidState, kRegexInvalidState, 0)); - root_ = e->start; - -#if CEREAL_RAPIDJSON_REGEX_VERBOSE - printf("root: %d\n", root_); - for (SizeType i = 0; i < stateCount_ ; i++) { - State& s = GetState(i); - printf("[%2d] out: %2d out1: %2d c: '%c'\n", i, s.out, s.out1, (char)s.codepoint); - } - printf("\n"); -#endif - } - } - - SizeType NewState(SizeType out, SizeType out1, unsigned codepoint) { - State* s = states_.template Push(); - s->out = out; - s->out1 = out1; - s->codepoint = codepoint; - s->rangeStart = kRegexInvalidRange; - return stateCount_++; - } - - void PushOperand(Stack& operandStack, unsigned codepoint) { - SizeType s = NewState(kRegexInvalidState, kRegexInvalidState, codepoint); - *operandStack.template Push() = Frag(s, s, s); - } - - void ImplicitConcatenation(Stack& atomCountStack, Stack& operatorStack) { - if (*atomCountStack.template Top()) - *operatorStack.template Push() = kConcatenation; - (*atomCountStack.template Top())++; - } - - SizeType Append(SizeType l1, SizeType l2) { - SizeType old = l1; - while (GetState(l1).out != kRegexInvalidState) - l1 = GetState(l1).out; - GetState(l1).out = l2; - return old; - } - - void Patch(SizeType l, SizeType s) { - for (SizeType next; l != kRegexInvalidState; l = next) { - next = GetState(l).out; - GetState(l).out = s; - } - } - - bool Eval(Stack& operandStack, Operator op) { - switch (op) { - case kConcatenation: - CEREAL_RAPIDJSON_ASSERT(operandStack.GetSize() >= sizeof(Frag) * 2); - { - Frag e2 = *operandStack.template Pop(1); - Frag e1 = *operandStack.template Pop(1); - Patch(e1.out, e2.start); - *operandStack.template Push() = Frag(e1.start, e2.out, Min(e1.minIndex, e2.minIndex)); - } - return true; - - case kAlternation: - if (operandStack.GetSize() >= sizeof(Frag) * 2) { - Frag e2 = *operandStack.template Pop(1); - Frag e1 = *operandStack.template Pop(1); - SizeType s = NewState(e1.start, e2.start, 0); - *operandStack.template Push() = Frag(s, Append(e1.out, e2.out), Min(e1.minIndex, e2.minIndex)); - return true; - } - return false; - - case kZeroOrOne: - if (operandStack.GetSize() >= sizeof(Frag)) { - Frag e = *operandStack.template Pop(1); - SizeType s = NewState(kRegexInvalidState, e.start, 0); - *operandStack.template Push() = Frag(s, Append(e.out, s), e.minIndex); - return true; - } - return false; - - case kZeroOrMore: - if (operandStack.GetSize() >= sizeof(Frag)) { - Frag e = *operandStack.template Pop(1); - SizeType s = NewState(kRegexInvalidState, e.start, 0); - Patch(e.out, s); - *operandStack.template Push() = Frag(s, s, e.minIndex); - return true; - } - return false; - - case kOneOrMore: - if (operandStack.GetSize() >= sizeof(Frag)) { - Frag e = *operandStack.template Pop(1); - SizeType s = NewState(kRegexInvalidState, e.start, 0); - Patch(e.out, s); - *operandStack.template Push() = Frag(e.start, s, e.minIndex); - return true; - } - return false; - - default: - // syntax error (e.g. unclosed kLeftParenthesis) - return false; - } - } - - bool EvalQuantifier(Stack& operandStack, unsigned n, unsigned m) { - CEREAL_RAPIDJSON_ASSERT(n <= m); - CEREAL_RAPIDJSON_ASSERT(operandStack.GetSize() >= sizeof(Frag)); - - if (n == 0) { - if (m == 0) // a{0} not support - return false; - else if (m == kInfinityQuantifier) - Eval(operandStack, kZeroOrMore); // a{0,} -> a* - else { - Eval(operandStack, kZeroOrOne); // a{0,5} -> a? - for (unsigned i = 0; i < m - 1; i++) - CloneTopOperand(operandStack); // a{0,5} -> a? a? a? a? a? - for (unsigned i = 0; i < m - 1; i++) - Eval(operandStack, kConcatenation); // a{0,5} -> a?a?a?a?a? - } - return true; - } - - for (unsigned i = 0; i < n - 1; i++) // a{3} -> a a a - CloneTopOperand(operandStack); - - if (m == kInfinityQuantifier) - Eval(operandStack, kOneOrMore); // a{3,} -> a a a+ - else if (m > n) { - CloneTopOperand(operandStack); // a{3,5} -> a a a a - Eval(operandStack, kZeroOrOne); // a{3,5} -> a a a a? - for (unsigned i = n; i < m - 1; i++) - CloneTopOperand(operandStack); // a{3,5} -> a a a a? a? - for (unsigned i = n; i < m; i++) - Eval(operandStack, kConcatenation); // a{3,5} -> a a aa?a? - } - - for (unsigned i = 0; i < n - 1; i++) - Eval(operandStack, kConcatenation); // a{3} -> aaa, a{3,} -> aaa+, a{3.5} -> aaaa?a? - - return true; - } - - static SizeType Min(SizeType a, SizeType b) { return a < b ? a : b; } - - void CloneTopOperand(Stack& operandStack) { - const Frag src = *operandStack.template Top(); // Copy constructor to prevent invalidation - SizeType count = stateCount_ - src.minIndex; // Assumes top operand contains states in [src->minIndex, stateCount_) - State* s = states_.template Push(count); - memcpy(s, &GetState(src.minIndex), count * sizeof(State)); - for (SizeType j = 0; j < count; j++) { - if (s[j].out != kRegexInvalidState) - s[j].out += count; - if (s[j].out1 != kRegexInvalidState) - s[j].out1 += count; - } - *operandStack.template Push() = Frag(src.start + count, src.out + count, src.minIndex + count); - stateCount_ += count; - } - - template - bool ParseUnsigned(DecodedStream& ds, unsigned* u) { - unsigned r = 0; - if (ds.Peek() < '0' || ds.Peek() > '9') - return false; - while (ds.Peek() >= '0' && ds.Peek() <= '9') { - if (r >= 429496729 && ds.Peek() > '5') // 2^32 - 1 = 4294967295 - return false; // overflow - r = r * 10 + (ds.Take() - '0'); - } - *u = r; - return true; - } - - template - bool ParseRange(DecodedStream& ds, SizeType* range) { - bool isBegin = true; - bool negate = false; - int step = 0; - SizeType start = kRegexInvalidRange; - SizeType current = kRegexInvalidRange; - unsigned codepoint; - while ((codepoint = ds.Take()) != 0) { - if (isBegin) { - isBegin = false; - if (codepoint == '^') { - negate = true; - continue; - } - } - - switch (codepoint) { - case ']': - if (start == kRegexInvalidRange) - return false; // Error: nothing inside [] - if (step == 2) { // Add trailing '-' - SizeType r = NewRange('-'); - CEREAL_RAPIDJSON_ASSERT(current != kRegexInvalidRange); - GetRange(current).next = r; - } - if (negate) - GetRange(start).start |= kRangeNegationFlag; - *range = start; - return true; - - case '\\': - if (ds.Peek() == 'b') { - ds.Take(); - codepoint = 0x0008; // Escape backspace character - } - else if (!CharacterEscape(ds, &codepoint)) - return false; - // fall through to default - - default: - switch (step) { - case 1: - if (codepoint == '-') { - step++; - break; - } - // fall through to step 0 for other characters - - case 0: - { - SizeType r = NewRange(codepoint); - if (current != kRegexInvalidRange) - GetRange(current).next = r; - if (start == kRegexInvalidRange) - start = r; - current = r; - } - step = 1; - break; - - default: - CEREAL_RAPIDJSON_ASSERT(step == 2); - GetRange(current).end = codepoint; - step = 0; - } - } - } - return false; - } - - SizeType NewRange(unsigned codepoint) { - Range* r = ranges_.template Push(); - r->start = r->end = codepoint; - r->next = kRegexInvalidRange; - return rangeCount_++; - } - - template - bool CharacterEscape(DecodedStream& ds, unsigned* escapedCodepoint) { - unsigned codepoint; - switch (codepoint = ds.Take()) { - case '^': - case '$': - case '|': - case '(': - case ')': - case '?': - case '*': - case '+': - case '.': - case '[': - case ']': - case '{': - case '}': - case '\\': - *escapedCodepoint = codepoint; return true; - case 'f': *escapedCodepoint = 0x000C; return true; - case 'n': *escapedCodepoint = 0x000A; return true; - case 'r': *escapedCodepoint = 0x000D; return true; - case 't': *escapedCodepoint = 0x0009; return true; - case 'v': *escapedCodepoint = 0x000B; return true; - default: - return false; // Unsupported escape character - } - } - - Allocator* ownAllocator_; - Allocator* allocator_; - Stack states_; - Stack ranges_; - SizeType root_; - SizeType stateCount_; - SizeType rangeCount_; - - static const unsigned kInfinityQuantifier = ~0u; - - // For SearchWithAnchoring() - bool anchorBegin_; - bool anchorEnd_; -}; - -template -class GenericRegexSearch { -public: - typedef typename RegexType::EncodingType Encoding; - typedef typename Encoding::Ch Ch; - - GenericRegexSearch(const RegexType& regex, Allocator* allocator = 0) : - regex_(regex), allocator_(allocator), ownAllocator_(0), - state0_(allocator, 0), state1_(allocator, 0), stateSet_() - { - CEREAL_RAPIDJSON_ASSERT(regex_.IsValid()); - if (!allocator_) - ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator)(); - stateSet_ = static_cast(allocator_->Malloc(GetStateSetSize())); - state0_.template Reserve(regex_.stateCount_); - state1_.template Reserve(regex_.stateCount_); - } - - ~GenericRegexSearch() { - Allocator::Free(stateSet_); - CEREAL_RAPIDJSON_DELETE(ownAllocator_); - } - - template - bool Match(InputStream& is) { - return SearchWithAnchoring(is, true, true); - } - - bool Match(const Ch* s) { - GenericStringStream is(s); - return Match(is); - } - - template - bool Search(InputStream& is) { - return SearchWithAnchoring(is, regex_.anchorBegin_, regex_.anchorEnd_); - } - - bool Search(const Ch* s) { - GenericStringStream is(s); - return Search(is); - } - -private: - typedef typename RegexType::State State; - typedef typename RegexType::Range Range; - - template - bool SearchWithAnchoring(InputStream& is, bool anchorBegin, bool anchorEnd) { - DecodedStream ds(is); - - state0_.Clear(); - Stack *current = &state0_, *next = &state1_; - const size_t stateSetSize = GetStateSetSize(); - std::memset(stateSet_, 0, stateSetSize); - - bool matched = AddState(*current, regex_.root_); - unsigned codepoint; - while (!current->Empty() && (codepoint = ds.Take()) != 0) { - std::memset(stateSet_, 0, stateSetSize); - next->Clear(); - matched = false; - for (const SizeType* s = current->template Bottom(); s != current->template End(); ++s) { - const State& sr = regex_.GetState(*s); - if (sr.codepoint == codepoint || - sr.codepoint == RegexType::kAnyCharacterClass || - (sr.codepoint == RegexType::kRangeCharacterClass && MatchRange(sr.rangeStart, codepoint))) - { - matched = AddState(*next, sr.out) || matched; - if (!anchorEnd && matched) - return true; - } - if (!anchorBegin) - AddState(*next, regex_.root_); - } - internal::Swap(current, next); - } - - return matched; - } - - size_t GetStateSetSize() const { - return (regex_.stateCount_ + 31) / 32 * 4; - } - - // Return whether the added states is a match state - bool AddState(Stack& l, SizeType index) { - CEREAL_RAPIDJSON_ASSERT(index != kRegexInvalidState); - - const State& s = regex_.GetState(index); - if (s.out1 != kRegexInvalidState) { // Split - bool matched = AddState(l, s.out); - return AddState(l, s.out1) || matched; - } - else if (!(stateSet_[index >> 5] & (1u << (index & 31)))) { - stateSet_[index >> 5] |= (1u << (index & 31)); - *l.template PushUnsafe() = index; - } - return s.out == kRegexInvalidState; // by using PushUnsafe() above, we can ensure s is not validated due to reallocation. - } - - bool MatchRange(SizeType rangeIndex, unsigned codepoint) const { - bool yes = (regex_.GetRange(rangeIndex).start & RegexType::kRangeNegationFlag) == 0; - while (rangeIndex != kRegexInvalidRange) { - const Range& r = regex_.GetRange(rangeIndex); - if (codepoint >= (r.start & ~RegexType::kRangeNegationFlag) && codepoint <= r.end) - return yes; - rangeIndex = r.next; - } - return !yes; - } - - const RegexType& regex_; - Allocator* allocator_; - Allocator* ownAllocator_; - Stack state0_; - Stack state1_; - uint32_t* stateSet_; -}; - -typedef GenericRegex > Regex; -typedef GenericRegexSearch RegexSearch; - -} // namespace internal -CEREAL_RAPIDJSON_NAMESPACE_END - -#ifdef __GNUC__ -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#if defined(__clang__) || defined(_MSC_VER) -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#endif // CEREAL_RAPIDJSON_INTERNAL_REGEX_H_ diff --git a/include/cereal/external/rapidjson/internal/stack.h b/include/cereal/external/rapidjson/internal/stack.h deleted file mode 100644 index be77088..0000000 --- a/include/cereal/external/rapidjson/internal/stack.h +++ /dev/null @@ -1,232 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_INTERNAL_STACK_H_ -#define CEREAL_RAPIDJSON_INTERNAL_STACK_H_ - -#include "../allocators.h" -#include "swap.h" -#include - -#if defined(__clang__) -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(c++98-compat) -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN -namespace internal { - -/////////////////////////////////////////////////////////////////////////////// -// Stack - -//! A type-unsafe stack for storing different types of data. -/*! \tparam Allocator Allocator for allocating stack memory. -*/ -template -class Stack { -public: - // Optimization note: Do not allocate memory for stack_ in constructor. - // Do it lazily when first Push() -> Expand() -> Resize(). - Stack(Allocator* allocator, size_t stackCapacity) : allocator_(allocator), ownAllocator_(0), stack_(0), stackTop_(0), stackEnd_(0), initialCapacity_(stackCapacity) { - } - -#if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - Stack(Stack&& rhs) - : allocator_(rhs.allocator_), - ownAllocator_(rhs.ownAllocator_), - stack_(rhs.stack_), - stackTop_(rhs.stackTop_), - stackEnd_(rhs.stackEnd_), - initialCapacity_(rhs.initialCapacity_) - { - rhs.allocator_ = 0; - rhs.ownAllocator_ = 0; - rhs.stack_ = 0; - rhs.stackTop_ = 0; - rhs.stackEnd_ = 0; - rhs.initialCapacity_ = 0; - } -#endif - - ~Stack() { - Destroy(); - } - -#if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - Stack& operator=(Stack&& rhs) { - if (&rhs != this) - { - Destroy(); - - allocator_ = rhs.allocator_; - ownAllocator_ = rhs.ownAllocator_; - stack_ = rhs.stack_; - stackTop_ = rhs.stackTop_; - stackEnd_ = rhs.stackEnd_; - initialCapacity_ = rhs.initialCapacity_; - - rhs.allocator_ = 0; - rhs.ownAllocator_ = 0; - rhs.stack_ = 0; - rhs.stackTop_ = 0; - rhs.stackEnd_ = 0; - rhs.initialCapacity_ = 0; - } - return *this; - } -#endif - - void Swap(Stack& rhs) CEREAL_RAPIDJSON_NOEXCEPT { - internal::Swap(allocator_, rhs.allocator_); - internal::Swap(ownAllocator_, rhs.ownAllocator_); - internal::Swap(stack_, rhs.stack_); - internal::Swap(stackTop_, rhs.stackTop_); - internal::Swap(stackEnd_, rhs.stackEnd_); - internal::Swap(initialCapacity_, rhs.initialCapacity_); - } - - void Clear() { stackTop_ = stack_; } - - void ShrinkToFit() { - if (Empty()) { - // If the stack is empty, completely deallocate the memory. - Allocator::Free(stack_); // NOLINT (+clang-analyzer-unix.Malloc) - stack_ = 0; - stackTop_ = 0; - stackEnd_ = 0; - } - else - Resize(GetSize()); - } - - // Optimization note: try to minimize the size of this function for force inline. - // Expansion is run very infrequently, so it is moved to another (probably non-inline) function. - template - CEREAL_RAPIDJSON_FORCEINLINE void Reserve(size_t count = 1) { - // Expand the stack if needed - if (CEREAL_RAPIDJSON_UNLIKELY(static_cast(sizeof(T) * count) > (stackEnd_ - stackTop_))) - Expand(count); - } - - template - CEREAL_RAPIDJSON_FORCEINLINE T* Push(size_t count = 1) { - Reserve(count); - return PushUnsafe(count); - } - - template - CEREAL_RAPIDJSON_FORCEINLINE T* PushUnsafe(size_t count = 1) { - CEREAL_RAPIDJSON_ASSERT(stackTop_); - CEREAL_RAPIDJSON_ASSERT(static_cast(sizeof(T) * count) <= (stackEnd_ - stackTop_)); - T* ret = reinterpret_cast(stackTop_); - stackTop_ += sizeof(T) * count; - return ret; - } - - template - T* Pop(size_t count) { - CEREAL_RAPIDJSON_ASSERT(GetSize() >= count * sizeof(T)); - stackTop_ -= count * sizeof(T); - return reinterpret_cast(stackTop_); - } - - template - T* Top() { - CEREAL_RAPIDJSON_ASSERT(GetSize() >= sizeof(T)); - return reinterpret_cast(stackTop_ - sizeof(T)); - } - - template - const T* Top() const { - CEREAL_RAPIDJSON_ASSERT(GetSize() >= sizeof(T)); - return reinterpret_cast(stackTop_ - sizeof(T)); - } - - template - T* End() { return reinterpret_cast(stackTop_); } - - template - const T* End() const { return reinterpret_cast(stackTop_); } - - template - T* Bottom() { return reinterpret_cast(stack_); } - - template - const T* Bottom() const { return reinterpret_cast(stack_); } - - bool HasAllocator() const { - return allocator_ != 0; - } - - Allocator& GetAllocator() { - CEREAL_RAPIDJSON_ASSERT(allocator_); - return *allocator_; - } - - bool Empty() const { return stackTop_ == stack_; } - size_t GetSize() const { return static_cast(stackTop_ - stack_); } - size_t GetCapacity() const { return static_cast(stackEnd_ - stack_); } - -private: - template - void Expand(size_t count) { - // Only expand the capacity if the current stack exists. Otherwise just create a stack with initial capacity. - size_t newCapacity; - if (stack_ == 0) { - if (!allocator_) - ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator)(); - newCapacity = initialCapacity_; - } else { - newCapacity = GetCapacity(); - newCapacity += (newCapacity + 1) / 2; - } - size_t newSize = GetSize() + sizeof(T) * count; - if (newCapacity < newSize) - newCapacity = newSize; - - Resize(newCapacity); - } - - void Resize(size_t newCapacity) { - const size_t size = GetSize(); // Backup the current size - stack_ = static_cast(allocator_->Realloc(stack_, GetCapacity(), newCapacity)); - stackTop_ = stack_ + size; - stackEnd_ = stack_ + newCapacity; - } - - void Destroy() { - Allocator::Free(stack_); - CEREAL_RAPIDJSON_DELETE(ownAllocator_); // Only delete if it is owned by the stack - } - - // Prohibit copy constructor & assignment operator. - Stack(const Stack&); - Stack& operator=(const Stack&); - - Allocator* allocator_; - Allocator* ownAllocator_; - char *stack_; - char *stackTop_; - char *stackEnd_; - size_t initialCapacity_; -}; - -} // namespace internal -CEREAL_RAPIDJSON_NAMESPACE_END - -#if defined(__clang__) -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#endif // CEREAL_RAPIDJSON_STACK_H_ diff --git a/include/cereal/external/rapidjson/internal/strfunc.h b/include/cereal/external/rapidjson/internal/strfunc.h deleted file mode 100644 index 44af229..0000000 --- a/include/cereal/external/rapidjson/internal/strfunc.h +++ /dev/null @@ -1,69 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_INTERNAL_STRFUNC_H_ -#define CEREAL_RAPIDJSON_INTERNAL_STRFUNC_H_ - -#include "../stream.h" -#include - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN -namespace internal { - -//! Custom strlen() which works on different character types. -/*! \tparam Ch Character type (e.g. char, wchar_t, short) - \param s Null-terminated input string. - \return Number of characters in the string. - \note This has the same semantics as strlen(), the return value is not number of Unicode codepoints. -*/ -template -inline SizeType StrLen(const Ch* s) { - CEREAL_RAPIDJSON_ASSERT(s != 0); - const Ch* p = s; - while (*p) ++p; - return SizeType(p - s); -} - -template <> -inline SizeType StrLen(const char* s) { - return SizeType(std::strlen(s)); -} - -template <> -inline SizeType StrLen(const wchar_t* s) { - return SizeType(std::wcslen(s)); -} - -//! Returns number of code points in a encoded string. -template -bool CountStringCodePoint(const typename Encoding::Ch* s, SizeType length, SizeType* outCount) { - CEREAL_RAPIDJSON_ASSERT(s != 0); - CEREAL_RAPIDJSON_ASSERT(outCount != 0); - GenericStringStream is(s); - const typename Encoding::Ch* end = s + length; - SizeType count = 0; - while (is.src_ < end) { - unsigned codepoint; - if (!Encoding::Decode(is, &codepoint)) - return false; - count++; - } - *outCount = count; - return true; -} - -} // namespace internal -CEREAL_RAPIDJSON_NAMESPACE_END - -#endif // CEREAL_RAPIDJSON_INTERNAL_STRFUNC_H_ diff --git a/include/cereal/external/rapidjson/internal/strtod.h b/include/cereal/external/rapidjson/internal/strtod.h deleted file mode 100644 index d60c740..0000000 --- a/include/cereal/external/rapidjson/internal/strtod.h +++ /dev/null @@ -1,290 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_STRTOD_ -#define CEREAL_RAPIDJSON_STRTOD_ - -#include "ieee754.h" -#include "biginteger.h" -#include "diyfp.h" -#include "pow10.h" -#include -#include - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN -namespace internal { - -inline double FastPath(double significand, int exp) { - if (exp < -308) - return 0.0; - else if (exp >= 0) - return significand * internal::Pow10(exp); - else - return significand / internal::Pow10(-exp); -} - -inline double StrtodNormalPrecision(double d, int p) { - if (p < -308) { - // Prevent expSum < -308, making Pow10(p) = 0 - d = FastPath(d, -308); - d = FastPath(d, p + 308); - } - else - d = FastPath(d, p); - return d; -} - -template -inline T Min3(T a, T b, T c) { - T m = a; - if (m > b) m = b; - if (m > c) m = c; - return m; -} - -inline int CheckWithinHalfULP(double b, const BigInteger& d, int dExp) { - const Double db(b); - const uint64_t bInt = db.IntegerSignificand(); - const int bExp = db.IntegerExponent(); - const int hExp = bExp - 1; - - int dS_Exp2 = 0, dS_Exp5 = 0, bS_Exp2 = 0, bS_Exp5 = 0, hS_Exp2 = 0, hS_Exp5 = 0; - - // Adjust for decimal exponent - if (dExp >= 0) { - dS_Exp2 += dExp; - dS_Exp5 += dExp; - } - else { - bS_Exp2 -= dExp; - bS_Exp5 -= dExp; - hS_Exp2 -= dExp; - hS_Exp5 -= dExp; - } - - // Adjust for binary exponent - if (bExp >= 0) - bS_Exp2 += bExp; - else { - dS_Exp2 -= bExp; - hS_Exp2 -= bExp; - } - - // Adjust for half ulp exponent - if (hExp >= 0) - hS_Exp2 += hExp; - else { - dS_Exp2 -= hExp; - bS_Exp2 -= hExp; - } - - // Remove common power of two factor from all three scaled values - int common_Exp2 = Min3(dS_Exp2, bS_Exp2, hS_Exp2); - dS_Exp2 -= common_Exp2; - bS_Exp2 -= common_Exp2; - hS_Exp2 -= common_Exp2; - - BigInteger dS = d; - dS.MultiplyPow5(static_cast(dS_Exp5)) <<= static_cast(dS_Exp2); - - BigInteger bS(bInt); - bS.MultiplyPow5(static_cast(bS_Exp5)) <<= static_cast(bS_Exp2); - - BigInteger hS(1); - hS.MultiplyPow5(static_cast(hS_Exp5)) <<= static_cast(hS_Exp2); - - BigInteger delta(0); - dS.Difference(bS, &delta); - - return delta.Compare(hS); -} - -inline bool StrtodFast(double d, int p, double* result) { - // Use fast path for string-to-double conversion if possible - // see http://www.exploringbinary.com/fast-path-decimal-to-floating-point-conversion/ - if (p > 22 && p < 22 + 16) { - // Fast Path Cases In Disguise - d *= internal::Pow10(p - 22); - p = 22; - } - - if (p >= -22 && p <= 22 && d <= 9007199254740991.0) { // 2^53 - 1 - *result = FastPath(d, p); - return true; - } - else - return false; -} - -// Compute an approximation and see if it is within 1/2 ULP -inline bool StrtodDiyFp(const char* decimals, int dLen, int dExp, double* result) { - uint64_t significand = 0; - int i = 0; // 2^64 - 1 = 18446744073709551615, 1844674407370955161 = 0x1999999999999999 - for (; i < dLen; i++) { - if (significand > CEREAL_RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) || - (significand == CEREAL_RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) && decimals[i] > '5')) - break; - significand = significand * 10u + static_cast(decimals[i] - '0'); - } - - if (i < dLen && decimals[i] >= '5') // Rounding - significand++; - - int remaining = dLen - i; - const int kUlpShift = 3; - const int kUlp = 1 << kUlpShift; - int64_t error = (remaining == 0) ? 0 : kUlp / 2; - - DiyFp v(significand, 0); - v = v.Normalize(); - error <<= -v.e; - - dExp += remaining; - - int actualExp; - DiyFp cachedPower = GetCachedPower10(dExp, &actualExp); - if (actualExp != dExp) { - static const DiyFp kPow10[] = { - DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0xa0000000, 0x00000000), -60), // 10^1 - DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0xc8000000, 0x00000000), -57), // 10^2 - DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0xfa000000, 0x00000000), -54), // 10^3 - DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0x9c400000, 0x00000000), -50), // 10^4 - DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0xc3500000, 0x00000000), -47), // 10^5 - DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0xf4240000, 0x00000000), -44), // 10^6 - DiyFp(CEREAL_RAPIDJSON_UINT64_C2(0x98968000, 0x00000000), -40) // 10^7 - }; - int adjustment = dExp - actualExp; - CEREAL_RAPIDJSON_ASSERT(adjustment >= 1 && adjustment < 8); - v = v * kPow10[adjustment - 1]; - if (dLen + adjustment > 19) // has more digits than decimal digits in 64-bit - error += kUlp / 2; - } - - v = v * cachedPower; - - error += kUlp + (error == 0 ? 0 : 1); - - const int oldExp = v.e; - v = v.Normalize(); - error <<= oldExp - v.e; - - const int effectiveSignificandSize = Double::EffectiveSignificandSize(64 + v.e); - int precisionSize = 64 - effectiveSignificandSize; - if (precisionSize + kUlpShift >= 64) { - int scaleExp = (precisionSize + kUlpShift) - 63; - v.f >>= scaleExp; - v.e += scaleExp; - error = (error >> scaleExp) + 1 + kUlp; - precisionSize -= scaleExp; - } - - DiyFp rounded(v.f >> precisionSize, v.e + precisionSize); - const uint64_t precisionBits = (v.f & ((uint64_t(1) << precisionSize) - 1)) * kUlp; - const uint64_t halfWay = (uint64_t(1) << (precisionSize - 1)) * kUlp; - if (precisionBits >= halfWay + static_cast(error)) { - rounded.f++; - if (rounded.f & (DiyFp::kDpHiddenBit << 1)) { // rounding overflows mantissa (issue #340) - rounded.f >>= 1; - rounded.e++; - } - } - - *result = rounded.ToDouble(); - - return halfWay - static_cast(error) >= precisionBits || precisionBits >= halfWay + static_cast(error); -} - -inline double StrtodBigInteger(double approx, const char* decimals, int dLen, int dExp) { - CEREAL_RAPIDJSON_ASSERT(dLen >= 0); - const BigInteger dInt(decimals, static_cast(dLen)); - Double a(approx); - int cmp = CheckWithinHalfULP(a.Value(), dInt, dExp); - if (cmp < 0) - return a.Value(); // within half ULP - else if (cmp == 0) { - // Round towards even - if (a.Significand() & 1) - return a.NextPositiveDouble(); - else - return a.Value(); - } - else // adjustment - return a.NextPositiveDouble(); -} - -inline double StrtodFullPrecision(double d, int p, const char* decimals, size_t length, size_t decimalPosition, int exp) { - CEREAL_RAPIDJSON_ASSERT(d >= 0.0); - CEREAL_RAPIDJSON_ASSERT(length >= 1); - - double result = 0.0; - if (StrtodFast(d, p, &result)) - return result; - - CEREAL_RAPIDJSON_ASSERT(length <= INT_MAX); - int dLen = static_cast(length); - - CEREAL_RAPIDJSON_ASSERT(length >= decimalPosition); - CEREAL_RAPIDJSON_ASSERT(length - decimalPosition <= INT_MAX); - int dExpAdjust = static_cast(length - decimalPosition); - - CEREAL_RAPIDJSON_ASSERT(exp >= INT_MIN + dExpAdjust); - int dExp = exp - dExpAdjust; - - // Make sure length+dExp does not overflow - CEREAL_RAPIDJSON_ASSERT(dExp <= INT_MAX - dLen); - - // Trim leading zeros - while (dLen > 0 && *decimals == '0') { - dLen--; - decimals++; - } - - // Trim trailing zeros - while (dLen > 0 && decimals[dLen - 1] == '0') { - dLen--; - dExp++; - } - - if (dLen == 0) { // Buffer only contains zeros. - return 0.0; - } - - // Trim right-most digits - const int kMaxDecimalDigit = 767 + 1; - if (dLen > kMaxDecimalDigit) { - dExp += dLen - kMaxDecimalDigit; - dLen = kMaxDecimalDigit; - } - - // If too small, underflow to zero. - // Any x <= 10^-324 is interpreted as zero. - if (dLen + dExp <= -324) - return 0.0; - - // If too large, overflow to infinity. - // Any x >= 10^309 is interpreted as +infinity. - if (dLen + dExp > 309) - return std::numeric_limits::infinity(); - - if (StrtodDiyFp(decimals, dLen, dExp, &result)) - return result; - - // Use approximation from StrtodDiyFp and make adjustment with BigInteger comparison - return StrtodBigInteger(result, decimals, dLen, dExp); -} - -} // namespace internal -CEREAL_RAPIDJSON_NAMESPACE_END - -#endif // CEREAL_RAPIDJSON_STRTOD_ diff --git a/include/cereal/external/rapidjson/internal/swap.h b/include/cereal/external/rapidjson/internal/swap.h deleted file mode 100644 index 5d8910c..0000000 --- a/include/cereal/external/rapidjson/internal/swap.h +++ /dev/null @@ -1,46 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_INTERNAL_SWAP_H_ -#define CEREAL_RAPIDJSON_INTERNAL_SWAP_H_ - -#include "../rapidjson.h" - -#if defined(__clang__) -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(c++98-compat) -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN -namespace internal { - -//! Custom swap() to avoid dependency on C++ header -/*! \tparam T Type of the arguments to swap, should be instantiated with primitive C++ types only. - \note This has the same semantics as std::swap(). -*/ -template -inline void Swap(T& a, T& b) CEREAL_RAPIDJSON_NOEXCEPT { - T tmp = a; - a = b; - b = tmp; -} - -} // namespace internal -CEREAL_RAPIDJSON_NAMESPACE_END - -#if defined(__clang__) -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#endif // CEREAL_RAPIDJSON_INTERNAL_SWAP_H_ diff --git a/include/cereal/external/rapidjson/istreamwrapper.h b/include/cereal/external/rapidjson/istreamwrapper.h deleted file mode 100644 index 4df7ce3..0000000 --- a/include/cereal/external/rapidjson/istreamwrapper.h +++ /dev/null @@ -1,128 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_ISTREAMWRAPPER_H_ -#define CEREAL_RAPIDJSON_ISTREAMWRAPPER_H_ - -#include "stream.h" -#include -#include - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(padded) -#elif defined(_MSC_VER) -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(4351) // new behavior: elements of array 'array' will be default initialized -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -//! Wrapper of \c std::basic_istream into RapidJSON's Stream concept. -/*! - The classes can be wrapped including but not limited to: - - - \c std::istringstream - - \c std::stringstream - - \c std::wistringstream - - \c std::wstringstream - - \c std::ifstream - - \c std::fstream - - \c std::wifstream - - \c std::wfstream - - \tparam StreamType Class derived from \c std::basic_istream. -*/ - -template -class BasicIStreamWrapper { -public: - typedef typename StreamType::char_type Ch; - - //! Constructor. - /*! - \param stream stream opened for read. - */ - BasicIStreamWrapper(StreamType &stream) : stream_(stream), buffer_(peekBuffer_), bufferSize_(4), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) { - Read(); - } - - //! Constructor. - /*! - \param stream stream opened for read. - \param buffer user-supplied buffer. - \param bufferSize size of buffer in bytes. Must >=4 bytes. - */ - BasicIStreamWrapper(StreamType &stream, char* buffer, size_t bufferSize) : stream_(stream), buffer_(buffer), bufferSize_(bufferSize), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) { - CEREAL_RAPIDJSON_ASSERT(bufferSize >= 4); - Read(); - } - - Ch Peek() const { return *current_; } - Ch Take() { Ch c = *current_; Read(); return c; } - size_t Tell() const { return count_ + static_cast(current_ - buffer_); } - - // Not implemented - void Put(Ch) { CEREAL_RAPIDJSON_ASSERT(false); } - void Flush() { CEREAL_RAPIDJSON_ASSERT(false); } - Ch* PutBegin() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - size_t PutEnd(Ch*) { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - - // For encoding detection only. - const Ch* Peek4() const { - return (current_ + 4 - !eof_ <= bufferLast_) ? current_ : 0; - } - -private: - BasicIStreamWrapper(); - BasicIStreamWrapper(const BasicIStreamWrapper&); - BasicIStreamWrapper& operator=(const BasicIStreamWrapper&); - - void Read() { - if (current_ < bufferLast_) - ++current_; - else if (!eof_) { - count_ += readCount_; - readCount_ = bufferSize_; - bufferLast_ = buffer_ + readCount_ - 1; - current_ = buffer_; - - if (!stream_.read(buffer_, static_cast(bufferSize_))) { - readCount_ = static_cast(stream_.gcount()); - *(bufferLast_ = buffer_ + readCount_) = '\0'; - eof_ = true; - } - } - } - - StreamType &stream_; - Ch peekBuffer_[4], *buffer_; - size_t bufferSize_; - Ch *bufferLast_; - Ch *current_; - size_t readCount_; - size_t count_; //!< Number of characters read - bool eof_; -}; - -typedef BasicIStreamWrapper IStreamWrapper; -typedef BasicIStreamWrapper WIStreamWrapper; - -#if defined(__clang__) || defined(_MSC_VER) -CEREAL_RAPIDJSON_DIAG_POP -#endif - -CEREAL_RAPIDJSON_NAMESPACE_END - -#endif // CEREAL_RAPIDJSON_ISTREAMWRAPPER_H_ diff --git a/include/cereal/external/rapidjson/memorybuffer.h b/include/cereal/external/rapidjson/memorybuffer.h deleted file mode 100644 index 0cd75cf..0000000 --- a/include/cereal/external/rapidjson/memorybuffer.h +++ /dev/null @@ -1,70 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_MEMORYBUFFER_H_ -#define CEREAL_RAPIDJSON_MEMORYBUFFER_H_ - -#include "stream.h" -#include "internal/stack.h" - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -//! Represents an in-memory output byte stream. -/*! - This class is mainly for being wrapped by EncodedOutputStream or AutoUTFOutputStream. - - It is similar to FileWriteBuffer but the destination is an in-memory buffer instead of a file. - - Differences between MemoryBuffer and StringBuffer: - 1. StringBuffer has Encoding but MemoryBuffer is only a byte buffer. - 2. StringBuffer::GetString() returns a null-terminated string. MemoryBuffer::GetBuffer() returns a buffer without terminator. - - \tparam Allocator type for allocating memory buffer. - \note implements Stream concept -*/ -template -struct GenericMemoryBuffer { - typedef char Ch; // byte - - GenericMemoryBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {} - - void Put(Ch c) { *stack_.template Push() = c; } - void Flush() {} - - void Clear() { stack_.Clear(); } - void ShrinkToFit() { stack_.ShrinkToFit(); } - Ch* Push(size_t count) { return stack_.template Push(count); } - void Pop(size_t count) { stack_.template Pop(count); } - - const Ch* GetBuffer() const { - return stack_.template Bottom(); - } - - size_t GetSize() const { return stack_.GetSize(); } - - static const size_t kDefaultCapacity = 256; - mutable internal::Stack stack_; -}; - -typedef GenericMemoryBuffer<> MemoryBuffer; - -//! Implement specialized version of PutN() with memset() for better performance. -template<> -inline void PutN(MemoryBuffer& memoryBuffer, char c, size_t n) { - std::memset(memoryBuffer.stack_.Push(n), c, n * sizeof(c)); -} - -CEREAL_RAPIDJSON_NAMESPACE_END - -#endif // CEREAL_RAPIDJSON_MEMORYBUFFER_H_ diff --git a/include/cereal/external/rapidjson/memorystream.h b/include/cereal/external/rapidjson/memorystream.h deleted file mode 100644 index 326bda5..0000000 --- a/include/cereal/external/rapidjson/memorystream.h +++ /dev/null @@ -1,71 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_MEMORYSTREAM_H_ -#define CEREAL_RAPIDJSON_MEMORYSTREAM_H_ - -#include "stream.h" - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(unreachable-code) -CEREAL_RAPIDJSON_DIAG_OFF(missing-noreturn) -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -//! Represents an in-memory input byte stream. -/*! - This class is mainly for being wrapped by EncodedInputStream or AutoUTFInputStream. - - It is similar to FileReadBuffer but the source is an in-memory buffer instead of a file. - - Differences between MemoryStream and StringStream: - 1. StringStream has encoding but MemoryStream is a byte stream. - 2. MemoryStream needs size of the source buffer and the buffer don't need to be null terminated. StringStream assume null-terminated string as source. - 3. MemoryStream supports Peek4() for encoding detection. StringStream is specified with an encoding so it should not have Peek4(). - \note implements Stream concept -*/ -struct MemoryStream { - typedef char Ch; // byte - - MemoryStream(const Ch *src, size_t size) : src_(src), begin_(src), end_(src + size), size_(size) {} - - Ch Peek() const { return CEREAL_RAPIDJSON_UNLIKELY(src_ == end_) ? '\0' : *src_; } - Ch Take() { return CEREAL_RAPIDJSON_UNLIKELY(src_ == end_) ? '\0' : *src_++; } - size_t Tell() const { return static_cast(src_ - begin_); } - - Ch* PutBegin() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - void Put(Ch) { CEREAL_RAPIDJSON_ASSERT(false); } - void Flush() { CEREAL_RAPIDJSON_ASSERT(false); } - size_t PutEnd(Ch*) { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - - // For encoding detection only. - const Ch* Peek4() const { - return Tell() + 4 <= size_ ? src_ : 0; - } - - const Ch* src_; //!< Current read position. - const Ch* begin_; //!< Original head of the string. - const Ch* end_; //!< End of stream. - size_t size_; //!< Size of the stream. -}; - -CEREAL_RAPIDJSON_NAMESPACE_END - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#endif // CEREAL_RAPIDJSON_MEMORYBUFFER_H_ diff --git a/include/cereal/external/rapidjson/msinttypes/LICENSE b/include/cereal/external/rapidjson/msinttypes/LICENSE deleted file mode 100644 index e3d96f8..0000000 --- a/include/cereal/external/rapidjson/msinttypes/LICENSE +++ /dev/null @@ -1,29 +0,0 @@ -ISO C9x compliant stdint.h for Microsoft Visual Studio -Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 - - Copyright (c) 2006-2013 Alexander Chemeris - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - 3. Neither the name of the product nor the names of its contributors may - be used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/include/cereal/external/rapidjson/msinttypes/inttypes.h b/include/cereal/external/rapidjson/msinttypes/inttypes.h deleted file mode 100644 index 1811128..0000000 --- a/include/cereal/external/rapidjson/msinttypes/inttypes.h +++ /dev/null @@ -1,316 +0,0 @@ -// ISO C9x compliant inttypes.h for Microsoft Visual Studio -// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 -// -// Copyright (c) 2006-2013 Alexander Chemeris -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the product nor the names of its contributors may -// be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -/////////////////////////////////////////////////////////////////////////////// - -// The above software in this distribution may have been modified by -// THL A29 Limited ("Tencent Modifications"). -// All Tencent Modifications are Copyright (C) 2015 THL A29 Limited. - -#ifndef _MSC_VER // [ -#error "Use this header only with Microsoft Visual C++ compilers!" -#endif // _MSC_VER ] - -#ifndef _MSC_INTTYPES_H_ // [ -#define _MSC_INTTYPES_H_ - -#if _MSC_VER > 1000 -#pragma once -#endif - -#include "stdint.h" - -// miloyip: VC supports inttypes.h since VC2013 -#if _MSC_VER >= 1800 -#include -#else - -// 7.8 Format conversion of integer types - -typedef struct { - intmax_t quot; - intmax_t rem; -} imaxdiv_t; - -// 7.8.1 Macros for format specifiers - -#if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS) // [ See footnote 185 at page 198 - -// The fprintf macros for signed integers are: -#define PRId8 "d" -#define PRIi8 "i" -#define PRIdLEAST8 "d" -#define PRIiLEAST8 "i" -#define PRIdFAST8 "d" -#define PRIiFAST8 "i" - -#define PRId16 "hd" -#define PRIi16 "hi" -#define PRIdLEAST16 "hd" -#define PRIiLEAST16 "hi" -#define PRIdFAST16 "hd" -#define PRIiFAST16 "hi" - -#define PRId32 "I32d" -#define PRIi32 "I32i" -#define PRIdLEAST32 "I32d" -#define PRIiLEAST32 "I32i" -#define PRIdFAST32 "I32d" -#define PRIiFAST32 "I32i" - -#define PRId64 "I64d" -#define PRIi64 "I64i" -#define PRIdLEAST64 "I64d" -#define PRIiLEAST64 "I64i" -#define PRIdFAST64 "I64d" -#define PRIiFAST64 "I64i" - -#define PRIdMAX "I64d" -#define PRIiMAX "I64i" - -#define PRIdPTR "Id" -#define PRIiPTR "Ii" - -// The fprintf macros for unsigned integers are: -#define PRIo8 "o" -#define PRIu8 "u" -#define PRIx8 "x" -#define PRIX8 "X" -#define PRIoLEAST8 "o" -#define PRIuLEAST8 "u" -#define PRIxLEAST8 "x" -#define PRIXLEAST8 "X" -#define PRIoFAST8 "o" -#define PRIuFAST8 "u" -#define PRIxFAST8 "x" -#define PRIXFAST8 "X" - -#define PRIo16 "ho" -#define PRIu16 "hu" -#define PRIx16 "hx" -#define PRIX16 "hX" -#define PRIoLEAST16 "ho" -#define PRIuLEAST16 "hu" -#define PRIxLEAST16 "hx" -#define PRIXLEAST16 "hX" -#define PRIoFAST16 "ho" -#define PRIuFAST16 "hu" -#define PRIxFAST16 "hx" -#define PRIXFAST16 "hX" - -#define PRIo32 "I32o" -#define PRIu32 "I32u" -#define PRIx32 "I32x" -#define PRIX32 "I32X" -#define PRIoLEAST32 "I32o" -#define PRIuLEAST32 "I32u" -#define PRIxLEAST32 "I32x" -#define PRIXLEAST32 "I32X" -#define PRIoFAST32 "I32o" -#define PRIuFAST32 "I32u" -#define PRIxFAST32 "I32x" -#define PRIXFAST32 "I32X" - -#define PRIo64 "I64o" -#define PRIu64 "I64u" -#define PRIx64 "I64x" -#define PRIX64 "I64X" -#define PRIoLEAST64 "I64o" -#define PRIuLEAST64 "I64u" -#define PRIxLEAST64 "I64x" -#define PRIXLEAST64 "I64X" -#define PRIoFAST64 "I64o" -#define PRIuFAST64 "I64u" -#define PRIxFAST64 "I64x" -#define PRIXFAST64 "I64X" - -#define PRIoMAX "I64o" -#define PRIuMAX "I64u" -#define PRIxMAX "I64x" -#define PRIXMAX "I64X" - -#define PRIoPTR "Io" -#define PRIuPTR "Iu" -#define PRIxPTR "Ix" -#define PRIXPTR "IX" - -// The fscanf macros for signed integers are: -#define SCNd8 "d" -#define SCNi8 "i" -#define SCNdLEAST8 "d" -#define SCNiLEAST8 "i" -#define SCNdFAST8 "d" -#define SCNiFAST8 "i" - -#define SCNd16 "hd" -#define SCNi16 "hi" -#define SCNdLEAST16 "hd" -#define SCNiLEAST16 "hi" -#define SCNdFAST16 "hd" -#define SCNiFAST16 "hi" - -#define SCNd32 "ld" -#define SCNi32 "li" -#define SCNdLEAST32 "ld" -#define SCNiLEAST32 "li" -#define SCNdFAST32 "ld" -#define SCNiFAST32 "li" - -#define SCNd64 "I64d" -#define SCNi64 "I64i" -#define SCNdLEAST64 "I64d" -#define SCNiLEAST64 "I64i" -#define SCNdFAST64 "I64d" -#define SCNiFAST64 "I64i" - -#define SCNdMAX "I64d" -#define SCNiMAX "I64i" - -#ifdef _WIN64 // [ -# define SCNdPTR "I64d" -# define SCNiPTR "I64i" -#else // _WIN64 ][ -# define SCNdPTR "ld" -# define SCNiPTR "li" -#endif // _WIN64 ] - -// The fscanf macros for unsigned integers are: -#define SCNo8 "o" -#define SCNu8 "u" -#define SCNx8 "x" -#define SCNX8 "X" -#define SCNoLEAST8 "o" -#define SCNuLEAST8 "u" -#define SCNxLEAST8 "x" -#define SCNXLEAST8 "X" -#define SCNoFAST8 "o" -#define SCNuFAST8 "u" -#define SCNxFAST8 "x" -#define SCNXFAST8 "X" - -#define SCNo16 "ho" -#define SCNu16 "hu" -#define SCNx16 "hx" -#define SCNX16 "hX" -#define SCNoLEAST16 "ho" -#define SCNuLEAST16 "hu" -#define SCNxLEAST16 "hx" -#define SCNXLEAST16 "hX" -#define SCNoFAST16 "ho" -#define SCNuFAST16 "hu" -#define SCNxFAST16 "hx" -#define SCNXFAST16 "hX" - -#define SCNo32 "lo" -#define SCNu32 "lu" -#define SCNx32 "lx" -#define SCNX32 "lX" -#define SCNoLEAST32 "lo" -#define SCNuLEAST32 "lu" -#define SCNxLEAST32 "lx" -#define SCNXLEAST32 "lX" -#define SCNoFAST32 "lo" -#define SCNuFAST32 "lu" -#define SCNxFAST32 "lx" -#define SCNXFAST32 "lX" - -#define SCNo64 "I64o" -#define SCNu64 "I64u" -#define SCNx64 "I64x" -#define SCNX64 "I64X" -#define SCNoLEAST64 "I64o" -#define SCNuLEAST64 "I64u" -#define SCNxLEAST64 "I64x" -#define SCNXLEAST64 "I64X" -#define SCNoFAST64 "I64o" -#define SCNuFAST64 "I64u" -#define SCNxFAST64 "I64x" -#define SCNXFAST64 "I64X" - -#define SCNoMAX "I64o" -#define SCNuMAX "I64u" -#define SCNxMAX "I64x" -#define SCNXMAX "I64X" - -#ifdef _WIN64 // [ -# define SCNoPTR "I64o" -# define SCNuPTR "I64u" -# define SCNxPTR "I64x" -# define SCNXPTR "I64X" -#else // _WIN64 ][ -# define SCNoPTR "lo" -# define SCNuPTR "lu" -# define SCNxPTR "lx" -# define SCNXPTR "lX" -#endif // _WIN64 ] - -#endif // __STDC_FORMAT_MACROS ] - -// 7.8.2 Functions for greatest-width integer types - -// 7.8.2.1 The imaxabs function -#define imaxabs _abs64 - -// 7.8.2.2 The imaxdiv function - -// This is modified version of div() function from Microsoft's div.c found -// in %MSVC.NET%\crt\src\div.c -#ifdef STATIC_IMAXDIV // [ -static -#else // STATIC_IMAXDIV ][ -_inline -#endif // STATIC_IMAXDIV ] -imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom) -{ - imaxdiv_t result; - - result.quot = numer / denom; - result.rem = numer % denom; - - if (numer < 0 && result.rem > 0) { - // did division wrong; must fix up - ++result.quot; - result.rem -= denom; - } - - return result; -} - -// 7.8.2.3 The strtoimax and strtoumax functions -#define strtoimax _strtoi64 -#define strtoumax _strtoui64 - -// 7.8.2.4 The wcstoimax and wcstoumax functions -#define wcstoimax _wcstoi64 -#define wcstoumax _wcstoui64 - -#endif // _MSC_VER >= 1800 - -#endif // _MSC_INTTYPES_H_ ] diff --git a/include/cereal/external/rapidjson/msinttypes/stdint.h b/include/cereal/external/rapidjson/msinttypes/stdint.h deleted file mode 100644 index 3d4477b..0000000 --- a/include/cereal/external/rapidjson/msinttypes/stdint.h +++ /dev/null @@ -1,300 +0,0 @@ -// ISO C9x compliant stdint.h for Microsoft Visual Studio -// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 -// -// Copyright (c) 2006-2013 Alexander Chemeris -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the product nor the names of its contributors may -// be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -/////////////////////////////////////////////////////////////////////////////// - -// The above software in this distribution may have been modified by -// THL A29 Limited ("Tencent Modifications"). -// All Tencent Modifications are Copyright (C) 2015 THL A29 Limited. - -#ifndef _MSC_VER // [ -#error "Use this header only with Microsoft Visual C++ compilers!" -#endif // _MSC_VER ] - -#ifndef _MSC_STDINT_H_ // [ -#define _MSC_STDINT_H_ - -#if _MSC_VER > 1000 -#pragma once -#endif - -// miloyip: Originally Visual Studio 2010 uses its own stdint.h. However it generates warning with INT64_C(), so change to use this file for vs2010. -#if _MSC_VER >= 1600 // [ -#include - -#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 - -#undef INT8_C -#undef INT16_C -#undef INT32_C -#undef INT64_C -#undef UINT8_C -#undef UINT16_C -#undef UINT32_C -#undef UINT64_C - -// 7.18.4.1 Macros for minimum-width integer constants - -#define INT8_C(val) val##i8 -#define INT16_C(val) val##i16 -#define INT32_C(val) val##i32 -#define INT64_C(val) val##i64 - -#define UINT8_C(val) val##ui8 -#define UINT16_C(val) val##ui16 -#define UINT32_C(val) val##ui32 -#define UINT64_C(val) val##ui64 - -// 7.18.4.2 Macros for greatest-width integer constants -// These #ifndef's are needed to prevent collisions with . -// Check out Issue 9 for the details. -#ifndef INTMAX_C // [ -# define INTMAX_C INT64_C -#endif // INTMAX_C ] -#ifndef UINTMAX_C // [ -# define UINTMAX_C UINT64_C -#endif // UINTMAX_C ] - -#endif // __STDC_CONSTANT_MACROS ] - -#else // ] _MSC_VER >= 1700 [ - -#include - -// For Visual Studio 6 in C++ mode and for many Visual Studio versions when -// compiling for ARM we have to wrap include with 'extern "C++" {}' -// or compiler would give many errors like this: -// error C2733: second C linkage of overloaded function 'wmemchr' not allowed -#if defined(__cplusplus) && !defined(_M_ARM) -extern "C" { -#endif -# include -#if defined(__cplusplus) && !defined(_M_ARM) -} -#endif - -// Define _W64 macros to mark types changing their size, like intptr_t. -#ifndef _W64 -# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 -# define _W64 __w64 -# else -# define _W64 -# endif -#endif - - -// 7.18.1 Integer types - -// 7.18.1.1 Exact-width integer types - -// Visual Studio 6 and Embedded Visual C++ 4 doesn't -// realize that, e.g. char has the same size as __int8 -// so we give up on __intX for them. -#if (_MSC_VER < 1300) - typedef signed char int8_t; - typedef signed short int16_t; - typedef signed int int32_t; - typedef unsigned char uint8_t; - typedef unsigned short uint16_t; - typedef unsigned int uint32_t; -#else - typedef signed __int8 int8_t; - typedef signed __int16 int16_t; - typedef signed __int32 int32_t; - typedef unsigned __int8 uint8_t; - typedef unsigned __int16 uint16_t; - typedef unsigned __int32 uint32_t; -#endif -typedef signed __int64 int64_t; -typedef unsigned __int64 uint64_t; - - -// 7.18.1.2 Minimum-width integer types -typedef int8_t int_least8_t; -typedef int16_t int_least16_t; -typedef int32_t int_least32_t; -typedef int64_t int_least64_t; -typedef uint8_t uint_least8_t; -typedef uint16_t uint_least16_t; -typedef uint32_t uint_least32_t; -typedef uint64_t uint_least64_t; - -// 7.18.1.3 Fastest minimum-width integer types -typedef int8_t int_fast8_t; -typedef int16_t int_fast16_t; -typedef int32_t int_fast32_t; -typedef int64_t int_fast64_t; -typedef uint8_t uint_fast8_t; -typedef uint16_t uint_fast16_t; -typedef uint32_t uint_fast32_t; -typedef uint64_t uint_fast64_t; - -// 7.18.1.4 Integer types capable of holding object pointers -#ifdef _WIN64 // [ - typedef signed __int64 intptr_t; - typedef unsigned __int64 uintptr_t; -#else // _WIN64 ][ - typedef _W64 signed int intptr_t; - typedef _W64 unsigned int uintptr_t; -#endif // _WIN64 ] - -// 7.18.1.5 Greatest-width integer types -typedef int64_t intmax_t; -typedef uint64_t uintmax_t; - - -// 7.18.2 Limits of specified-width integer types - -#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 - -// 7.18.2.1 Limits of exact-width integer types -#define INT8_MIN ((int8_t)_I8_MIN) -#define INT8_MAX _I8_MAX -#define INT16_MIN ((int16_t)_I16_MIN) -#define INT16_MAX _I16_MAX -#define INT32_MIN ((int32_t)_I32_MIN) -#define INT32_MAX _I32_MAX -#define INT64_MIN ((int64_t)_I64_MIN) -#define INT64_MAX _I64_MAX -#define UINT8_MAX _UI8_MAX -#define UINT16_MAX _UI16_MAX -#define UINT32_MAX _UI32_MAX -#define UINT64_MAX _UI64_MAX - -// 7.18.2.2 Limits of minimum-width integer types -#define INT_LEAST8_MIN INT8_MIN -#define INT_LEAST8_MAX INT8_MAX -#define INT_LEAST16_MIN INT16_MIN -#define INT_LEAST16_MAX INT16_MAX -#define INT_LEAST32_MIN INT32_MIN -#define INT_LEAST32_MAX INT32_MAX -#define INT_LEAST64_MIN INT64_MIN -#define INT_LEAST64_MAX INT64_MAX -#define UINT_LEAST8_MAX UINT8_MAX -#define UINT_LEAST16_MAX UINT16_MAX -#define UINT_LEAST32_MAX UINT32_MAX -#define UINT_LEAST64_MAX UINT64_MAX - -// 7.18.2.3 Limits of fastest minimum-width integer types -#define INT_FAST8_MIN INT8_MIN -#define INT_FAST8_MAX INT8_MAX -#define INT_FAST16_MIN INT16_MIN -#define INT_FAST16_MAX INT16_MAX -#define INT_FAST32_MIN INT32_MIN -#define INT_FAST32_MAX INT32_MAX -#define INT_FAST64_MIN INT64_MIN -#define INT_FAST64_MAX INT64_MAX -#define UINT_FAST8_MAX UINT8_MAX -#define UINT_FAST16_MAX UINT16_MAX -#define UINT_FAST32_MAX UINT32_MAX -#define UINT_FAST64_MAX UINT64_MAX - -// 7.18.2.4 Limits of integer types capable of holding object pointers -#ifdef _WIN64 // [ -# define INTPTR_MIN INT64_MIN -# define INTPTR_MAX INT64_MAX -# define UINTPTR_MAX UINT64_MAX -#else // _WIN64 ][ -# define INTPTR_MIN INT32_MIN -# define INTPTR_MAX INT32_MAX -# define UINTPTR_MAX UINT32_MAX -#endif // _WIN64 ] - -// 7.18.2.5 Limits of greatest-width integer types -#define INTMAX_MIN INT64_MIN -#define INTMAX_MAX INT64_MAX -#define UINTMAX_MAX UINT64_MAX - -// 7.18.3 Limits of other integer types - -#ifdef _WIN64 // [ -# define PTRDIFF_MIN _I64_MIN -# define PTRDIFF_MAX _I64_MAX -#else // _WIN64 ][ -# define PTRDIFF_MIN _I32_MIN -# define PTRDIFF_MAX _I32_MAX -#endif // _WIN64 ] - -#define SIG_ATOMIC_MIN INT_MIN -#define SIG_ATOMIC_MAX INT_MAX - -#ifndef SIZE_MAX // [ -# ifdef _WIN64 // [ -# define SIZE_MAX _UI64_MAX -# else // _WIN64 ][ -# define SIZE_MAX _UI32_MAX -# endif // _WIN64 ] -#endif // SIZE_MAX ] - -// WCHAR_MIN and WCHAR_MAX are also defined in -#ifndef WCHAR_MIN // [ -# define WCHAR_MIN 0 -#endif // WCHAR_MIN ] -#ifndef WCHAR_MAX // [ -# define WCHAR_MAX _UI16_MAX -#endif // WCHAR_MAX ] - -#define WINT_MIN 0 -#define WINT_MAX _UI16_MAX - -#endif // __STDC_LIMIT_MACROS ] - - -// 7.18.4 Limits of other integer types - -#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 - -// 7.18.4.1 Macros for minimum-width integer constants - -#define INT8_C(val) val##i8 -#define INT16_C(val) val##i16 -#define INT32_C(val) val##i32 -#define INT64_C(val) val##i64 - -#define UINT8_C(val) val##ui8 -#define UINT16_C(val) val##ui16 -#define UINT32_C(val) val##ui32 -#define UINT64_C(val) val##ui64 - -// 7.18.4.2 Macros for greatest-width integer constants -// These #ifndef's are needed to prevent collisions with . -// Check out Issue 9 for the details. -#ifndef INTMAX_C // [ -# define INTMAX_C INT64_C -#endif // INTMAX_C ] -#ifndef UINTMAX_C // [ -# define UINTMAX_C UINT64_C -#endif // UINTMAX_C ] - -#endif // __STDC_CONSTANT_MACROS ] - -#endif // _MSC_VER >= 1600 ] - -#endif // _MSC_STDINT_H_ ] diff --git a/include/cereal/external/rapidjson/ostreamwrapper.h b/include/cereal/external/rapidjson/ostreamwrapper.h deleted file mode 100644 index 58c034a..0000000 --- a/include/cereal/external/rapidjson/ostreamwrapper.h +++ /dev/null @@ -1,81 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_OSTREAMWRAPPER_H_ -#define CEREAL_RAPIDJSON_OSTREAMWRAPPER_H_ - -#include "stream.h" -#include - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(padded) -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -//! Wrapper of \c std::basic_ostream into RapidJSON's Stream concept. -/*! - The classes can be wrapped including but not limited to: - - - \c std::ostringstream - - \c std::stringstream - - \c std::wpstringstream - - \c std::wstringstream - - \c std::ifstream - - \c std::fstream - - \c std::wofstream - - \c std::wfstream - - \tparam StreamType Class derived from \c std::basic_ostream. -*/ - -template -class BasicOStreamWrapper { -public: - typedef typename StreamType::char_type Ch; - BasicOStreamWrapper(StreamType& stream) : stream_(stream) {} - - void Put(Ch c) { - stream_.put(c); - } - - void Flush() { - stream_.flush(); - } - - // Not implemented - char Peek() const { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - char Take() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - size_t Tell() const { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - char* PutBegin() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - size_t PutEnd(char*) { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - -private: - BasicOStreamWrapper(const BasicOStreamWrapper&); - BasicOStreamWrapper& operator=(const BasicOStreamWrapper&); - - StreamType& stream_; -}; - -typedef BasicOStreamWrapper OStreamWrapper; -typedef BasicOStreamWrapper WOStreamWrapper; - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_POP -#endif - -CEREAL_RAPIDJSON_NAMESPACE_END - -#endif // CEREAL_RAPIDJSON_OSTREAMWRAPPER_H_ diff --git a/include/cereal/external/rapidjson/pointer.h b/include/cereal/external/rapidjson/pointer.h deleted file mode 100644 index 930970f..0000000 --- a/include/cereal/external/rapidjson/pointer.h +++ /dev/null @@ -1,1414 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_POINTER_H_ -#define CEREAL_RAPIDJSON_POINTER_H_ - -#include "document.h" -#include "internal/itoa.h" - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(switch-enum) -#elif defined(_MSC_VER) -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -static const SizeType kPointerInvalidIndex = ~SizeType(0); //!< Represents an invalid index in GenericPointer::Token - -//! Error code of parsing. -/*! \ingroup CEREAL_RAPIDJSON_ERRORS - \see GenericPointer::GenericPointer, GenericPointer::GetParseErrorCode -*/ -enum PointerParseErrorCode { - kPointerParseErrorNone = 0, //!< The parse is successful - - kPointerParseErrorTokenMustBeginWithSolidus, //!< A token must begin with a '/' - kPointerParseErrorInvalidEscape, //!< Invalid escape - kPointerParseErrorInvalidPercentEncoding, //!< Invalid percent encoding in URI fragment - kPointerParseErrorCharacterMustPercentEncode //!< A character must percent encoded in URI fragment -}; - -/////////////////////////////////////////////////////////////////////////////// -// GenericPointer - -//! Represents a JSON Pointer. Use Pointer for UTF8 encoding and default allocator. -/*! - This class implements RFC 6901 "JavaScript Object Notation (JSON) Pointer" - (https://tools.ietf.org/html/rfc6901). - - A JSON pointer is for identifying a specific value in a JSON document - (GenericDocument). It can simplify coding of DOM tree manipulation, because it - can access multiple-level depth of DOM tree with single API call. - - After it parses a string representation (e.g. "/foo/0" or URI fragment - representation (e.g. "#/foo/0") into its internal representation (tokens), - it can be used to resolve a specific value in multiple documents, or sub-tree - of documents. - - Contrary to GenericValue, Pointer can be copy constructed and copy assigned. - Apart from assignment, a Pointer cannot be modified after construction. - - Although Pointer is very convenient, please aware that constructing Pointer - involves parsing and dynamic memory allocation. A special constructor with user- - supplied tokens eliminates these. - - GenericPointer depends on GenericDocument and GenericValue. - - \tparam ValueType The value type of the DOM tree. E.g. GenericValue > - \tparam Allocator The allocator type for allocating memory for internal representation. - - \note GenericPointer uses same encoding of ValueType. - However, Allocator of GenericPointer is independent of Allocator of Value. -*/ -template -class GenericPointer { -public: - typedef typename ValueType::EncodingType EncodingType; //!< Encoding type from Value - typedef typename ValueType::Ch Ch; //!< Character type from Value - - //! A token is the basic units of internal representation. - /*! - A JSON pointer string representation "/foo/123" is parsed to two tokens: - "foo" and 123. 123 will be represented in both numeric form and string form. - They are resolved according to the actual value type (object or array). - - For token that are not numbers, or the numeric value is out of bound - (greater than limits of SizeType), they are only treated as string form - (i.e. the token's index will be equal to kPointerInvalidIndex). - - This struct is public so that user can create a Pointer without parsing and - allocation, using a special constructor. - */ - struct Token { - const Ch* name; //!< Name of the token. It has null character at the end but it can contain null character. - SizeType length; //!< Length of the name. - SizeType index; //!< A valid array index, if it is not equal to kPointerInvalidIndex. - }; - - //!@name Constructors and destructor. - //@{ - - //! Default constructor. - GenericPointer(Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {} - - //! Constructor that parses a string or URI fragment representation. - /*! - \param source A null-terminated, string or URI fragment representation of JSON pointer. - \param allocator User supplied allocator for this pointer. If no allocator is provided, it creates a self-owned one. - */ - explicit GenericPointer(const Ch* source, Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { - Parse(source, internal::StrLen(source)); - } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - //! Constructor that parses a string or URI fragment representation. - /*! - \param source A string or URI fragment representation of JSON pointer. - \param allocator User supplied allocator for this pointer. If no allocator is provided, it creates a self-owned one. - \note Requires the definition of the preprocessor symbol \ref CEREAL_RAPIDJSON_HAS_STDSTRING. - */ - explicit GenericPointer(const std::basic_string& source, Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { - Parse(source.c_str(), source.size()); - } -#endif - - //! Constructor that parses a string or URI fragment representation, with length of the source string. - /*! - \param source A string or URI fragment representation of JSON pointer. - \param length Length of source. - \param allocator User supplied allocator for this pointer. If no allocator is provided, it creates a self-owned one. - \note Slightly faster than the overload without length. - */ - GenericPointer(const Ch* source, size_t length, Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { - Parse(source, length); - } - - //! Constructor with user-supplied tokens. - /*! - This constructor let user supplies const array of tokens. - This prevents the parsing process and eliminates allocation. - This is preferred for memory constrained environments. - - \param tokens An constant array of tokens representing the JSON pointer. - \param tokenCount Number of tokens. - - \b Example - \code - #define NAME(s) { s, sizeof(s) / sizeof(s[0]) - 1, kPointerInvalidIndex } - #define INDEX(i) { #i, sizeof(#i) - 1, i } - - static const Pointer::Token kTokens[] = { NAME("foo"), INDEX(123) }; - static const Pointer p(kTokens, sizeof(kTokens) / sizeof(kTokens[0])); - // Equivalent to static const Pointer p("/foo/123"); - - #undef NAME - #undef INDEX - \endcode - */ - GenericPointer(const Token* tokens, size_t tokenCount) : allocator_(), ownAllocator_(), nameBuffer_(), tokens_(const_cast(tokens)), tokenCount_(tokenCount), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {} - - //! Copy constructor. - GenericPointer(const GenericPointer& rhs) : allocator_(rhs.allocator_), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { - *this = rhs; - } - - //! Copy constructor. - GenericPointer(const GenericPointer& rhs, Allocator* allocator) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { - *this = rhs; - } - - //! Destructor. - ~GenericPointer() { - if (nameBuffer_) // If user-supplied tokens constructor is used, nameBuffer_ is nullptr and tokens_ are not deallocated. - Allocator::Free(tokens_); - CEREAL_RAPIDJSON_DELETE(ownAllocator_); - } - - //! Assignment operator. - GenericPointer& operator=(const GenericPointer& rhs) { - if (this != &rhs) { - // Do not delete ownAllcator - if (nameBuffer_) - Allocator::Free(tokens_); - - tokenCount_ = rhs.tokenCount_; - parseErrorOffset_ = rhs.parseErrorOffset_; - parseErrorCode_ = rhs.parseErrorCode_; - - if (rhs.nameBuffer_) - CopyFromRaw(rhs); // Normally parsed tokens. - else { - tokens_ = rhs.tokens_; // User supplied const tokens. - nameBuffer_ = 0; - } - } - return *this; - } - - //! Swap the content of this pointer with an other. - /*! - \param other The pointer to swap with. - \note Constant complexity. - */ - GenericPointer& Swap(GenericPointer& other) CEREAL_RAPIDJSON_NOEXCEPT { - internal::Swap(allocator_, other.allocator_); - internal::Swap(ownAllocator_, other.ownAllocator_); - internal::Swap(nameBuffer_, other.nameBuffer_); - internal::Swap(tokens_, other.tokens_); - internal::Swap(tokenCount_, other.tokenCount_); - internal::Swap(parseErrorOffset_, other.parseErrorOffset_); - internal::Swap(parseErrorCode_, other.parseErrorCode_); - return *this; - } - - //! free-standing swap function helper - /*! - Helper function to enable support for common swap implementation pattern based on \c std::swap: - \code - void swap(MyClass& a, MyClass& b) { - using std::swap; - swap(a.pointer, b.pointer); - // ... - } - \endcode - \see Swap() - */ - friend inline void swap(GenericPointer& a, GenericPointer& b) CEREAL_RAPIDJSON_NOEXCEPT { a.Swap(b); } - - //@} - - //!@name Append token - //@{ - - //! Append a token and return a new Pointer - /*! - \param token Token to be appended. - \param allocator Allocator for the newly return Pointer. - \return A new Pointer with appended token. - */ - GenericPointer Append(const Token& token, Allocator* allocator = 0) const { - GenericPointer r; - r.allocator_ = allocator; - Ch *p = r.CopyFromRaw(*this, 1, token.length + 1); - std::memcpy(p, token.name, (token.length + 1) * sizeof(Ch)); - r.tokens_[tokenCount_].name = p; - r.tokens_[tokenCount_].length = token.length; - r.tokens_[tokenCount_].index = token.index; - return r; - } - - //! Append a name token with length, and return a new Pointer - /*! - \param name Name to be appended. - \param length Length of name. - \param allocator Allocator for the newly return Pointer. - \return A new Pointer with appended token. - */ - GenericPointer Append(const Ch* name, SizeType length, Allocator* allocator = 0) const { - Token token = { name, length, kPointerInvalidIndex }; - return Append(token, allocator); - } - - //! Append a name token without length, and return a new Pointer - /*! - \param name Name (const Ch*) to be appended. - \param allocator Allocator for the newly return Pointer. - \return A new Pointer with appended token. - */ - template - CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr::Type, Ch> >), (GenericPointer)) - Append(T* name, Allocator* allocator = 0) const { - return Append(name, internal::StrLen(name), allocator); - } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - //! Append a name token, and return a new Pointer - /*! - \param name Name to be appended. - \param allocator Allocator for the newly return Pointer. - \return A new Pointer with appended token. - */ - GenericPointer Append(const std::basic_string& name, Allocator* allocator = 0) const { - return Append(name.c_str(), static_cast(name.size()), allocator); - } -#endif - - //! Append a index token, and return a new Pointer - /*! - \param index Index to be appended. - \param allocator Allocator for the newly return Pointer. - \return A new Pointer with appended token. - */ - GenericPointer Append(SizeType index, Allocator* allocator = 0) const { - char buffer[21]; - char* end = sizeof(SizeType) == 4 ? internal::u32toa(index, buffer) : internal::u64toa(index, buffer); - SizeType length = static_cast(end - buffer); - buffer[length] = '\0'; - - if (sizeof(Ch) == 1) { - Token token = { reinterpret_cast(buffer), length, index }; - return Append(token, allocator); - } - else { - Ch name[21]; - for (size_t i = 0; i <= length; i++) - name[i] = static_cast(buffer[i]); - Token token = { name, length, index }; - return Append(token, allocator); - } - } - - //! Append a token by value, and return a new Pointer - /*! - \param token token to be appended. - \param allocator Allocator for the newly return Pointer. - \return A new Pointer with appended token. - */ - GenericPointer Append(const ValueType& token, Allocator* allocator = 0) const { - if (token.IsString()) - return Append(token.GetString(), token.GetStringLength(), allocator); - else { - CEREAL_RAPIDJSON_ASSERT(token.IsUint64()); - CEREAL_RAPIDJSON_ASSERT(token.GetUint64() <= SizeType(~0)); - return Append(static_cast(token.GetUint64()), allocator); - } - } - - //!@name Handling Parse Error - //@{ - - //! Check whether this is a valid pointer. - bool IsValid() const { return parseErrorCode_ == kPointerParseErrorNone; } - - //! Get the parsing error offset in code unit. - size_t GetParseErrorOffset() const { return parseErrorOffset_; } - - //! Get the parsing error code. - PointerParseErrorCode GetParseErrorCode() const { return parseErrorCode_; } - - //@} - - //! Get the allocator of this pointer. - Allocator& GetAllocator() { return *allocator_; } - - //!@name Tokens - //@{ - - //! Get the token array (const version only). - const Token* GetTokens() const { return tokens_; } - - //! Get the number of tokens. - size_t GetTokenCount() const { return tokenCount_; } - - //@} - - //!@name Equality/inequality operators - //@{ - - //! Equality operator. - /*! - \note When any pointers are invalid, always returns false. - */ - bool operator==(const GenericPointer& rhs) const { - if (!IsValid() || !rhs.IsValid() || tokenCount_ != rhs.tokenCount_) - return false; - - for (size_t i = 0; i < tokenCount_; i++) { - if (tokens_[i].index != rhs.tokens_[i].index || - tokens_[i].length != rhs.tokens_[i].length || - (tokens_[i].length != 0 && std::memcmp(tokens_[i].name, rhs.tokens_[i].name, sizeof(Ch)* tokens_[i].length) != 0)) - { - return false; - } - } - - return true; - } - - //! Inequality operator. - /*! - \note When any pointers are invalid, always returns true. - */ - bool operator!=(const GenericPointer& rhs) const { return !(*this == rhs); } - - //! Less than operator. - /*! - \note Invalid pointers are always greater than valid ones. - */ - bool operator<(const GenericPointer& rhs) const { - if (!IsValid()) - return false; - if (!rhs.IsValid()) - return true; - - if (tokenCount_ != rhs.tokenCount_) - return tokenCount_ < rhs.tokenCount_; - - for (size_t i = 0; i < tokenCount_; i++) { - if (tokens_[i].index != rhs.tokens_[i].index) - return tokens_[i].index < rhs.tokens_[i].index; - - if (tokens_[i].length != rhs.tokens_[i].length) - return tokens_[i].length < rhs.tokens_[i].length; - - if (int cmp = std::memcmp(tokens_[i].name, rhs.tokens_[i].name, sizeof(Ch) * tokens_[i].length)) - return cmp < 0; - } - - return false; - } - - //@} - - //!@name Stringify - //@{ - - //! Stringify the pointer into string representation. - /*! - \tparam OutputStream Type of output stream. - \param os The output stream. - */ - template - bool Stringify(OutputStream& os) const { - return Stringify(os); - } - - //! Stringify the pointer into URI fragment representation. - /*! - \tparam OutputStream Type of output stream. - \param os The output stream. - */ - template - bool StringifyUriFragment(OutputStream& os) const { - return Stringify(os); - } - - //@} - - //!@name Create value - //@{ - - //! Create a value in a subtree. - /*! - If the value is not exist, it creates all parent values and a JSON Null value. - So it always succeed and return the newly created or existing value. - - Remind that it may change types of parents according to tokens, so it - potentially removes previously stored values. For example, if a document - was an array, and "/foo" is used to create a value, then the document - will be changed to an object, and all existing array elements are lost. - - \param root Root value of a DOM subtree to be resolved. It can be any value other than document root. - \param allocator Allocator for creating the values if the specified value or its parents are not exist. - \param alreadyExist If non-null, it stores whether the resolved value is already exist. - \return The resolved newly created (a JSON Null value), or already exists value. - */ - ValueType& Create(ValueType& root, typename ValueType::AllocatorType& allocator, bool* alreadyExist = 0) const { - CEREAL_RAPIDJSON_ASSERT(IsValid()); - ValueType* v = &root; - bool exist = true; - for (const Token *t = tokens_; t != tokens_ + tokenCount_; ++t) { - if (v->IsArray() && t->name[0] == '-' && t->length == 1) { - v->PushBack(ValueType().Move(), allocator); - v = &((*v)[v->Size() - 1]); - exist = false; - } - else { - if (t->index == kPointerInvalidIndex) { // must be object name - if (!v->IsObject()) - v->SetObject(); // Change to Object - } - else { // object name or array index - if (!v->IsArray() && !v->IsObject()) - v->SetArray(); // Change to Array - } - - if (v->IsArray()) { - if (t->index >= v->Size()) { - v->Reserve(t->index + 1, allocator); - while (t->index >= v->Size()) - v->PushBack(ValueType().Move(), allocator); - exist = false; - } - v = &((*v)[t->index]); - } - else { - typename ValueType::MemberIterator m = v->FindMember(GenericStringRef(t->name, t->length)); - if (m == v->MemberEnd()) { - v->AddMember(ValueType(t->name, t->length, allocator).Move(), ValueType().Move(), allocator); - v = &(--v->MemberEnd())->value; // Assumes AddMember() appends at the end - exist = false; - } - else - v = &m->value; - } - } - } - - if (alreadyExist) - *alreadyExist = exist; - - return *v; - } - - //! Creates a value in a document. - /*! - \param document A document to be resolved. - \param alreadyExist If non-null, it stores whether the resolved value is already exist. - \return The resolved newly created, or already exists value. - */ - template - ValueType& Create(GenericDocument& document, bool* alreadyExist = 0) const { - return Create(document, document.GetAllocator(), alreadyExist); - } - - //@} - - //!@name Query value - //@{ - - //! Query a value in a subtree. - /*! - \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root. - \param unresolvedTokenIndex If the pointer cannot resolve a token in the pointer, this parameter can obtain the index of unresolved token. - \return Pointer to the value if it can be resolved. Otherwise null. - - \note - There are only 3 situations when a value cannot be resolved: - 1. A value in the path is not an array nor object. - 2. An object value does not contain the token. - 3. A token is out of range of an array value. - - Use unresolvedTokenIndex to retrieve the token index. - */ - ValueType* Get(ValueType& root, size_t* unresolvedTokenIndex = 0) const { - CEREAL_RAPIDJSON_ASSERT(IsValid()); - ValueType* v = &root; - for (const Token *t = tokens_; t != tokens_ + tokenCount_; ++t) { - switch (v->GetType()) { - case kObjectType: - { - typename ValueType::MemberIterator m = v->FindMember(GenericStringRef(t->name, t->length)); - if (m == v->MemberEnd()) - break; - v = &m->value; - } - continue; - case kArrayType: - if (t->index == kPointerInvalidIndex || t->index >= v->Size()) - break; - v = &((*v)[t->index]); - continue; - default: - break; - } - - // Error: unresolved token - if (unresolvedTokenIndex) - *unresolvedTokenIndex = static_cast(t - tokens_); - return 0; - } - return v; - } - - //! Query a const value in a const subtree. - /*! - \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root. - \return Pointer to the value if it can be resolved. Otherwise null. - */ - const ValueType* Get(const ValueType& root, size_t* unresolvedTokenIndex = 0) const { - return Get(const_cast(root), unresolvedTokenIndex); - } - - //@} - - //!@name Query a value with default - //@{ - - //! Query a value in a subtree with default value. - /*! - Similar to Get(), but if the specified value do not exists, it creates all parents and clone the default value. - So that this function always succeed. - - \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root. - \param defaultValue Default value to be cloned if the value was not exists. - \param allocator Allocator for creating the values if the specified value or its parents are not exist. - \see Create() - */ - ValueType& GetWithDefault(ValueType& root, const ValueType& defaultValue, typename ValueType::AllocatorType& allocator) const { - bool alreadyExist; - ValueType& v = Create(root, allocator, &alreadyExist); - return alreadyExist ? v : v.CopyFrom(defaultValue, allocator); - } - - //! Query a value in a subtree with default null-terminated string. - ValueType& GetWithDefault(ValueType& root, const Ch* defaultValue, typename ValueType::AllocatorType& allocator) const { - bool alreadyExist; - ValueType& v = Create(root, allocator, &alreadyExist); - return alreadyExist ? v : v.SetString(defaultValue, allocator); - } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - //! Query a value in a subtree with default std::basic_string. - ValueType& GetWithDefault(ValueType& root, const std::basic_string& defaultValue, typename ValueType::AllocatorType& allocator) const { - bool alreadyExist; - ValueType& v = Create(root, allocator, &alreadyExist); - return alreadyExist ? v : v.SetString(defaultValue, allocator); - } -#endif - - //! Query a value in a subtree with default primitive value. - /*! - \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool - */ - template - CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (ValueType&)) - GetWithDefault(ValueType& root, T defaultValue, typename ValueType::AllocatorType& allocator) const { - return GetWithDefault(root, ValueType(defaultValue).Move(), allocator); - } - - //! Query a value in a document with default value. - template - ValueType& GetWithDefault(GenericDocument& document, const ValueType& defaultValue) const { - return GetWithDefault(document, defaultValue, document.GetAllocator()); - } - - //! Query a value in a document with default null-terminated string. - template - ValueType& GetWithDefault(GenericDocument& document, const Ch* defaultValue) const { - return GetWithDefault(document, defaultValue, document.GetAllocator()); - } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - //! Query a value in a document with default std::basic_string. - template - ValueType& GetWithDefault(GenericDocument& document, const std::basic_string& defaultValue) const { - return GetWithDefault(document, defaultValue, document.GetAllocator()); - } -#endif - - //! Query a value in a document with default primitive value. - /*! - \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool - */ - template - CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (ValueType&)) - GetWithDefault(GenericDocument& document, T defaultValue) const { - return GetWithDefault(document, defaultValue, document.GetAllocator()); - } - - //@} - - //!@name Set a value - //@{ - - //! Set a value in a subtree, with move semantics. - /*! - It creates all parents if they are not exist or types are different to the tokens. - So this function always succeeds but potentially remove existing values. - - \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root. - \param value Value to be set. - \param allocator Allocator for creating the values if the specified value or its parents are not exist. - \see Create() - */ - ValueType& Set(ValueType& root, ValueType& value, typename ValueType::AllocatorType& allocator) const { - return Create(root, allocator) = value; - } - - //! Set a value in a subtree, with copy semantics. - ValueType& Set(ValueType& root, const ValueType& value, typename ValueType::AllocatorType& allocator) const { - return Create(root, allocator).CopyFrom(value, allocator); - } - - //! Set a null-terminated string in a subtree. - ValueType& Set(ValueType& root, const Ch* value, typename ValueType::AllocatorType& allocator) const { - return Create(root, allocator) = ValueType(value, allocator).Move(); - } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - //! Set a std::basic_string in a subtree. - ValueType& Set(ValueType& root, const std::basic_string& value, typename ValueType::AllocatorType& allocator) const { - return Create(root, allocator) = ValueType(value, allocator).Move(); - } -#endif - - //! Set a primitive value in a subtree. - /*! - \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool - */ - template - CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (ValueType&)) - Set(ValueType& root, T value, typename ValueType::AllocatorType& allocator) const { - return Create(root, allocator) = ValueType(value).Move(); - } - - //! Set a value in a document, with move semantics. - template - ValueType& Set(GenericDocument& document, ValueType& value) const { - return Create(document) = value; - } - - //! Set a value in a document, with copy semantics. - template - ValueType& Set(GenericDocument& document, const ValueType& value) const { - return Create(document).CopyFrom(value, document.GetAllocator()); - } - - //! Set a null-terminated string in a document. - template - ValueType& Set(GenericDocument& document, const Ch* value) const { - return Create(document) = ValueType(value, document.GetAllocator()).Move(); - } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - //! Sets a std::basic_string in a document. - template - ValueType& Set(GenericDocument& document, const std::basic_string& value) const { - return Create(document) = ValueType(value, document.GetAllocator()).Move(); - } -#endif - - //! Set a primitive value in a document. - /*! - \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool - */ - template - CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (ValueType&)) - Set(GenericDocument& document, T value) const { - return Create(document) = value; - } - - //@} - - //!@name Swap a value - //@{ - - //! Swap a value with a value in a subtree. - /*! - It creates all parents if they are not exist or types are different to the tokens. - So this function always succeeds but potentially remove existing values. - - \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root. - \param value Value to be swapped. - \param allocator Allocator for creating the values if the specified value or its parents are not exist. - \see Create() - */ - ValueType& Swap(ValueType& root, ValueType& value, typename ValueType::AllocatorType& allocator) const { - return Create(root, allocator).Swap(value); - } - - //! Swap a value with a value in a document. - template - ValueType& Swap(GenericDocument& document, ValueType& value) const { - return Create(document).Swap(value); - } - - //@} - - //! Erase a value in a subtree. - /*! - \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root. - \return Whether the resolved value is found and erased. - - \note Erasing with an empty pointer \c Pointer(""), i.e. the root, always fail and return false. - */ - bool Erase(ValueType& root) const { - CEREAL_RAPIDJSON_ASSERT(IsValid()); - if (tokenCount_ == 0) // Cannot erase the root - return false; - - ValueType* v = &root; - const Token* last = tokens_ + (tokenCount_ - 1); - for (const Token *t = tokens_; t != last; ++t) { - switch (v->GetType()) { - case kObjectType: - { - typename ValueType::MemberIterator m = v->FindMember(GenericStringRef(t->name, t->length)); - if (m == v->MemberEnd()) - return false; - v = &m->value; - } - break; - case kArrayType: - if (t->index == kPointerInvalidIndex || t->index >= v->Size()) - return false; - v = &((*v)[t->index]); - break; - default: - return false; - } - } - - switch (v->GetType()) { - case kObjectType: - return v->EraseMember(GenericStringRef(last->name, last->length)); - case kArrayType: - if (last->index == kPointerInvalidIndex || last->index >= v->Size()) - return false; - v->Erase(v->Begin() + last->index); - return true; - default: - return false; - } - } - -private: - //! Clone the content from rhs to this. - /*! - \param rhs Source pointer. - \param extraToken Extra tokens to be allocated. - \param extraNameBufferSize Extra name buffer size (in number of Ch) to be allocated. - \return Start of non-occupied name buffer, for storing extra names. - */ - Ch* CopyFromRaw(const GenericPointer& rhs, size_t extraToken = 0, size_t extraNameBufferSize = 0) { - if (!allocator_) // allocator is independently owned. - ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator)(); - - size_t nameBufferSize = rhs.tokenCount_; // null terminators for tokens - for (Token *t = rhs.tokens_; t != rhs.tokens_ + rhs.tokenCount_; ++t) - nameBufferSize += t->length; - - tokenCount_ = rhs.tokenCount_ + extraToken; - tokens_ = static_cast(allocator_->Malloc(tokenCount_ * sizeof(Token) + (nameBufferSize + extraNameBufferSize) * sizeof(Ch))); - nameBuffer_ = reinterpret_cast(tokens_ + tokenCount_); - if (rhs.tokenCount_ > 0) { - std::memcpy(tokens_, rhs.tokens_, rhs.tokenCount_ * sizeof(Token)); - } - if (nameBufferSize > 0) { - std::memcpy(nameBuffer_, rhs.nameBuffer_, nameBufferSize * sizeof(Ch)); - } - - // Adjust pointers to name buffer - std::ptrdiff_t diff = nameBuffer_ - rhs.nameBuffer_; - for (Token *t = tokens_; t != tokens_ + rhs.tokenCount_; ++t) - t->name += diff; - - return nameBuffer_ + nameBufferSize; - } - - //! Check whether a character should be percent-encoded. - /*! - According to RFC 3986 2.3 Unreserved Characters. - \param c The character (code unit) to be tested. - */ - bool NeedPercentEncode(Ch c) const { - return !((c >= '0' && c <= '9') || (c >= 'A' && c <='Z') || (c >= 'a' && c <= 'z') || c == '-' || c == '.' || c == '_' || c =='~'); - } - - //! Parse a JSON String or its URI fragment representation into tokens. -#ifndef __clang__ // -Wdocumentation - /*! - \param source Either a JSON Pointer string, or its URI fragment representation. Not need to be null terminated. - \param length Length of the source string. - \note Source cannot be JSON String Representation of JSON Pointer, e.g. In "/\u0000", \u0000 will not be unescaped. - */ -#endif - void Parse(const Ch* source, size_t length) { - CEREAL_RAPIDJSON_ASSERT(source != NULL); - CEREAL_RAPIDJSON_ASSERT(nameBuffer_ == 0); - CEREAL_RAPIDJSON_ASSERT(tokens_ == 0); - - // Create own allocator if user did not supply. - if (!allocator_) - ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator)(); - - // Count number of '/' as tokenCount - tokenCount_ = 0; - for (const Ch* s = source; s != source + length; s++) - if (*s == '/') - tokenCount_++; - - Token* token = tokens_ = static_cast(allocator_->Malloc(tokenCount_ * sizeof(Token) + length * sizeof(Ch))); - Ch* name = nameBuffer_ = reinterpret_cast(tokens_ + tokenCount_); - size_t i = 0; - - // Detect if it is a URI fragment - bool uriFragment = false; - if (source[i] == '#') { - uriFragment = true; - i++; - } - - if (i != length && source[i] != '/') { - parseErrorCode_ = kPointerParseErrorTokenMustBeginWithSolidus; - goto error; - } - - while (i < length) { - CEREAL_RAPIDJSON_ASSERT(source[i] == '/'); - i++; // consumes '/' - - token->name = name; - bool isNumber = true; - - while (i < length && source[i] != '/') { - Ch c = source[i]; - if (uriFragment) { - // Decoding percent-encoding for URI fragment - if (c == '%') { - PercentDecodeStream is(&source[i], source + length); - GenericInsituStringStream os(name); - Ch* begin = os.PutBegin(); - if (!Transcoder, EncodingType>().Validate(is, os) || !is.IsValid()) { - parseErrorCode_ = kPointerParseErrorInvalidPercentEncoding; - goto error; - } - size_t len = os.PutEnd(begin); - i += is.Tell() - 1; - if (len == 1) - c = *name; - else { - name += len; - isNumber = false; - i++; - continue; - } - } - else if (NeedPercentEncode(c)) { - parseErrorCode_ = kPointerParseErrorCharacterMustPercentEncode; - goto error; - } - } - - i++; - - // Escaping "~0" -> '~', "~1" -> '/' - if (c == '~') { - if (i < length) { - c = source[i]; - if (c == '0') c = '~'; - else if (c == '1') c = '/'; - else { - parseErrorCode_ = kPointerParseErrorInvalidEscape; - goto error; - } - i++; - } - else { - parseErrorCode_ = kPointerParseErrorInvalidEscape; - goto error; - } - } - - // First check for index: all of characters are digit - if (c < '0' || c > '9') - isNumber = false; - - *name++ = c; - } - token->length = static_cast(name - token->name); - if (token->length == 0) - isNumber = false; - *name++ = '\0'; // Null terminator - - // Second check for index: more than one digit cannot have leading zero - if (isNumber && token->length > 1 && token->name[0] == '0') - isNumber = false; - - // String to SizeType conversion - SizeType n = 0; - if (isNumber) { - for (size_t j = 0; j < token->length; j++) { - SizeType m = n * 10 + static_cast(token->name[j] - '0'); - if (m < n) { // overflow detection - isNumber = false; - break; - } - n = m; - } - } - - token->index = isNumber ? n : kPointerInvalidIndex; - token++; - } - - CEREAL_RAPIDJSON_ASSERT(name <= nameBuffer_ + length); // Should not overflow buffer - parseErrorCode_ = kPointerParseErrorNone; - return; - - error: - Allocator::Free(tokens_); - nameBuffer_ = 0; - tokens_ = 0; - tokenCount_ = 0; - parseErrorOffset_ = i; - return; - } - - //! Stringify to string or URI fragment representation. - /*! - \tparam uriFragment True for stringifying to URI fragment representation. False for string representation. - \tparam OutputStream type of output stream. - \param os The output stream. - */ - template - bool Stringify(OutputStream& os) const { - CEREAL_RAPIDJSON_ASSERT(IsValid()); - - if (uriFragment) - os.Put('#'); - - for (Token *t = tokens_; t != tokens_ + tokenCount_; ++t) { - os.Put('/'); - for (size_t j = 0; j < t->length; j++) { - Ch c = t->name[j]; - if (c == '~') { - os.Put('~'); - os.Put('0'); - } - else if (c == '/') { - os.Put('~'); - os.Put('1'); - } - else if (uriFragment && NeedPercentEncode(c)) { - // Transcode to UTF8 sequence - GenericStringStream source(&t->name[j]); - PercentEncodeStream target(os); - if (!Transcoder >().Validate(source, target)) - return false; - j += source.Tell() - 1; - } - else - os.Put(c); - } - } - return true; - } - - //! A helper stream for decoding a percent-encoded sequence into code unit. - /*! - This stream decodes %XY triplet into code unit (0-255). - If it encounters invalid characters, it sets output code unit as 0 and - mark invalid, and to be checked by IsValid(). - */ - class PercentDecodeStream { - public: - typedef typename ValueType::Ch Ch; - - //! Constructor - /*! - \param source Start of the stream - \param end Past-the-end of the stream. - */ - PercentDecodeStream(const Ch* source, const Ch* end) : src_(source), head_(source), end_(end), valid_(true) {} - - Ch Take() { - if (*src_ != '%' || src_ + 3 > end_) { // %XY triplet - valid_ = false; - return 0; - } - src_++; - Ch c = 0; - for (int j = 0; j < 2; j++) { - c = static_cast(c << 4); - Ch h = *src_; - if (h >= '0' && h <= '9') c = static_cast(c + h - '0'); - else if (h >= 'A' && h <= 'F') c = static_cast(c + h - 'A' + 10); - else if (h >= 'a' && h <= 'f') c = static_cast(c + h - 'a' + 10); - else { - valid_ = false; - return 0; - } - src_++; - } - return c; - } - - size_t Tell() const { return static_cast(src_ - head_); } - bool IsValid() const { return valid_; } - - private: - const Ch* src_; //!< Current read position. - const Ch* head_; //!< Original head of the string. - const Ch* end_; //!< Past-the-end position. - bool valid_; //!< Whether the parsing is valid. - }; - - //! A helper stream to encode character (UTF-8 code unit) into percent-encoded sequence. - template - class PercentEncodeStream { - public: - PercentEncodeStream(OutputStream& os) : os_(os) {} - void Put(char c) { // UTF-8 must be byte - unsigned char u = static_cast(c); - static const char hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; - os_.Put('%'); - os_.Put(static_cast(hexDigits[u >> 4])); - os_.Put(static_cast(hexDigits[u & 15])); - } - private: - OutputStream& os_; - }; - - Allocator* allocator_; //!< The current allocator. It is either user-supplied or equal to ownAllocator_. - Allocator* ownAllocator_; //!< Allocator owned by this Pointer. - Ch* nameBuffer_; //!< A buffer containing all names in tokens. - Token* tokens_; //!< A list of tokens. - size_t tokenCount_; //!< Number of tokens in tokens_. - size_t parseErrorOffset_; //!< Offset in code unit when parsing fail. - PointerParseErrorCode parseErrorCode_; //!< Parsing error code. -}; - -//! GenericPointer for Value (UTF-8, default allocator). -typedef GenericPointer Pointer; - -//!@name Helper functions for GenericPointer -//@{ - -////////////////////////////////////////////////////////////////////////////// - -template -typename T::ValueType& CreateValueByPointer(T& root, const GenericPointer& pointer, typename T::AllocatorType& a) { - return pointer.Create(root, a); -} - -template -typename T::ValueType& CreateValueByPointer(T& root, const CharType(&source)[N], typename T::AllocatorType& a) { - return GenericPointer(source, N - 1).Create(root, a); -} - -// No allocator parameter - -template -typename DocumentType::ValueType& CreateValueByPointer(DocumentType& document, const GenericPointer& pointer) { - return pointer.Create(document); -} - -template -typename DocumentType::ValueType& CreateValueByPointer(DocumentType& document, const CharType(&source)[N]) { - return GenericPointer(source, N - 1).Create(document); -} - -////////////////////////////////////////////////////////////////////////////// - -template -typename T::ValueType* GetValueByPointer(T& root, const GenericPointer& pointer, size_t* unresolvedTokenIndex = 0) { - return pointer.Get(root, unresolvedTokenIndex); -} - -template -const typename T::ValueType* GetValueByPointer(const T& root, const GenericPointer& pointer, size_t* unresolvedTokenIndex = 0) { - return pointer.Get(root, unresolvedTokenIndex); -} - -template -typename T::ValueType* GetValueByPointer(T& root, const CharType (&source)[N], size_t* unresolvedTokenIndex = 0) { - return GenericPointer(source, N - 1).Get(root, unresolvedTokenIndex); -} - -template -const typename T::ValueType* GetValueByPointer(const T& root, const CharType(&source)[N], size_t* unresolvedTokenIndex = 0) { - return GenericPointer(source, N - 1).Get(root, unresolvedTokenIndex); -} - -////////////////////////////////////////////////////////////////////////////// - -template -typename T::ValueType& GetValueByPointerWithDefault(T& root, const GenericPointer& pointer, const typename T::ValueType& defaultValue, typename T::AllocatorType& a) { - return pointer.GetWithDefault(root, defaultValue, a); -} - -template -typename T::ValueType& GetValueByPointerWithDefault(T& root, const GenericPointer& pointer, const typename T::Ch* defaultValue, typename T::AllocatorType& a) { - return pointer.GetWithDefault(root, defaultValue, a); -} - -#if CEREAL_RAPIDJSON_HAS_STDSTRING -template -typename T::ValueType& GetValueByPointerWithDefault(T& root, const GenericPointer& pointer, const std::basic_string& defaultValue, typename T::AllocatorType& a) { - return pointer.GetWithDefault(root, defaultValue, a); -} -#endif - -template -CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (typename T::ValueType&)) -GetValueByPointerWithDefault(T& root, const GenericPointer& pointer, T2 defaultValue, typename T::AllocatorType& a) { - return pointer.GetWithDefault(root, defaultValue, a); -} - -template -typename T::ValueType& GetValueByPointerWithDefault(T& root, const CharType(&source)[N], const typename T::ValueType& defaultValue, typename T::AllocatorType& a) { - return GenericPointer(source, N - 1).GetWithDefault(root, defaultValue, a); -} - -template -typename T::ValueType& GetValueByPointerWithDefault(T& root, const CharType(&source)[N], const typename T::Ch* defaultValue, typename T::AllocatorType& a) { - return GenericPointer(source, N - 1).GetWithDefault(root, defaultValue, a); -} - -#if CEREAL_RAPIDJSON_HAS_STDSTRING -template -typename T::ValueType& GetValueByPointerWithDefault(T& root, const CharType(&source)[N], const std::basic_string& defaultValue, typename T::AllocatorType& a) { - return GenericPointer(source, N - 1).GetWithDefault(root, defaultValue, a); -} -#endif - -template -CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (typename T::ValueType&)) -GetValueByPointerWithDefault(T& root, const CharType(&source)[N], T2 defaultValue, typename T::AllocatorType& a) { - return GenericPointer(source, N - 1).GetWithDefault(root, defaultValue, a); -} - -// No allocator parameter - -template -typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const GenericPointer& pointer, const typename DocumentType::ValueType& defaultValue) { - return pointer.GetWithDefault(document, defaultValue); -} - -template -typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const GenericPointer& pointer, const typename DocumentType::Ch* defaultValue) { - return pointer.GetWithDefault(document, defaultValue); -} - -#if CEREAL_RAPIDJSON_HAS_STDSTRING -template -typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const GenericPointer& pointer, const std::basic_string& defaultValue) { - return pointer.GetWithDefault(document, defaultValue); -} -#endif - -template -CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (typename DocumentType::ValueType&)) -GetValueByPointerWithDefault(DocumentType& document, const GenericPointer& pointer, T2 defaultValue) { - return pointer.GetWithDefault(document, defaultValue); -} - -template -typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], const typename DocumentType::ValueType& defaultValue) { - return GenericPointer(source, N - 1).GetWithDefault(document, defaultValue); -} - -template -typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], const typename DocumentType::Ch* defaultValue) { - return GenericPointer(source, N - 1).GetWithDefault(document, defaultValue); -} - -#if CEREAL_RAPIDJSON_HAS_STDSTRING -template -typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], const std::basic_string& defaultValue) { - return GenericPointer(source, N - 1).GetWithDefault(document, defaultValue); -} -#endif - -template -CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (typename DocumentType::ValueType&)) -GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], T2 defaultValue) { - return GenericPointer(source, N - 1).GetWithDefault(document, defaultValue); -} - -////////////////////////////////////////////////////////////////////////////// - -template -typename T::ValueType& SetValueByPointer(T& root, const GenericPointer& pointer, typename T::ValueType& value, typename T::AllocatorType& a) { - return pointer.Set(root, value, a); -} - -template -typename T::ValueType& SetValueByPointer(T& root, const GenericPointer& pointer, const typename T::ValueType& value, typename T::AllocatorType& a) { - return pointer.Set(root, value, a); -} - -template -typename T::ValueType& SetValueByPointer(T& root, const GenericPointer& pointer, const typename T::Ch* value, typename T::AllocatorType& a) { - return pointer.Set(root, value, a); -} - -#if CEREAL_RAPIDJSON_HAS_STDSTRING -template -typename T::ValueType& SetValueByPointer(T& root, const GenericPointer& pointer, const std::basic_string& value, typename T::AllocatorType& a) { - return pointer.Set(root, value, a); -} -#endif - -template -CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (typename T::ValueType&)) -SetValueByPointer(T& root, const GenericPointer& pointer, T2 value, typename T::AllocatorType& a) { - return pointer.Set(root, value, a); -} - -template -typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], typename T::ValueType& value, typename T::AllocatorType& a) { - return GenericPointer(source, N - 1).Set(root, value, a); -} - -template -typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], const typename T::ValueType& value, typename T::AllocatorType& a) { - return GenericPointer(source, N - 1).Set(root, value, a); -} - -template -typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], const typename T::Ch* value, typename T::AllocatorType& a) { - return GenericPointer(source, N - 1).Set(root, value, a); -} - -#if CEREAL_RAPIDJSON_HAS_STDSTRING -template -typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], const std::basic_string& value, typename T::AllocatorType& a) { - return GenericPointer(source, N - 1).Set(root, value, a); -} -#endif - -template -CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (typename T::ValueType&)) -SetValueByPointer(T& root, const CharType(&source)[N], T2 value, typename T::AllocatorType& a) { - return GenericPointer(source, N - 1).Set(root, value, a); -} - -// No allocator parameter - -template -typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer& pointer, typename DocumentType::ValueType& value) { - return pointer.Set(document, value); -} - -template -typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer& pointer, const typename DocumentType::ValueType& value) { - return pointer.Set(document, value); -} - -template -typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer& pointer, const typename DocumentType::Ch* value) { - return pointer.Set(document, value); -} - -#if CEREAL_RAPIDJSON_HAS_STDSTRING -template -typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer& pointer, const std::basic_string& value) { - return pointer.Set(document, value); -} -#endif - -template -CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (typename DocumentType::ValueType&)) -SetValueByPointer(DocumentType& document, const GenericPointer& pointer, T2 value) { - return pointer.Set(document, value); -} - -template -typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], typename DocumentType::ValueType& value) { - return GenericPointer(source, N - 1).Set(document, value); -} - -template -typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], const typename DocumentType::ValueType& value) { - return GenericPointer(source, N - 1).Set(document, value); -} - -template -typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], const typename DocumentType::Ch* value) { - return GenericPointer(source, N - 1).Set(document, value); -} - -#if CEREAL_RAPIDJSON_HAS_STDSTRING -template -typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], const std::basic_string& value) { - return GenericPointer(source, N - 1).Set(document, value); -} -#endif - -template -CEREAL_RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (typename DocumentType::ValueType&)) -SetValueByPointer(DocumentType& document, const CharType(&source)[N], T2 value) { - return GenericPointer(source, N - 1).Set(document, value); -} - -////////////////////////////////////////////////////////////////////////////// - -template -typename T::ValueType& SwapValueByPointer(T& root, const GenericPointer& pointer, typename T::ValueType& value, typename T::AllocatorType& a) { - return pointer.Swap(root, value, a); -} - -template -typename T::ValueType& SwapValueByPointer(T& root, const CharType(&source)[N], typename T::ValueType& value, typename T::AllocatorType& a) { - return GenericPointer(source, N - 1).Swap(root, value, a); -} - -template -typename DocumentType::ValueType& SwapValueByPointer(DocumentType& document, const GenericPointer& pointer, typename DocumentType::ValueType& value) { - return pointer.Swap(document, value); -} - -template -typename DocumentType::ValueType& SwapValueByPointer(DocumentType& document, const CharType(&source)[N], typename DocumentType::ValueType& value) { - return GenericPointer(source, N - 1).Swap(document, value); -} - -////////////////////////////////////////////////////////////////////////////// - -template -bool EraseValueByPointer(T& root, const GenericPointer& pointer) { - return pointer.Erase(root); -} - -template -bool EraseValueByPointer(T& root, const CharType(&source)[N]) { - return GenericPointer(source, N - 1).Erase(root); -} - -//@} - -CEREAL_RAPIDJSON_NAMESPACE_END - -#if defined(__clang__) || defined(_MSC_VER) -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#endif // CEREAL_RAPIDJSON_POINTER_H_ diff --git a/include/cereal/external/rapidjson/prettywriter.h b/include/cereal/external/rapidjson/prettywriter.h deleted file mode 100644 index 0c2beb4..0000000 --- a/include/cereal/external/rapidjson/prettywriter.h +++ /dev/null @@ -1,277 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_PRETTYWRITER_H_ -#define CEREAL_RAPIDJSON_PRETTYWRITER_H_ - -#include "writer.h" - -#ifdef __GNUC__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(effc++) -#endif - -#if defined(__clang__) -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(c++98-compat) -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -//! Combination of PrettyWriter format flags. -/*! \see PrettyWriter::SetFormatOptions - */ -enum PrettyFormatOptions { - kFormatDefault = 0, //!< Default pretty formatting. - kFormatSingleLineArray = 1 //!< Format arrays on a single line. -}; - -//! Writer with indentation and spacing. -/*! - \tparam OutputStream Type of output os. - \tparam SourceEncoding Encoding of source string. - \tparam TargetEncoding Encoding of output stream. - \tparam StackAllocator Type of allocator for allocating memory of stack. -*/ -template, typename TargetEncoding = UTF8<>, typename StackAllocator = CrtAllocator, unsigned writeFlags = kWriteDefaultFlags> -class PrettyWriter : public Writer { -public: - typedef Writer Base; - typedef typename Base::Ch Ch; - - //! Constructor - /*! \param os Output stream. - \param allocator User supplied allocator. If it is null, it will create a private one. - \param levelDepth Initial capacity of stack. - */ - explicit PrettyWriter(OutputStream& os, StackAllocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) : - Base(os, allocator, levelDepth), indentChar_(' '), indentCharCount_(4), formatOptions_(kFormatDefault) {} - - - explicit PrettyWriter(StackAllocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) : - Base(allocator, levelDepth), indentChar_(' '), indentCharCount_(4) {} - -#if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - PrettyWriter(PrettyWriter&& rhs) : - Base(std::forward(rhs)), indentChar_(rhs.indentChar_), indentCharCount_(rhs.indentCharCount_), formatOptions_(rhs.formatOptions_) {} -#endif - - //! Set custom indentation. - /*! \param indentChar Character for indentation. Must be whitespace character (' ', '\\t', '\\n', '\\r'). - \param indentCharCount Number of indent characters for each indentation level. - \note The default indentation is 4 spaces. - */ - PrettyWriter& SetIndent(Ch indentChar, unsigned indentCharCount) { - CEREAL_RAPIDJSON_ASSERT(indentChar == ' ' || indentChar == '\t' || indentChar == '\n' || indentChar == '\r'); - indentChar_ = indentChar; - indentCharCount_ = indentCharCount; - return *this; - } - - //! Set pretty writer formatting options. - /*! \param options Formatting options. - */ - PrettyWriter& SetFormatOptions(PrettyFormatOptions options) { - formatOptions_ = options; - return *this; - } - - /*! @name Implementation of Handler - \see Handler - */ - //@{ - - bool Null() { PrettyPrefix(kNullType); return Base::EndValue(Base::WriteNull()); } - bool Bool(bool b) { PrettyPrefix(b ? kTrueType : kFalseType); return Base::EndValue(Base::WriteBool(b)); } - bool Int(int i) { PrettyPrefix(kNumberType); return Base::EndValue(Base::WriteInt(i)); } - bool Uint(unsigned u) { PrettyPrefix(kNumberType); return Base::EndValue(Base::WriteUint(u)); } - bool Int64(int64_t i64) { PrettyPrefix(kNumberType); return Base::EndValue(Base::WriteInt64(i64)); } - bool Uint64(uint64_t u64) { PrettyPrefix(kNumberType); return Base::EndValue(Base::WriteUint64(u64)); } - bool Double(double d) { PrettyPrefix(kNumberType); return Base::EndValue(Base::WriteDouble(d)); } - - bool RawNumber(const Ch* str, SizeType length, bool copy = false) { - CEREAL_RAPIDJSON_ASSERT(str != 0); - (void)copy; - PrettyPrefix(kNumberType); - return Base::EndValue(Base::WriteString(str, length)); - } - - bool String(const Ch* str, SizeType length, bool copy = false) { - CEREAL_RAPIDJSON_ASSERT(str != 0); - (void)copy; - PrettyPrefix(kStringType); - return Base::EndValue(Base::WriteString(str, length)); - } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - bool String(const std::basic_string& str) { - return String(str.data(), SizeType(str.size())); - } -#endif - - bool StartObject() { - PrettyPrefix(kObjectType); - new (Base::level_stack_.template Push()) typename Base::Level(false); - return Base::WriteStartObject(); - } - - bool Key(const Ch* str, SizeType length, bool copy = false) { return String(str, length, copy); } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - bool Key(const std::basic_string& str) { - return Key(str.data(), SizeType(str.size())); - } -#endif - - bool EndObject(SizeType memberCount = 0) { - (void)memberCount; - CEREAL_RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level)); // not inside an Object - CEREAL_RAPIDJSON_ASSERT(!Base::level_stack_.template Top()->inArray); // currently inside an Array, not Object - CEREAL_RAPIDJSON_ASSERT(0 == Base::level_stack_.template Top()->valueCount % 2); // Object has a Key without a Value - - bool empty = Base::level_stack_.template Pop(1)->valueCount == 0; - - if (!empty) { - Base::os_->Put('\n'); - WriteIndent(); - } - bool ret = Base::EndValue(Base::WriteEndObject()); - (void)ret; - CEREAL_RAPIDJSON_ASSERT(ret == true); - if (Base::level_stack_.Empty()) // end of json text - Base::Flush(); - return true; - } - - bool StartArray() { - PrettyPrefix(kArrayType); - new (Base::level_stack_.template Push()) typename Base::Level(true); - return Base::WriteStartArray(); - } - - bool EndArray(SizeType memberCount = 0) { - (void)memberCount; - CEREAL_RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level)); - CEREAL_RAPIDJSON_ASSERT(Base::level_stack_.template Top()->inArray); - bool empty = Base::level_stack_.template Pop(1)->valueCount == 0; - - if (!empty && !(formatOptions_ & kFormatSingleLineArray)) { - Base::os_->Put('\n'); - WriteIndent(); - } - bool ret = Base::EndValue(Base::WriteEndArray()); - (void)ret; - CEREAL_RAPIDJSON_ASSERT(ret == true); - if (Base::level_stack_.Empty()) // end of json text - Base::Flush(); - return true; - } - - //@} - - /*! @name Convenience extensions */ - //@{ - - //! Simpler but slower overload. - bool String(const Ch* str) { return String(str, internal::StrLen(str)); } - bool Key(const Ch* str) { return Key(str, internal::StrLen(str)); } - - //@} - - //! Write a raw JSON value. - /*! - For user to write a stringified JSON as a value. - - \param json A well-formed JSON value. It should not contain null character within [0, length - 1] range. - \param length Length of the json. - \param type Type of the root of json. - \note When using PrettyWriter::RawValue(), the result json may not be indented correctly. - */ - bool RawValue(const Ch* json, size_t length, Type type) { - CEREAL_RAPIDJSON_ASSERT(json != 0); - PrettyPrefix(type); - return Base::EndValue(Base::WriteRawValue(json, length)); - } - -protected: - void PrettyPrefix(Type type) { - (void)type; - if (Base::level_stack_.GetSize() != 0) { // this value is not at root - typename Base::Level* level = Base::level_stack_.template Top(); - - if (level->inArray) { - if (level->valueCount > 0) { - Base::os_->Put(','); // add comma if it is not the first element in array - if (formatOptions_ & kFormatSingleLineArray) - Base::os_->Put(' '); - } - - if (!(formatOptions_ & kFormatSingleLineArray)) { - Base::os_->Put('\n'); - WriteIndent(); - } - } - else { // in object - if (level->valueCount > 0) { - if (level->valueCount % 2 == 0) { - Base::os_->Put(','); - Base::os_->Put('\n'); - } - else { - Base::os_->Put(':'); - Base::os_->Put(' '); - } - } - else - Base::os_->Put('\n'); - - if (level->valueCount % 2 == 0) - WriteIndent(); - } - if (!level->inArray && level->valueCount % 2 == 0) - CEREAL_RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name - level->valueCount++; - } - else { - CEREAL_RAPIDJSON_ASSERT(!Base::hasRoot_); // Should only has one and only one root. - Base::hasRoot_ = true; - } - } - - void WriteIndent() { - size_t count = (Base::level_stack_.GetSize() / sizeof(typename Base::Level)) * indentCharCount_; - PutN(*Base::os_, static_cast(indentChar_), count); - } - - Ch indentChar_; - unsigned indentCharCount_; - PrettyFormatOptions formatOptions_; - -private: - // Prohibit copy constructor & assignment operator. - PrettyWriter(const PrettyWriter&); - PrettyWriter& operator=(const PrettyWriter&); -}; - -CEREAL_RAPIDJSON_NAMESPACE_END - -#if defined(__clang__) -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#ifdef __GNUC__ -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#endif // CEREAL_RAPIDJSON_CEREAL_RAPIDJSON_H_ diff --git a/include/cereal/external/rapidjson/rapidjson.h b/include/cereal/external/rapidjson/rapidjson.h deleted file mode 100644 index 3eefe60..0000000 --- a/include/cereal/external/rapidjson/rapidjson.h +++ /dev/null @@ -1,656 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_CEREAL_RAPIDJSON_H_ -#define CEREAL_RAPIDJSON_CEREAL_RAPIDJSON_H_ - -/*!\file rapidjson.h - \brief common definitions and configuration - - \see CEREAL_RAPIDJSON_CONFIG - */ - -/*! \defgroup CEREAL_RAPIDJSON_CONFIG RapidJSON configuration - \brief Configuration macros for library features - - Some RapidJSON features are configurable to adapt the library to a wide - variety of platforms, environments and usage scenarios. Most of the - features can be configured in terms of overridden or predefined - preprocessor macros at compile-time. - - Some additional customization is available in the \ref CEREAL_RAPIDJSON_ERRORS APIs. - - \note These macros should be given on the compiler command-line - (where applicable) to avoid inconsistent values when compiling - different translation units of a single application. - */ - -#include // malloc(), realloc(), free(), size_t -#include // memset(), memcpy(), memmove(), memcmp() - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_VERSION_STRING -// -// ALWAYS synchronize the following 3 macros with corresponding variables in /CMakeLists.txt. -// - -//!@cond CEREAL_RAPIDJSON_HIDDEN_FROM_DOXYGEN -// token stringification -#define CEREAL_RAPIDJSON_STRINGIFY(x) CEREAL_RAPIDJSON_DO_STRINGIFY(x) -#define CEREAL_RAPIDJSON_DO_STRINGIFY(x) #x - -// token concatenation -#define CEREAL_RAPIDJSON_JOIN(X, Y) CEREAL_RAPIDJSON_DO_JOIN(X, Y) -#define CEREAL_RAPIDJSON_DO_JOIN(X, Y) CEREAL_RAPIDJSON_DO_JOIN2(X, Y) -#define CEREAL_RAPIDJSON_DO_JOIN2(X, Y) X##Y -//!@endcond - -/*! \def CEREAL_RAPIDJSON_MAJOR_VERSION - \ingroup CEREAL_RAPIDJSON_CONFIG - \brief Major version of RapidJSON in integer. -*/ -/*! \def CEREAL_RAPIDJSON_MINOR_VERSION - \ingroup CEREAL_RAPIDJSON_CONFIG - \brief Minor version of RapidJSON in integer. -*/ -/*! \def CEREAL_RAPIDJSON_PATCH_VERSION - \ingroup CEREAL_RAPIDJSON_CONFIG - \brief Patch version of RapidJSON in integer. -*/ -/*! \def CEREAL_RAPIDJSON_VERSION_STRING - \ingroup CEREAL_RAPIDJSON_CONFIG - \brief Version of RapidJSON in ".." string format. -*/ -#define CEREAL_RAPIDJSON_MAJOR_VERSION 1 -#define CEREAL_RAPIDJSON_MINOR_VERSION 1 -#define CEREAL_RAPIDJSON_PATCH_VERSION 0 -#define CEREAL_RAPIDJSON_VERSION_STRING \ - CEREAL_RAPIDJSON_STRINGIFY(CEREAL_RAPIDJSON_MAJOR_VERSION.CEREAL_RAPIDJSON_MINOR_VERSION.CEREAL_RAPIDJSON_PATCH_VERSION) - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_NAMESPACE_(BEGIN|END) -/*! \def CEREAL_RAPIDJSON_NAMESPACE - \ingroup CEREAL_RAPIDJSON_CONFIG - \brief provide custom rapidjson namespace - - In order to avoid symbol clashes and/or "One Definition Rule" errors - between multiple inclusions of (different versions of) RapidJSON in - a single binary, users can customize the name of the main RapidJSON - namespace. - - In case of a single nesting level, defining \c CEREAL_RAPIDJSON_NAMESPACE - to a custom name (e.g. \c MyRapidJSON) is sufficient. If multiple - levels are needed, both \ref CEREAL_RAPIDJSON_NAMESPACE_BEGIN and \ref - CEREAL_RAPIDJSON_NAMESPACE_END need to be defined as well: - - \code - // in some .cpp file - #define CEREAL_RAPIDJSON_NAMESPACE my::rapidjson - #define CEREAL_RAPIDJSON_NAMESPACE_BEGIN namespace my { namespace rapidjson { - #define CEREAL_RAPIDJSON_NAMESPACE_END } } - #include "rapidjson/..." - \endcode - - \see rapidjson - */ -/*! \def CEREAL_RAPIDJSON_NAMESPACE_BEGIN - \ingroup CEREAL_RAPIDJSON_CONFIG - \brief provide custom rapidjson namespace (opening expression) - \see CEREAL_RAPIDJSON_NAMESPACE -*/ -/*! \def CEREAL_RAPIDJSON_NAMESPACE_END - \ingroup CEREAL_RAPIDJSON_CONFIG - \brief provide custom rapidjson namespace (closing expression) - \see CEREAL_RAPIDJSON_NAMESPACE -*/ -#ifndef CEREAL_RAPIDJSON_NAMESPACE -#define CEREAL_RAPIDJSON_NAMESPACE rapidjson -#endif -#ifndef CEREAL_RAPIDJSON_NAMESPACE_BEGIN -#define CEREAL_RAPIDJSON_NAMESPACE_BEGIN namespace CEREAL_RAPIDJSON_NAMESPACE { -#endif -#ifndef CEREAL_RAPIDJSON_NAMESPACE_END -#define CEREAL_RAPIDJSON_NAMESPACE_END } -#endif - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_HAS_STDSTRING - -#ifndef CEREAL_RAPIDJSON_HAS_STDSTRING -#ifdef CEREAL_RAPIDJSON_DOXYGEN_RUNNING -#define CEREAL_RAPIDJSON_HAS_STDSTRING 1 // force generation of documentation -#else -#define CEREAL_RAPIDJSON_HAS_STDSTRING 0 // no std::string support by default -#endif -/*! \def CEREAL_RAPIDJSON_HAS_STDSTRING - \ingroup CEREAL_RAPIDJSON_CONFIG - \brief Enable RapidJSON support for \c std::string - - By defining this preprocessor symbol to \c 1, several convenience functions for using - \ref rapidjson::GenericValue with \c std::string are enabled, especially - for construction and comparison. - - \hideinitializer -*/ -#endif // !defined(CEREAL_RAPIDJSON_HAS_STDSTRING) - -#if CEREAL_RAPIDJSON_HAS_STDSTRING -#include -#endif // CEREAL_RAPIDJSON_HAS_STDSTRING - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_NO_INT64DEFINE - -/*! \def CEREAL_RAPIDJSON_NO_INT64DEFINE - \ingroup CEREAL_RAPIDJSON_CONFIG - \brief Use external 64-bit integer types. - - RapidJSON requires the 64-bit integer types \c int64_t and \c uint64_t types - to be available at global scope. - - If users have their own definition, define CEREAL_RAPIDJSON_NO_INT64DEFINE to - prevent RapidJSON from defining its own types. -*/ -#ifndef CEREAL_RAPIDJSON_NO_INT64DEFINE -//!@cond CEREAL_RAPIDJSON_HIDDEN_FROM_DOXYGEN -#if defined(_MSC_VER) && (_MSC_VER < 1800) // Visual Studio 2013 -#include "msinttypes/stdint.h" -#include "msinttypes/inttypes.h" -#else -// Other compilers should have this. -#include -#include -#endif -//!@endcond -#ifdef CEREAL_RAPIDJSON_DOXYGEN_RUNNING -#define CEREAL_RAPIDJSON_NO_INT64DEFINE -#endif -#endif // CEREAL_RAPIDJSON_NO_INT64TYPEDEF - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_FORCEINLINE - -#ifndef CEREAL_RAPIDJSON_FORCEINLINE -//!@cond CEREAL_RAPIDJSON_HIDDEN_FROM_DOXYGEN -#if defined(_MSC_VER) && defined(NDEBUG) -#define CEREAL_RAPIDJSON_FORCEINLINE __forceinline -#elif defined(__GNUC__) && __GNUC__ >= 4 && defined(NDEBUG) -#define CEREAL_RAPIDJSON_FORCEINLINE __attribute__((always_inline)) -#else -#define CEREAL_RAPIDJSON_FORCEINLINE -#endif -//!@endcond -#endif // CEREAL_RAPIDJSON_FORCEINLINE - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_ENDIAN -#define CEREAL_RAPIDJSON_LITTLEENDIAN 0 //!< Little endian machine -#define CEREAL_RAPIDJSON_BIGENDIAN 1 //!< Big endian machine - -//! Endianness of the machine. -/*! - \def CEREAL_RAPIDJSON_ENDIAN - \ingroup CEREAL_RAPIDJSON_CONFIG - - GCC 4.6 provided macro for detecting endianness of the target machine. But other - compilers may not have this. User can define CEREAL_RAPIDJSON_ENDIAN to either - \ref CEREAL_RAPIDJSON_LITTLEENDIAN or \ref CEREAL_RAPIDJSON_BIGENDIAN. - - Default detection implemented with reference to - \li https://gcc.gnu.org/onlinedocs/gcc-4.6.0/cpp/Common-Predefined-Macros.html - \li http://www.boost.org/doc/libs/1_42_0/boost/detail/endian.hpp -*/ -#ifndef CEREAL_RAPIDJSON_ENDIAN -// Detect with GCC 4.6's macro -# ifdef __BYTE_ORDER__ -# if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ -# define CEREAL_RAPIDJSON_ENDIAN CEREAL_RAPIDJSON_LITTLEENDIAN -# elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ -# define CEREAL_RAPIDJSON_ENDIAN CEREAL_RAPIDJSON_BIGENDIAN -# else -# error Unknown machine endianness detected. User needs to define CEREAL_RAPIDJSON_ENDIAN. -# endif // __BYTE_ORDER__ -// Detect with GLIBC's endian.h -# elif defined(__GLIBC__) -# include -# if (__BYTE_ORDER == __LITTLE_ENDIAN) -# define CEREAL_RAPIDJSON_ENDIAN CEREAL_RAPIDJSON_LITTLEENDIAN -# elif (__BYTE_ORDER == __BIG_ENDIAN) -# define CEREAL_RAPIDJSON_ENDIAN CEREAL_RAPIDJSON_BIGENDIAN -# else -# error Unknown machine endianness detected. User needs to define CEREAL_RAPIDJSON_ENDIAN. -# endif // __GLIBC__ -// Detect with _LITTLE_ENDIAN and _BIG_ENDIAN macro -# elif defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN) -# define CEREAL_RAPIDJSON_ENDIAN CEREAL_RAPIDJSON_LITTLEENDIAN -# elif defined(_BIG_ENDIAN) && !defined(_LITTLE_ENDIAN) -# define CEREAL_RAPIDJSON_ENDIAN CEREAL_RAPIDJSON_BIGENDIAN -// Detect with architecture macros -# elif defined(__sparc) || defined(__sparc__) || defined(_POWER) || defined(__powerpc__) || defined(__ppc__) || defined(__hpux) || defined(__hppa) || defined(_MIPSEB) || defined(_POWER) || defined(__s390__) -# define CEREAL_RAPIDJSON_ENDIAN CEREAL_RAPIDJSON_BIGENDIAN -# 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__) -# define CEREAL_RAPIDJSON_ENDIAN CEREAL_RAPIDJSON_LITTLEENDIAN -# elif defined(_MSC_VER) && (defined(_M_ARM) || defined(_M_ARM64)) -# define CEREAL_RAPIDJSON_ENDIAN CEREAL_RAPIDJSON_LITTLEENDIAN -# elif defined(CEREAL_RAPIDJSON_DOXYGEN_RUNNING) -# define CEREAL_RAPIDJSON_ENDIAN -# else -# error Unknown machine endianness detected. User needs to define CEREAL_RAPIDJSON_ENDIAN. -# endif -#endif // CEREAL_RAPIDJSON_ENDIAN - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_64BIT - -//! Whether using 64-bit architecture -#ifndef CEREAL_RAPIDJSON_64BIT -#if defined(__LP64__) || (defined(__x86_64__) && defined(__ILP32__)) || defined(_WIN64) || defined(__EMSCRIPTEN__) -#define CEREAL_RAPIDJSON_64BIT 1 -#else -#define CEREAL_RAPIDJSON_64BIT 0 -#endif -#endif // CEREAL_RAPIDJSON_64BIT - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_ALIGN - -//! Data alignment of the machine. -/*! \ingroup CEREAL_RAPIDJSON_CONFIG - \param x pointer to align - - Some machines require strict data alignment. The default is 8 bytes. - User can customize by defining the CEREAL_RAPIDJSON_ALIGN function macro. -*/ -#ifndef CEREAL_RAPIDJSON_ALIGN -#define CEREAL_RAPIDJSON_ALIGN(x) (((x) + static_cast(7u)) & ~static_cast(7u)) -#endif - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_UINT64_C2 - -//! Construct a 64-bit literal by a pair of 32-bit integer. -/*! - 64-bit literal with or without ULL suffix is prone to compiler warnings. - UINT64_C() is C macro which cause compilation problems. - Use this macro to define 64-bit constants by a pair of 32-bit integer. -*/ -#ifndef CEREAL_RAPIDJSON_UINT64_C2 -#define CEREAL_RAPIDJSON_UINT64_C2(high32, low32) ((static_cast(high32) << 32) | static_cast(low32)) -#endif - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_48BITPOINTER_OPTIMIZATION - -//! Use only lower 48-bit address for some pointers. -/*! - \ingroup CEREAL_RAPIDJSON_CONFIG - - This optimization uses the fact that current X86-64 architecture only implement lower 48-bit virtual address. - The higher 16-bit can be used for storing other data. - \c GenericValue uses this optimization to reduce its size form 24 bytes to 16 bytes in 64-bit architecture. -*/ -#ifndef CEREAL_RAPIDJSON_48BITPOINTER_OPTIMIZATION -#if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64) -#define CEREAL_RAPIDJSON_48BITPOINTER_OPTIMIZATION 1 -#else -#define CEREAL_RAPIDJSON_48BITPOINTER_OPTIMIZATION 0 -#endif -#endif // CEREAL_RAPIDJSON_48BITPOINTER_OPTIMIZATION - -#if CEREAL_RAPIDJSON_48BITPOINTER_OPTIMIZATION == 1 -#if CEREAL_RAPIDJSON_64BIT != 1 -#error CEREAL_RAPIDJSON_48BITPOINTER_OPTIMIZATION can only be set to 1 when CEREAL_RAPIDJSON_64BIT=1 -#endif -#define CEREAL_RAPIDJSON_SETPOINTER(type, p, x) (p = reinterpret_cast((reinterpret_cast(p) & static_cast(CEREAL_RAPIDJSON_UINT64_C2(0xFFFF0000, 0x00000000))) | reinterpret_cast(reinterpret_cast(x)))) -#define CEREAL_RAPIDJSON_GETPOINTER(type, p) (reinterpret_cast(reinterpret_cast(p) & static_cast(CEREAL_RAPIDJSON_UINT64_C2(0x0000FFFF, 0xFFFFFFFF)))) -#else -#define CEREAL_RAPIDJSON_SETPOINTER(type, p, x) (p = (x)) -#define CEREAL_RAPIDJSON_GETPOINTER(type, p) (p) -#endif - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_SSE2/CEREAL_RAPIDJSON_SSE42/CEREAL_RAPIDJSON_NEON/CEREAL_RAPIDJSON_SIMD - -/*! \def CEREAL_RAPIDJSON_SIMD - \ingroup CEREAL_RAPIDJSON_CONFIG - \brief Enable SSE2/SSE4.2/Neon optimization. - - RapidJSON supports optimized implementations for some parsing operations - based on the SSE2, SSE4.2 or NEon SIMD extensions on modern Intel - or ARM compatible processors. - - To enable these optimizations, three different symbols can be defined; - \code - // Enable SSE2 optimization. - #define CEREAL_RAPIDJSON_SSE2 - - // Enable SSE4.2 optimization. - #define CEREAL_RAPIDJSON_SSE42 - \endcode - - // Enable ARM Neon optimization. - #define CEREAL_RAPIDJSON_NEON - \endcode - - \c CEREAL_RAPIDJSON_SSE42 takes precedence over SSE2, if both are defined. - - If any of these symbols is defined, RapidJSON defines the macro - \c CEREAL_RAPIDJSON_SIMD to indicate the availability of the optimized code. -*/ -#if defined(CEREAL_RAPIDJSON_SSE2) || defined(CEREAL_RAPIDJSON_SSE42) \ - || defined(CEREAL_RAPIDJSON_NEON) || defined(CEREAL_RAPIDJSON_DOXYGEN_RUNNING) -#define CEREAL_RAPIDJSON_SIMD -#endif - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_NO_SIZETYPEDEFINE - -#ifndef CEREAL_RAPIDJSON_NO_SIZETYPEDEFINE -/*! \def CEREAL_RAPIDJSON_NO_SIZETYPEDEFINE - \ingroup CEREAL_RAPIDJSON_CONFIG - \brief User-provided \c SizeType definition. - - In order to avoid using 32-bit size types for indexing strings and arrays, - define this preprocessor symbol and provide the type rapidjson::SizeType - before including RapidJSON: - \code - #define CEREAL_RAPIDJSON_NO_SIZETYPEDEFINE - namespace rapidjson { typedef ::std::size_t SizeType; } - #include "rapidjson/..." - \endcode - - \see rapidjson::SizeType -*/ -#ifdef CEREAL_RAPIDJSON_DOXYGEN_RUNNING -#define CEREAL_RAPIDJSON_NO_SIZETYPEDEFINE -#endif -CEREAL_RAPIDJSON_NAMESPACE_BEGIN -//! Size type (for string lengths, array sizes, etc.) -/*! RapidJSON uses 32-bit array/string indices even on 64-bit platforms, - instead of using \c size_t. Users may override the SizeType by defining - \ref CEREAL_RAPIDJSON_NO_SIZETYPEDEFINE. -*/ -typedef unsigned SizeType; -CEREAL_RAPIDJSON_NAMESPACE_END -#endif - -// always import std::size_t to rapidjson namespace -CEREAL_RAPIDJSON_NAMESPACE_BEGIN -using std::size_t; -CEREAL_RAPIDJSON_NAMESPACE_END - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_ASSERT - -//! Assertion. -/*! \ingroup CEREAL_RAPIDJSON_CONFIG - By default, rapidjson uses C \c assert() for internal assertions. - User can override it by defining CEREAL_RAPIDJSON_ASSERT(x) macro. - - \note Parsing errors are handled and can be customized by the - \ref CEREAL_RAPIDJSON_ERRORS APIs. -*/ -#ifndef CEREAL_RAPIDJSON_ASSERT -#include -#define CEREAL_RAPIDJSON_ASSERT(x) assert(x) -#endif // CEREAL_RAPIDJSON_ASSERT - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_STATIC_ASSERT - -// Prefer C++11 static_assert, if available -#ifndef CEREAL_RAPIDJSON_STATIC_ASSERT -#if __cplusplus >= 201103L || ( defined(_MSC_VER) && _MSC_VER >= 1800 ) -#define CEREAL_RAPIDJSON_STATIC_ASSERT(x) \ - static_assert(x, CEREAL_RAPIDJSON_STRINGIFY(x)) -#endif // C++11 -#endif // CEREAL_RAPIDJSON_STATIC_ASSERT - -// Adopt C++03 implementation from boost -#ifndef CEREAL_RAPIDJSON_STATIC_ASSERT -#ifndef __clang__ -//!@cond CEREAL_RAPIDJSON_HIDDEN_FROM_DOXYGEN -#endif -CEREAL_RAPIDJSON_NAMESPACE_BEGIN -template struct STATIC_ASSERTION_FAILURE; -template <> struct STATIC_ASSERTION_FAILURE { enum { value = 1 }; }; -template struct StaticAssertTest {}; -CEREAL_RAPIDJSON_NAMESPACE_END - -#if defined(__GNUC__) || defined(__clang__) -#define CEREAL_RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE __attribute__((unused)) -#else -#define CEREAL_RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE -#endif -#ifndef __clang__ -//!@endcond -#endif - -/*! \def CEREAL_RAPIDJSON_STATIC_ASSERT - \brief (Internal) macro to check for conditions at compile-time - \param x compile-time condition - \hideinitializer - */ -#define CEREAL_RAPIDJSON_STATIC_ASSERT(x) \ - typedef ::CEREAL_RAPIDJSON_NAMESPACE::StaticAssertTest< \ - sizeof(::CEREAL_RAPIDJSON_NAMESPACE::STATIC_ASSERTION_FAILURE)> \ - CEREAL_RAPIDJSON_JOIN(StaticAssertTypedef, __LINE__) CEREAL_RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE -#endif // CEREAL_RAPIDJSON_STATIC_ASSERT - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_LIKELY, CEREAL_RAPIDJSON_UNLIKELY - -//! Compiler branching hint for expression with high probability to be true. -/*! - \ingroup CEREAL_RAPIDJSON_CONFIG - \param x Boolean expression likely to be true. -*/ -#ifndef CEREAL_RAPIDJSON_LIKELY -#if defined(__GNUC__) || defined(__clang__) -#define CEREAL_RAPIDJSON_LIKELY(x) __builtin_expect(!!(x), 1) -#else -#define CEREAL_RAPIDJSON_LIKELY(x) (x) -#endif -#endif - -//! Compiler branching hint for expression with low probability to be true. -/*! - \ingroup CEREAL_RAPIDJSON_CONFIG - \param x Boolean expression unlikely to be true. -*/ -#ifndef CEREAL_RAPIDJSON_UNLIKELY -#if defined(__GNUC__) || defined(__clang__) -#define CEREAL_RAPIDJSON_UNLIKELY(x) __builtin_expect(!!(x), 0) -#else -#define CEREAL_RAPIDJSON_UNLIKELY(x) (x) -#endif -#endif - -/////////////////////////////////////////////////////////////////////////////// -// Helpers - -//!@cond CEREAL_RAPIDJSON_HIDDEN_FROM_DOXYGEN - -#define CEREAL_RAPIDJSON_MULTILINEMACRO_BEGIN do { -#define CEREAL_RAPIDJSON_MULTILINEMACRO_END \ -} while((void)0, 0) - -// adopted from Boost -#define CEREAL_RAPIDJSON_VERSION_CODE(x,y,z) \ - (((x)*100000) + ((y)*100) + (z)) - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_DIAG_PUSH/POP, CEREAL_RAPIDJSON_DIAG_OFF - -#if defined(__GNUC__) -#define CEREAL_RAPIDJSON_GNUC \ - CEREAL_RAPIDJSON_VERSION_CODE(__GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__) -#endif - -#if defined(__clang__) || (defined(CEREAL_RAPIDJSON_GNUC) && CEREAL_RAPIDJSON_GNUC >= CEREAL_RAPIDJSON_VERSION_CODE(4,2,0)) - -#define CEREAL_RAPIDJSON_PRAGMA(x) _Pragma(CEREAL_RAPIDJSON_STRINGIFY(x)) -#define CEREAL_RAPIDJSON_DIAG_PRAGMA(x) CEREAL_RAPIDJSON_PRAGMA(GCC diagnostic x) -#define CEREAL_RAPIDJSON_DIAG_OFF(x) \ - CEREAL_RAPIDJSON_DIAG_PRAGMA(ignored CEREAL_RAPIDJSON_STRINGIFY(CEREAL_RAPIDJSON_JOIN(-W,x))) - -// push/pop support in Clang and GCC>=4.6 -#if defined(__clang__) || (defined(CEREAL_RAPIDJSON_GNUC) && CEREAL_RAPIDJSON_GNUC >= CEREAL_RAPIDJSON_VERSION_CODE(4,6,0)) -#define CEREAL_RAPIDJSON_DIAG_PUSH CEREAL_RAPIDJSON_DIAG_PRAGMA(push) -#define CEREAL_RAPIDJSON_DIAG_POP CEREAL_RAPIDJSON_DIAG_PRAGMA(pop) -#else // GCC >= 4.2, < 4.6 -#define CEREAL_RAPIDJSON_DIAG_PUSH /* ignored */ -#define CEREAL_RAPIDJSON_DIAG_POP /* ignored */ -#endif - -#elif defined(_MSC_VER) - -// pragma (MSVC specific) -#define CEREAL_RAPIDJSON_PRAGMA(x) __pragma(x) -#define CEREAL_RAPIDJSON_DIAG_PRAGMA(x) CEREAL_RAPIDJSON_PRAGMA(warning(x)) - -#define CEREAL_RAPIDJSON_DIAG_OFF(x) CEREAL_RAPIDJSON_DIAG_PRAGMA(disable: x) -#define CEREAL_RAPIDJSON_DIAG_PUSH CEREAL_RAPIDJSON_DIAG_PRAGMA(push) -#define CEREAL_RAPIDJSON_DIAG_POP CEREAL_RAPIDJSON_DIAG_PRAGMA(pop) - -#else - -#define CEREAL_RAPIDJSON_DIAG_OFF(x) /* ignored */ -#define CEREAL_RAPIDJSON_DIAG_PUSH /* ignored */ -#define CEREAL_RAPIDJSON_DIAG_POP /* ignored */ - -#endif // CEREAL_RAPIDJSON_DIAG_* - -/////////////////////////////////////////////////////////////////////////////// -// C++11 features - -#ifndef CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS -#if defined(__clang__) -#if __has_feature(cxx_rvalue_references) && \ - (defined(_MSC_VER) || defined(_LIBCPP_VERSION) || defined(__GLIBCXX__) && __GLIBCXX__ >= 20080306) -#define CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS 1 -#else -#define CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS 0 -#endif -#elif (defined(CEREAL_RAPIDJSON_GNUC) && (CEREAL_RAPIDJSON_GNUC >= CEREAL_RAPIDJSON_VERSION_CODE(4,3,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__)) || \ - (defined(_MSC_VER) && _MSC_VER >= 1600) || \ - (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140 && defined(__GXX_EXPERIMENTAL_CXX0X__)) - -#define CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS 1 -#else -#define CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS 0 -#endif -#endif // CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - -#ifndef CEREAL_RAPIDJSON_HAS_CXX11_NOEXCEPT -#if defined(__clang__) -#define CEREAL_RAPIDJSON_HAS_CXX11_NOEXCEPT __has_feature(cxx_noexcept) -#elif (defined(CEREAL_RAPIDJSON_GNUC) && (CEREAL_RAPIDJSON_GNUC >= CEREAL_RAPIDJSON_VERSION_CODE(4,6,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__)) || \ - (defined(_MSC_VER) && _MSC_VER >= 1900) || \ - (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140 && defined(__GXX_EXPERIMENTAL_CXX0X__)) -#define CEREAL_RAPIDJSON_HAS_CXX11_NOEXCEPT 1 -#else -#define CEREAL_RAPIDJSON_HAS_CXX11_NOEXCEPT 0 -#endif -#endif -#if CEREAL_RAPIDJSON_HAS_CXX11_NOEXCEPT -#define CEREAL_RAPIDJSON_NOEXCEPT noexcept -#else -#define CEREAL_RAPIDJSON_NOEXCEPT /* noexcept */ -#endif // CEREAL_RAPIDJSON_HAS_CXX11_NOEXCEPT - -// no automatic detection, yet -#ifndef CEREAL_RAPIDJSON_HAS_CXX11_TYPETRAITS -#if (defined(_MSC_VER) && _MSC_VER >= 1700) -#define CEREAL_RAPIDJSON_HAS_CXX11_TYPETRAITS 1 -#else -#define CEREAL_RAPIDJSON_HAS_CXX11_TYPETRAITS 0 -#endif -#endif - -#ifndef CEREAL_RAPIDJSON_HAS_CXX11_RANGE_FOR -#if defined(__clang__) -#define CEREAL_RAPIDJSON_HAS_CXX11_RANGE_FOR __has_feature(cxx_range_for) -#elif (defined(CEREAL_RAPIDJSON_GNUC) && (CEREAL_RAPIDJSON_GNUC >= CEREAL_RAPIDJSON_VERSION_CODE(4,6,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__)) || \ - (defined(_MSC_VER) && _MSC_VER >= 1700) || \ - (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5140 && defined(__GXX_EXPERIMENTAL_CXX0X__)) -#define CEREAL_RAPIDJSON_HAS_CXX11_RANGE_FOR 1 -#else -#define CEREAL_RAPIDJSON_HAS_CXX11_RANGE_FOR 0 -#endif -#endif // CEREAL_RAPIDJSON_HAS_CXX11_RANGE_FOR - -//!@endcond - -//! Assertion (in non-throwing contexts). - /*! \ingroup CEREAL_RAPIDJSON_CONFIG - Some functions provide a \c noexcept guarantee, if the compiler supports it. - In these cases, the \ref CEREAL_RAPIDJSON_ASSERT macro cannot be overridden to - throw an exception. This macro adds a separate customization point for - such cases. - - Defaults to C \c assert() (as \ref CEREAL_RAPIDJSON_ASSERT), if \c noexcept is - supported, and to \ref CEREAL_RAPIDJSON_ASSERT otherwise. - */ - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_NOEXCEPT_ASSERT - -#ifndef CEREAL_RAPIDJSON_NOEXCEPT_ASSERT -#ifdef CEREAL_RAPIDJSON_ASSERT_THROWS -#if CEREAL_RAPIDJSON_HAS_CXX11_NOEXCEPT -#define CEREAL_RAPIDJSON_NOEXCEPT_ASSERT(x) -#else -#define CEREAL_RAPIDJSON_NOEXCEPT_ASSERT(x) CEREAL_RAPIDJSON_ASSERT(x) -#endif // CEREAL_RAPIDJSON_HAS_CXX11_NOEXCEPT -#else -#define CEREAL_RAPIDJSON_NOEXCEPT_ASSERT(x) CEREAL_RAPIDJSON_ASSERT(x) -#endif // CEREAL_RAPIDJSON_ASSERT_THROWS -#endif // CEREAL_RAPIDJSON_NOEXCEPT_ASSERT - -/////////////////////////////////////////////////////////////////////////////// -// new/delete - -#ifndef CEREAL_RAPIDJSON_NEW -///! customization point for global \c new -#define CEREAL_RAPIDJSON_NEW(TypeName) new TypeName -#endif -#ifndef CEREAL_RAPIDJSON_DELETE -///! customization point for global \c delete -#define CEREAL_RAPIDJSON_DELETE(x) delete x -#endif - -/////////////////////////////////////////////////////////////////////////////// -// Type - -/*! \namespace rapidjson - \brief main RapidJSON namespace - \see CEREAL_RAPIDJSON_NAMESPACE -*/ -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -//! Type of JSON value -enum Type { - kNullType = 0, //!< null - kFalseType = 1, //!< false - kTrueType = 2, //!< true - kObjectType = 3, //!< object - kArrayType = 4, //!< array - kStringType = 5, //!< string - kNumberType = 6 //!< number -}; - -CEREAL_RAPIDJSON_NAMESPACE_END - -#endif // CEREAL_RAPIDJSON_CEREAL_RAPIDJSON_H_ diff --git a/include/cereal/external/rapidjson/reader.h b/include/cereal/external/rapidjson/reader.h deleted file mode 100644 index 43eb525..0000000 --- a/include/cereal/external/rapidjson/reader.h +++ /dev/null @@ -1,2230 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_READER_H_ -#define CEREAL_RAPIDJSON_READER_H_ - -/*! \file reader.h */ - -#include "allocators.h" -#include "stream.h" -#include "encodedstream.h" -#include "internal/meta.h" -#include "internal/stack.h" -#include "internal/strtod.h" -#include - -#if defined(CEREAL_RAPIDJSON_SIMD) && defined(_MSC_VER) -#include -#pragma intrinsic(_BitScanForward) -#endif -#ifdef CEREAL_RAPIDJSON_SSE42 -#include -#elif defined(CEREAL_RAPIDJSON_SSE2) -#include -#elif defined(CEREAL_RAPIDJSON_NEON) -#include -#endif - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(old-style-cast) -CEREAL_RAPIDJSON_DIAG_OFF(padded) -CEREAL_RAPIDJSON_DIAG_OFF(switch-enum) -#elif defined(_MSC_VER) -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant -CEREAL_RAPIDJSON_DIAG_OFF(4702) // unreachable code -#endif - -#ifdef __GNUC__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(effc++) -#endif - -//!@cond CEREAL_RAPIDJSON_HIDDEN_FROM_DOXYGEN -#define CEREAL_RAPIDJSON_NOTHING /* deliberately empty */ -#ifndef CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN -#define CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(value) \ - CEREAL_RAPIDJSON_MULTILINEMACRO_BEGIN \ - if (CEREAL_RAPIDJSON_UNLIKELY(HasParseError())) { return value; } \ - CEREAL_RAPIDJSON_MULTILINEMACRO_END -#endif -#define CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID \ - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(CEREAL_RAPIDJSON_NOTHING) -//!@endcond - -/*! \def CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN - \ingroup CEREAL_RAPIDJSON_ERRORS - \brief Macro to indicate a parse error. - \param parseErrorCode \ref rapidjson::ParseErrorCode of the error - \param offset position of the error in JSON input (\c size_t) - - This macros can be used as a customization point for the internal - error handling mechanism of RapidJSON. - - A common usage model is to throw an exception instead of requiring the - caller to explicitly check the \ref rapidjson::GenericReader::Parse's - return value: - - \code - #define CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode,offset) \ - throw ParseException(parseErrorCode, #parseErrorCode, offset) - - #include // std::runtime_error - #include "rapidjson/error/error.h" // rapidjson::ParseResult - - struct ParseException : std::runtime_error, rapidjson::ParseResult { - ParseException(rapidjson::ParseErrorCode code, const char* msg, size_t offset) - : std::runtime_error(msg), ParseResult(code, offset) {} - }; - - #include "rapidjson/reader.h" - \endcode - - \see CEREAL_RAPIDJSON_PARSE_ERROR, rapidjson::GenericReader::Parse - */ -#ifndef CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN -#define CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset) \ - CEREAL_RAPIDJSON_MULTILINEMACRO_BEGIN \ - CEREAL_RAPIDJSON_ASSERT(!HasParseError()); /* Error can only be assigned once */ \ - SetParseError(parseErrorCode, offset); \ - CEREAL_RAPIDJSON_MULTILINEMACRO_END -#endif - -/*! \def CEREAL_RAPIDJSON_PARSE_ERROR - \ingroup CEREAL_RAPIDJSON_ERRORS - \brief (Internal) macro to indicate and handle a parse error. - \param parseErrorCode \ref rapidjson::ParseErrorCode of the error - \param offset position of the error in JSON input (\c size_t) - - Invokes CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN and stops the parsing. - - \see CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN - \hideinitializer - */ -#ifndef CEREAL_RAPIDJSON_PARSE_ERROR -#define CEREAL_RAPIDJSON_PARSE_ERROR(parseErrorCode, offset) \ - CEREAL_RAPIDJSON_MULTILINEMACRO_BEGIN \ - CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset); \ - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; \ - CEREAL_RAPIDJSON_MULTILINEMACRO_END -#endif - -#include "error/error.h" // ParseErrorCode, ParseResult - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -/////////////////////////////////////////////////////////////////////////////// -// ParseFlag - -/*! \def CEREAL_RAPIDJSON_PARSE_DEFAULT_FLAGS - \ingroup CEREAL_RAPIDJSON_CONFIG - \brief User-defined kParseDefaultFlags definition. - - User can define this as any \c ParseFlag combinations. -*/ -#ifndef CEREAL_RAPIDJSON_PARSE_DEFAULT_FLAGS -#define CEREAL_RAPIDJSON_PARSE_DEFAULT_FLAGS kParseNoFlags -#endif - -//! Combination of parseFlags -/*! \see Reader::Parse, Document::Parse, Document::ParseInsitu, Document::ParseStream - */ -enum ParseFlag { - kParseNoFlags = 0, //!< No flags are set. - kParseInsituFlag = 1, //!< In-situ(destructive) parsing. - kParseValidateEncodingFlag = 2, //!< Validate encoding of JSON strings. - kParseIterativeFlag = 4, //!< Iterative(constant complexity in terms of function call stack size) parsing. - kParseStopWhenDoneFlag = 8, //!< After parsing a complete JSON root from stream, stop further processing the rest of stream. When this flag is used, parser will not generate kParseErrorDocumentRootNotSingular error. - kParseFullPrecisionFlag = 16, //!< Parse number in full precision (but slower). - kParseCommentsFlag = 32, //!< Allow one-line (//) and multi-line (/**/) comments. - kParseNumbersAsStringsFlag = 64, //!< Parse all numbers (ints/doubles) as strings. - kParseTrailingCommasFlag = 128, //!< Allow trailing commas at the end of objects and arrays. - kParseNanAndInfFlag = 256, //!< Allow parsing NaN, Inf, Infinity, -Inf and -Infinity as doubles. - kParseDefaultFlags = CEREAL_RAPIDJSON_PARSE_DEFAULT_FLAGS //!< Default parse flags. Can be customized by defining CEREAL_RAPIDJSON_PARSE_DEFAULT_FLAGS -}; - -/////////////////////////////////////////////////////////////////////////////// -// Handler - -/*! \class rapidjson::Handler - \brief Concept for receiving events from GenericReader upon parsing. - The functions return true if no error occurs. If they return false, - the event publisher should terminate the process. -\code -concept Handler { - typename Ch; - - bool Null(); - bool Bool(bool b); - bool Int(int i); - bool Uint(unsigned i); - bool Int64(int64_t i); - bool Uint64(uint64_t i); - bool Double(double d); - /// enabled via kParseNumbersAsStringsFlag, string is not null-terminated (use length) - bool RawNumber(const Ch* str, SizeType length, bool copy); - bool String(const Ch* str, SizeType length, bool copy); - bool StartObject(); - bool Key(const Ch* str, SizeType length, bool copy); - bool EndObject(SizeType memberCount); - bool StartArray(); - bool EndArray(SizeType elementCount); -}; -\endcode -*/ -/////////////////////////////////////////////////////////////////////////////// -// BaseReaderHandler - -//! Default implementation of Handler. -/*! This can be used as base class of any reader handler. - \note implements Handler concept -*/ -template, typename Derived = void> -struct BaseReaderHandler { - typedef typename Encoding::Ch Ch; - - typedef typename internal::SelectIf, BaseReaderHandler, Derived>::Type Override; - - bool Default() { return true; } - bool Null() { return static_cast(*this).Default(); } - bool Bool(bool) { return static_cast(*this).Default(); } - bool Int(int) { return static_cast(*this).Default(); } - bool Uint(unsigned) { return static_cast(*this).Default(); } - bool Int64(int64_t) { return static_cast(*this).Default(); } - bool Uint64(uint64_t) { return static_cast(*this).Default(); } - bool Double(double) { return static_cast(*this).Default(); } - /// enabled via kParseNumbersAsStringsFlag, string is not null-terminated (use length) - bool RawNumber(const Ch* str, SizeType len, bool copy) { return static_cast(*this).String(str, len, copy); } - bool String(const Ch*, SizeType, bool) { return static_cast(*this).Default(); } - bool StartObject() { return static_cast(*this).Default(); } - bool Key(const Ch* str, SizeType len, bool copy) { return static_cast(*this).String(str, len, copy); } - bool EndObject(SizeType) { return static_cast(*this).Default(); } - bool StartArray() { return static_cast(*this).Default(); } - bool EndArray(SizeType) { return static_cast(*this).Default(); } -}; - -/////////////////////////////////////////////////////////////////////////////// -// StreamLocalCopy - -namespace internal { - -template::copyOptimization> -class StreamLocalCopy; - -//! Do copy optimization. -template -class StreamLocalCopy { -public: - StreamLocalCopy(Stream& original) : s(original), original_(original) {} - ~StreamLocalCopy() { original_ = s; } - - Stream s; - -private: - StreamLocalCopy& operator=(const StreamLocalCopy&) /* = delete */; - - Stream& original_; -}; - -//! Keep reference. -template -class StreamLocalCopy { -public: - StreamLocalCopy(Stream& original) : s(original) {} - - Stream& s; - -private: - StreamLocalCopy& operator=(const StreamLocalCopy&) /* = delete */; -}; - -} // namespace internal - -/////////////////////////////////////////////////////////////////////////////// -// SkipWhitespace - -//! Skip the JSON white spaces in a stream. -/*! \param is A input stream for skipping white spaces. - \note This function has SSE2/SSE4.2 specialization. -*/ -template -void SkipWhitespace(InputStream& is) { - internal::StreamLocalCopy copy(is); - InputStream& s(copy.s); - - typename InputStream::Ch c; - while ((c = s.Peek()) == ' ' || c == '\n' || c == '\r' || c == '\t') - s.Take(); -} - -inline const char* SkipWhitespace(const char* p, const char* end) { - while (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) - ++p; - return p; -} - -#ifdef CEREAL_RAPIDJSON_SSE42 -//! Skip whitespace with SSE 4.2 pcmpistrm instruction, testing 16 8-byte characters at once. -inline const char *SkipWhitespace_SIMD(const char* p) { - // Fast return for single non-whitespace - if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') - ++p; - else - return p; - - // 16-byte align to the next boundary - const char* nextAligned = reinterpret_cast((reinterpret_cast(p) + 15) & static_cast(~15)); - while (p != nextAligned) - if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') - ++p; - else - return p; - - // The rest of string using SIMD - static const char whitespace[16] = " \n\r\t"; - const __m128i w = _mm_loadu_si128(reinterpret_cast(&whitespace[0])); - - for (;; p += 16) { - const __m128i s = _mm_load_si128(reinterpret_cast(p)); - const int r = _mm_cmpistri(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_LEAST_SIGNIFICANT | _SIDD_NEGATIVE_POLARITY); - if (r != 16) // some of characters is non-whitespace - return p + r; - } -} - -inline const char *SkipWhitespace_SIMD(const char* p, const char* end) { - // Fast return for single non-whitespace - if (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) - ++p; - else - return p; - - // The middle of string using SIMD - static const char whitespace[16] = " \n\r\t"; - const __m128i w = _mm_loadu_si128(reinterpret_cast(&whitespace[0])); - - for (; p <= end - 16; p += 16) { - const __m128i s = _mm_loadu_si128(reinterpret_cast(p)); - const int r = _mm_cmpistri(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_LEAST_SIGNIFICANT | _SIDD_NEGATIVE_POLARITY); - if (r != 16) // some of characters is non-whitespace - return p + r; - } - - return SkipWhitespace(p, end); -} - -#elif defined(CEREAL_RAPIDJSON_SSE2) - -//! Skip whitespace with SSE2 instructions, testing 16 8-byte characters at once. -inline const char *SkipWhitespace_SIMD(const char* p) { - // Fast return for single non-whitespace - if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') - ++p; - else - return p; - - // 16-byte align to the next boundary - const char* nextAligned = reinterpret_cast((reinterpret_cast(p) + 15) & static_cast(~15)); - while (p != nextAligned) - if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') - ++p; - else - return p; - - // The rest of string - #define C16(c) { c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c } - static const char whitespaces[4][16] = { C16(' '), C16('\n'), C16('\r'), C16('\t') }; - #undef C16 - - const __m128i w0 = _mm_loadu_si128(reinterpret_cast(&whitespaces[0][0])); - const __m128i w1 = _mm_loadu_si128(reinterpret_cast(&whitespaces[1][0])); - const __m128i w2 = _mm_loadu_si128(reinterpret_cast(&whitespaces[2][0])); - const __m128i w3 = _mm_loadu_si128(reinterpret_cast(&whitespaces[3][0])); - - for (;; p += 16) { - const __m128i s = _mm_load_si128(reinterpret_cast(p)); - __m128i x = _mm_cmpeq_epi8(s, w0); - x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w1)); - x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w2)); - x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w3)); - unsigned short r = static_cast(~_mm_movemask_epi8(x)); - if (r != 0) { // some of characters may be non-whitespace -#ifdef _MSC_VER // Find the index of first non-whitespace - unsigned long offset; - _BitScanForward(&offset, r); - return p + offset; -#else - return p + __builtin_ffs(r) - 1; -#endif - } - } -} - -inline const char *SkipWhitespace_SIMD(const char* p, const char* end) { - // Fast return for single non-whitespace - if (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) - ++p; - else - return p; - - // The rest of string - #define C16(c) { c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c } - static const char whitespaces[4][16] = { C16(' '), C16('\n'), C16('\r'), C16('\t') }; - #undef C16 - - const __m128i w0 = _mm_loadu_si128(reinterpret_cast(&whitespaces[0][0])); - const __m128i w1 = _mm_loadu_si128(reinterpret_cast(&whitespaces[1][0])); - const __m128i w2 = _mm_loadu_si128(reinterpret_cast(&whitespaces[2][0])); - const __m128i w3 = _mm_loadu_si128(reinterpret_cast(&whitespaces[3][0])); - - for (; p <= end - 16; p += 16) { - const __m128i s = _mm_loadu_si128(reinterpret_cast(p)); - __m128i x = _mm_cmpeq_epi8(s, w0); - x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w1)); - x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w2)); - x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w3)); - unsigned short r = static_cast(~_mm_movemask_epi8(x)); - if (r != 0) { // some of characters may be non-whitespace -#ifdef _MSC_VER // Find the index of first non-whitespace - unsigned long offset; - _BitScanForward(&offset, r); - return p + offset; -#else - return p + __builtin_ffs(r) - 1; -#endif - } - } - - return SkipWhitespace(p, end); -} - -#elif defined(CEREAL_RAPIDJSON_NEON) - -//! Skip whitespace with ARM Neon instructions, testing 16 8-byte characters at once. -inline const char *SkipWhitespace_SIMD(const char* p) { - // Fast return for single non-whitespace - if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') - ++p; - else - return p; - - // 16-byte align to the next boundary - const char* nextAligned = reinterpret_cast((reinterpret_cast(p) + 15) & static_cast(~15)); - while (p != nextAligned) - if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') - ++p; - else - return p; - - const uint8x16_t w0 = vmovq_n_u8(' '); - const uint8x16_t w1 = vmovq_n_u8('\n'); - const uint8x16_t w2 = vmovq_n_u8('\r'); - const uint8x16_t w3 = vmovq_n_u8('\t'); - - for (;; p += 16) { - const uint8x16_t s = vld1q_u8(reinterpret_cast(p)); - uint8x16_t x = vceqq_u8(s, w0); - x = vorrq_u8(x, vceqq_u8(s, w1)); - x = vorrq_u8(x, vceqq_u8(s, w2)); - x = vorrq_u8(x, vceqq_u8(s, w3)); - - x = vmvnq_u8(x); // Negate - x = vrev64q_u8(x); // Rev in 64 - uint64_t low = vgetq_lane_u64(reinterpret_cast(x), 0); // extract - uint64_t high = vgetq_lane_u64(reinterpret_cast(x), 1); // extract - - if (low == 0) { - if (high != 0) { - int lz =__builtin_clzll(high);; - return p + 8 + (lz >> 3); - } - } else { - int lz = __builtin_clzll(low);; - return p + (lz >> 3); - } - } -} - -inline const char *SkipWhitespace_SIMD(const char* p, const char* end) { - // Fast return for single non-whitespace - if (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) - ++p; - else - return p; - - const uint8x16_t w0 = vmovq_n_u8(' '); - const uint8x16_t w1 = vmovq_n_u8('\n'); - const uint8x16_t w2 = vmovq_n_u8('\r'); - const uint8x16_t w3 = vmovq_n_u8('\t'); - - for (; p <= end - 16; p += 16) { - const uint8x16_t s = vld1q_u8(reinterpret_cast(p)); - uint8x16_t x = vceqq_u8(s, w0); - x = vorrq_u8(x, vceqq_u8(s, w1)); - x = vorrq_u8(x, vceqq_u8(s, w2)); - x = vorrq_u8(x, vceqq_u8(s, w3)); - - x = vmvnq_u8(x); // Negate - x = vrev64q_u8(x); // Rev in 64 - uint64_t low = vgetq_lane_u64(reinterpret_cast(x), 0); // extract - uint64_t high = vgetq_lane_u64(reinterpret_cast(x), 1); // extract - - if (low == 0) { - if (high != 0) { - int lz = __builtin_clzll(high); - return p + 8 + (lz >> 3); - } - } else { - int lz = __builtin_clzll(low); - return p + (lz >> 3); - } - } - - return SkipWhitespace(p, end); -} - -#endif // CEREAL_RAPIDJSON_NEON - -#ifdef CEREAL_RAPIDJSON_SIMD -//! Template function specialization for InsituStringStream -template<> inline void SkipWhitespace(InsituStringStream& is) { - is.src_ = const_cast(SkipWhitespace_SIMD(is.src_)); -} - -//! Template function specialization for StringStream -template<> inline void SkipWhitespace(StringStream& is) { - is.src_ = SkipWhitespace_SIMD(is.src_); -} - -template<> inline void SkipWhitespace(EncodedInputStream, MemoryStream>& is) { - is.is_.src_ = SkipWhitespace_SIMD(is.is_.src_, is.is_.end_); -} -#endif // CEREAL_RAPIDJSON_SIMD - -/////////////////////////////////////////////////////////////////////////////// -// GenericReader - -//! SAX-style JSON parser. Use \ref Reader for UTF8 encoding and default allocator. -/*! GenericReader parses JSON text from a stream, and send events synchronously to an - object implementing Handler concept. - - It needs to allocate a stack for storing a single decoded string during - non-destructive parsing. - - For in-situ parsing, the decoded string is directly written to the source - text string, no temporary buffer is required. - - A GenericReader object can be reused for parsing multiple JSON text. - - \tparam SourceEncoding Encoding of the input stream. - \tparam TargetEncoding Encoding of the parse output. - \tparam StackAllocator Allocator type for stack. -*/ -template -class GenericReader { -public: - typedef typename SourceEncoding::Ch Ch; //!< SourceEncoding character type - - //! Constructor. - /*! \param stackAllocator Optional allocator for allocating stack memory. (Only use for non-destructive parsing) - \param stackCapacity stack capacity in bytes for storing a single decoded string. (Only use for non-destructive parsing) - */ - GenericReader(StackAllocator* stackAllocator = 0, size_t stackCapacity = kDefaultStackCapacity) : - stack_(stackAllocator, stackCapacity), parseResult_(), state_(IterativeParsingStartState) {} - - //! Parse JSON text. - /*! \tparam parseFlags Combination of \ref ParseFlag. - \tparam InputStream Type of input stream, implementing Stream concept. - \tparam Handler Type of handler, implementing Handler concept. - \param is Input stream to be parsed. - \param handler The handler to receive events. - \return Whether the parsing is successful. - */ - template - ParseResult Parse(InputStream& is, Handler& handler) { - if (parseFlags & kParseIterativeFlag) - return IterativeParse(is, handler); - - parseResult_.Clear(); - - ClearStackOnExit scope(*this); - - SkipWhitespaceAndComments(is); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); - - if (CEREAL_RAPIDJSON_UNLIKELY(is.Peek() == '\0')) { - CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorDocumentEmpty, is.Tell()); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); - } - else { - ParseValue(is, handler); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); - - if (!(parseFlags & kParseStopWhenDoneFlag)) { - SkipWhitespaceAndComments(is); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); - - if (CEREAL_RAPIDJSON_UNLIKELY(is.Peek() != '\0')) { - CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorDocumentRootNotSingular, is.Tell()); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); - } - } - } - - return parseResult_; - } - - //! Parse JSON text (with \ref kParseDefaultFlags) - /*! \tparam InputStream Type of input stream, implementing Stream concept - \tparam Handler Type of handler, implementing Handler concept. - \param is Input stream to be parsed. - \param handler The handler to receive events. - \return Whether the parsing is successful. - */ - template - ParseResult Parse(InputStream& is, Handler& handler) { - return Parse(is, handler); - } - - //! Initialize JSON text token-by-token parsing - /*! - */ - void IterativeParseInit() { - parseResult_.Clear(); - state_ = IterativeParsingStartState; - } - - //! Parse one token from JSON text - /*! \tparam InputStream Type of input stream, implementing Stream concept - \tparam Handler Type of handler, implementing Handler concept. - \param is Input stream to be parsed. - \param handler The handler to receive events. - \return Whether the parsing is successful. - */ - template - bool IterativeParseNext(InputStream& is, Handler& handler) { - while (CEREAL_RAPIDJSON_LIKELY(is.Peek() != '\0')) { - SkipWhitespaceAndComments(is); - - Token t = Tokenize(is.Peek()); - IterativeParsingState n = Predict(state_, t); - IterativeParsingState d = Transit(state_, t, n, is, handler); - - // If we've finished or hit an error... - if (CEREAL_RAPIDJSON_UNLIKELY(IsIterativeParsingCompleteState(d))) { - // Report errors. - if (d == IterativeParsingErrorState) { - HandleError(state_, is); - return false; - } - - // Transition to the finish state. - CEREAL_RAPIDJSON_ASSERT(d == IterativeParsingFinishState); - state_ = d; - - // If StopWhenDone is not set... - if (!(parseFlags & kParseStopWhenDoneFlag)) { - // ... and extra non-whitespace data is found... - SkipWhitespaceAndComments(is); - if (is.Peek() != '\0') { - // ... this is considered an error. - HandleError(state_, is); - return false; - } - } - - // Success! We are done! - return true; - } - - // Transition to the new state. - state_ = d; - - // If we parsed anything other than a delimiter, we invoked the handler, so we can return true now. - if (!IsIterativeParsingDelimiterState(n)) - return true; - } - - // We reached the end of file. - stack_.Clear(); - - if (state_ != IterativeParsingFinishState) { - HandleError(state_, is); - return false; - } - - return true; - } - - //! Check if token-by-token parsing JSON text is complete - /*! \return Whether the JSON has been fully decoded. - */ - CEREAL_RAPIDJSON_FORCEINLINE bool IterativeParseComplete() const { - return IsIterativeParsingCompleteState(state_); - } - - //! Whether a parse error has occurred in the last parsing. - bool HasParseError() const { return parseResult_.IsError(); } - - //! Get the \ref ParseErrorCode of last parsing. - ParseErrorCode GetParseErrorCode() const { return parseResult_.Code(); } - - //! Get the position of last parsing error in input, 0 otherwise. - size_t GetErrorOffset() const { return parseResult_.Offset(); } - -protected: - void SetParseError(ParseErrorCode code, size_t offset) { parseResult_.Set(code, offset); } - -private: - // Prohibit copy constructor & assignment operator. - GenericReader(const GenericReader&); - GenericReader& operator=(const GenericReader&); - - void ClearStack() { stack_.Clear(); } - - // clear stack on any exit from ParseStream, e.g. due to exception - struct ClearStackOnExit { - explicit ClearStackOnExit(GenericReader& r) : r_(r) {} - ~ClearStackOnExit() { r_.ClearStack(); } - private: - GenericReader& r_; - ClearStackOnExit(const ClearStackOnExit&); - ClearStackOnExit& operator=(const ClearStackOnExit&); - }; - - template - void SkipWhitespaceAndComments(InputStream& is) { - SkipWhitespace(is); - - if (parseFlags & kParseCommentsFlag) { - while (CEREAL_RAPIDJSON_UNLIKELY(Consume(is, '/'))) { - if (Consume(is, '*')) { - while (true) { - if (CEREAL_RAPIDJSON_UNLIKELY(is.Peek() == '\0')) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorUnspecificSyntaxError, is.Tell()); - else if (Consume(is, '*')) { - if (Consume(is, '/')) - break; - } - else - is.Take(); - } - } - else if (CEREAL_RAPIDJSON_LIKELY(Consume(is, '/'))) - while (is.Peek() != '\0' && is.Take() != '\n') {} - else - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorUnspecificSyntaxError, is.Tell()); - - SkipWhitespace(is); - } - } - } - - // Parse object: { string : value, ... } - template - void ParseObject(InputStream& is, Handler& handler) { - CEREAL_RAPIDJSON_ASSERT(is.Peek() == '{'); - is.Take(); // Skip '{' - - if (CEREAL_RAPIDJSON_UNLIKELY(!handler.StartObject())) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); - - SkipWhitespaceAndComments(is); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; - - if (Consume(is, '}')) { - if (CEREAL_RAPIDJSON_UNLIKELY(!handler.EndObject(0))) // empty object - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); - return; - } - - for (SizeType memberCount = 0;;) { - if (CEREAL_RAPIDJSON_UNLIKELY(is.Peek() != '"')) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissName, is.Tell()); - - ParseString(is, handler, true); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; - - SkipWhitespaceAndComments(is); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; - - if (CEREAL_RAPIDJSON_UNLIKELY(!Consume(is, ':'))) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissColon, is.Tell()); - - SkipWhitespaceAndComments(is); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; - - ParseValue(is, handler); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; - - SkipWhitespaceAndComments(is); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; - - ++memberCount; - - switch (is.Peek()) { - case ',': - is.Take(); - SkipWhitespaceAndComments(is); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; - break; - case '}': - is.Take(); - if (CEREAL_RAPIDJSON_UNLIKELY(!handler.EndObject(memberCount))) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); - return; - default: - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, is.Tell()); break; // This useless break is only for making warning and coverage happy - } - - if (parseFlags & kParseTrailingCommasFlag) { - if (is.Peek() == '}') { - if (CEREAL_RAPIDJSON_UNLIKELY(!handler.EndObject(memberCount))) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); - is.Take(); - return; - } - } - } - } - - // Parse array: [ value, ... ] - template - void ParseArray(InputStream& is, Handler& handler) { - CEREAL_RAPIDJSON_ASSERT(is.Peek() == '['); - is.Take(); // Skip '[' - - if (CEREAL_RAPIDJSON_UNLIKELY(!handler.StartArray())) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); - - SkipWhitespaceAndComments(is); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; - - if (Consume(is, ']')) { - if (CEREAL_RAPIDJSON_UNLIKELY(!handler.EndArray(0))) // empty array - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); - return; - } - - for (SizeType elementCount = 0;;) { - ParseValue(is, handler); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; - - ++elementCount; - SkipWhitespaceAndComments(is); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; - - if (Consume(is, ',')) { - SkipWhitespaceAndComments(is); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; - } - else if (Consume(is, ']')) { - if (CEREAL_RAPIDJSON_UNLIKELY(!handler.EndArray(elementCount))) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); - return; - } - else - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorArrayMissCommaOrSquareBracket, is.Tell()); - - if (parseFlags & kParseTrailingCommasFlag) { - if (is.Peek() == ']') { - if (CEREAL_RAPIDJSON_UNLIKELY(!handler.EndArray(elementCount))) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); - is.Take(); - return; - } - } - } - } - - template - void ParseNull(InputStream& is, Handler& handler) { - CEREAL_RAPIDJSON_ASSERT(is.Peek() == 'n'); - is.Take(); - - if (CEREAL_RAPIDJSON_LIKELY(Consume(is, 'u') && Consume(is, 'l') && Consume(is, 'l'))) { - if (CEREAL_RAPIDJSON_UNLIKELY(!handler.Null())) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); - } - else - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); - } - - template - void ParseTrue(InputStream& is, Handler& handler) { - CEREAL_RAPIDJSON_ASSERT(is.Peek() == 't'); - is.Take(); - - if (CEREAL_RAPIDJSON_LIKELY(Consume(is, 'r') && Consume(is, 'u') && Consume(is, 'e'))) { - if (CEREAL_RAPIDJSON_UNLIKELY(!handler.Bool(true))) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); - } - else - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); - } - - template - void ParseFalse(InputStream& is, Handler& handler) { - CEREAL_RAPIDJSON_ASSERT(is.Peek() == 'f'); - is.Take(); - - if (CEREAL_RAPIDJSON_LIKELY(Consume(is, 'a') && Consume(is, 'l') && Consume(is, 's') && Consume(is, 'e'))) { - if (CEREAL_RAPIDJSON_UNLIKELY(!handler.Bool(false))) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); - } - else - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); - } - - template - CEREAL_RAPIDJSON_FORCEINLINE static bool Consume(InputStream& is, typename InputStream::Ch expect) { - if (CEREAL_RAPIDJSON_LIKELY(is.Peek() == expect)) { - is.Take(); - return true; - } - else - return false; - } - - // Helper function to parse four hexadecimal digits in \uXXXX in ParseString(). - template - unsigned ParseHex4(InputStream& is, size_t escapeOffset) { - unsigned codepoint = 0; - for (int i = 0; i < 4; i++) { - Ch c = is.Peek(); - codepoint <<= 4; - codepoint += static_cast(c); - if (c >= '0' && c <= '9') - codepoint -= '0'; - else if (c >= 'A' && c <= 'F') - codepoint -= 'A' - 10; - else if (c >= 'a' && c <= 'f') - codepoint -= 'a' - 10; - else { - CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorStringUnicodeEscapeInvalidHex, escapeOffset); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(0); - } - is.Take(); - } - return codepoint; - } - - template - class StackStream { - public: - typedef CharType Ch; - - StackStream(internal::Stack& stack) : stack_(stack), length_(0) {} - CEREAL_RAPIDJSON_FORCEINLINE void Put(Ch c) { - *stack_.template Push() = c; - ++length_; - } - - CEREAL_RAPIDJSON_FORCEINLINE void* Push(SizeType count) { - length_ += count; - return stack_.template Push(count); - } - - size_t Length() const { return length_; } - - Ch* Pop() { - return stack_.template Pop(length_); - } - - private: - StackStream(const StackStream&); - StackStream& operator=(const StackStream&); - - internal::Stack& stack_; - SizeType length_; - }; - - // Parse string and generate String event. Different code paths for kParseInsituFlag. - template - void ParseString(InputStream& is, Handler& handler, bool isKey = false) { - internal::StreamLocalCopy copy(is); - InputStream& s(copy.s); - - CEREAL_RAPIDJSON_ASSERT(s.Peek() == '\"'); - s.Take(); // Skip '\"' - - bool success = false; - if (parseFlags & kParseInsituFlag) { - typename InputStream::Ch *head = s.PutBegin(); - ParseStringToStream(s, s); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; - size_t length = s.PutEnd(head) - 1; - CEREAL_RAPIDJSON_ASSERT(length <= 0xFFFFFFFF); - const typename TargetEncoding::Ch* const str = reinterpret_cast(head); - success = (isKey ? handler.Key(str, SizeType(length), false) : handler.String(str, SizeType(length), false)); - } - else { - StackStream stackStream(stack_); - ParseStringToStream(s, stackStream); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; - SizeType length = static_cast(stackStream.Length()) - 1; - const typename TargetEncoding::Ch* const str = stackStream.Pop(); - success = (isKey ? handler.Key(str, length, true) : handler.String(str, length, true)); - } - if (CEREAL_RAPIDJSON_UNLIKELY(!success)) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, s.Tell()); - } - - // Parse string to an output is - // This function handles the prefix/suffix double quotes, escaping, and optional encoding validation. - template - CEREAL_RAPIDJSON_FORCEINLINE void ParseStringToStream(InputStream& is, OutputStream& os) { -//!@cond CEREAL_RAPIDJSON_HIDDEN_FROM_DOXYGEN -#define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 - static const char escape[256] = { - Z16, Z16, 0, 0,'\"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'/', - Z16, Z16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\\', 0, 0, 0, - 0, 0,'\b', 0, 0, 0,'\f', 0, 0, 0, 0, 0, 0, 0,'\n', 0, - 0, 0,'\r', 0,'\t', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16 - }; -#undef Z16 -//!@endcond - - for (;;) { - // Scan and copy string before "\\\"" or < 0x20. This is an optional optimzation. - if (!(parseFlags & kParseValidateEncodingFlag)) - ScanCopyUnescapedString(is, os); - - Ch c = is.Peek(); - if (CEREAL_RAPIDJSON_UNLIKELY(c == '\\')) { // Escape - size_t escapeOffset = is.Tell(); // For invalid escaping, report the initial '\\' as error offset - is.Take(); - Ch e = is.Peek(); - if ((sizeof(Ch) == 1 || unsigned(e) < 256) && CEREAL_RAPIDJSON_LIKELY(escape[static_cast(e)])) { - is.Take(); - os.Put(static_cast(escape[static_cast(e)])); - } - else if (CEREAL_RAPIDJSON_LIKELY(e == 'u')) { // Unicode - is.Take(); - unsigned codepoint = ParseHex4(is, escapeOffset); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; - if (CEREAL_RAPIDJSON_UNLIKELY(codepoint >= 0xD800 && codepoint <= 0xDBFF)) { - // Handle UTF-16 surrogate pair - if (CEREAL_RAPIDJSON_UNLIKELY(!Consume(is, '\\') || !Consume(is, 'u'))) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorStringUnicodeSurrogateInvalid, escapeOffset); - unsigned codepoint2 = ParseHex4(is, escapeOffset); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; - if (CEREAL_RAPIDJSON_UNLIKELY(codepoint2 < 0xDC00 || codepoint2 > 0xDFFF)) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorStringUnicodeSurrogateInvalid, escapeOffset); - codepoint = (((codepoint - 0xD800) << 10) | (codepoint2 - 0xDC00)) + 0x10000; - } - TEncoding::Encode(os, codepoint); - } - else - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorStringEscapeInvalid, escapeOffset); - } - else if (CEREAL_RAPIDJSON_UNLIKELY(c == '"')) { // Closing double quote - is.Take(); - os.Put('\0'); // null-terminate the string - return; - } - else if (CEREAL_RAPIDJSON_UNLIKELY(static_cast(c) < 0x20)) { // RFC 4627: unescaped = %x20-21 / %x23-5B / %x5D-10FFFF - if (c == '\0') - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorStringMissQuotationMark, is.Tell()); - else - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorStringInvalidEncoding, is.Tell()); - } - else { - size_t offset = is.Tell(); - if (CEREAL_RAPIDJSON_UNLIKELY((parseFlags & kParseValidateEncodingFlag ? - !Transcoder::Validate(is, os) : - !Transcoder::Transcode(is, os)))) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorStringInvalidEncoding, offset); - } - } - } - - template - static CEREAL_RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(InputStream&, OutputStream&) { - // Do nothing for generic version - } - -#if defined(CEREAL_RAPIDJSON_SSE2) || defined(CEREAL_RAPIDJSON_SSE42) - // StringStream -> StackStream - static CEREAL_RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(StringStream& is, StackStream& os) { - const char* p = is.src_; - - // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) - const char* nextAligned = reinterpret_cast((reinterpret_cast(p) + 15) & static_cast(~15)); - while (p != nextAligned) - if (CEREAL_RAPIDJSON_UNLIKELY(*p == '\"') || CEREAL_RAPIDJSON_UNLIKELY(*p == '\\') || CEREAL_RAPIDJSON_UNLIKELY(static_cast(*p) < 0x20)) { - is.src_ = p; - return; - } - else - os.Put(*p++); - - // The rest of string using SIMD - static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' }; - static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; - static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F }; - const __m128i dq = _mm_loadu_si128(reinterpret_cast(&dquote[0])); - const __m128i bs = _mm_loadu_si128(reinterpret_cast(&bslash[0])); - const __m128i sp = _mm_loadu_si128(reinterpret_cast(&space[0])); - - for (;; p += 16) { - const __m128i s = _mm_load_si128(reinterpret_cast(p)); - const __m128i t1 = _mm_cmpeq_epi8(s, dq); - const __m128i t2 = _mm_cmpeq_epi8(s, bs); - const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F - const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); - unsigned short r = static_cast(_mm_movemask_epi8(x)); - if (CEREAL_RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped - SizeType length; - #ifdef _MSC_VER // Find the index of first escaped - unsigned long offset; - _BitScanForward(&offset, r); - length = offset; - #else - length = static_cast(__builtin_ffs(r) - 1); - #endif - if (length != 0) { - char* q = reinterpret_cast(os.Push(length)); - for (size_t i = 0; i < length; i++) - q[i] = p[i]; - - p += length; - } - break; - } - _mm_storeu_si128(reinterpret_cast<__m128i *>(os.Push(16)), s); - } - - is.src_ = p; - } - - // InsituStringStream -> InsituStringStream - static CEREAL_RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(InsituStringStream& is, InsituStringStream& os) { - CEREAL_RAPIDJSON_ASSERT(&is == &os); - (void)os; - - if (is.src_ == is.dst_) { - SkipUnescapedString(is); - return; - } - - char* p = is.src_; - char *q = is.dst_; - - // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) - const char* nextAligned = reinterpret_cast((reinterpret_cast(p) + 15) & static_cast(~15)); - while (p != nextAligned) - if (CEREAL_RAPIDJSON_UNLIKELY(*p == '\"') || CEREAL_RAPIDJSON_UNLIKELY(*p == '\\') || CEREAL_RAPIDJSON_UNLIKELY(static_cast(*p) < 0x20)) { - is.src_ = p; - is.dst_ = q; - return; - } - else - *q++ = *p++; - - // The rest of string using SIMD - static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' }; - static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; - static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F }; - const __m128i dq = _mm_loadu_si128(reinterpret_cast(&dquote[0])); - const __m128i bs = _mm_loadu_si128(reinterpret_cast(&bslash[0])); - const __m128i sp = _mm_loadu_si128(reinterpret_cast(&space[0])); - - for (;; p += 16, q += 16) { - const __m128i s = _mm_load_si128(reinterpret_cast(p)); - const __m128i t1 = _mm_cmpeq_epi8(s, dq); - const __m128i t2 = _mm_cmpeq_epi8(s, bs); - const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F - const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); - unsigned short r = static_cast(_mm_movemask_epi8(x)); - if (CEREAL_RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped - size_t length; -#ifdef _MSC_VER // Find the index of first escaped - unsigned long offset; - _BitScanForward(&offset, r); - length = offset; -#else - length = static_cast(__builtin_ffs(r) - 1); -#endif - for (const char* pend = p + length; p != pend; ) - *q++ = *p++; - break; - } - _mm_storeu_si128(reinterpret_cast<__m128i *>(q), s); - } - - is.src_ = p; - is.dst_ = q; - } - - // When read/write pointers are the same for insitu stream, just skip unescaped characters - static CEREAL_RAPIDJSON_FORCEINLINE void SkipUnescapedString(InsituStringStream& is) { - CEREAL_RAPIDJSON_ASSERT(is.src_ == is.dst_); - char* p = is.src_; - - // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) - const char* nextAligned = reinterpret_cast((reinterpret_cast(p) + 15) & static_cast(~15)); - for (; p != nextAligned; p++) - if (CEREAL_RAPIDJSON_UNLIKELY(*p == '\"') || CEREAL_RAPIDJSON_UNLIKELY(*p == '\\') || CEREAL_RAPIDJSON_UNLIKELY(static_cast(*p) < 0x20)) { - is.src_ = is.dst_ = p; - return; - } - - // The rest of string using SIMD - static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' }; - static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; - static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F }; - const __m128i dq = _mm_loadu_si128(reinterpret_cast(&dquote[0])); - const __m128i bs = _mm_loadu_si128(reinterpret_cast(&bslash[0])); - const __m128i sp = _mm_loadu_si128(reinterpret_cast(&space[0])); - - for (;; p += 16) { - const __m128i s = _mm_load_si128(reinterpret_cast(p)); - const __m128i t1 = _mm_cmpeq_epi8(s, dq); - const __m128i t2 = _mm_cmpeq_epi8(s, bs); - const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F - const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); - unsigned short r = static_cast(_mm_movemask_epi8(x)); - if (CEREAL_RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped - size_t length; -#ifdef _MSC_VER // Find the index of first escaped - unsigned long offset; - _BitScanForward(&offset, r); - length = offset; -#else - length = static_cast(__builtin_ffs(r) - 1); -#endif - p += length; - break; - } - } - - is.src_ = is.dst_ = p; - } -#elif defined(CEREAL_RAPIDJSON_NEON) - // StringStream -> StackStream - static CEREAL_RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(StringStream& is, StackStream& os) { - const char* p = is.src_; - - // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) - const char* nextAligned = reinterpret_cast((reinterpret_cast(p) + 15) & static_cast(~15)); - while (p != nextAligned) - if (CEREAL_RAPIDJSON_UNLIKELY(*p == '\"') || CEREAL_RAPIDJSON_UNLIKELY(*p == '\\') || CEREAL_RAPIDJSON_UNLIKELY(static_cast(*p) < 0x20)) { - is.src_ = p; - return; - } - else - os.Put(*p++); - - // The rest of string using SIMD - const uint8x16_t s0 = vmovq_n_u8('"'); - const uint8x16_t s1 = vmovq_n_u8('\\'); - const uint8x16_t s2 = vmovq_n_u8('\b'); - const uint8x16_t s3 = vmovq_n_u8(32); - - for (;; p += 16) { - const uint8x16_t s = vld1q_u8(reinterpret_cast(p)); - uint8x16_t x = vceqq_u8(s, s0); - x = vorrq_u8(x, vceqq_u8(s, s1)); - x = vorrq_u8(x, vceqq_u8(s, s2)); - x = vorrq_u8(x, vcltq_u8(s, s3)); - - x = vrev64q_u8(x); // Rev in 64 - uint64_t low = vgetq_lane_u64(reinterpret_cast(x), 0); // extract - uint64_t high = vgetq_lane_u64(reinterpret_cast(x), 1); // extract - - SizeType length = 0; - bool escaped = false; - if (low == 0) { - if (high != 0) { - unsigned lz = (unsigned)__builtin_clzll(high);; - length = 8 + (lz >> 3); - escaped = true; - } - } else { - unsigned lz = (unsigned)__builtin_clzll(low);; - length = lz >> 3; - escaped = true; - } - if (CEREAL_RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped - if (length != 0) { - char* q = reinterpret_cast(os.Push(length)); - for (size_t i = 0; i < length; i++) - q[i] = p[i]; - - p += length; - } - break; - } - vst1q_u8(reinterpret_cast(os.Push(16)), s); - } - - is.src_ = p; - } - - // InsituStringStream -> InsituStringStream - static CEREAL_RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(InsituStringStream& is, InsituStringStream& os) { - CEREAL_RAPIDJSON_ASSERT(&is == &os); - (void)os; - - if (is.src_ == is.dst_) { - SkipUnescapedString(is); - return; - } - - char* p = is.src_; - char *q = is.dst_; - - // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) - const char* nextAligned = reinterpret_cast((reinterpret_cast(p) + 15) & static_cast(~15)); - while (p != nextAligned) - if (CEREAL_RAPIDJSON_UNLIKELY(*p == '\"') || CEREAL_RAPIDJSON_UNLIKELY(*p == '\\') || CEREAL_RAPIDJSON_UNLIKELY(static_cast(*p) < 0x20)) { - is.src_ = p; - is.dst_ = q; - return; - } - else - *q++ = *p++; - - // The rest of string using SIMD - const uint8x16_t s0 = vmovq_n_u8('"'); - const uint8x16_t s1 = vmovq_n_u8('\\'); - const uint8x16_t s2 = vmovq_n_u8('\b'); - const uint8x16_t s3 = vmovq_n_u8(32); - - for (;; p += 16, q += 16) { - const uint8x16_t s = vld1q_u8(reinterpret_cast(p)); - uint8x16_t x = vceqq_u8(s, s0); - x = vorrq_u8(x, vceqq_u8(s, s1)); - x = vorrq_u8(x, vceqq_u8(s, s2)); - x = vorrq_u8(x, vcltq_u8(s, s3)); - - x = vrev64q_u8(x); // Rev in 64 - uint64_t low = vgetq_lane_u64(reinterpret_cast(x), 0); // extract - uint64_t high = vgetq_lane_u64(reinterpret_cast(x), 1); // extract - - SizeType length = 0; - bool escaped = false; - if (low == 0) { - if (high != 0) { - unsigned lz = (unsigned)__builtin_clzll(high); - length = 8 + (lz >> 3); - escaped = true; - } - } else { - unsigned lz = (unsigned)__builtin_clzll(low); - length = lz >> 3; - escaped = true; - } - if (CEREAL_RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped - for (const char* pend = p + length; p != pend; ) { - *q++ = *p++; - } - break; - } - vst1q_u8(reinterpret_cast(q), s); - } - - is.src_ = p; - is.dst_ = q; - } - - // When read/write pointers are the same for insitu stream, just skip unescaped characters - static CEREAL_RAPIDJSON_FORCEINLINE void SkipUnescapedString(InsituStringStream& is) { - CEREAL_RAPIDJSON_ASSERT(is.src_ == is.dst_); - char* p = is.src_; - - // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) - const char* nextAligned = reinterpret_cast((reinterpret_cast(p) + 15) & static_cast(~15)); - for (; p != nextAligned; p++) - if (CEREAL_RAPIDJSON_UNLIKELY(*p == '\"') || CEREAL_RAPIDJSON_UNLIKELY(*p == '\\') || CEREAL_RAPIDJSON_UNLIKELY(static_cast(*p) < 0x20)) { - is.src_ = is.dst_ = p; - return; - } - - // The rest of string using SIMD - const uint8x16_t s0 = vmovq_n_u8('"'); - const uint8x16_t s1 = vmovq_n_u8('\\'); - const uint8x16_t s2 = vmovq_n_u8('\b'); - const uint8x16_t s3 = vmovq_n_u8(32); - - for (;; p += 16) { - const uint8x16_t s = vld1q_u8(reinterpret_cast(p)); - uint8x16_t x = vceqq_u8(s, s0); - x = vorrq_u8(x, vceqq_u8(s, s1)); - x = vorrq_u8(x, vceqq_u8(s, s2)); - x = vorrq_u8(x, vcltq_u8(s, s3)); - - x = vrev64q_u8(x); // Rev in 64 - uint64_t low = vgetq_lane_u64(reinterpret_cast(x), 0); // extract - uint64_t high = vgetq_lane_u64(reinterpret_cast(x), 1); // extract - - if (low == 0) { - if (high != 0) { - int lz = __builtin_clzll(high); - p += 8 + (lz >> 3); - break; - } - } else { - int lz = __builtin_clzll(low); - p += lz >> 3; - break; - } - } - - is.src_ = is.dst_ = p; - } -#endif // CEREAL_RAPIDJSON_NEON - - template - class NumberStream; - - template - class NumberStream { - public: - typedef typename InputStream::Ch Ch; - - NumberStream(GenericReader& reader, InputStream& s) : is(s) { (void)reader; } - - CEREAL_RAPIDJSON_FORCEINLINE Ch Peek() const { return is.Peek(); } - CEREAL_RAPIDJSON_FORCEINLINE Ch TakePush() { return is.Take(); } - CEREAL_RAPIDJSON_FORCEINLINE Ch Take() { return is.Take(); } - CEREAL_RAPIDJSON_FORCEINLINE void Push(char) {} - - size_t Tell() { return is.Tell(); } - size_t Length() { return 0; } - const char* Pop() { return 0; } - - protected: - NumberStream& operator=(const NumberStream&); - - InputStream& is; - }; - - template - class NumberStream : public NumberStream { - typedef NumberStream Base; - public: - NumberStream(GenericReader& reader, InputStream& s) : Base(reader, s), stackStream(reader.stack_) {} - - CEREAL_RAPIDJSON_FORCEINLINE Ch TakePush() { - stackStream.Put(static_cast(Base::is.Peek())); - return Base::is.Take(); - } - - CEREAL_RAPIDJSON_FORCEINLINE void Push(char c) { - stackStream.Put(c); - } - - size_t Length() { return stackStream.Length(); } - - const char* Pop() { - stackStream.Put('\0'); - return stackStream.Pop(); - } - - private: - StackStream stackStream; - }; - - template - class NumberStream : public NumberStream { - typedef NumberStream Base; - public: - NumberStream(GenericReader& reader, InputStream& is) : Base(reader, is) {} - - CEREAL_RAPIDJSON_FORCEINLINE Ch Take() { return Base::TakePush(); } - }; - - template - void ParseNumber(InputStream& is, Handler& handler) { - internal::StreamLocalCopy copy(is); - NumberStream s(*this, copy.s); - - size_t startOffset = s.Tell(); - double d = 0.0; - bool useNanOrInf = false; - - // Parse minus - bool minus = Consume(s, '-'); - - // Parse int: zero / ( digit1-9 *DIGIT ) - unsigned i = 0; - uint64_t i64 = 0; - bool use64bit = false; - int significandDigit = 0; - if (CEREAL_RAPIDJSON_UNLIKELY(s.Peek() == '0')) { - i = 0; - s.TakePush(); - } - else if (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '1' && s.Peek() <= '9')) { - i = static_cast(s.TakePush() - '0'); - - if (minus) - while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { - if (CEREAL_RAPIDJSON_UNLIKELY(i >= 214748364)) { // 2^31 = 2147483648 - if (CEREAL_RAPIDJSON_LIKELY(i != 214748364 || s.Peek() > '8')) { - i64 = i; - use64bit = true; - break; - } - } - i = i * 10 + static_cast(s.TakePush() - '0'); - significandDigit++; - } - else - while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { - if (CEREAL_RAPIDJSON_UNLIKELY(i >= 429496729)) { // 2^32 - 1 = 4294967295 - if (CEREAL_RAPIDJSON_LIKELY(i != 429496729 || s.Peek() > '5')) { - i64 = i; - use64bit = true; - break; - } - } - i = i * 10 + static_cast(s.TakePush() - '0'); - significandDigit++; - } - } - // Parse NaN or Infinity here - else if ((parseFlags & kParseNanAndInfFlag) && CEREAL_RAPIDJSON_LIKELY((s.Peek() == 'I' || s.Peek() == 'N'))) { - if (Consume(s, 'N')) { - if (Consume(s, 'a') && Consume(s, 'N')) { - d = std::numeric_limits::quiet_NaN(); - useNanOrInf = true; - } - } - else if (CEREAL_RAPIDJSON_LIKELY(Consume(s, 'I'))) { - if (Consume(s, 'n') && Consume(s, 'f')) { - d = (minus ? -std::numeric_limits::infinity() : std::numeric_limits::infinity()); - useNanOrInf = true; - - if (CEREAL_RAPIDJSON_UNLIKELY(s.Peek() == 'i' && !(Consume(s, 'i') && Consume(s, 'n') - && Consume(s, 'i') && Consume(s, 't') && Consume(s, 'y')))) { - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell()); - } - } - } - - if (CEREAL_RAPIDJSON_UNLIKELY(!useNanOrInf)) { - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell()); - } - } - else - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell()); - - // Parse 64bit int - bool useDouble = false; - if (use64bit) { - if (minus) - while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { - if (CEREAL_RAPIDJSON_UNLIKELY(i64 >= CEREAL_RAPIDJSON_UINT64_C2(0x0CCCCCCC, 0xCCCCCCCC))) // 2^63 = 9223372036854775808 - if (CEREAL_RAPIDJSON_LIKELY(i64 != CEREAL_RAPIDJSON_UINT64_C2(0x0CCCCCCC, 0xCCCCCCCC) || s.Peek() > '8')) { - d = static_cast(i64); - useDouble = true; - break; - } - i64 = i64 * 10 + static_cast(s.TakePush() - '0'); - significandDigit++; - } - else - while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { - if (CEREAL_RAPIDJSON_UNLIKELY(i64 >= CEREAL_RAPIDJSON_UINT64_C2(0x19999999, 0x99999999))) // 2^64 - 1 = 18446744073709551615 - if (CEREAL_RAPIDJSON_LIKELY(i64 != CEREAL_RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) || s.Peek() > '5')) { - d = static_cast(i64); - useDouble = true; - break; - } - i64 = i64 * 10 + static_cast(s.TakePush() - '0'); - significandDigit++; - } - } - - // Force double for big integer - if (useDouble) { - while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { - d = d * 10 + (s.TakePush() - '0'); - } - } - - // Parse frac = decimal-point 1*DIGIT - int expFrac = 0; - size_t decimalPosition; - if (Consume(s, '.')) { - decimalPosition = s.Length(); - - if (CEREAL_RAPIDJSON_UNLIKELY(!(s.Peek() >= '0' && s.Peek() <= '9'))) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorNumberMissFraction, s.Tell()); - - if (!useDouble) { -#if CEREAL_RAPIDJSON_64BIT - // Use i64 to store significand in 64-bit architecture - if (!use64bit) - i64 = i; - - while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { - if (i64 > CEREAL_RAPIDJSON_UINT64_C2(0x1FFFFF, 0xFFFFFFFF)) // 2^53 - 1 for fast path - break; - else { - i64 = i64 * 10 + static_cast(s.TakePush() - '0'); - --expFrac; - if (i64 != 0) - significandDigit++; - } - } - - d = static_cast(i64); -#else - // Use double to store significand in 32-bit architecture - d = static_cast(use64bit ? i64 : i); -#endif - useDouble = true; - } - - while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { - if (significandDigit < 17) { - d = d * 10.0 + (s.TakePush() - '0'); - --expFrac; - if (CEREAL_RAPIDJSON_LIKELY(d > 0.0)) - significandDigit++; - } - else - s.TakePush(); - } - } - else - decimalPosition = s.Length(); // decimal position at the end of integer. - - // Parse exp = e [ minus / plus ] 1*DIGIT - int exp = 0; - if (Consume(s, 'e') || Consume(s, 'E')) { - if (!useDouble) { - d = static_cast(use64bit ? i64 : i); - useDouble = true; - } - - bool expMinus = false; - if (Consume(s, '+')) - ; - else if (Consume(s, '-')) - expMinus = true; - - if (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { - exp = static_cast(s.Take() - '0'); - if (expMinus) { - // (exp + expFrac) must not underflow int => we're detecting when -exp gets - // dangerously close to INT_MIN (a pessimistic next digit 9 would push it into - // underflow territory): - // - // -(exp * 10 + 9) + expFrac >= INT_MIN - // <=> exp <= (expFrac - INT_MIN - 9) / 10 - CEREAL_RAPIDJSON_ASSERT(expFrac <= 0); - int maxExp = (expFrac + 2147483639) / 10; - - while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { - exp = exp * 10 + static_cast(s.Take() - '0'); - if (CEREAL_RAPIDJSON_UNLIKELY(exp > maxExp)) { - while (CEREAL_RAPIDJSON_UNLIKELY(s.Peek() >= '0' && s.Peek() <= '9')) // Consume the rest of exponent - s.Take(); - } - } - } - else { // positive exp - int maxExp = 308 - expFrac; - while (CEREAL_RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { - exp = exp * 10 + static_cast(s.Take() - '0'); - if (CEREAL_RAPIDJSON_UNLIKELY(exp > maxExp)) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorNumberTooBig, startOffset); - } - } - } - else - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorNumberMissExponent, s.Tell()); - - if (expMinus) - exp = -exp; - } - - // Finish parsing, call event according to the type of number. - bool cont = true; - - if (parseFlags & kParseNumbersAsStringsFlag) { - if (parseFlags & kParseInsituFlag) { - s.Pop(); // Pop stack no matter if it will be used or not. - typename InputStream::Ch* head = is.PutBegin(); - const size_t length = s.Tell() - startOffset; - CEREAL_RAPIDJSON_ASSERT(length <= 0xFFFFFFFF); - // unable to insert the \0 character here, it will erase the comma after this number - const typename TargetEncoding::Ch* const str = reinterpret_cast(head); - cont = handler.RawNumber(str, SizeType(length), false); - } - else { - SizeType numCharsToCopy = static_cast(s.Length()); - StringStream srcStream(s.Pop()); - StackStream dstStream(stack_); - while (numCharsToCopy--) { - Transcoder, TargetEncoding>::Transcode(srcStream, dstStream); - } - dstStream.Put('\0'); - const typename TargetEncoding::Ch* str = dstStream.Pop(); - const SizeType length = static_cast(dstStream.Length()) - 1; - cont = handler.RawNumber(str, SizeType(length), true); - } - } - else { - size_t length = s.Length(); - const char* decimal = s.Pop(); // Pop stack no matter if it will be used or not. - - if (useDouble) { - int p = exp + expFrac; - if (parseFlags & kParseFullPrecisionFlag) - d = internal::StrtodFullPrecision(d, p, decimal, length, decimalPosition, exp); - else - d = internal::StrtodNormalPrecision(d, p); - - // Use > max, instead of == inf, to fix bogus warning -Wfloat-equal - if (d > (std::numeric_limits::max)()) { - // Overflow - // TODO: internal::StrtodX should report overflow (or underflow) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorNumberTooBig, startOffset); - } - - cont = handler.Double(minus ? -d : d); - } - else if (useNanOrInf) { - cont = handler.Double(d); - } - else { - if (use64bit) { - if (minus) - cont = handler.Int64(static_cast(~i64 + 1)); - else - cont = handler.Uint64(i64); - } - else { - if (minus) - cont = handler.Int(static_cast(~i + 1)); - else - cont = handler.Uint(i); - } - } - } - if (CEREAL_RAPIDJSON_UNLIKELY(!cont)) - CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorTermination, startOffset); - } - - // Parse any JSON value - template - void ParseValue(InputStream& is, Handler& handler) { - switch (is.Peek()) { - case 'n': ParseNull (is, handler); break; - case 't': ParseTrue (is, handler); break; - case 'f': ParseFalse (is, handler); break; - case '"': ParseString(is, handler); break; - case '{': ParseObject(is, handler); break; - case '[': ParseArray (is, handler); break; - default : - ParseNumber(is, handler); - break; - - } - } - - // Iterative Parsing - - // States - enum IterativeParsingState { - IterativeParsingFinishState = 0, // sink states at top - IterativeParsingErrorState, // sink states at top - IterativeParsingStartState, - - // Object states - IterativeParsingObjectInitialState, - IterativeParsingMemberKeyState, - IterativeParsingMemberValueState, - IterativeParsingObjectFinishState, - - // Array states - IterativeParsingArrayInitialState, - IterativeParsingElementState, - IterativeParsingArrayFinishState, - - // Single value state - IterativeParsingValueState, - - // Delimiter states (at bottom) - IterativeParsingElementDelimiterState, - IterativeParsingMemberDelimiterState, - IterativeParsingKeyValueDelimiterState, - - cIterativeParsingStateCount - }; - - // Tokens - enum Token { - LeftBracketToken = 0, - RightBracketToken, - - LeftCurlyBracketToken, - RightCurlyBracketToken, - - CommaToken, - ColonToken, - - StringToken, - FalseToken, - TrueToken, - NullToken, - NumberToken, - - kTokenCount - }; - - CEREAL_RAPIDJSON_FORCEINLINE Token Tokenize(Ch c) const { - -//!@cond CEREAL_RAPIDJSON_HIDDEN_FROM_DOXYGEN -#define N NumberToken -#define N16 N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N - // Maps from ASCII to Token - static const unsigned char tokenMap[256] = { - N16, // 00~0F - N16, // 10~1F - N, N, StringToken, N, N, N, N, N, N, N, N, N, CommaToken, N, N, N, // 20~2F - N, N, N, N, N, N, N, N, N, N, ColonToken, N, N, N, N, N, // 30~3F - N16, // 40~4F - N, N, N, N, N, N, N, N, N, N, N, LeftBracketToken, N, RightBracketToken, N, N, // 50~5F - N, N, N, N, N, N, FalseToken, N, N, N, N, N, N, N, NullToken, N, // 60~6F - N, N, N, N, TrueToken, N, N, N, N, N, N, LeftCurlyBracketToken, N, RightCurlyBracketToken, N, N, // 70~7F - N16, N16, N16, N16, N16, N16, N16, N16 // 80~FF - }; -#undef N -#undef N16 -//!@endcond - - if (sizeof(Ch) == 1 || static_cast(c) < 256) - return static_cast(tokenMap[static_cast(c)]); - else - return NumberToken; - } - - CEREAL_RAPIDJSON_FORCEINLINE IterativeParsingState Predict(IterativeParsingState state, Token token) const { - // current state x one lookahead token -> new state - static const char G[cIterativeParsingStateCount][kTokenCount] = { - // Finish(sink state) - { - IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, - IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, - IterativeParsingErrorState - }, - // Error(sink state) - { - IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, - IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, - IterativeParsingErrorState - }, - // Start - { - IterativeParsingArrayInitialState, // Left bracket - IterativeParsingErrorState, // Right bracket - IterativeParsingObjectInitialState, // Left curly bracket - IterativeParsingErrorState, // Right curly bracket - IterativeParsingErrorState, // Comma - IterativeParsingErrorState, // Colon - IterativeParsingValueState, // String - IterativeParsingValueState, // False - IterativeParsingValueState, // True - IterativeParsingValueState, // Null - IterativeParsingValueState // Number - }, - // ObjectInitial - { - IterativeParsingErrorState, // Left bracket - IterativeParsingErrorState, // Right bracket - IterativeParsingErrorState, // Left curly bracket - IterativeParsingObjectFinishState, // Right curly bracket - IterativeParsingErrorState, // Comma - IterativeParsingErrorState, // Colon - IterativeParsingMemberKeyState, // String - IterativeParsingErrorState, // False - IterativeParsingErrorState, // True - IterativeParsingErrorState, // Null - IterativeParsingErrorState // Number - }, - // MemberKey - { - IterativeParsingErrorState, // Left bracket - IterativeParsingErrorState, // Right bracket - IterativeParsingErrorState, // Left curly bracket - IterativeParsingErrorState, // Right curly bracket - IterativeParsingErrorState, // Comma - IterativeParsingKeyValueDelimiterState, // Colon - IterativeParsingErrorState, // String - IterativeParsingErrorState, // False - IterativeParsingErrorState, // True - IterativeParsingErrorState, // Null - IterativeParsingErrorState // Number - }, - // MemberValue - { - IterativeParsingErrorState, // Left bracket - IterativeParsingErrorState, // Right bracket - IterativeParsingErrorState, // Left curly bracket - IterativeParsingObjectFinishState, // Right curly bracket - IterativeParsingMemberDelimiterState, // Comma - IterativeParsingErrorState, // Colon - IterativeParsingErrorState, // String - IterativeParsingErrorState, // False - IterativeParsingErrorState, // True - IterativeParsingErrorState, // Null - IterativeParsingErrorState // Number - }, - // ObjectFinish(sink state) - { - IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, - IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, - IterativeParsingErrorState - }, - // ArrayInitial - { - IterativeParsingArrayInitialState, // Left bracket(push Element state) - IterativeParsingArrayFinishState, // Right bracket - IterativeParsingObjectInitialState, // Left curly bracket(push Element state) - IterativeParsingErrorState, // Right curly bracket - IterativeParsingErrorState, // Comma - IterativeParsingErrorState, // Colon - IterativeParsingElementState, // String - IterativeParsingElementState, // False - IterativeParsingElementState, // True - IterativeParsingElementState, // Null - IterativeParsingElementState // Number - }, - // Element - { - IterativeParsingErrorState, // Left bracket - IterativeParsingArrayFinishState, // Right bracket - IterativeParsingErrorState, // Left curly bracket - IterativeParsingErrorState, // Right curly bracket - IterativeParsingElementDelimiterState, // Comma - IterativeParsingErrorState, // Colon - IterativeParsingErrorState, // String - IterativeParsingErrorState, // False - IterativeParsingErrorState, // True - IterativeParsingErrorState, // Null - IterativeParsingErrorState // Number - }, - // ArrayFinish(sink state) - { - IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, - IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, - IterativeParsingErrorState - }, - // Single Value (sink state) - { - IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, - IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, - IterativeParsingErrorState - }, - // ElementDelimiter - { - IterativeParsingArrayInitialState, // Left bracket(push Element state) - IterativeParsingArrayFinishState, // Right bracket - IterativeParsingObjectInitialState, // Left curly bracket(push Element state) - IterativeParsingErrorState, // Right curly bracket - IterativeParsingErrorState, // Comma - IterativeParsingErrorState, // Colon - IterativeParsingElementState, // String - IterativeParsingElementState, // False - IterativeParsingElementState, // True - IterativeParsingElementState, // Null - IterativeParsingElementState // Number - }, - // MemberDelimiter - { - IterativeParsingErrorState, // Left bracket - IterativeParsingErrorState, // Right bracket - IterativeParsingErrorState, // Left curly bracket - IterativeParsingObjectFinishState, // Right curly bracket - IterativeParsingErrorState, // Comma - IterativeParsingErrorState, // Colon - IterativeParsingMemberKeyState, // String - IterativeParsingErrorState, // False - IterativeParsingErrorState, // True - IterativeParsingErrorState, // Null - IterativeParsingErrorState // Number - }, - // KeyValueDelimiter - { - IterativeParsingArrayInitialState, // Left bracket(push MemberValue state) - IterativeParsingErrorState, // Right bracket - IterativeParsingObjectInitialState, // Left curly bracket(push MemberValue state) - IterativeParsingErrorState, // Right curly bracket - IterativeParsingErrorState, // Comma - IterativeParsingErrorState, // Colon - IterativeParsingMemberValueState, // String - IterativeParsingMemberValueState, // False - IterativeParsingMemberValueState, // True - IterativeParsingMemberValueState, // Null - IterativeParsingMemberValueState // Number - }, - }; // End of G - - return static_cast(G[state][token]); - } - - // Make an advance in the token stream and state based on the candidate destination state which was returned by Transit(). - // May return a new state on state pop. - template - CEREAL_RAPIDJSON_FORCEINLINE IterativeParsingState Transit(IterativeParsingState src, Token token, IterativeParsingState dst, InputStream& is, Handler& handler) { - (void)token; - - switch (dst) { - case IterativeParsingErrorState: - return dst; - - case IterativeParsingObjectInitialState: - case IterativeParsingArrayInitialState: - { - // Push the state(Element or MemeberValue) if we are nested in another array or value of member. - // In this way we can get the correct state on ObjectFinish or ArrayFinish by frame pop. - IterativeParsingState n = src; - if (src == IterativeParsingArrayInitialState || src == IterativeParsingElementDelimiterState) - n = IterativeParsingElementState; - else if (src == IterativeParsingKeyValueDelimiterState) - n = IterativeParsingMemberValueState; - // Push current state. - *stack_.template Push(1) = n; - // Initialize and push the member/element count. - *stack_.template Push(1) = 0; - // Call handler - bool hr = (dst == IterativeParsingObjectInitialState) ? handler.StartObject() : handler.StartArray(); - // On handler short circuits the parsing. - if (!hr) { - CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell()); - return IterativeParsingErrorState; - } - else { - is.Take(); - return dst; - } - } - - case IterativeParsingMemberKeyState: - ParseString(is, handler, true); - if (HasParseError()) - return IterativeParsingErrorState; - else - return dst; - - case IterativeParsingKeyValueDelimiterState: - CEREAL_RAPIDJSON_ASSERT(token == ColonToken); - is.Take(); - return dst; - - case IterativeParsingMemberValueState: - // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state. - ParseValue(is, handler); - if (HasParseError()) { - return IterativeParsingErrorState; - } - return dst; - - case IterativeParsingElementState: - // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state. - ParseValue(is, handler); - if (HasParseError()) { - return IterativeParsingErrorState; - } - return dst; - - case IterativeParsingMemberDelimiterState: - case IterativeParsingElementDelimiterState: - is.Take(); - // Update member/element count. - *stack_.template Top() = *stack_.template Top() + 1; - return dst; - - case IterativeParsingObjectFinishState: - { - // Transit from delimiter is only allowed when trailing commas are enabled - if (!(parseFlags & kParseTrailingCommasFlag) && src == IterativeParsingMemberDelimiterState) { - CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorObjectMissName, is.Tell()); - return IterativeParsingErrorState; - } - // Get member count. - SizeType c = *stack_.template Pop(1); - // If the object is not empty, count the last member. - if (src == IterativeParsingMemberValueState) - ++c; - // Restore the state. - IterativeParsingState n = static_cast(*stack_.template Pop(1)); - // Transit to Finish state if this is the topmost scope. - if (n == IterativeParsingStartState) - n = IterativeParsingFinishState; - // Call handler - bool hr = handler.EndObject(c); - // On handler short circuits the parsing. - if (!hr) { - CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell()); - return IterativeParsingErrorState; - } - else { - is.Take(); - return n; - } - } - - case IterativeParsingArrayFinishState: - { - // Transit from delimiter is only allowed when trailing commas are enabled - if (!(parseFlags & kParseTrailingCommasFlag) && src == IterativeParsingElementDelimiterState) { - CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorValueInvalid, is.Tell()); - return IterativeParsingErrorState; - } - // Get element count. - SizeType c = *stack_.template Pop(1); - // If the array is not empty, count the last element. - if (src == IterativeParsingElementState) - ++c; - // Restore the state. - IterativeParsingState n = static_cast(*stack_.template Pop(1)); - // Transit to Finish state if this is the topmost scope. - if (n == IterativeParsingStartState) - n = IterativeParsingFinishState; - // Call handler - bool hr = handler.EndArray(c); - // On handler short circuits the parsing. - if (!hr) { - CEREAL_RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell()); - return IterativeParsingErrorState; - } - else { - is.Take(); - return n; - } - } - - default: - // This branch is for IterativeParsingValueState actually. - // Use `default:` rather than - // `case IterativeParsingValueState:` is for code coverage. - - // The IterativeParsingStartState is not enumerated in this switch-case. - // It is impossible for that case. And it can be caught by following assertion. - - // The IterativeParsingFinishState is not enumerated in this switch-case either. - // It is a "derivative" state which cannot triggered from Predict() directly. - // Therefore it cannot happen here. And it can be caught by following assertion. - CEREAL_RAPIDJSON_ASSERT(dst == IterativeParsingValueState); - - // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state. - ParseValue(is, handler); - if (HasParseError()) { - return IterativeParsingErrorState; - } - return IterativeParsingFinishState; - } - } - - template - void HandleError(IterativeParsingState src, InputStream& is) { - if (HasParseError()) { - // Error flag has been set. - return; - } - - switch (src) { - case IterativeParsingStartState: CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorDocumentEmpty, is.Tell()); return; - case IterativeParsingFinishState: CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorDocumentRootNotSingular, is.Tell()); return; - case IterativeParsingObjectInitialState: - case IterativeParsingMemberDelimiterState: CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissName, is.Tell()); return; - case IterativeParsingMemberKeyState: CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissColon, is.Tell()); return; - case IterativeParsingMemberValueState: CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, is.Tell()); return; - case IterativeParsingKeyValueDelimiterState: - case IterativeParsingArrayInitialState: - case IterativeParsingElementDelimiterState: CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); return; - default: CEREAL_RAPIDJSON_ASSERT(src == IterativeParsingElementState); CEREAL_RAPIDJSON_PARSE_ERROR(kParseErrorArrayMissCommaOrSquareBracket, is.Tell()); return; - } - } - - CEREAL_RAPIDJSON_FORCEINLINE bool IsIterativeParsingDelimiterState(IterativeParsingState s) const { - return s >= IterativeParsingElementDelimiterState; - } - - CEREAL_RAPIDJSON_FORCEINLINE bool IsIterativeParsingCompleteState(IterativeParsingState s) const { - return s <= IterativeParsingErrorState; - } - - template - ParseResult IterativeParse(InputStream& is, Handler& handler) { - parseResult_.Clear(); - ClearStackOnExit scope(*this); - IterativeParsingState state = IterativeParsingStartState; - - SkipWhitespaceAndComments(is); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); - while (is.Peek() != '\0') { - Token t = Tokenize(is.Peek()); - IterativeParsingState n = Predict(state, t); - IterativeParsingState d = Transit(state, t, n, is, handler); - - if (d == IterativeParsingErrorState) { - HandleError(state, is); - break; - } - - state = d; - - // Do not further consume streams if a root JSON has been parsed. - if ((parseFlags & kParseStopWhenDoneFlag) && state == IterativeParsingFinishState) - break; - - SkipWhitespaceAndComments(is); - CEREAL_RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); - } - - // Handle the end of file. - if (state != IterativeParsingFinishState) - HandleError(state, is); - - return parseResult_; - } - - static const size_t kDefaultStackCapacity = 256; //!< Default stack capacity in bytes for storing a single decoded string. - internal::Stack stack_; //!< A stack for storing decoded string temporarily during non-destructive parsing. - ParseResult parseResult_; - IterativeParsingState state_; -}; // class GenericReader - -//! Reader with UTF8 encoding and default allocator. -typedef GenericReader, UTF8<> > Reader; - -CEREAL_RAPIDJSON_NAMESPACE_END - -#if defined(__clang__) || defined(_MSC_VER) -CEREAL_RAPIDJSON_DIAG_POP -#endif - - -#ifdef __GNUC__ -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#endif // CEREAL_RAPIDJSON_READER_H_ diff --git a/include/cereal/external/rapidjson/schema.h b/include/cereal/external/rapidjson/schema.h deleted file mode 100644 index 17366c6..0000000 --- a/include/cereal/external/rapidjson/schema.h +++ /dev/null @@ -1,2497 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available-> -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip-> All rights reserved-> -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License-> You may obtain a copy of the License at -// -// http://opensource->org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied-> See the License for the -// specific language governing permissions and limitations under the License-> - -#ifndef CEREAL_RAPIDJSON_SCHEMA_H_ -#define CEREAL_RAPIDJSON_SCHEMA_H_ - -#include "document.h" -#include "pointer.h" -#include "stringbuffer.h" -#include // abs, floor - -#if !defined(CEREAL_RAPIDJSON_SCHEMA_USE_INTERNALREGEX) -#define CEREAL_RAPIDJSON_SCHEMA_USE_INTERNALREGEX 1 -#else -#define CEREAL_RAPIDJSON_SCHEMA_USE_INTERNALREGEX 0 -#endif - -#if !CEREAL_RAPIDJSON_SCHEMA_USE_INTERNALREGEX && defined(CEREAL_RAPIDJSON_SCHEMA_USE_STDREGEX) && (__cplusplus >=201103L || (defined(_MSC_VER) && _MSC_VER >= 1800)) -#define CEREAL_RAPIDJSON_SCHEMA_USE_STDREGEX 1 -#else -#define CEREAL_RAPIDJSON_SCHEMA_USE_STDREGEX 0 -#endif - -#if CEREAL_RAPIDJSON_SCHEMA_USE_INTERNALREGEX -#include "internal/regex.h" -#elif CEREAL_RAPIDJSON_SCHEMA_USE_STDREGEX -#include -#endif - -#if CEREAL_RAPIDJSON_SCHEMA_USE_INTERNALREGEX || CEREAL_RAPIDJSON_SCHEMA_USE_STDREGEX -#define CEREAL_RAPIDJSON_SCHEMA_HAS_REGEX 1 -#else -#define CEREAL_RAPIDJSON_SCHEMA_HAS_REGEX 0 -#endif - -#ifndef CEREAL_RAPIDJSON_SCHEMA_VERBOSE -#define CEREAL_RAPIDJSON_SCHEMA_VERBOSE 0 -#endif - -#if CEREAL_RAPIDJSON_SCHEMA_VERBOSE -#include "stringbuffer.h" -#endif - -CEREAL_RAPIDJSON_DIAG_PUSH - -#if defined(__GNUC__) -CEREAL_RAPIDJSON_DIAG_OFF(effc++) -#endif - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_OFF(weak-vtables) -CEREAL_RAPIDJSON_DIAG_OFF(exit-time-destructors) -CEREAL_RAPIDJSON_DIAG_OFF(c++98-compat-pedantic) -CEREAL_RAPIDJSON_DIAG_OFF(variadic-macros) -#elif defined(_MSC_VER) -CEREAL_RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -/////////////////////////////////////////////////////////////////////////////// -// Verbose Utilities - -#if CEREAL_RAPIDJSON_SCHEMA_VERBOSE - -namespace internal { - -inline void PrintInvalidKeyword(const char* keyword) { - printf("Fail keyword: %s\n", keyword); -} - -inline void PrintInvalidKeyword(const wchar_t* keyword) { - wprintf(L"Fail keyword: %ls\n", keyword); -} - -inline void PrintInvalidDocument(const char* document) { - printf("Fail document: %s\n\n", document); -} - -inline void PrintInvalidDocument(const wchar_t* document) { - wprintf(L"Fail document: %ls\n\n", document); -} - -inline void PrintValidatorPointers(unsigned depth, const char* s, const char* d) { - printf("S: %*s%s\nD: %*s%s\n\n", depth * 4, " ", s, depth * 4, " ", d); -} - -inline void PrintValidatorPointers(unsigned depth, const wchar_t* s, const wchar_t* d) { - wprintf(L"S: %*ls%ls\nD: %*ls%ls\n\n", depth * 4, L" ", s, depth * 4, L" ", d); -} - -} // namespace internal - -#endif // CEREAL_RAPIDJSON_SCHEMA_VERBOSE - -/////////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN - -#if CEREAL_RAPIDJSON_SCHEMA_VERBOSE -#define CEREAL_RAPIDJSON_INVALID_KEYWORD_VERBOSE(keyword) internal::PrintInvalidKeyword(keyword) -#else -#define CEREAL_RAPIDJSON_INVALID_KEYWORD_VERBOSE(keyword) -#endif - -#define CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(keyword)\ -CEREAL_RAPIDJSON_MULTILINEMACRO_BEGIN\ - context.invalidKeyword = keyword.GetString();\ - CEREAL_RAPIDJSON_INVALID_KEYWORD_VERBOSE(keyword.GetString());\ - return false;\ -CEREAL_RAPIDJSON_MULTILINEMACRO_END - -/////////////////////////////////////////////////////////////////////////////// -// Forward declarations - -template -class GenericSchemaDocument; - -namespace internal { - -template -class Schema; - -/////////////////////////////////////////////////////////////////////////////// -// ISchemaValidator - -class ISchemaValidator { -public: - virtual ~ISchemaValidator() {} - virtual bool IsValid() const = 0; -}; - -/////////////////////////////////////////////////////////////////////////////// -// ISchemaStateFactory - -template -class ISchemaStateFactory { -public: - virtual ~ISchemaStateFactory() {} - virtual ISchemaValidator* CreateSchemaValidator(const SchemaType&) = 0; - virtual void DestroySchemaValidator(ISchemaValidator* validator) = 0; - virtual void* CreateHasher() = 0; - virtual uint64_t GetHashCode(void* hasher) = 0; - virtual void DestroryHasher(void* hasher) = 0; - virtual void* MallocState(size_t size) = 0; - virtual void FreeState(void* p) = 0; -}; - -/////////////////////////////////////////////////////////////////////////////// -// IValidationErrorHandler - -template -class IValidationErrorHandler { -public: - typedef typename SchemaType::Ch Ch; - typedef typename SchemaType::SValue SValue; - - virtual ~IValidationErrorHandler() {} - - virtual void NotMultipleOf(int64_t actual, const SValue& expected) = 0; - virtual void NotMultipleOf(uint64_t actual, const SValue& expected) = 0; - virtual void NotMultipleOf(double actual, const SValue& expected) = 0; - virtual void AboveMaximum(int64_t actual, const SValue& expected, bool exclusive) = 0; - virtual void AboveMaximum(uint64_t actual, const SValue& expected, bool exclusive) = 0; - virtual void AboveMaximum(double actual, const SValue& expected, bool exclusive) = 0; - virtual void BelowMinimum(int64_t actual, const SValue& expected, bool exclusive) = 0; - virtual void BelowMinimum(uint64_t actual, const SValue& expected, bool exclusive) = 0; - virtual void BelowMinimum(double actual, const SValue& expected, bool exclusive) = 0; - - virtual void TooLong(const Ch* str, SizeType length, SizeType expected) = 0; - virtual void TooShort(const Ch* str, SizeType length, SizeType expected) = 0; - virtual void DoesNotMatch(const Ch* str, SizeType length) = 0; - - virtual void DisallowedItem(SizeType index) = 0; - virtual void TooFewItems(SizeType actualCount, SizeType expectedCount) = 0; - virtual void TooManyItems(SizeType actualCount, SizeType expectedCount) = 0; - virtual void DuplicateItems(SizeType index1, SizeType index2) = 0; - - virtual void TooManyProperties(SizeType actualCount, SizeType expectedCount) = 0; - virtual void TooFewProperties(SizeType actualCount, SizeType expectedCount) = 0; - virtual void StartMissingProperties() = 0; - virtual void AddMissingProperty(const SValue& name) = 0; - virtual bool EndMissingProperties() = 0; - virtual void PropertyViolations(ISchemaValidator** subvalidators, SizeType count) = 0; - virtual void DisallowedProperty(const Ch* name, SizeType length) = 0; - - virtual void StartDependencyErrors() = 0; - virtual void StartMissingDependentProperties() = 0; - virtual void AddMissingDependentProperty(const SValue& targetName) = 0; - virtual void EndMissingDependentProperties(const SValue& sourceName) = 0; - virtual void AddDependencySchemaError(const SValue& souceName, ISchemaValidator* subvalidator) = 0; - virtual bool EndDependencyErrors() = 0; - - virtual void DisallowedValue() = 0; - virtual void StartDisallowedType() = 0; - virtual void AddExpectedType(const typename SchemaType::ValueType& expectedType) = 0; - virtual void EndDisallowedType(const typename SchemaType::ValueType& actualType) = 0; - virtual void NotAllOf(ISchemaValidator** subvalidators, SizeType count) = 0; - virtual void NoneOf(ISchemaValidator** subvalidators, SizeType count) = 0; - virtual void NotOneOf(ISchemaValidator** subvalidators, SizeType count) = 0; - virtual void Disallowed() = 0; -}; - - -/////////////////////////////////////////////////////////////////////////////// -// Hasher - -// For comparison of compound value -template -class Hasher { -public: - typedef typename Encoding::Ch Ch; - - Hasher(Allocator* allocator = 0, size_t stackCapacity = kDefaultSize) : stack_(allocator, stackCapacity) {} - - bool Null() { return WriteType(kNullType); } - bool Bool(bool b) { return WriteType(b ? kTrueType : kFalseType); } - bool Int(int i) { Number n; n.u.i = i; n.d = static_cast(i); return WriteNumber(n); } - bool Uint(unsigned u) { Number n; n.u.u = u; n.d = static_cast(u); return WriteNumber(n); } - bool Int64(int64_t i) { Number n; n.u.i = i; n.d = static_cast(i); return WriteNumber(n); } - bool Uint64(uint64_t u) { Number n; n.u.u = u; n.d = static_cast(u); return WriteNumber(n); } - bool Double(double d) { - Number n; - if (d < 0) n.u.i = static_cast(d); - else n.u.u = static_cast(d); - n.d = d; - return WriteNumber(n); - } - - bool RawNumber(const Ch* str, SizeType len, bool) { - WriteBuffer(kNumberType, str, len * sizeof(Ch)); - return true; - } - - bool String(const Ch* str, SizeType len, bool) { - WriteBuffer(kStringType, str, len * sizeof(Ch)); - return true; - } - - bool StartObject() { return true; } - bool Key(const Ch* str, SizeType len, bool copy) { return String(str, len, copy); } - bool EndObject(SizeType memberCount) { - uint64_t h = Hash(0, kObjectType); - uint64_t* kv = stack_.template Pop(memberCount * 2); - for (SizeType i = 0; i < memberCount; i++) - h ^= Hash(kv[i * 2], kv[i * 2 + 1]); // Use xor to achieve member order insensitive - *stack_.template Push() = h; - return true; - } - - bool StartArray() { return true; } - bool EndArray(SizeType elementCount) { - uint64_t h = Hash(0, kArrayType); - uint64_t* e = stack_.template Pop(elementCount); - for (SizeType i = 0; i < elementCount; i++) - h = Hash(h, e[i]); // Use hash to achieve element order sensitive - *stack_.template Push() = h; - return true; - } - - bool IsValid() const { return stack_.GetSize() == sizeof(uint64_t); } - - uint64_t GetHashCode() const { - CEREAL_RAPIDJSON_ASSERT(IsValid()); - return *stack_.template Top(); - } - -private: - static const size_t kDefaultSize = 256; - struct Number { - union U { - uint64_t u; - int64_t i; - }u; - double d; - }; - - bool WriteType(Type type) { return WriteBuffer(type, 0, 0); } - - bool WriteNumber(const Number& n) { return WriteBuffer(kNumberType, &n, sizeof(n)); } - - bool WriteBuffer(Type type, const void* data, size_t len) { - // FNV-1a from http://isthe.com/chongo/tech/comp/fnv/ - uint64_t h = Hash(CEREAL_RAPIDJSON_UINT64_C2(0x84222325, 0xcbf29ce4), type); - const unsigned char* d = static_cast(data); - for (size_t i = 0; i < len; i++) - h = Hash(h, d[i]); - *stack_.template Push() = h; - return true; - } - - static uint64_t Hash(uint64_t h, uint64_t d) { - static const uint64_t kPrime = CEREAL_RAPIDJSON_UINT64_C2(0x00000100, 0x000001b3); - h ^= d; - h *= kPrime; - return h; - } - - Stack stack_; -}; - -/////////////////////////////////////////////////////////////////////////////// -// SchemaValidationContext - -template -struct SchemaValidationContext { - typedef Schema SchemaType; - typedef ISchemaStateFactory SchemaValidatorFactoryType; - typedef IValidationErrorHandler ErrorHandlerType; - typedef typename SchemaType::ValueType ValueType; - typedef typename ValueType::Ch Ch; - - enum PatternValidatorType { - kPatternValidatorOnly, - kPatternValidatorWithProperty, - kPatternValidatorWithAdditionalProperty - }; - - SchemaValidationContext(SchemaValidatorFactoryType& f, ErrorHandlerType& eh, const SchemaType* s) : - factory(f), - error_handler(eh), - schema(s), - valueSchema(), - invalidKeyword(), - hasher(), - arrayElementHashCodes(), - validators(), - validatorCount(), - patternPropertiesValidators(), - patternPropertiesValidatorCount(), - patternPropertiesSchemas(), - patternPropertiesSchemaCount(), - valuePatternValidatorType(kPatternValidatorOnly), - propertyExist(), - inArray(false), - valueUniqueness(false), - arrayUniqueness(false) - { - } - - ~SchemaValidationContext() { - if (hasher) - factory.DestroryHasher(hasher); - if (validators) { - for (SizeType i = 0; i < validatorCount; i++) - factory.DestroySchemaValidator(validators[i]); - factory.FreeState(validators); - } - if (patternPropertiesValidators) { - for (SizeType i = 0; i < patternPropertiesValidatorCount; i++) - factory.DestroySchemaValidator(patternPropertiesValidators[i]); - factory.FreeState(patternPropertiesValidators); - } - if (patternPropertiesSchemas) - factory.FreeState(patternPropertiesSchemas); - if (propertyExist) - factory.FreeState(propertyExist); - } - - SchemaValidatorFactoryType& factory; - ErrorHandlerType& error_handler; - const SchemaType* schema; - const SchemaType* valueSchema; - const Ch* invalidKeyword; - void* hasher; // Only validator access - void* arrayElementHashCodes; // Only validator access this - ISchemaValidator** validators; - SizeType validatorCount; - ISchemaValidator** patternPropertiesValidators; - SizeType patternPropertiesValidatorCount; - const SchemaType** patternPropertiesSchemas; - SizeType patternPropertiesSchemaCount; - PatternValidatorType valuePatternValidatorType; - PatternValidatorType objectPatternValidatorType; - SizeType arrayElementIndex; - bool* propertyExist; - bool inArray; - bool valueUniqueness; - bool arrayUniqueness; -}; - -/////////////////////////////////////////////////////////////////////////////// -// Schema - -template -class Schema { -public: - typedef typename SchemaDocumentType::ValueType ValueType; - typedef typename SchemaDocumentType::AllocatorType AllocatorType; - typedef typename SchemaDocumentType::PointerType PointerType; - typedef typename ValueType::EncodingType EncodingType; - typedef typename EncodingType::Ch Ch; - typedef SchemaValidationContext Context; - typedef Schema SchemaType; - typedef GenericValue SValue; - typedef IValidationErrorHandler ErrorHandler; - friend class GenericSchemaDocument; - - Schema(SchemaDocumentType* schemaDocument, const PointerType& p, const ValueType& value, const ValueType& document, AllocatorType* allocator) : - allocator_(allocator), - uri_(schemaDocument->GetURI(), *allocator), - pointer_(p, allocator), - typeless_(schemaDocument->GetTypeless()), - enum_(), - enumCount_(), - not_(), - type_((1 << kTotalSchemaType) - 1), // typeless - validatorCount_(), - notValidatorIndex_(), - properties_(), - additionalPropertiesSchema_(), - patternProperties_(), - patternPropertyCount_(), - propertyCount_(), - minProperties_(), - maxProperties_(SizeType(~0)), - additionalProperties_(true), - hasDependencies_(), - hasRequired_(), - hasSchemaDependencies_(), - additionalItemsSchema_(), - itemsList_(), - itemsTuple_(), - itemsTupleCount_(), - minItems_(), - maxItems_(SizeType(~0)), - additionalItems_(true), - uniqueItems_(false), - pattern_(), - minLength_(0), - maxLength_(~SizeType(0)), - exclusiveMinimum_(false), - exclusiveMaximum_(false), - defaultValueLength_(0) - { - typedef typename SchemaDocumentType::ValueType ValueType; - typedef typename ValueType::ConstValueIterator ConstValueIterator; - typedef typename ValueType::ConstMemberIterator ConstMemberIterator; - - if (!value.IsObject()) - return; - - if (const ValueType* v = GetMember(value, GetTypeString())) { - type_ = 0; - if (v->IsString()) - AddType(*v); - else if (v->IsArray()) - for (ConstValueIterator itr = v->Begin(); itr != v->End(); ++itr) - AddType(*itr); - } - - if (const ValueType* v = GetMember(value, GetEnumString())) - if (v->IsArray() && v->Size() > 0) { - enum_ = static_cast(allocator_->Malloc(sizeof(uint64_t) * v->Size())); - for (ConstValueIterator itr = v->Begin(); itr != v->End(); ++itr) { - typedef Hasher > EnumHasherType; - char buffer[256u + 24]; - MemoryPoolAllocator<> hasherAllocator(buffer, sizeof(buffer)); - EnumHasherType h(&hasherAllocator, 256); - itr->Accept(h); - enum_[enumCount_++] = h.GetHashCode(); - } - } - - if (schemaDocument) { - AssignIfExist(allOf_, *schemaDocument, p, value, GetAllOfString(), document); - AssignIfExist(anyOf_, *schemaDocument, p, value, GetAnyOfString(), document); - AssignIfExist(oneOf_, *schemaDocument, p, value, GetOneOfString(), document); - } - - if (const ValueType* v = GetMember(value, GetNotString())) { - schemaDocument->CreateSchema(¬_, p.Append(GetNotString(), allocator_), *v, document); - notValidatorIndex_ = validatorCount_; - validatorCount_++; - } - - // Object - - const ValueType* properties = GetMember(value, GetPropertiesString()); - const ValueType* required = GetMember(value, GetRequiredString()); - const ValueType* dependencies = GetMember(value, GetDependenciesString()); - { - // Gather properties from properties/required/dependencies - SValue allProperties(kArrayType); - - if (properties && properties->IsObject()) - for (ConstMemberIterator itr = properties->MemberBegin(); itr != properties->MemberEnd(); ++itr) - AddUniqueElement(allProperties, itr->name); - - if (required && required->IsArray()) - for (ConstValueIterator itr = required->Begin(); itr != required->End(); ++itr) - if (itr->IsString()) - AddUniqueElement(allProperties, *itr); - - if (dependencies && dependencies->IsObject()) - for (ConstMemberIterator itr = dependencies->MemberBegin(); itr != dependencies->MemberEnd(); ++itr) { - AddUniqueElement(allProperties, itr->name); - if (itr->value.IsArray()) - for (ConstValueIterator i = itr->value.Begin(); i != itr->value.End(); ++i) - if (i->IsString()) - AddUniqueElement(allProperties, *i); - } - - if (allProperties.Size() > 0) { - propertyCount_ = allProperties.Size(); - properties_ = static_cast(allocator_->Malloc(sizeof(Property) * propertyCount_)); - for (SizeType i = 0; i < propertyCount_; i++) { - new (&properties_[i]) Property(); - properties_[i].name = allProperties[i]; - properties_[i].schema = typeless_; - } - } - } - - if (properties && properties->IsObject()) { - PointerType q = p.Append(GetPropertiesString(), allocator_); - for (ConstMemberIterator itr = properties->MemberBegin(); itr != properties->MemberEnd(); ++itr) { - SizeType index; - if (FindPropertyIndex(itr->name, &index)) - schemaDocument->CreateSchema(&properties_[index].schema, q.Append(itr->name, allocator_), itr->value, document); - } - } - - if (const ValueType* v = GetMember(value, GetPatternPropertiesString())) { - PointerType q = p.Append(GetPatternPropertiesString(), allocator_); - patternProperties_ = static_cast(allocator_->Malloc(sizeof(PatternProperty) * v->MemberCount())); - patternPropertyCount_ = 0; - - for (ConstMemberIterator itr = v->MemberBegin(); itr != v->MemberEnd(); ++itr) { - new (&patternProperties_[patternPropertyCount_]) PatternProperty(); - patternProperties_[patternPropertyCount_].pattern = CreatePattern(itr->name); - schemaDocument->CreateSchema(&patternProperties_[patternPropertyCount_].schema, q.Append(itr->name, allocator_), itr->value, document); - patternPropertyCount_++; - } - } - - if (required && required->IsArray()) - for (ConstValueIterator itr = required->Begin(); itr != required->End(); ++itr) - if (itr->IsString()) { - SizeType index; - if (FindPropertyIndex(*itr, &index)) { - properties_[index].required = true; - hasRequired_ = true; - } - } - - if (dependencies && dependencies->IsObject()) { - PointerType q = p.Append(GetDependenciesString(), allocator_); - hasDependencies_ = true; - for (ConstMemberIterator itr = dependencies->MemberBegin(); itr != dependencies->MemberEnd(); ++itr) { - SizeType sourceIndex; - if (FindPropertyIndex(itr->name, &sourceIndex)) { - if (itr->value.IsArray()) { - properties_[sourceIndex].dependencies = static_cast(allocator_->Malloc(sizeof(bool) * propertyCount_)); - std::memset(properties_[sourceIndex].dependencies, 0, sizeof(bool)* propertyCount_); - for (ConstValueIterator targetItr = itr->value.Begin(); targetItr != itr->value.End(); ++targetItr) { - SizeType targetIndex; - if (FindPropertyIndex(*targetItr, &targetIndex)) - properties_[sourceIndex].dependencies[targetIndex] = true; - } - } - else if (itr->value.IsObject()) { - hasSchemaDependencies_ = true; - schemaDocument->CreateSchema(&properties_[sourceIndex].dependenciesSchema, q.Append(itr->name, allocator_), itr->value, document); - properties_[sourceIndex].dependenciesValidatorIndex = validatorCount_; - validatorCount_++; - } - } - } - } - - if (const ValueType* v = GetMember(value, GetAdditionalPropertiesString())) { - if (v->IsBool()) - additionalProperties_ = v->GetBool(); - else if (v->IsObject()) - schemaDocument->CreateSchema(&additionalPropertiesSchema_, p.Append(GetAdditionalPropertiesString(), allocator_), *v, document); - } - - AssignIfExist(minProperties_, value, GetMinPropertiesString()); - AssignIfExist(maxProperties_, value, GetMaxPropertiesString()); - - // Array - if (const ValueType* v = GetMember(value, GetItemsString())) { - PointerType q = p.Append(GetItemsString(), allocator_); - if (v->IsObject()) // List validation - schemaDocument->CreateSchema(&itemsList_, q, *v, document); - else if (v->IsArray()) { // Tuple validation - itemsTuple_ = static_cast(allocator_->Malloc(sizeof(const Schema*) * v->Size())); - SizeType index = 0; - for (ConstValueIterator itr = v->Begin(); itr != v->End(); ++itr, index++) - schemaDocument->CreateSchema(&itemsTuple_[itemsTupleCount_++], q.Append(index, allocator_), *itr, document); - } - } - - AssignIfExist(minItems_, value, GetMinItemsString()); - AssignIfExist(maxItems_, value, GetMaxItemsString()); - - if (const ValueType* v = GetMember(value, GetAdditionalItemsString())) { - if (v->IsBool()) - additionalItems_ = v->GetBool(); - else if (v->IsObject()) - schemaDocument->CreateSchema(&additionalItemsSchema_, p.Append(GetAdditionalItemsString(), allocator_), *v, document); - } - - AssignIfExist(uniqueItems_, value, GetUniqueItemsString()); - - // String - AssignIfExist(minLength_, value, GetMinLengthString()); - AssignIfExist(maxLength_, value, GetMaxLengthString()); - - if (const ValueType* v = GetMember(value, GetPatternString())) - pattern_ = CreatePattern(*v); - - // Number - if (const ValueType* v = GetMember(value, GetMinimumString())) - if (v->IsNumber()) - minimum_.CopyFrom(*v, *allocator_); - - if (const ValueType* v = GetMember(value, GetMaximumString())) - if (v->IsNumber()) - maximum_.CopyFrom(*v, *allocator_); - - AssignIfExist(exclusiveMinimum_, value, GetExclusiveMinimumString()); - AssignIfExist(exclusiveMaximum_, value, GetExclusiveMaximumString()); - - if (const ValueType* v = GetMember(value, GetMultipleOfString())) - if (v->IsNumber() && v->GetDouble() > 0.0) - multipleOf_.CopyFrom(*v, *allocator_); - - // Default - if (const ValueType* v = GetMember(value, GetDefaultValueString())) - if (v->IsString()) - defaultValueLength_ = v->GetStringLength(); - - } - - ~Schema() { - AllocatorType::Free(enum_); - if (properties_) { - for (SizeType i = 0; i < propertyCount_; i++) - properties_[i].~Property(); - AllocatorType::Free(properties_); - } - if (patternProperties_) { - for (SizeType i = 0; i < patternPropertyCount_; i++) - patternProperties_[i].~PatternProperty(); - AllocatorType::Free(patternProperties_); - } - AllocatorType::Free(itemsTuple_); -#if CEREAL_RAPIDJSON_SCHEMA_HAS_REGEX - if (pattern_) { - pattern_->~RegexType(); - AllocatorType::Free(pattern_); - } -#endif - } - - const SValue& GetURI() const { - return uri_; - } - - const PointerType& GetPointer() const { - return pointer_; - } - - bool BeginValue(Context& context) const { - if (context.inArray) { - if (uniqueItems_) - context.valueUniqueness = true; - - if (itemsList_) - context.valueSchema = itemsList_; - else if (itemsTuple_) { - if (context.arrayElementIndex < itemsTupleCount_) - context.valueSchema = itemsTuple_[context.arrayElementIndex]; - else if (additionalItemsSchema_) - context.valueSchema = additionalItemsSchema_; - else if (additionalItems_) - context.valueSchema = typeless_; - else { - context.error_handler.DisallowedItem(context.arrayElementIndex); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetItemsString()); - } - } - else - context.valueSchema = typeless_; - - context.arrayElementIndex++; - } - return true; - } - - CEREAL_RAPIDJSON_FORCEINLINE bool EndValue(Context& context) const { - if (context.patternPropertiesValidatorCount > 0) { - bool otherValid = false; - SizeType count = context.patternPropertiesValidatorCount; - if (context.objectPatternValidatorType != Context::kPatternValidatorOnly) - otherValid = context.patternPropertiesValidators[--count]->IsValid(); - - bool patternValid = true; - for (SizeType i = 0; i < count; i++) - if (!context.patternPropertiesValidators[i]->IsValid()) { - patternValid = false; - break; - } - - if (context.objectPatternValidatorType == Context::kPatternValidatorOnly) { - if (!patternValid) { - context.error_handler.PropertyViolations(context.patternPropertiesValidators, count); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString()); - } - } - else if (context.objectPatternValidatorType == Context::kPatternValidatorWithProperty) { - if (!patternValid || !otherValid) { - context.error_handler.PropertyViolations(context.patternPropertiesValidators, count + 1); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString()); - } - } - else if (!patternValid && !otherValid) { // kPatternValidatorWithAdditionalProperty) - context.error_handler.PropertyViolations(context.patternPropertiesValidators, count + 1); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString()); - } - } - - if (enum_) { - const uint64_t h = context.factory.GetHashCode(context.hasher); - for (SizeType i = 0; i < enumCount_; i++) - if (enum_[i] == h) - goto foundEnum; - context.error_handler.DisallowedValue(); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetEnumString()); - foundEnum:; - } - - if (allOf_.schemas) - for (SizeType i = allOf_.begin; i < allOf_.begin + allOf_.count; i++) - if (!context.validators[i]->IsValid()) { - context.error_handler.NotAllOf(&context.validators[allOf_.begin], allOf_.count); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetAllOfString()); - } - - if (anyOf_.schemas) { - for (SizeType i = anyOf_.begin; i < anyOf_.begin + anyOf_.count; i++) - if (context.validators[i]->IsValid()) - goto foundAny; - context.error_handler.NoneOf(&context.validators[anyOf_.begin], anyOf_.count); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetAnyOfString()); - foundAny:; - } - - if (oneOf_.schemas) { - bool oneValid = false; - for (SizeType i = oneOf_.begin; i < oneOf_.begin + oneOf_.count; i++) - if (context.validators[i]->IsValid()) { - if (oneValid) { - context.error_handler.NotOneOf(&context.validators[oneOf_.begin], oneOf_.count); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetOneOfString()); - } else - oneValid = true; - } - if (!oneValid) { - context.error_handler.NotOneOf(&context.validators[oneOf_.begin], oneOf_.count); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetOneOfString()); - } - } - - if (not_ && context.validators[notValidatorIndex_]->IsValid()) { - context.error_handler.Disallowed(); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetNotString()); - } - - return true; - } - - bool Null(Context& context) const { - if (!(type_ & (1 << kNullSchemaType))) { - DisallowedType(context, GetNullString()); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); - } - return CreateParallelValidator(context); - } - - bool Bool(Context& context, bool) const { - if (!(type_ & (1 << kBooleanSchemaType))) { - DisallowedType(context, GetBooleanString()); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); - } - return CreateParallelValidator(context); - } - - bool Int(Context& context, int i) const { - if (!CheckInt(context, i)) - return false; - return CreateParallelValidator(context); - } - - bool Uint(Context& context, unsigned u) const { - if (!CheckUint(context, u)) - return false; - return CreateParallelValidator(context); - } - - bool Int64(Context& context, int64_t i) const { - if (!CheckInt(context, i)) - return false; - return CreateParallelValidator(context); - } - - bool Uint64(Context& context, uint64_t u) const { - if (!CheckUint(context, u)) - return false; - return CreateParallelValidator(context); - } - - bool Double(Context& context, double d) const { - if (!(type_ & (1 << kNumberSchemaType))) { - DisallowedType(context, GetNumberString()); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); - } - - if (!minimum_.IsNull() && !CheckDoubleMinimum(context, d)) - return false; - - if (!maximum_.IsNull() && !CheckDoubleMaximum(context, d)) - return false; - - if (!multipleOf_.IsNull() && !CheckDoubleMultipleOf(context, d)) - return false; - - return CreateParallelValidator(context); - } - - bool String(Context& context, const Ch* str, SizeType length, bool) const { - if (!(type_ & (1 << kStringSchemaType))) { - DisallowedType(context, GetStringString()); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); - } - - if (minLength_ != 0 || maxLength_ != SizeType(~0)) { - SizeType count; - if (internal::CountStringCodePoint(str, length, &count)) { - if (count < minLength_) { - context.error_handler.TooShort(str, length, minLength_); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinLengthString()); - } - if (count > maxLength_) { - context.error_handler.TooLong(str, length, maxLength_); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxLengthString()); - } - } - } - - if (pattern_ && !IsPatternMatch(pattern_, str, length)) { - context.error_handler.DoesNotMatch(str, length); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternString()); - } - - return CreateParallelValidator(context); - } - - bool StartObject(Context& context) const { - if (!(type_ & (1 << kObjectSchemaType))) { - DisallowedType(context, GetObjectString()); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); - } - - if (hasDependencies_ || hasRequired_) { - context.propertyExist = static_cast(context.factory.MallocState(sizeof(bool) * propertyCount_)); - std::memset(context.propertyExist, 0, sizeof(bool) * propertyCount_); - } - - if (patternProperties_) { // pre-allocate schema array - SizeType count = patternPropertyCount_ + 1; // extra for valuePatternValidatorType - context.patternPropertiesSchemas = static_cast(context.factory.MallocState(sizeof(const SchemaType*) * count)); - context.patternPropertiesSchemaCount = 0; - std::memset(context.patternPropertiesSchemas, 0, sizeof(SchemaType*) * count); - } - - return CreateParallelValidator(context); - } - - bool Key(Context& context, const Ch* str, SizeType len, bool) const { - if (patternProperties_) { - context.patternPropertiesSchemaCount = 0; - for (SizeType i = 0; i < patternPropertyCount_; i++) - if (patternProperties_[i].pattern && IsPatternMatch(patternProperties_[i].pattern, str, len)) { - context.patternPropertiesSchemas[context.patternPropertiesSchemaCount++] = patternProperties_[i].schema; - context.valueSchema = typeless_; - } - } - - SizeType index; - if (FindPropertyIndex(ValueType(str, len).Move(), &index)) { - if (context.patternPropertiesSchemaCount > 0) { - context.patternPropertiesSchemas[context.patternPropertiesSchemaCount++] = properties_[index].schema; - context.valueSchema = typeless_; - context.valuePatternValidatorType = Context::kPatternValidatorWithProperty; - } - else - context.valueSchema = properties_[index].schema; - - if (context.propertyExist) - context.propertyExist[index] = true; - - return true; - } - - if (additionalPropertiesSchema_) { - if (additionalPropertiesSchema_ && context.patternPropertiesSchemaCount > 0) { - context.patternPropertiesSchemas[context.patternPropertiesSchemaCount++] = additionalPropertiesSchema_; - context.valueSchema = typeless_; - context.valuePatternValidatorType = Context::kPatternValidatorWithAdditionalProperty; - } - else - context.valueSchema = additionalPropertiesSchema_; - return true; - } - else if (additionalProperties_) { - context.valueSchema = typeless_; - return true; - } - - if (context.patternPropertiesSchemaCount == 0) { // patternProperties are not additional properties - context.error_handler.DisallowedProperty(str, len); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetAdditionalPropertiesString()); - } - - return true; - } - - bool EndObject(Context& context, SizeType memberCount) const { - if (hasRequired_) { - context.error_handler.StartMissingProperties(); - for (SizeType index = 0; index < propertyCount_; index++) - if (properties_[index].required && !context.propertyExist[index]) - if (properties_[index].schema->defaultValueLength_ == 0 ) - context.error_handler.AddMissingProperty(properties_[index].name); - if (context.error_handler.EndMissingProperties()) - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetRequiredString()); - } - - if (memberCount < minProperties_) { - context.error_handler.TooFewProperties(memberCount, minProperties_); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinPropertiesString()); - } - - if (memberCount > maxProperties_) { - context.error_handler.TooManyProperties(memberCount, maxProperties_); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxPropertiesString()); - } - - if (hasDependencies_) { - context.error_handler.StartDependencyErrors(); - for (SizeType sourceIndex = 0; sourceIndex < propertyCount_; sourceIndex++) { - const Property& source = properties_[sourceIndex]; - if (context.propertyExist[sourceIndex]) { - if (source.dependencies) { - context.error_handler.StartMissingDependentProperties(); - for (SizeType targetIndex = 0; targetIndex < propertyCount_; targetIndex++) - if (source.dependencies[targetIndex] && !context.propertyExist[targetIndex]) - context.error_handler.AddMissingDependentProperty(properties_[targetIndex].name); - context.error_handler.EndMissingDependentProperties(source.name); - } - else if (source.dependenciesSchema) { - ISchemaValidator* dependenciesValidator = context.validators[source.dependenciesValidatorIndex]; - if (!dependenciesValidator->IsValid()) - context.error_handler.AddDependencySchemaError(source.name, dependenciesValidator); - } - } - } - if (context.error_handler.EndDependencyErrors()) - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetDependenciesString()); - } - - return true; - } - - bool StartArray(Context& context) const { - if (!(type_ & (1 << kArraySchemaType))) { - DisallowedType(context, GetArrayString()); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); - } - - context.arrayElementIndex = 0; - context.inArray = true; - - return CreateParallelValidator(context); - } - - bool EndArray(Context& context, SizeType elementCount) const { - context.inArray = false; - - if (elementCount < minItems_) { - context.error_handler.TooFewItems(elementCount, minItems_); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinItemsString()); - } - - if (elementCount > maxItems_) { - context.error_handler.TooManyItems(elementCount, maxItems_); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxItemsString()); - } - - return true; - } - - // Generate functions for string literal according to Ch -#define CEREAL_RAPIDJSON_STRING_(name, ...) \ - static const ValueType& Get##name##String() {\ - static const Ch s[] = { __VA_ARGS__, '\0' };\ - static const ValueType v(s, static_cast(sizeof(s) / sizeof(Ch) - 1));\ - return v;\ - } - - CEREAL_RAPIDJSON_STRING_(Null, 'n', 'u', 'l', 'l') - CEREAL_RAPIDJSON_STRING_(Boolean, 'b', 'o', 'o', 'l', 'e', 'a', 'n') - CEREAL_RAPIDJSON_STRING_(Object, 'o', 'b', 'j', 'e', 'c', 't') - CEREAL_RAPIDJSON_STRING_(Array, 'a', 'r', 'r', 'a', 'y') - CEREAL_RAPIDJSON_STRING_(String, 's', 't', 'r', 'i', 'n', 'g') - CEREAL_RAPIDJSON_STRING_(Number, 'n', 'u', 'm', 'b', 'e', 'r') - CEREAL_RAPIDJSON_STRING_(Integer, 'i', 'n', 't', 'e', 'g', 'e', 'r') - CEREAL_RAPIDJSON_STRING_(Type, 't', 'y', 'p', 'e') - CEREAL_RAPIDJSON_STRING_(Enum, 'e', 'n', 'u', 'm') - CEREAL_RAPIDJSON_STRING_(AllOf, 'a', 'l', 'l', 'O', 'f') - CEREAL_RAPIDJSON_STRING_(AnyOf, 'a', 'n', 'y', 'O', 'f') - CEREAL_RAPIDJSON_STRING_(OneOf, 'o', 'n', 'e', 'O', 'f') - CEREAL_RAPIDJSON_STRING_(Not, 'n', 'o', 't') - CEREAL_RAPIDJSON_STRING_(Properties, 'p', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's') - CEREAL_RAPIDJSON_STRING_(Required, 'r', 'e', 'q', 'u', 'i', 'r', 'e', 'd') - CEREAL_RAPIDJSON_STRING_(Dependencies, 'd', 'e', 'p', 'e', 'n', 'd', 'e', 'n', 'c', 'i', 'e', 's') - CEREAL_RAPIDJSON_STRING_(PatternProperties, 'p', 'a', 't', 't', 'e', 'r', 'n', 'P', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's') - CEREAL_RAPIDJSON_STRING_(AdditionalProperties, 'a', 'd', 'd', 'i', 't', 'i', 'o', 'n', 'a', 'l', 'P', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's') - CEREAL_RAPIDJSON_STRING_(MinProperties, 'm', 'i', 'n', 'P', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's') - CEREAL_RAPIDJSON_STRING_(MaxProperties, 'm', 'a', 'x', 'P', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's') - CEREAL_RAPIDJSON_STRING_(Items, 'i', 't', 'e', 'm', 's') - CEREAL_RAPIDJSON_STRING_(MinItems, 'm', 'i', 'n', 'I', 't', 'e', 'm', 's') - CEREAL_RAPIDJSON_STRING_(MaxItems, 'm', 'a', 'x', 'I', 't', 'e', 'm', 's') - CEREAL_RAPIDJSON_STRING_(AdditionalItems, 'a', 'd', 'd', 'i', 't', 'i', 'o', 'n', 'a', 'l', 'I', 't', 'e', 'm', 's') - CEREAL_RAPIDJSON_STRING_(UniqueItems, 'u', 'n', 'i', 'q', 'u', 'e', 'I', 't', 'e', 'm', 's') - CEREAL_RAPIDJSON_STRING_(MinLength, 'm', 'i', 'n', 'L', 'e', 'n', 'g', 't', 'h') - CEREAL_RAPIDJSON_STRING_(MaxLength, 'm', 'a', 'x', 'L', 'e', 'n', 'g', 't', 'h') - CEREAL_RAPIDJSON_STRING_(Pattern, 'p', 'a', 't', 't', 'e', 'r', 'n') - CEREAL_RAPIDJSON_STRING_(Minimum, 'm', 'i', 'n', 'i', 'm', 'u', 'm') - CEREAL_RAPIDJSON_STRING_(Maximum, 'm', 'a', 'x', 'i', 'm', 'u', 'm') - CEREAL_RAPIDJSON_STRING_(ExclusiveMinimum, 'e', 'x', 'c', 'l', 'u', 's', 'i', 'v', 'e', 'M', 'i', 'n', 'i', 'm', 'u', 'm') - CEREAL_RAPIDJSON_STRING_(ExclusiveMaximum, 'e', 'x', 'c', 'l', 'u', 's', 'i', 'v', 'e', 'M', 'a', 'x', 'i', 'm', 'u', 'm') - CEREAL_RAPIDJSON_STRING_(MultipleOf, 'm', 'u', 'l', 't', 'i', 'p', 'l', 'e', 'O', 'f') - CEREAL_RAPIDJSON_STRING_(DefaultValue, 'd', 'e', 'f', 'a', 'u', 'l', 't') - -#undef CEREAL_RAPIDJSON_STRING_ - -private: - enum SchemaValueType { - kNullSchemaType, - kBooleanSchemaType, - kObjectSchemaType, - kArraySchemaType, - kStringSchemaType, - kNumberSchemaType, - kIntegerSchemaType, - kTotalSchemaType - }; - -#if CEREAL_RAPIDJSON_SCHEMA_USE_INTERNALREGEX - typedef internal::GenericRegex RegexType; -#elif CEREAL_RAPIDJSON_SCHEMA_USE_STDREGEX - typedef std::basic_regex RegexType; -#else - typedef char RegexType; -#endif - - struct SchemaArray { - SchemaArray() : schemas(), count() {} - ~SchemaArray() { AllocatorType::Free(schemas); } - const SchemaType** schemas; - SizeType begin; // begin index of context.validators - SizeType count; - }; - - template - void AddUniqueElement(V1& a, const V2& v) { - for (typename V1::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr) - if (*itr == v) - return; - V1 c(v, *allocator_); - a.PushBack(c, *allocator_); - } - - static const ValueType* GetMember(const ValueType& value, const ValueType& name) { - typename ValueType::ConstMemberIterator itr = value.FindMember(name); - return itr != value.MemberEnd() ? &(itr->value) : 0; - } - - static void AssignIfExist(bool& out, const ValueType& value, const ValueType& name) { - if (const ValueType* v = GetMember(value, name)) - if (v->IsBool()) - out = v->GetBool(); - } - - static void AssignIfExist(SizeType& out, const ValueType& value, const ValueType& name) { - if (const ValueType* v = GetMember(value, name)) - if (v->IsUint64() && v->GetUint64() <= SizeType(~0)) - out = static_cast(v->GetUint64()); - } - - void AssignIfExist(SchemaArray& out, SchemaDocumentType& schemaDocument, const PointerType& p, const ValueType& value, const ValueType& name, const ValueType& document) { - if (const ValueType* v = GetMember(value, name)) { - if (v->IsArray() && v->Size() > 0) { - PointerType q = p.Append(name, allocator_); - out.count = v->Size(); - out.schemas = static_cast(allocator_->Malloc(out.count * sizeof(const Schema*))); - memset(out.schemas, 0, sizeof(Schema*)* out.count); - for (SizeType i = 0; i < out.count; i++) - schemaDocument.CreateSchema(&out.schemas[i], q.Append(i, allocator_), (*v)[i], document); - out.begin = validatorCount_; - validatorCount_ += out.count; - } - } - } - -#if CEREAL_RAPIDJSON_SCHEMA_USE_INTERNALREGEX - template - RegexType* CreatePattern(const ValueType& value) { - if (value.IsString()) { - RegexType* r = new (allocator_->Malloc(sizeof(RegexType))) RegexType(value.GetString(), allocator_); - if (!r->IsValid()) { - r->~RegexType(); - AllocatorType::Free(r); - r = 0; - } - return r; - } - return 0; - } - - static bool IsPatternMatch(const RegexType* pattern, const Ch *str, SizeType) { - GenericRegexSearch rs(*pattern); - return rs.Search(str); - } -#elif CEREAL_RAPIDJSON_SCHEMA_USE_STDREGEX - template - RegexType* CreatePattern(const ValueType& value) { - if (value.IsString()) { - RegexType *r = static_cast(allocator_->Malloc(sizeof(RegexType))); - try { - return new (r) RegexType(value.GetString(), std::size_t(value.GetStringLength()), std::regex_constants::ECMAScript); - } - catch (const std::regex_error&) { - AllocatorType::Free(r); - } - } - return 0; - } - - static bool IsPatternMatch(const RegexType* pattern, const Ch *str, SizeType length) { - std::match_results r; - return std::regex_search(str, str + length, r, *pattern); - } -#else - template - RegexType* CreatePattern(const ValueType&) { return 0; } - - static bool IsPatternMatch(const RegexType*, const Ch *, SizeType) { return true; } -#endif // CEREAL_RAPIDJSON_SCHEMA_USE_STDREGEX - - void AddType(const ValueType& type) { - if (type == GetNullString() ) type_ |= 1 << kNullSchemaType; - else if (type == GetBooleanString()) type_ |= 1 << kBooleanSchemaType; - else if (type == GetObjectString() ) type_ |= 1 << kObjectSchemaType; - else if (type == GetArrayString() ) type_ |= 1 << kArraySchemaType; - else if (type == GetStringString() ) type_ |= 1 << kStringSchemaType; - else if (type == GetIntegerString()) type_ |= 1 << kIntegerSchemaType; - else if (type == GetNumberString() ) type_ |= (1 << kNumberSchemaType) | (1 << kIntegerSchemaType); - } - - bool CreateParallelValidator(Context& context) const { - if (enum_ || context.arrayUniqueness) - context.hasher = context.factory.CreateHasher(); - - if (validatorCount_) { - CEREAL_RAPIDJSON_ASSERT(context.validators == 0); - context.validators = static_cast(context.factory.MallocState(sizeof(ISchemaValidator*) * validatorCount_)); - context.validatorCount = validatorCount_; - - if (allOf_.schemas) - CreateSchemaValidators(context, allOf_); - - if (anyOf_.schemas) - CreateSchemaValidators(context, anyOf_); - - if (oneOf_.schemas) - CreateSchemaValidators(context, oneOf_); - - if (not_) - context.validators[notValidatorIndex_] = context.factory.CreateSchemaValidator(*not_); - - if (hasSchemaDependencies_) { - for (SizeType i = 0; i < propertyCount_; i++) - if (properties_[i].dependenciesSchema) - context.validators[properties_[i].dependenciesValidatorIndex] = context.factory.CreateSchemaValidator(*properties_[i].dependenciesSchema); - } - } - - return true; - } - - void CreateSchemaValidators(Context& context, const SchemaArray& schemas) const { - for (SizeType i = 0; i < schemas.count; i++) - context.validators[schemas.begin + i] = context.factory.CreateSchemaValidator(*schemas.schemas[i]); - } - - // O(n) - bool FindPropertyIndex(const ValueType& name, SizeType* outIndex) const { - SizeType len = name.GetStringLength(); - const Ch* str = name.GetString(); - for (SizeType index = 0; index < propertyCount_; index++) - if (properties_[index].name.GetStringLength() == len && - (std::memcmp(properties_[index].name.GetString(), str, sizeof(Ch) * len) == 0)) - { - *outIndex = index; - return true; - } - return false; - } - - bool CheckInt(Context& context, int64_t i) const { - if (!(type_ & ((1 << kIntegerSchemaType) | (1 << kNumberSchemaType)))) { - DisallowedType(context, GetIntegerString()); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); - } - - if (!minimum_.IsNull()) { - if (minimum_.IsInt64()) { - if (exclusiveMinimum_ ? i <= minimum_.GetInt64() : i < minimum_.GetInt64()) { - context.error_handler.BelowMinimum(i, minimum_, exclusiveMinimum_); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); - } - } - else if (minimum_.IsUint64()) { - context.error_handler.BelowMinimum(i, minimum_, exclusiveMinimum_); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); // i <= max(int64_t) < minimum.GetUint64() - } - else if (!CheckDoubleMinimum(context, static_cast(i))) - return false; - } - - if (!maximum_.IsNull()) { - if (maximum_.IsInt64()) { - if (exclusiveMaximum_ ? i >= maximum_.GetInt64() : i > maximum_.GetInt64()) { - context.error_handler.AboveMaximum(i, maximum_, exclusiveMaximum_); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); - } - } - else if (maximum_.IsUint64()) { } - /* do nothing */ // i <= max(int64_t) < maximum_.GetUint64() - else if (!CheckDoubleMaximum(context, static_cast(i))) - return false; - } - - if (!multipleOf_.IsNull()) { - if (multipleOf_.IsUint64()) { - if (static_cast(i >= 0 ? i : -i) % multipleOf_.GetUint64() != 0) { - context.error_handler.NotMultipleOf(i, multipleOf_); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString()); - } - } - else if (!CheckDoubleMultipleOf(context, static_cast(i))) - return false; - } - - return true; - } - - bool CheckUint(Context& context, uint64_t i) const { - if (!(type_ & ((1 << kIntegerSchemaType) | (1 << kNumberSchemaType)))) { - DisallowedType(context, GetIntegerString()); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); - } - - if (!minimum_.IsNull()) { - if (minimum_.IsUint64()) { - if (exclusiveMinimum_ ? i <= minimum_.GetUint64() : i < minimum_.GetUint64()) { - context.error_handler.BelowMinimum(i, minimum_, exclusiveMinimum_); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); - } - } - else if (minimum_.IsInt64()) - /* do nothing */; // i >= 0 > minimum.Getint64() - else if (!CheckDoubleMinimum(context, static_cast(i))) - return false; - } - - if (!maximum_.IsNull()) { - if (maximum_.IsUint64()) { - if (exclusiveMaximum_ ? i >= maximum_.GetUint64() : i > maximum_.GetUint64()) { - context.error_handler.AboveMaximum(i, maximum_, exclusiveMaximum_); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); - } - } - else if (maximum_.IsInt64()) { - context.error_handler.AboveMaximum(i, maximum_, exclusiveMaximum_); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); // i >= 0 > maximum_ - } - else if (!CheckDoubleMaximum(context, static_cast(i))) - return false; - } - - if (!multipleOf_.IsNull()) { - if (multipleOf_.IsUint64()) { - if (i % multipleOf_.GetUint64() != 0) { - context.error_handler.NotMultipleOf(i, multipleOf_); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString()); - } - } - else if (!CheckDoubleMultipleOf(context, static_cast(i))) - return false; - } - - return true; - } - - bool CheckDoubleMinimum(Context& context, double d) const { - if (exclusiveMinimum_ ? d <= minimum_.GetDouble() : d < minimum_.GetDouble()) { - context.error_handler.BelowMinimum(d, minimum_, exclusiveMinimum_); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); - } - return true; - } - - bool CheckDoubleMaximum(Context& context, double d) const { - if (exclusiveMaximum_ ? d >= maximum_.GetDouble() : d > maximum_.GetDouble()) { - context.error_handler.AboveMaximum(d, maximum_, exclusiveMaximum_); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); - } - return true; - } - - bool CheckDoubleMultipleOf(Context& context, double d) const { - double a = std::abs(d), b = std::abs(multipleOf_.GetDouble()); - double q = std::floor(a / b); - double r = a - q * b; - if (r > 0.0) { - context.error_handler.NotMultipleOf(d, multipleOf_); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString()); - } - return true; - } - - void DisallowedType(Context& context, const ValueType& actualType) const { - ErrorHandler& eh = context.error_handler; - eh.StartDisallowedType(); - - if (type_ & (1 << kNullSchemaType)) eh.AddExpectedType(GetNullString()); - if (type_ & (1 << kBooleanSchemaType)) eh.AddExpectedType(GetBooleanString()); - if (type_ & (1 << kObjectSchemaType)) eh.AddExpectedType(GetObjectString()); - if (type_ & (1 << kArraySchemaType)) eh.AddExpectedType(GetArrayString()); - if (type_ & (1 << kStringSchemaType)) eh.AddExpectedType(GetStringString()); - - if (type_ & (1 << kNumberSchemaType)) eh.AddExpectedType(GetNumberString()); - else if (type_ & (1 << kIntegerSchemaType)) eh.AddExpectedType(GetIntegerString()); - - eh.EndDisallowedType(actualType); - } - - struct Property { - Property() : schema(), dependenciesSchema(), dependenciesValidatorIndex(), dependencies(), required(false) {} - ~Property() { AllocatorType::Free(dependencies); } - SValue name; - const SchemaType* schema; - const SchemaType* dependenciesSchema; - SizeType dependenciesValidatorIndex; - bool* dependencies; - bool required; - }; - - struct PatternProperty { - PatternProperty() : schema(), pattern() {} - ~PatternProperty() { - if (pattern) { - pattern->~RegexType(); - AllocatorType::Free(pattern); - } - } - const SchemaType* schema; - RegexType* pattern; - }; - - AllocatorType* allocator_; - SValue uri_; - PointerType pointer_; - const SchemaType* typeless_; - uint64_t* enum_; - SizeType enumCount_; - SchemaArray allOf_; - SchemaArray anyOf_; - SchemaArray oneOf_; - const SchemaType* not_; - unsigned type_; // bitmask of kSchemaType - SizeType validatorCount_; - SizeType notValidatorIndex_; - - Property* properties_; - const SchemaType* additionalPropertiesSchema_; - PatternProperty* patternProperties_; - SizeType patternPropertyCount_; - SizeType propertyCount_; - SizeType minProperties_; - SizeType maxProperties_; - bool additionalProperties_; - bool hasDependencies_; - bool hasRequired_; - bool hasSchemaDependencies_; - - const SchemaType* additionalItemsSchema_; - const SchemaType* itemsList_; - const SchemaType** itemsTuple_; - SizeType itemsTupleCount_; - SizeType minItems_; - SizeType maxItems_; - bool additionalItems_; - bool uniqueItems_; - - RegexType* pattern_; - SizeType minLength_; - SizeType maxLength_; - - SValue minimum_; - SValue maximum_; - SValue multipleOf_; - bool exclusiveMinimum_; - bool exclusiveMaximum_; - - SizeType defaultValueLength_; -}; - -template -struct TokenHelper { - CEREAL_RAPIDJSON_FORCEINLINE static void AppendIndexToken(Stack& documentStack, SizeType index) { - *documentStack.template Push() = '/'; - char buffer[21]; - size_t length = static_cast((sizeof(SizeType) == 4 ? u32toa(index, buffer) : u64toa(index, buffer)) - buffer); - for (size_t i = 0; i < length; i++) - *documentStack.template Push() = static_cast(buffer[i]); - } -}; - -// Partial specialized version for char to prevent buffer copying. -template -struct TokenHelper { - CEREAL_RAPIDJSON_FORCEINLINE static void AppendIndexToken(Stack& documentStack, SizeType index) { - if (sizeof(SizeType) == 4) { - char *buffer = documentStack.template Push(1 + 10); // '/' + uint - *buffer++ = '/'; - const char* end = internal::u32toa(index, buffer); - documentStack.template Pop(static_cast(10 - (end - buffer))); - } - else { - char *buffer = documentStack.template Push(1 + 20); // '/' + uint64 - *buffer++ = '/'; - const char* end = internal::u64toa(index, buffer); - documentStack.template Pop(static_cast(20 - (end - buffer))); - } - } -}; - -} // namespace internal - -/////////////////////////////////////////////////////////////////////////////// -// IGenericRemoteSchemaDocumentProvider - -template -class IGenericRemoteSchemaDocumentProvider { -public: - typedef typename SchemaDocumentType::Ch Ch; - - virtual ~IGenericRemoteSchemaDocumentProvider() {} - virtual const SchemaDocumentType* GetRemoteDocument(const Ch* uri, SizeType length) = 0; -}; - -/////////////////////////////////////////////////////////////////////////////// -// GenericSchemaDocument - -//! JSON schema document. -/*! - A JSON schema document is a compiled version of a JSON schema. - It is basically a tree of internal::Schema. - - \note This is an immutable class (i.e. its instance cannot be modified after construction). - \tparam ValueT Type of JSON value (e.g. \c Value ), which also determine the encoding. - \tparam Allocator Allocator type for allocating memory of this document. -*/ -template -class GenericSchemaDocument { -public: - typedef ValueT ValueType; - typedef IGenericRemoteSchemaDocumentProvider IRemoteSchemaDocumentProviderType; - typedef Allocator AllocatorType; - typedef typename ValueType::EncodingType EncodingType; - typedef typename EncodingType::Ch Ch; - typedef internal::Schema SchemaType; - typedef GenericPointer PointerType; - typedef GenericValue URIType; - friend class internal::Schema; - template - friend class GenericSchemaValidator; - - //! Constructor. - /*! - Compile a JSON document into schema document. - - \param document A JSON document as source. - \param uri The base URI of this schema document for purposes of violation reporting. - \param uriLength Length of \c name, in code points. - \param remoteProvider An optional remote schema document provider for resolving remote reference. Can be null. - \param allocator An optional allocator instance for allocating memory. Can be null. - */ - explicit GenericSchemaDocument(const ValueType& document, const Ch* uri = 0, SizeType uriLength = 0, - IRemoteSchemaDocumentProviderType* remoteProvider = 0, Allocator* allocator = 0) : - remoteProvider_(remoteProvider), - allocator_(allocator), - ownAllocator_(), - root_(), - typeless_(), - schemaMap_(allocator, kInitialSchemaMapSize), - schemaRef_(allocator, kInitialSchemaRefSize) - { - if (!allocator_) - ownAllocator_ = allocator_ = CEREAL_RAPIDJSON_NEW(Allocator)(); - - Ch noUri[1] = {0}; - uri_.SetString(uri ? uri : noUri, uriLength, *allocator_); - - typeless_ = static_cast(allocator_->Malloc(sizeof(SchemaType))); - new (typeless_) SchemaType(this, PointerType(), ValueType(kObjectType).Move(), ValueType(kObjectType).Move(), allocator_); - - // Generate root schema, it will call CreateSchema() to create sub-schemas, - // And call AddRefSchema() if there are $ref. - CreateSchemaRecursive(&root_, PointerType(), document, document); - - // Resolve $ref - while (!schemaRef_.Empty()) { - SchemaRefEntry* refEntry = schemaRef_.template Pop(1); - if (const SchemaType* s = GetSchema(refEntry->target)) { - if (refEntry->schema) - *refEntry->schema = s; - - // Create entry in map if not exist - if (!GetSchema(refEntry->source)) { - new (schemaMap_.template Push()) SchemaEntry(refEntry->source, const_cast(s), false, allocator_); - } - } - else if (refEntry->schema) - *refEntry->schema = typeless_; - - refEntry->~SchemaRefEntry(); - } - - CEREAL_RAPIDJSON_ASSERT(root_ != 0); - - schemaRef_.ShrinkToFit(); // Deallocate all memory for ref - } - -#if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - //! Move constructor in C++11 - GenericSchemaDocument(GenericSchemaDocument&& rhs) CEREAL_RAPIDJSON_NOEXCEPT : - remoteProvider_(rhs.remoteProvider_), - allocator_(rhs.allocator_), - ownAllocator_(rhs.ownAllocator_), - root_(rhs.root_), - typeless_(rhs.typeless_), - schemaMap_(std::move(rhs.schemaMap_)), - schemaRef_(std::move(rhs.schemaRef_)), - uri_(std::move(rhs.uri_)) - { - rhs.remoteProvider_ = 0; - rhs.allocator_ = 0; - rhs.ownAllocator_ = 0; - rhs.typeless_ = 0; - } -#endif - - //! Destructor - ~GenericSchemaDocument() { - while (!schemaMap_.Empty()) - schemaMap_.template Pop(1)->~SchemaEntry(); - - if (typeless_) { - typeless_->~SchemaType(); - Allocator::Free(typeless_); - } - - CEREAL_RAPIDJSON_DELETE(ownAllocator_); - } - - const URIType& GetURI() const { return uri_; } - - //! Get the root schema. - const SchemaType& GetRoot() const { return *root_; } - -private: - //! Prohibit copying - GenericSchemaDocument(const GenericSchemaDocument&); - //! Prohibit assignment - GenericSchemaDocument& operator=(const GenericSchemaDocument&); - - struct SchemaRefEntry { - SchemaRefEntry(const PointerType& s, const PointerType& t, const SchemaType** outSchema, Allocator *allocator) : source(s, allocator), target(t, allocator), schema(outSchema) {} - PointerType source; - PointerType target; - const SchemaType** schema; - }; - - struct SchemaEntry { - SchemaEntry(const PointerType& p, SchemaType* s, bool o, Allocator* allocator) : pointer(p, allocator), schema(s), owned(o) {} - ~SchemaEntry() { - if (owned) { - schema->~SchemaType(); - Allocator::Free(schema); - } - } - PointerType pointer; - SchemaType* schema; - bool owned; - }; - - void CreateSchemaRecursive(const SchemaType** schema, const PointerType& pointer, const ValueType& v, const ValueType& document) { - if (schema) - *schema = typeless_; - - if (v.GetType() == kObjectType) { - const SchemaType* s = GetSchema(pointer); - if (!s) - CreateSchema(schema, pointer, v, document); - - for (typename ValueType::ConstMemberIterator itr = v.MemberBegin(); itr != v.MemberEnd(); ++itr) - CreateSchemaRecursive(0, pointer.Append(itr->name, allocator_), itr->value, document); - } - else if (v.GetType() == kArrayType) - for (SizeType i = 0; i < v.Size(); i++) - CreateSchemaRecursive(0, pointer.Append(i, allocator_), v[i], document); - } - - void CreateSchema(const SchemaType** schema, const PointerType& pointer, const ValueType& v, const ValueType& document) { - CEREAL_RAPIDJSON_ASSERT(pointer.IsValid()); - if (v.IsObject()) { - if (!HandleRefSchema(pointer, schema, v, document)) { - SchemaType* s = new (allocator_->Malloc(sizeof(SchemaType))) SchemaType(this, pointer, v, document, allocator_); - new (schemaMap_.template Push()) SchemaEntry(pointer, s, true, allocator_); - if (schema) - *schema = s; - } - } - } - - bool HandleRefSchema(const PointerType& source, const SchemaType** schema, const ValueType& v, const ValueType& document) { - static const Ch kRefString[] = { '$', 'r', 'e', 'f', '\0' }; - static const ValueType kRefValue(kRefString, 4); - - typename ValueType::ConstMemberIterator itr = v.FindMember(kRefValue); - if (itr == v.MemberEnd()) - return false; - - if (itr->value.IsString()) { - SizeType len = itr->value.GetStringLength(); - if (len > 0) { - const Ch* s = itr->value.GetString(); - SizeType i = 0; - while (i < len && s[i] != '#') // Find the first # - i++; - - if (i > 0) { // Remote reference, resolve immediately - if (remoteProvider_) { - if (const GenericSchemaDocument* remoteDocument = remoteProvider_->GetRemoteDocument(s, i)) { - PointerType pointer(&s[i], len - i, allocator_); - if (pointer.IsValid()) { - if (const SchemaType* sc = remoteDocument->GetSchema(pointer)) { - if (schema) - *schema = sc; - new (schemaMap_.template Push()) SchemaEntry(source, const_cast(sc), false, allocator_); - return true; - } - } - } - } - } - else if (s[i] == '#') { // Local reference, defer resolution - PointerType pointer(&s[i], len - i, allocator_); - if (pointer.IsValid()) { - if (const ValueType* nv = pointer.Get(document)) - if (HandleRefSchema(source, schema, *nv, document)) - return true; - - new (schemaRef_.template Push()) SchemaRefEntry(source, pointer, schema, allocator_); - return true; - } - } - } - } - return false; - } - - const SchemaType* GetSchema(const PointerType& pointer) const { - for (const SchemaEntry* target = schemaMap_.template Bottom(); target != schemaMap_.template End(); ++target) - if (pointer == target->pointer) - return target->schema; - return 0; - } - - PointerType GetPointer(const SchemaType* schema) const { - for (const SchemaEntry* target = schemaMap_.template Bottom(); target != schemaMap_.template End(); ++target) - if (schema == target->schema) - return target->pointer; - return PointerType(); - } - - const SchemaType* GetTypeless() const { return typeless_; } - - static const size_t kInitialSchemaMapSize = 64; - static const size_t kInitialSchemaRefSize = 64; - - IRemoteSchemaDocumentProviderType* remoteProvider_; - Allocator *allocator_; - Allocator *ownAllocator_; - const SchemaType* root_; //!< Root schema. - SchemaType* typeless_; - internal::Stack schemaMap_; // Stores created Pointer -> Schemas - internal::Stack schemaRef_; // Stores Pointer from $ref and schema which holds the $ref - URIType uri_; -}; - -//! GenericSchemaDocument using Value type. -typedef GenericSchemaDocument SchemaDocument; -//! IGenericRemoteSchemaDocumentProvider using SchemaDocument. -typedef IGenericRemoteSchemaDocumentProvider IRemoteSchemaDocumentProvider; - -/////////////////////////////////////////////////////////////////////////////// -// GenericSchemaValidator - -//! JSON Schema Validator. -/*! - A SAX style JSON schema validator. - It uses a \c GenericSchemaDocument to validate SAX events. - It delegates the incoming SAX events to an output handler. - The default output handler does nothing. - It can be reused multiple times by calling \c Reset(). - - \tparam SchemaDocumentType Type of schema document. - \tparam OutputHandler Type of output handler. Default handler does nothing. - \tparam StateAllocator Allocator for storing the internal validation states. -*/ -template < - typename SchemaDocumentType, - typename OutputHandler = BaseReaderHandler, - typename StateAllocator = CrtAllocator> -class GenericSchemaValidator : - public internal::ISchemaStateFactory, - public internal::ISchemaValidator, - public internal::IValidationErrorHandler -{ -public: - typedef typename SchemaDocumentType::SchemaType SchemaType; - typedef typename SchemaDocumentType::PointerType PointerType; - typedef typename SchemaType::EncodingType EncodingType; - typedef typename SchemaType::SValue SValue; - typedef typename EncodingType::Ch Ch; - typedef GenericStringRef StringRefType; - typedef GenericValue ValueType; - - //! Constructor without output handler. - /*! - \param schemaDocument The schema document to conform to. - \param allocator Optional allocator for storing internal validation states. - \param schemaStackCapacity Optional initial capacity of schema path stack. - \param documentStackCapacity Optional initial capacity of document path stack. - */ - GenericSchemaValidator( - const SchemaDocumentType& schemaDocument, - StateAllocator* allocator = 0, - size_t schemaStackCapacity = kDefaultSchemaStackCapacity, - size_t documentStackCapacity = kDefaultDocumentStackCapacity) - : - schemaDocument_(&schemaDocument), - root_(schemaDocument.GetRoot()), - stateAllocator_(allocator), - ownStateAllocator_(0), - schemaStack_(allocator, schemaStackCapacity), - documentStack_(allocator, documentStackCapacity), - outputHandler_(0), - error_(kObjectType), - currentError_(), - missingDependents_(), - valid_(true) -#if CEREAL_RAPIDJSON_SCHEMA_VERBOSE - , depth_(0) -#endif - { - } - - //! Constructor with output handler. - /*! - \param schemaDocument The schema document to conform to. - \param allocator Optional allocator for storing internal validation states. - \param schemaStackCapacity Optional initial capacity of schema path stack. - \param documentStackCapacity Optional initial capacity of document path stack. - */ - GenericSchemaValidator( - const SchemaDocumentType& schemaDocument, - OutputHandler& outputHandler, - StateAllocator* allocator = 0, - size_t schemaStackCapacity = kDefaultSchemaStackCapacity, - size_t documentStackCapacity = kDefaultDocumentStackCapacity) - : - schemaDocument_(&schemaDocument), - root_(schemaDocument.GetRoot()), - stateAllocator_(allocator), - ownStateAllocator_(0), - schemaStack_(allocator, schemaStackCapacity), - documentStack_(allocator, documentStackCapacity), - outputHandler_(&outputHandler), - error_(kObjectType), - currentError_(), - missingDependents_(), - valid_(true) -#if CEREAL_RAPIDJSON_SCHEMA_VERBOSE - , depth_(0) -#endif - { - } - - //! Destructor. - ~GenericSchemaValidator() { - Reset(); - CEREAL_RAPIDJSON_DELETE(ownStateAllocator_); - } - - //! Reset the internal states. - void Reset() { - while (!schemaStack_.Empty()) - PopSchema(); - documentStack_.Clear(); - error_.SetObject(); - currentError_.SetNull(); - missingDependents_.SetNull(); - valid_ = true; - } - - //! Checks whether the current state is valid. - // Implementation of ISchemaValidator - virtual bool IsValid() const { return valid_; } - - //! Gets the error object. - ValueType& GetError() { return error_; } - const ValueType& GetError() const { return error_; } - - //! Gets the JSON pointer pointed to the invalid schema. - PointerType GetInvalidSchemaPointer() const { - return schemaStack_.Empty() ? PointerType() : CurrentSchema().GetPointer(); - } - - //! Gets the keyword of invalid schema. - const Ch* GetInvalidSchemaKeyword() const { - return schemaStack_.Empty() ? 0 : CurrentContext().invalidKeyword; - } - - //! Gets the JSON pointer pointed to the invalid value. - PointerType GetInvalidDocumentPointer() const { - if (documentStack_.Empty()) { - return PointerType(); - } - else { - return PointerType(documentStack_.template Bottom(), documentStack_.GetSize() / sizeof(Ch)); - } - } - - void NotMultipleOf(int64_t actual, const SValue& expected) { - AddNumberError(SchemaType::GetMultipleOfString(), ValueType(actual).Move(), expected); - } - void NotMultipleOf(uint64_t actual, const SValue& expected) { - AddNumberError(SchemaType::GetMultipleOfString(), ValueType(actual).Move(), expected); - } - void NotMultipleOf(double actual, const SValue& expected) { - AddNumberError(SchemaType::GetMultipleOfString(), ValueType(actual).Move(), expected); - } - void AboveMaximum(int64_t actual, const SValue& expected, bool exclusive) { - AddNumberError(SchemaType::GetMaximumString(), ValueType(actual).Move(), expected, - exclusive ? &SchemaType::GetExclusiveMaximumString : 0); - } - void AboveMaximum(uint64_t actual, const SValue& expected, bool exclusive) { - AddNumberError(SchemaType::GetMaximumString(), ValueType(actual).Move(), expected, - exclusive ? &SchemaType::GetExclusiveMaximumString : 0); - } - void AboveMaximum(double actual, const SValue& expected, bool exclusive) { - AddNumberError(SchemaType::GetMaximumString(), ValueType(actual).Move(), expected, - exclusive ? &SchemaType::GetExclusiveMaximumString : 0); - } - void BelowMinimum(int64_t actual, const SValue& expected, bool exclusive) { - AddNumberError(SchemaType::GetMinimumString(), ValueType(actual).Move(), expected, - exclusive ? &SchemaType::GetExclusiveMinimumString : 0); - } - void BelowMinimum(uint64_t actual, const SValue& expected, bool exclusive) { - AddNumberError(SchemaType::GetMinimumString(), ValueType(actual).Move(), expected, - exclusive ? &SchemaType::GetExclusiveMinimumString : 0); - } - void BelowMinimum(double actual, const SValue& expected, bool exclusive) { - AddNumberError(SchemaType::GetMinimumString(), ValueType(actual).Move(), expected, - exclusive ? &SchemaType::GetExclusiveMinimumString : 0); - } - - void TooLong(const Ch* str, SizeType length, SizeType expected) { - AddNumberError(SchemaType::GetMaxLengthString(), - ValueType(str, length, GetStateAllocator()).Move(), SValue(expected).Move()); - } - void TooShort(const Ch* str, SizeType length, SizeType expected) { - AddNumberError(SchemaType::GetMinLengthString(), - ValueType(str, length, GetStateAllocator()).Move(), SValue(expected).Move()); - } - void DoesNotMatch(const Ch* str, SizeType length) { - currentError_.SetObject(); - currentError_.AddMember(GetActualString(), ValueType(str, length, GetStateAllocator()).Move(), GetStateAllocator()); - AddCurrentError(SchemaType::GetPatternString()); - } - - void DisallowedItem(SizeType index) { - currentError_.SetObject(); - currentError_.AddMember(GetDisallowedString(), ValueType(index).Move(), GetStateAllocator()); - AddCurrentError(SchemaType::GetAdditionalItemsString(), true); - } - void TooFewItems(SizeType actualCount, SizeType expectedCount) { - AddNumberError(SchemaType::GetMinItemsString(), - ValueType(actualCount).Move(), SValue(expectedCount).Move()); - } - void TooManyItems(SizeType actualCount, SizeType expectedCount) { - AddNumberError(SchemaType::GetMaxItemsString(), - ValueType(actualCount).Move(), SValue(expectedCount).Move()); - } - void DuplicateItems(SizeType index1, SizeType index2) { - ValueType duplicates(kArrayType); - duplicates.PushBack(index1, GetStateAllocator()); - duplicates.PushBack(index2, GetStateAllocator()); - currentError_.SetObject(); - currentError_.AddMember(GetDuplicatesString(), duplicates, GetStateAllocator()); - AddCurrentError(SchemaType::GetUniqueItemsString(), true); - } - - void TooManyProperties(SizeType actualCount, SizeType expectedCount) { - AddNumberError(SchemaType::GetMaxPropertiesString(), - ValueType(actualCount).Move(), SValue(expectedCount).Move()); - } - void TooFewProperties(SizeType actualCount, SizeType expectedCount) { - AddNumberError(SchemaType::GetMinPropertiesString(), - ValueType(actualCount).Move(), SValue(expectedCount).Move()); - } - void StartMissingProperties() { - currentError_.SetArray(); - } - void AddMissingProperty(const SValue& name) { - currentError_.PushBack(ValueType(name, GetStateAllocator()).Move(), GetStateAllocator()); - } - bool EndMissingProperties() { - if (currentError_.Empty()) - return false; - ValueType error(kObjectType); - error.AddMember(GetMissingString(), currentError_, GetStateAllocator()); - currentError_ = error; - AddCurrentError(SchemaType::GetRequiredString()); - return true; - } - void PropertyViolations(ISchemaValidator** subvalidators, SizeType count) { - for (SizeType i = 0; i < count; ++i) - MergeError(static_cast(subvalidators[i])->GetError()); - } - void DisallowedProperty(const Ch* name, SizeType length) { - currentError_.SetObject(); - currentError_.AddMember(GetDisallowedString(), ValueType(name, length, GetStateAllocator()).Move(), GetStateAllocator()); - AddCurrentError(SchemaType::GetAdditionalPropertiesString(), true); - } - - void StartDependencyErrors() { - currentError_.SetObject(); - } - void StartMissingDependentProperties() { - missingDependents_.SetArray(); - } - void AddMissingDependentProperty(const SValue& targetName) { - missingDependents_.PushBack(ValueType(targetName, GetStateAllocator()).Move(), GetStateAllocator()); - } - void EndMissingDependentProperties(const SValue& sourceName) { - if (!missingDependents_.Empty()) - currentError_.AddMember(ValueType(sourceName, GetStateAllocator()).Move(), - missingDependents_, GetStateAllocator()); - } - void AddDependencySchemaError(const SValue& sourceName, ISchemaValidator* subvalidator) { - currentError_.AddMember(ValueType(sourceName, GetStateAllocator()).Move(), - static_cast(subvalidator)->GetError(), GetStateAllocator()); - } - bool EndDependencyErrors() { - if (currentError_.ObjectEmpty()) - return false; - ValueType error(kObjectType); - error.AddMember(GetErrorsString(), currentError_, GetStateAllocator()); - currentError_ = error; - AddCurrentError(SchemaType::GetDependenciesString()); - return true; - } - - void DisallowedValue() { - currentError_.SetObject(); - AddCurrentError(SchemaType::GetEnumString()); - } - void StartDisallowedType() { - currentError_.SetArray(); - } - void AddExpectedType(const typename SchemaType::ValueType& expectedType) { - currentError_.PushBack(ValueType(expectedType, GetStateAllocator()).Move(), GetStateAllocator()); - } - void EndDisallowedType(const typename SchemaType::ValueType& actualType) { - ValueType error(kObjectType); - error.AddMember(GetExpectedString(), currentError_, GetStateAllocator()); - error.AddMember(GetActualString(), ValueType(actualType, GetStateAllocator()).Move(), GetStateAllocator()); - currentError_ = error; - AddCurrentError(SchemaType::GetTypeString()); - } - void NotAllOf(ISchemaValidator** subvalidators, SizeType count) { - for (SizeType i = 0; i < count; ++i) { - MergeError(static_cast(subvalidators[i])->GetError()); - } - } - void NoneOf(ISchemaValidator** subvalidators, SizeType count) { - AddErrorArray(SchemaType::GetAnyOfString(), subvalidators, count); - } - void NotOneOf(ISchemaValidator** subvalidators, SizeType count) { - AddErrorArray(SchemaType::GetOneOfString(), subvalidators, count); - } - void Disallowed() { - currentError_.SetObject(); - AddCurrentError(SchemaType::GetNotString()); - } - -#define CEREAL_RAPIDJSON_STRING_(name, ...) \ - static const StringRefType& Get##name##String() {\ - static const Ch s[] = { __VA_ARGS__, '\0' };\ - static const StringRefType v(s, static_cast(sizeof(s) / sizeof(Ch) - 1)); \ - return v;\ - } - - CEREAL_RAPIDJSON_STRING_(InstanceRef, 'i', 'n', 's', 't', 'a', 'n', 'c', 'e', 'R', 'e', 'f') - CEREAL_RAPIDJSON_STRING_(SchemaRef, 's', 'c', 'h', 'e', 'm', 'a', 'R', 'e', 'f') - CEREAL_RAPIDJSON_STRING_(Expected, 'e', 'x', 'p', 'e', 'c', 't', 'e', 'd') - CEREAL_RAPIDJSON_STRING_(Actual, 'a', 'c', 't', 'u', 'a', 'l') - CEREAL_RAPIDJSON_STRING_(Disallowed, 'd', 'i', 's', 'a', 'l', 'l', 'o', 'w', 'e', 'd') - CEREAL_RAPIDJSON_STRING_(Missing, 'm', 'i', 's', 's', 'i', 'n', 'g') - CEREAL_RAPIDJSON_STRING_(Errors, 'e', 'r', 'r', 'o', 'r', 's') - CEREAL_RAPIDJSON_STRING_(Duplicates, 'd', 'u', 'p', 'l', 'i', 'c', 'a', 't', 'e', 's') - -#undef CEREAL_RAPIDJSON_STRING_ - -#if CEREAL_RAPIDJSON_SCHEMA_VERBOSE -#define CEREAL_RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_() \ -CEREAL_RAPIDJSON_MULTILINEMACRO_BEGIN\ - *documentStack_.template Push() = '\0';\ - documentStack_.template Pop(1);\ - internal::PrintInvalidDocument(documentStack_.template Bottom());\ -CEREAL_RAPIDJSON_MULTILINEMACRO_END -#else -#define CEREAL_RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_() -#endif - -#define CEREAL_RAPIDJSON_SCHEMA_HANDLE_BEGIN_(method, arg1)\ - if (!valid_) return false; \ - if (!BeginValue() || !CurrentSchema().method arg1) {\ - CEREAL_RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_();\ - return valid_ = false;\ - } - -#define CEREAL_RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(method, arg2)\ - for (Context* context = schemaStack_.template Bottom(); context != schemaStack_.template End(); context++) {\ - if (context->hasher)\ - static_cast(context->hasher)->method arg2;\ - if (context->validators)\ - for (SizeType i_ = 0; i_ < context->validatorCount; i_++)\ - static_cast(context->validators[i_])->method arg2;\ - if (context->patternPropertiesValidators)\ - for (SizeType i_ = 0; i_ < context->patternPropertiesValidatorCount; i_++)\ - static_cast(context->patternPropertiesValidators[i_])->method arg2;\ - } - -#define CEREAL_RAPIDJSON_SCHEMA_HANDLE_END_(method, arg2)\ - return valid_ = EndValue() && (!outputHandler_ || outputHandler_->method arg2) - -#define CEREAL_RAPIDJSON_SCHEMA_HANDLE_VALUE_(method, arg1, arg2) \ - CEREAL_RAPIDJSON_SCHEMA_HANDLE_BEGIN_ (method, arg1);\ - CEREAL_RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(method, arg2);\ - CEREAL_RAPIDJSON_SCHEMA_HANDLE_END_ (method, arg2) - - bool Null() { CEREAL_RAPIDJSON_SCHEMA_HANDLE_VALUE_(Null, (CurrentContext()), ( )); } - bool Bool(bool b) { CEREAL_RAPIDJSON_SCHEMA_HANDLE_VALUE_(Bool, (CurrentContext(), b), (b)); } - bool Int(int i) { CEREAL_RAPIDJSON_SCHEMA_HANDLE_VALUE_(Int, (CurrentContext(), i), (i)); } - bool Uint(unsigned u) { CEREAL_RAPIDJSON_SCHEMA_HANDLE_VALUE_(Uint, (CurrentContext(), u), (u)); } - bool Int64(int64_t i) { CEREAL_RAPIDJSON_SCHEMA_HANDLE_VALUE_(Int64, (CurrentContext(), i), (i)); } - bool Uint64(uint64_t u) { CEREAL_RAPIDJSON_SCHEMA_HANDLE_VALUE_(Uint64, (CurrentContext(), u), (u)); } - bool Double(double d) { CEREAL_RAPIDJSON_SCHEMA_HANDLE_VALUE_(Double, (CurrentContext(), d), (d)); } - bool RawNumber(const Ch* str, SizeType length, bool copy) - { CEREAL_RAPIDJSON_SCHEMA_HANDLE_VALUE_(String, (CurrentContext(), str, length, copy), (str, length, copy)); } - bool String(const Ch* str, SizeType length, bool copy) - { CEREAL_RAPIDJSON_SCHEMA_HANDLE_VALUE_(String, (CurrentContext(), str, length, copy), (str, length, copy)); } - - bool StartObject() { - CEREAL_RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartObject, (CurrentContext())); - CEREAL_RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(StartObject, ()); - return valid_ = !outputHandler_ || outputHandler_->StartObject(); - } - - bool Key(const Ch* str, SizeType len, bool copy) { - if (!valid_) return false; - AppendToken(str, len); - if (!CurrentSchema().Key(CurrentContext(), str, len, copy)) return valid_ = false; - CEREAL_RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(Key, (str, len, copy)); - return valid_ = !outputHandler_ || outputHandler_->Key(str, len, copy); - } - - bool EndObject(SizeType memberCount) { - if (!valid_) return false; - CEREAL_RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(EndObject, (memberCount)); - if (!CurrentSchema().EndObject(CurrentContext(), memberCount)) return valid_ = false; - CEREAL_RAPIDJSON_SCHEMA_HANDLE_END_(EndObject, (memberCount)); - } - - bool StartArray() { - CEREAL_RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartArray, (CurrentContext())); - CEREAL_RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(StartArray, ()); - return valid_ = !outputHandler_ || outputHandler_->StartArray(); - } - - bool EndArray(SizeType elementCount) { - if (!valid_) return false; - CEREAL_RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(EndArray, (elementCount)); - if (!CurrentSchema().EndArray(CurrentContext(), elementCount)) return valid_ = false; - CEREAL_RAPIDJSON_SCHEMA_HANDLE_END_(EndArray, (elementCount)); - } - -#undef CEREAL_RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_ -#undef CEREAL_RAPIDJSON_SCHEMA_HANDLE_BEGIN_ -#undef CEREAL_RAPIDJSON_SCHEMA_HANDLE_PARALLEL_ -#undef CEREAL_RAPIDJSON_SCHEMA_HANDLE_VALUE_ - - // Implementation of ISchemaStateFactory - virtual ISchemaValidator* CreateSchemaValidator(const SchemaType& root) { - return new (GetStateAllocator().Malloc(sizeof(GenericSchemaValidator))) GenericSchemaValidator(*schemaDocument_, root, documentStack_.template Bottom(), documentStack_.GetSize(), -#if CEREAL_RAPIDJSON_SCHEMA_VERBOSE - depth_ + 1, -#endif - &GetStateAllocator()); - } - - virtual void DestroySchemaValidator(ISchemaValidator* validator) { - GenericSchemaValidator* v = static_cast(validator); - v->~GenericSchemaValidator(); - StateAllocator::Free(v); - } - - virtual void* CreateHasher() { - return new (GetStateAllocator().Malloc(sizeof(HasherType))) HasherType(&GetStateAllocator()); - } - - virtual uint64_t GetHashCode(void* hasher) { - return static_cast(hasher)->GetHashCode(); - } - - virtual void DestroryHasher(void* hasher) { - HasherType* h = static_cast(hasher); - h->~HasherType(); - StateAllocator::Free(h); - } - - virtual void* MallocState(size_t size) { - return GetStateAllocator().Malloc(size); - } - - virtual void FreeState(void* p) { - StateAllocator::Free(p); - } - -private: - typedef typename SchemaType::Context Context; - typedef GenericValue, StateAllocator> HashCodeArray; - typedef internal::Hasher HasherType; - - GenericSchemaValidator( - const SchemaDocumentType& schemaDocument, - const SchemaType& root, - const char* basePath, size_t basePathSize, -#if CEREAL_RAPIDJSON_SCHEMA_VERBOSE - unsigned depth, -#endif - StateAllocator* allocator = 0, - size_t schemaStackCapacity = kDefaultSchemaStackCapacity, - size_t documentStackCapacity = kDefaultDocumentStackCapacity) - : - schemaDocument_(&schemaDocument), - root_(root), - stateAllocator_(allocator), - ownStateAllocator_(0), - schemaStack_(allocator, schemaStackCapacity), - documentStack_(allocator, documentStackCapacity), - outputHandler_(0), - error_(kObjectType), - currentError_(), - missingDependents_(), - valid_(true) -#if CEREAL_RAPIDJSON_SCHEMA_VERBOSE - , depth_(depth) -#endif - { - if (basePath && basePathSize) - memcpy(documentStack_.template Push(basePathSize), basePath, basePathSize); - } - - StateAllocator& GetStateAllocator() { - if (!stateAllocator_) - stateAllocator_ = ownStateAllocator_ = CEREAL_RAPIDJSON_NEW(StateAllocator)(); - return *stateAllocator_; - } - - bool BeginValue() { - if (schemaStack_.Empty()) - PushSchema(root_); - else { - if (CurrentContext().inArray) - internal::TokenHelper, Ch>::AppendIndexToken(documentStack_, CurrentContext().arrayElementIndex); - - if (!CurrentSchema().BeginValue(CurrentContext())) - return false; - - SizeType count = CurrentContext().patternPropertiesSchemaCount; - const SchemaType** sa = CurrentContext().patternPropertiesSchemas; - typename Context::PatternValidatorType patternValidatorType = CurrentContext().valuePatternValidatorType; - bool valueUniqueness = CurrentContext().valueUniqueness; - CEREAL_RAPIDJSON_ASSERT(CurrentContext().valueSchema); - PushSchema(*CurrentContext().valueSchema); - - if (count > 0) { - CurrentContext().objectPatternValidatorType = patternValidatorType; - ISchemaValidator**& va = CurrentContext().patternPropertiesValidators; - SizeType& validatorCount = CurrentContext().patternPropertiesValidatorCount; - va = static_cast(MallocState(sizeof(ISchemaValidator*) * count)); - for (SizeType i = 0; i < count; i++) - va[validatorCount++] = CreateSchemaValidator(*sa[i]); - } - - CurrentContext().arrayUniqueness = valueUniqueness; - } - return true; - } - - bool EndValue() { - if (!CurrentSchema().EndValue(CurrentContext())) - return false; - -#if CEREAL_RAPIDJSON_SCHEMA_VERBOSE - GenericStringBuffer sb; - schemaDocument_->GetPointer(&CurrentSchema()).Stringify(sb); - - *documentStack_.template Push() = '\0'; - documentStack_.template Pop(1); - internal::PrintValidatorPointers(depth_, sb.GetString(), documentStack_.template Bottom()); -#endif - - uint64_t h = CurrentContext().arrayUniqueness ? static_cast(CurrentContext().hasher)->GetHashCode() : 0; - - PopSchema(); - - if (!schemaStack_.Empty()) { - Context& context = CurrentContext(); - if (context.valueUniqueness) { - HashCodeArray* a = static_cast(context.arrayElementHashCodes); - if (!a) - CurrentContext().arrayElementHashCodes = a = new (GetStateAllocator().Malloc(sizeof(HashCodeArray))) HashCodeArray(kArrayType); - for (typename HashCodeArray::ConstValueIterator itr = a->Begin(); itr != a->End(); ++itr) - if (itr->GetUint64() == h) { - DuplicateItems(static_cast(itr - a->Begin()), a->Size()); - CEREAL_RAPIDJSON_INVALID_KEYWORD_RETURN(SchemaType::GetUniqueItemsString()); - } - a->PushBack(h, GetStateAllocator()); - } - } - - // Remove the last token of document pointer - while (!documentStack_.Empty() && *documentStack_.template Pop(1) != '/') - ; - - return true; - } - - void AppendToken(const Ch* str, SizeType len) { - documentStack_.template Reserve(1 + len * 2); // worst case all characters are escaped as two characters - *documentStack_.template PushUnsafe() = '/'; - for (SizeType i = 0; i < len; i++) { - if (str[i] == '~') { - *documentStack_.template PushUnsafe() = '~'; - *documentStack_.template PushUnsafe() = '0'; - } - else if (str[i] == '/') { - *documentStack_.template PushUnsafe() = '~'; - *documentStack_.template PushUnsafe() = '1'; - } - else - *documentStack_.template PushUnsafe() = str[i]; - } - } - - CEREAL_RAPIDJSON_FORCEINLINE void PushSchema(const SchemaType& schema) { new (schemaStack_.template Push()) Context(*this, *this, &schema); } - - CEREAL_RAPIDJSON_FORCEINLINE void PopSchema() { - Context* c = schemaStack_.template Pop(1); - if (HashCodeArray* a = static_cast(c->arrayElementHashCodes)) { - a->~HashCodeArray(); - StateAllocator::Free(a); - } - c->~Context(); - } - - void AddErrorLocation(ValueType& result, bool parent) { - GenericStringBuffer sb; - PointerType instancePointer = GetInvalidDocumentPointer(); - ((parent && instancePointer.GetTokenCount() > 0) - ? PointerType(instancePointer.GetTokens(), instancePointer.GetTokenCount() - 1) - : instancePointer).StringifyUriFragment(sb); - ValueType instanceRef(sb.GetString(), static_cast(sb.GetSize() / sizeof(Ch)), - GetStateAllocator()); - result.AddMember(GetInstanceRefString(), instanceRef, GetStateAllocator()); - sb.Clear(); - memcpy(sb.Push(CurrentSchema().GetURI().GetStringLength()), - CurrentSchema().GetURI().GetString(), - CurrentSchema().GetURI().GetStringLength() * sizeof(Ch)); - GetInvalidSchemaPointer().StringifyUriFragment(sb); - ValueType schemaRef(sb.GetString(), static_cast(sb.GetSize() / sizeof(Ch)), - GetStateAllocator()); - result.AddMember(GetSchemaRefString(), schemaRef, GetStateAllocator()); - } - - void AddError(ValueType& keyword, ValueType& error) { - typename ValueType::MemberIterator member = error_.FindMember(keyword); - if (member == error_.MemberEnd()) - error_.AddMember(keyword, error, GetStateAllocator()); - else { - if (member->value.IsObject()) { - ValueType errors(kArrayType); - errors.PushBack(member->value, GetStateAllocator()); - member->value = errors; - } - member->value.PushBack(error, GetStateAllocator()); - } - } - - void AddCurrentError(const typename SchemaType::ValueType& keyword, bool parent = false) { - AddErrorLocation(currentError_, parent); - AddError(ValueType(keyword, GetStateAllocator(), false).Move(), currentError_); - } - - void MergeError(ValueType& other) { - for (typename ValueType::MemberIterator it = other.MemberBegin(), end = other.MemberEnd(); it != end; ++it) { - AddError(it->name, it->value); - } - } - - void AddNumberError(const typename SchemaType::ValueType& keyword, ValueType& actual, const SValue& expected, - const typename SchemaType::ValueType& (*exclusive)() = 0) { - currentError_.SetObject(); - currentError_.AddMember(GetActualString(), actual, GetStateAllocator()); - currentError_.AddMember(GetExpectedString(), ValueType(expected, GetStateAllocator()).Move(), GetStateAllocator()); - if (exclusive) - currentError_.AddMember(ValueType(exclusive(), GetStateAllocator()).Move(), true, GetStateAllocator()); - AddCurrentError(keyword); - } - - void AddErrorArray(const typename SchemaType::ValueType& keyword, - ISchemaValidator** subvalidators, SizeType count) { - ValueType errors(kArrayType); - for (SizeType i = 0; i < count; ++i) - errors.PushBack(static_cast(subvalidators[i])->GetError(), GetStateAllocator()); - currentError_.SetObject(); - currentError_.AddMember(GetErrorsString(), errors, GetStateAllocator()); - AddCurrentError(keyword); - } - - const SchemaType& CurrentSchema() const { return *schemaStack_.template Top()->schema; } - Context& CurrentContext() { return *schemaStack_.template Top(); } - const Context& CurrentContext() const { return *schemaStack_.template Top(); } - - static const size_t kDefaultSchemaStackCapacity = 1024; - static const size_t kDefaultDocumentStackCapacity = 256; - const SchemaDocumentType* schemaDocument_; - const SchemaType& root_; - StateAllocator* stateAllocator_; - StateAllocator* ownStateAllocator_; - internal::Stack schemaStack_; //!< stack to store the current path of schema (BaseSchemaType *) - internal::Stack documentStack_; //!< stack to store the current path of validating document (Ch) - OutputHandler* outputHandler_; - ValueType error_; - ValueType currentError_; - ValueType missingDependents_; - bool valid_; -#if CEREAL_RAPIDJSON_SCHEMA_VERBOSE - unsigned depth_; -#endif -}; - -typedef GenericSchemaValidator SchemaValidator; - -/////////////////////////////////////////////////////////////////////////////// -// SchemaValidatingReader - -//! A helper class for parsing with validation. -/*! - This helper class is a functor, designed as a parameter of \ref GenericDocument::Populate(). - - \tparam parseFlags Combination of \ref ParseFlag. - \tparam InputStream Type of input stream, implementing Stream concept. - \tparam SourceEncoding Encoding of the input stream. - \tparam SchemaDocumentType Type of schema document. - \tparam StackAllocator Allocator type for stack. -*/ -template < - unsigned parseFlags, - typename InputStream, - typename SourceEncoding, - typename SchemaDocumentType = SchemaDocument, - typename StackAllocator = CrtAllocator> -class SchemaValidatingReader { -public: - typedef typename SchemaDocumentType::PointerType PointerType; - typedef typename InputStream::Ch Ch; - typedef GenericValue ValueType; - - //! Constructor - /*! - \param is Input stream. - \param sd Schema document. - */ - SchemaValidatingReader(InputStream& is, const SchemaDocumentType& sd) : is_(is), sd_(sd), invalidSchemaKeyword_(), error_(kObjectType), isValid_(true) {} - - template - bool operator()(Handler& handler) { - GenericReader reader; - GenericSchemaValidator validator(sd_, handler); - parseResult_ = reader.template Parse(is_, validator); - - isValid_ = validator.IsValid(); - if (isValid_) { - invalidSchemaPointer_ = PointerType(); - invalidSchemaKeyword_ = 0; - invalidDocumentPointer_ = PointerType(); - error_.SetObject(); - } - else { - invalidSchemaPointer_ = validator.GetInvalidSchemaPointer(); - invalidSchemaKeyword_ = validator.GetInvalidSchemaKeyword(); - invalidDocumentPointer_ = validator.GetInvalidDocumentPointer(); - error_.CopyFrom(validator.GetError(), allocator_); - } - - return parseResult_; - } - - const ParseResult& GetParseResult() const { return parseResult_; } - bool IsValid() const { return isValid_; } - const PointerType& GetInvalidSchemaPointer() const { return invalidSchemaPointer_; } - const Ch* GetInvalidSchemaKeyword() const { return invalidSchemaKeyword_; } - const PointerType& GetInvalidDocumentPointer() const { return invalidDocumentPointer_; } - const ValueType& GetError() const { return error_; } - -private: - InputStream& is_; - const SchemaDocumentType& sd_; - - ParseResult parseResult_; - PointerType invalidSchemaPointer_; - const Ch* invalidSchemaKeyword_; - PointerType invalidDocumentPointer_; - StackAllocator allocator_; - ValueType error_; - bool isValid_; -}; - -CEREAL_RAPIDJSON_NAMESPACE_END -CEREAL_RAPIDJSON_DIAG_POP - -#endif // CEREAL_RAPIDJSON_SCHEMA_H_ diff --git a/include/cereal/external/rapidjson/stream.h b/include/cereal/external/rapidjson/stream.h deleted file mode 100644 index abc0153..0000000 --- a/include/cereal/external/rapidjson/stream.h +++ /dev/null @@ -1,223 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#include "rapidjson.h" - -#ifndef CEREAL_RAPIDJSON_STREAM_H_ -#define CEREAL_RAPIDJSON_STREAM_H_ - -#include "encodings.h" - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -/////////////////////////////////////////////////////////////////////////////// -// Stream - -/*! \class rapidjson::Stream - \brief Concept for reading and writing characters. - - For read-only stream, no need to implement PutBegin(), Put(), Flush() and PutEnd(). - - For write-only stream, only need to implement Put() and Flush(). - -\code -concept Stream { - typename Ch; //!< Character type of the stream. - - //! Read the current character from stream without moving the read cursor. - Ch Peek() const; - - //! Read the current character from stream and moving the read cursor to next character. - Ch Take(); - - //! Get the current read cursor. - //! \return Number of characters read from start. - size_t Tell(); - - //! Begin writing operation at the current read pointer. - //! \return The begin writer pointer. - Ch* PutBegin(); - - //! Write a character. - void Put(Ch c); - - //! Flush the buffer. - void Flush(); - - //! End the writing operation. - //! \param begin The begin write pointer returned by PutBegin(). - //! \return Number of characters written. - size_t PutEnd(Ch* begin); -} -\endcode -*/ - -//! Provides additional information for stream. -/*! - By using traits pattern, this type provides a default configuration for stream. - For custom stream, this type can be specialized for other configuration. - See TEST(Reader, CustomStringStream) in readertest.cpp for example. -*/ -template -struct StreamTraits { - //! Whether to make local copy of stream for optimization during parsing. - /*! - By default, for safety, streams do not use local copy optimization. - Stream that can be copied fast should specialize this, like StreamTraits. - */ - enum { copyOptimization = 0 }; -}; - -//! Reserve n characters for writing to a stream. -template -inline void PutReserve(Stream& stream, size_t count) { - (void)stream; - (void)count; -} - -//! Write character to a stream, presuming buffer is reserved. -template -inline void PutUnsafe(Stream& stream, typename Stream::Ch c) { - stream.Put(c); -} - -//! Put N copies of a character to a stream. -template -inline void PutN(Stream& stream, Ch c, size_t n) { - PutReserve(stream, n); - for (size_t i = 0; i < n; i++) - PutUnsafe(stream, c); -} - -/////////////////////////////////////////////////////////////////////////////// -// GenericStreamWrapper - -//! A Stream Wrapper -/*! \tThis string stream is a wrapper for any stream by just forwarding any - \treceived message to the origin stream. - \note implements Stream concept -*/ - -#if defined(_MSC_VER) && _MSC_VER <= 1800 -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(4702) // unreachable code -CEREAL_RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated -#endif - -template > -class GenericStreamWrapper { -public: - typedef typename Encoding::Ch Ch; - GenericStreamWrapper(InputStream& is): is_(is) {} - - Ch Peek() const { return is_.Peek(); } - Ch Take() { return is_.Take(); } - size_t Tell() { return is_.Tell(); } - Ch* PutBegin() { return is_.PutBegin(); } - void Put(Ch ch) { is_.Put(ch); } - void Flush() { is_.Flush(); } - size_t PutEnd(Ch* ch) { return is_.PutEnd(ch); } - - // wrapper for MemoryStream - const Ch* Peek4() const { return is_.Peek4(); } - - // wrapper for AutoUTFInputStream - UTFType GetType() const { return is_.GetType(); } - bool HasBOM() const { return is_.HasBOM(); } - -protected: - InputStream& is_; -}; - -#if defined(_MSC_VER) && _MSC_VER <= 1800 -CEREAL_RAPIDJSON_DIAG_POP -#endif - -/////////////////////////////////////////////////////////////////////////////// -// StringStream - -//! Read-only string stream. -/*! \note implements Stream concept -*/ -template -struct GenericStringStream { - typedef typename Encoding::Ch Ch; - - GenericStringStream(const Ch *src) : src_(src), head_(src) {} - - Ch Peek() const { return *src_; } - Ch Take() { return *src_++; } - size_t Tell() const { return static_cast(src_ - head_); } - - Ch* PutBegin() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - void Put(Ch) { CEREAL_RAPIDJSON_ASSERT(false); } - void Flush() { CEREAL_RAPIDJSON_ASSERT(false); } - size_t PutEnd(Ch*) { CEREAL_RAPIDJSON_ASSERT(false); return 0; } - - const Ch* src_; //!< Current read position. - const Ch* head_; //!< Original head of the string. -}; - -template -struct StreamTraits > { - enum { copyOptimization = 1 }; -}; - -//! String stream with UTF8 encoding. -typedef GenericStringStream > StringStream; - -/////////////////////////////////////////////////////////////////////////////// -// InsituStringStream - -//! A read-write string stream. -/*! This string stream is particularly designed for in-situ parsing. - \note implements Stream concept -*/ -template -struct GenericInsituStringStream { - typedef typename Encoding::Ch Ch; - - GenericInsituStringStream(Ch *src) : src_(src), dst_(0), head_(src) {} - - // Read - Ch Peek() { return *src_; } - Ch Take() { return *src_++; } - size_t Tell() { return static_cast(src_ - head_); } - - // Write - void Put(Ch c) { CEREAL_RAPIDJSON_ASSERT(dst_ != 0); *dst_++ = c; } - - Ch* PutBegin() { return dst_ = src_; } - size_t PutEnd(Ch* begin) { return static_cast(dst_ - begin); } - void Flush() {} - - Ch* Push(size_t count) { Ch* begin = dst_; dst_ += count; return begin; } - void Pop(size_t count) { dst_ -= count; } - - Ch* src_; - Ch* dst_; - Ch* head_; -}; - -template -struct StreamTraits > { - enum { copyOptimization = 1 }; -}; - -//! Insitu string stream with UTF8 encoding. -typedef GenericInsituStringStream > InsituStringStream; - -CEREAL_RAPIDJSON_NAMESPACE_END - -#endif // CEREAL_RAPIDJSON_STREAM_H_ diff --git a/include/cereal/external/rapidjson/stringbuffer.h b/include/cereal/external/rapidjson/stringbuffer.h deleted file mode 100644 index d010477..0000000 --- a/include/cereal/external/rapidjson/stringbuffer.h +++ /dev/null @@ -1,121 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_STRINGBUFFER_H_ -#define CEREAL_RAPIDJSON_STRINGBUFFER_H_ - -#include "stream.h" -#include "internal/stack.h" - -#if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS -#include // std::move -#endif - -#include "internal/stack.h" - -#if defined(__clang__) -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(c++98-compat) -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -//! Represents an in-memory output stream. -/*! - \tparam Encoding Encoding of the stream. - \tparam Allocator type for allocating memory buffer. - \note implements Stream concept -*/ -template -class GenericStringBuffer { -public: - typedef typename Encoding::Ch Ch; - - GenericStringBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {} - -#if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - GenericStringBuffer(GenericStringBuffer&& rhs) : stack_(std::move(rhs.stack_)) {} - GenericStringBuffer& operator=(GenericStringBuffer&& rhs) { - if (&rhs != this) - stack_ = std::move(rhs.stack_); - return *this; - } -#endif - - void Put(Ch c) { *stack_.template Push() = c; } - void PutUnsafe(Ch c) { *stack_.template PushUnsafe() = c; } - void Flush() {} - - void Clear() { stack_.Clear(); } - void ShrinkToFit() { - // Push and pop a null terminator. This is safe. - *stack_.template Push() = '\0'; - stack_.ShrinkToFit(); - stack_.template Pop(1); - } - - void Reserve(size_t count) { stack_.template Reserve(count); } - Ch* Push(size_t count) { return stack_.template Push(count); } - Ch* PushUnsafe(size_t count) { return stack_.template PushUnsafe(count); } - void Pop(size_t count) { stack_.template Pop(count); } - - const Ch* GetString() const { - // Push and pop a null terminator. This is safe. - *stack_.template Push() = '\0'; - stack_.template Pop(1); - - return stack_.template Bottom(); - } - - //! Get the size of string in bytes in the string buffer. - size_t GetSize() const { return stack_.GetSize(); } - - //! Get the length of string in Ch in the string buffer. - size_t GetLength() const { return stack_.GetSize() / sizeof(Ch); } - - static const size_t kDefaultCapacity = 256; - mutable internal::Stack stack_; - -private: - // Prohibit copy constructor & assignment operator. - GenericStringBuffer(const GenericStringBuffer&); - GenericStringBuffer& operator=(const GenericStringBuffer&); -}; - -//! String buffer with UTF8 encoding -typedef GenericStringBuffer > StringBuffer; - -template -inline void PutReserve(GenericStringBuffer& stream, size_t count) { - stream.Reserve(count); -} - -template -inline void PutUnsafe(GenericStringBuffer& stream, typename Encoding::Ch c) { - stream.PutUnsafe(c); -} - -//! Implement specialized version of PutN() with memset() for better performance. -template<> -inline void PutN(GenericStringBuffer >& stream, char c, size_t n) { - std::memset(stream.stack_.Push(n), c, n * sizeof(c)); -} - -CEREAL_RAPIDJSON_NAMESPACE_END - -#if defined(__clang__) -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#endif // CEREAL_RAPIDJSON_STRINGBUFFER_H_ diff --git a/include/cereal/external/rapidjson/writer.h b/include/cereal/external/rapidjson/writer.h deleted file mode 100644 index b8da773..0000000 --- a/include/cereal/external/rapidjson/writer.h +++ /dev/null @@ -1,709 +0,0 @@ -// Tencent is pleased to support the open source community by making RapidJSON available. -// -// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. -// -// Licensed under the MIT License (the "License"); you may not use this file except -// in compliance with the License. You may obtain a copy of the License at -// -// http://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software distributed -// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -#ifndef CEREAL_RAPIDJSON_WRITER_H_ -#define CEREAL_RAPIDJSON_WRITER_H_ - -#include "stream.h" -#include "internal/meta.h" -#include "internal/stack.h" -#include "internal/strfunc.h" -#include "internal/dtoa.h" -#include "internal/itoa.h" -#include "stringbuffer.h" -#include // placement new - -#if defined(CEREAL_RAPIDJSON_SIMD) && defined(_MSC_VER) -#include -#pragma intrinsic(_BitScanForward) -#endif -#ifdef CEREAL_RAPIDJSON_SSE42 -#include -#elif defined(CEREAL_RAPIDJSON_SSE2) -#include -#elif defined(CEREAL_RAPIDJSON_NEON) -#include -#endif - -#ifdef __clang__ -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(padded) -CEREAL_RAPIDJSON_DIAG_OFF(unreachable-code) -CEREAL_RAPIDJSON_DIAG_OFF(c++98-compat) -#elif defined(_MSC_VER) -CEREAL_RAPIDJSON_DIAG_PUSH -CEREAL_RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant -#endif - -CEREAL_RAPIDJSON_NAMESPACE_BEGIN - -/////////////////////////////////////////////////////////////////////////////// -// WriteFlag - -/*! \def CEREAL_RAPIDJSON_WRITE_DEFAULT_FLAGS - \ingroup CEREAL_RAPIDJSON_CONFIG - \brief User-defined kWriteDefaultFlags definition. - - User can define this as any \c WriteFlag combinations. -*/ -#ifndef CEREAL_RAPIDJSON_WRITE_DEFAULT_FLAGS -#define CEREAL_RAPIDJSON_WRITE_DEFAULT_FLAGS kWriteNoFlags -#endif - -//! Combination of writeFlags -enum WriteFlag { - kWriteNoFlags = 0, //!< No flags are set. - kWriteValidateEncodingFlag = 1, //!< Validate encoding of JSON strings. - kWriteNanAndInfFlag = 2, //!< Allow writing of Infinity, -Infinity and NaN. - kWriteDefaultFlags = CEREAL_RAPIDJSON_WRITE_DEFAULT_FLAGS //!< Default write flags. Can be customized by defining CEREAL_RAPIDJSON_WRITE_DEFAULT_FLAGS -}; - -//! JSON writer -/*! Writer implements the concept Handler. - It generates JSON text by events to an output os. - - User may programmatically calls the functions of a writer to generate JSON text. - - On the other side, a writer can also be passed to objects that generates events, - - for example Reader::Parse() and Document::Accept(). - - \tparam OutputStream Type of output stream. - \tparam SourceEncoding Encoding of source string. - \tparam TargetEncoding Encoding of output stream. - \tparam StackAllocator Type of allocator for allocating memory of stack. - \note implements Handler concept -*/ -template, typename TargetEncoding = UTF8<>, typename StackAllocator = CrtAllocator, unsigned writeFlags = kWriteDefaultFlags> -class Writer { -public: - typedef typename SourceEncoding::Ch Ch; - - static const int kDefaultMaxDecimalPlaces = 324; - - //! Constructor - /*! \param os Output stream. - \param stackAllocator User supplied allocator. If it is null, it will create a private one. - \param levelDepth Initial capacity of stack. - */ - explicit - Writer(OutputStream& os, StackAllocator* stackAllocator = 0, size_t levelDepth = kDefaultLevelDepth) : - os_(&os), level_stack_(stackAllocator, levelDepth * sizeof(Level)), maxDecimalPlaces_(kDefaultMaxDecimalPlaces), hasRoot_(false) {} - - explicit - Writer(StackAllocator* allocator = 0, size_t levelDepth = kDefaultLevelDepth) : - os_(0), level_stack_(allocator, levelDepth * sizeof(Level)), maxDecimalPlaces_(kDefaultMaxDecimalPlaces), hasRoot_(false) {} - -#if CEREAL_RAPIDJSON_HAS_CXX11_RVALUE_REFS - Writer(Writer&& rhs) : - os_(rhs.os_), level_stack_(std::move(rhs.level_stack_)), maxDecimalPlaces_(rhs.maxDecimalPlaces_), hasRoot_(rhs.hasRoot_) { - rhs.os_ = 0; - } -#endif - - //! Reset the writer with a new stream. - /*! - This function reset the writer with a new stream and default settings, - in order to make a Writer object reusable for output multiple JSONs. - - \param os New output stream. - \code - Writer writer(os1); - writer.StartObject(); - // ... - writer.EndObject(); - - writer.Reset(os2); - writer.StartObject(); - // ... - writer.EndObject(); - \endcode - */ - void Reset(OutputStream& os) { - os_ = &os; - hasRoot_ = false; - level_stack_.Clear(); - } - - //! Checks whether the output is a complete JSON. - /*! - A complete JSON has a complete root object or array. - */ - bool IsComplete() const { - return hasRoot_ && level_stack_.Empty(); - } - - int GetMaxDecimalPlaces() const { - return maxDecimalPlaces_; - } - - //! Sets the maximum number of decimal places for double output. - /*! - This setting truncates the output with specified number of decimal places. - - For example, - - \code - writer.SetMaxDecimalPlaces(3); - writer.StartArray(); - writer.Double(0.12345); // "0.123" - writer.Double(0.0001); // "0.0" - writer.Double(1.234567890123456e30); // "1.234567890123456e30" (do not truncate significand for positive exponent) - writer.Double(1.23e-4); // "0.0" (do truncate significand for negative exponent) - writer.EndArray(); - \endcode - - The default setting does not truncate any decimal places. You can restore to this setting by calling - \code - writer.SetMaxDecimalPlaces(Writer::kDefaultMaxDecimalPlaces); - \endcode - */ - void SetMaxDecimalPlaces(int maxDecimalPlaces) { - maxDecimalPlaces_ = maxDecimalPlaces; - } - - /*!@name Implementation of Handler - \see Handler - */ - //@{ - - bool Null() { Prefix(kNullType); return EndValue(WriteNull()); } - bool Bool(bool b) { Prefix(b ? kTrueType : kFalseType); return EndValue(WriteBool(b)); } - bool Int(int i) { Prefix(kNumberType); return EndValue(WriteInt(i)); } - bool Uint(unsigned u) { Prefix(kNumberType); return EndValue(WriteUint(u)); } - bool Int64(int64_t i64) { Prefix(kNumberType); return EndValue(WriteInt64(i64)); } - bool Uint64(uint64_t u64) { Prefix(kNumberType); return EndValue(WriteUint64(u64)); } - - //! Writes the given \c double value to the stream - /*! - \param d The value to be written. - \return Whether it is succeed. - */ - bool Double(double d) { Prefix(kNumberType); return EndValue(WriteDouble(d)); } - - bool RawNumber(const Ch* str, SizeType length, bool copy = false) { - CEREAL_RAPIDJSON_ASSERT(str != 0); - (void)copy; - Prefix(kNumberType); - return EndValue(WriteString(str, length)); - } - - bool String(const Ch* str, SizeType length, bool copy = false) { - CEREAL_RAPIDJSON_ASSERT(str != 0); - (void)copy; - Prefix(kStringType); - return EndValue(WriteString(str, length)); - } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - bool String(const std::basic_string& str) { - return String(str.data(), SizeType(str.size())); - } -#endif - - bool StartObject() { - Prefix(kObjectType); - new (level_stack_.template Push()) Level(false); - return WriteStartObject(); - } - - bool Key(const Ch* str, SizeType length, bool copy = false) { return String(str, length, copy); } - -#if CEREAL_RAPIDJSON_HAS_STDSTRING - bool Key(const std::basic_string& str) - { - return Key(str.data(), SizeType(str.size())); - } -#endif - - bool EndObject(SizeType memberCount = 0) { - (void)memberCount; - CEREAL_RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level)); // not inside an Object - CEREAL_RAPIDJSON_ASSERT(!level_stack_.template Top()->inArray); // currently inside an Array, not Object - CEREAL_RAPIDJSON_ASSERT(0 == level_stack_.template Top()->valueCount % 2); // Object has a Key without a Value - level_stack_.template Pop(1); - return EndValue(WriteEndObject()); - } - - bool StartArray() { - Prefix(kArrayType); - new (level_stack_.template Push()) Level(true); - return WriteStartArray(); - } - - bool EndArray(SizeType elementCount = 0) { - (void)elementCount; - CEREAL_RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level)); - CEREAL_RAPIDJSON_ASSERT(level_stack_.template Top()->inArray); - level_stack_.template Pop(1); - return EndValue(WriteEndArray()); - } - //@} - - /*! @name Convenience extensions */ - //@{ - - //! Simpler but slower overload. - bool String(const Ch* const& str) { return String(str, internal::StrLen(str)); } - bool Key(const Ch* const& str) { return Key(str, internal::StrLen(str)); } - - //@} - - //! Write a raw JSON value. - /*! - For user to write a stringified JSON as a value. - - \param json A well-formed JSON value. It should not contain null character within [0, length - 1] range. - \param length Length of the json. - \param type Type of the root of json. - */ - bool RawValue(const Ch* json, size_t length, Type type) { - CEREAL_RAPIDJSON_ASSERT(json != 0); - Prefix(type); - return EndValue(WriteRawValue(json, length)); - } - - //! Flush the output stream. - /*! - Allows the user to flush the output stream immediately. - */ - void Flush() { - os_->Flush(); - } - -protected: - //! Information for each nested level - struct Level { - Level(bool inArray_) : valueCount(0), inArray(inArray_) {} - size_t valueCount; //!< number of values in this level - bool inArray; //!< true if in array, otherwise in object - }; - - static const size_t kDefaultLevelDepth = 32; - - bool WriteNull() { - PutReserve(*os_, 4); - PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'u'); PutUnsafe(*os_, 'l'); PutUnsafe(*os_, 'l'); return true; - } - - bool WriteBool(bool b) { - if (b) { - PutReserve(*os_, 4); - PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'r'); PutUnsafe(*os_, 'u'); PutUnsafe(*os_, 'e'); - } - else { - PutReserve(*os_, 5); - PutUnsafe(*os_, 'f'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'l'); PutUnsafe(*os_, 's'); PutUnsafe(*os_, 'e'); - } - return true; - } - - bool WriteInt(int i) { - char buffer[11]; - const char* end = internal::i32toa(i, buffer); - PutReserve(*os_, static_cast(end - buffer)); - for (const char* p = buffer; p != end; ++p) - PutUnsafe(*os_, static_cast(*p)); - return true; - } - - bool WriteUint(unsigned u) { - char buffer[10]; - const char* end = internal::u32toa(u, buffer); - PutReserve(*os_, static_cast(end - buffer)); - for (const char* p = buffer; p != end; ++p) - PutUnsafe(*os_, static_cast(*p)); - return true; - } - - bool WriteInt64(int64_t i64) { - char buffer[21]; - const char* end = internal::i64toa(i64, buffer); - PutReserve(*os_, static_cast(end - buffer)); - for (const char* p = buffer; p != end; ++p) - PutUnsafe(*os_, static_cast(*p)); - return true; - } - - bool WriteUint64(uint64_t u64) { - char buffer[20]; - char* end = internal::u64toa(u64, buffer); - PutReserve(*os_, static_cast(end - buffer)); - for (char* p = buffer; p != end; ++p) - PutUnsafe(*os_, static_cast(*p)); - return true; - } - - bool WriteDouble(double d) { - if (internal::Double(d).IsNanOrInf()) { - if (!(writeFlags & kWriteNanAndInfFlag)) - return false; - if (internal::Double(d).IsNan()) { - PutReserve(*os_, 3); - PutUnsafe(*os_, 'N'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'N'); - return true; - } - if (internal::Double(d).Sign()) { - PutReserve(*os_, 9); - PutUnsafe(*os_, '-'); - } - else - PutReserve(*os_, 8); - PutUnsafe(*os_, 'I'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'f'); - PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'y'); - return true; - } - - char buffer[25]; - char* end = internal::dtoa(d, buffer, maxDecimalPlaces_); - PutReserve(*os_, static_cast(end - buffer)); - for (char* p = buffer; p != end; ++p) - PutUnsafe(*os_, static_cast(*p)); - return true; - } - - bool WriteString(const Ch* str, SizeType length) { - static const typename OutputStream::Ch hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; - static const char escape[256] = { -#define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 - //0 1 2 3 4 5 6 7 8 9 A B C D E F - 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'b', 't', 'n', 'u', 'f', 'r', 'u', 'u', // 00 - 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', // 10 - 0, 0, '"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20 - Z16, Z16, // 30~4F - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\\', 0, 0, 0, // 50 - Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16 // 60~FF -#undef Z16 - }; - - if (TargetEncoding::supportUnicode) - PutReserve(*os_, 2 + length * 6); // "\uxxxx..." - else - PutReserve(*os_, 2 + length * 12); // "\uxxxx\uyyyy..." - - PutUnsafe(*os_, '\"'); - GenericStringStream is(str); - while (ScanWriteUnescapedString(is, length)) { - const Ch c = is.Peek(); - if (!TargetEncoding::supportUnicode && static_cast(c) >= 0x80) { - // Unicode escaping - unsigned codepoint; - if (CEREAL_RAPIDJSON_UNLIKELY(!SourceEncoding::Decode(is, &codepoint))) - return false; - PutUnsafe(*os_, '\\'); - PutUnsafe(*os_, 'u'); - if (codepoint <= 0xD7FF || (codepoint >= 0xE000 && codepoint <= 0xFFFF)) { - PutUnsafe(*os_, hexDigits[(codepoint >> 12) & 15]); - PutUnsafe(*os_, hexDigits[(codepoint >> 8) & 15]); - PutUnsafe(*os_, hexDigits[(codepoint >> 4) & 15]); - PutUnsafe(*os_, hexDigits[(codepoint ) & 15]); - } - else { - CEREAL_RAPIDJSON_ASSERT(codepoint >= 0x010000 && codepoint <= 0x10FFFF); - // Surrogate pair - unsigned s = codepoint - 0x010000; - unsigned lead = (s >> 10) + 0xD800; - unsigned trail = (s & 0x3FF) + 0xDC00; - PutUnsafe(*os_, hexDigits[(lead >> 12) & 15]); - PutUnsafe(*os_, hexDigits[(lead >> 8) & 15]); - PutUnsafe(*os_, hexDigits[(lead >> 4) & 15]); - PutUnsafe(*os_, hexDigits[(lead ) & 15]); - PutUnsafe(*os_, '\\'); - PutUnsafe(*os_, 'u'); - PutUnsafe(*os_, hexDigits[(trail >> 12) & 15]); - PutUnsafe(*os_, hexDigits[(trail >> 8) & 15]); - PutUnsafe(*os_, hexDigits[(trail >> 4) & 15]); - PutUnsafe(*os_, hexDigits[(trail ) & 15]); - } - } - else if ((sizeof(Ch) == 1 || static_cast(c) < 256) && CEREAL_RAPIDJSON_UNLIKELY(escape[static_cast(c)])) { - is.Take(); - PutUnsafe(*os_, '\\'); - PutUnsafe(*os_, static_cast(escape[static_cast(c)])); - if (escape[static_cast(c)] == 'u') { - PutUnsafe(*os_, '0'); - PutUnsafe(*os_, '0'); - PutUnsafe(*os_, hexDigits[static_cast(c) >> 4]); - PutUnsafe(*os_, hexDigits[static_cast(c) & 0xF]); - } - } - else if (CEREAL_RAPIDJSON_UNLIKELY(!(writeFlags & kWriteValidateEncodingFlag ? - Transcoder::Validate(is, *os_) : - Transcoder::TranscodeUnsafe(is, *os_)))) - return false; - } - PutUnsafe(*os_, '\"'); - return true; - } - - bool ScanWriteUnescapedString(GenericStringStream& is, size_t length) { - return CEREAL_RAPIDJSON_LIKELY(is.Tell() < length); - } - - bool WriteStartObject() { os_->Put('{'); return true; } - bool WriteEndObject() { os_->Put('}'); return true; } - bool WriteStartArray() { os_->Put('['); return true; } - bool WriteEndArray() { os_->Put(']'); return true; } - - bool WriteRawValue(const Ch* json, size_t length) { - PutReserve(*os_, length); - GenericStringStream is(json); - while (CEREAL_RAPIDJSON_LIKELY(is.Tell() < length)) { - CEREAL_RAPIDJSON_ASSERT(is.Peek() != '\0'); - if (CEREAL_RAPIDJSON_UNLIKELY(!(writeFlags & kWriteValidateEncodingFlag ? - Transcoder::Validate(is, *os_) : - Transcoder::TranscodeUnsafe(is, *os_)))) - return false; - } - return true; - } - - void Prefix(Type type) { - (void)type; - if (CEREAL_RAPIDJSON_LIKELY(level_stack_.GetSize() != 0)) { // this value is not at root - Level* level = level_stack_.template Top(); - if (level->valueCount > 0) { - if (level->inArray) - os_->Put(','); // add comma if it is not the first element in array - else // in object - os_->Put((level->valueCount % 2 == 0) ? ',' : ':'); - } - if (!level->inArray && level->valueCount % 2 == 0) - CEREAL_RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name - level->valueCount++; - } - else { - CEREAL_RAPIDJSON_ASSERT(!hasRoot_); // Should only has one and only one root. - hasRoot_ = true; - } - } - - // Flush the value if it is the top level one. - bool EndValue(bool ret) { - if (CEREAL_RAPIDJSON_UNLIKELY(level_stack_.Empty())) // end of json text - Flush(); - return ret; - } - - OutputStream* os_; - internal::Stack level_stack_; - int maxDecimalPlaces_; - bool hasRoot_; - -private: - // Prohibit copy constructor & assignment operator. - Writer(const Writer&); - Writer& operator=(const Writer&); -}; - -// Full specialization for StringStream to prevent memory copying - -template<> -inline bool Writer::WriteInt(int i) { - char *buffer = os_->Push(11); - const char* end = internal::i32toa(i, buffer); - os_->Pop(static_cast(11 - (end - buffer))); - return true; -} - -template<> -inline bool Writer::WriteUint(unsigned u) { - char *buffer = os_->Push(10); - const char* end = internal::u32toa(u, buffer); - os_->Pop(static_cast(10 - (end - buffer))); - return true; -} - -template<> -inline bool Writer::WriteInt64(int64_t i64) { - char *buffer = os_->Push(21); - const char* end = internal::i64toa(i64, buffer); - os_->Pop(static_cast(21 - (end - buffer))); - return true; -} - -template<> -inline bool Writer::WriteUint64(uint64_t u) { - char *buffer = os_->Push(20); - const char* end = internal::u64toa(u, buffer); - os_->Pop(static_cast(20 - (end - buffer))); - return true; -} - -template<> -inline bool Writer::WriteDouble(double d) { - if (internal::Double(d).IsNanOrInf()) { - // Note: This code path can only be reached if (CEREAL_RAPIDJSON_WRITE_DEFAULT_FLAGS & kWriteNanAndInfFlag). - if (!(kWriteDefaultFlags & kWriteNanAndInfFlag)) - return false; - if (internal::Double(d).IsNan()) { - PutReserve(*os_, 3); - PutUnsafe(*os_, 'N'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'N'); - return true; - } - if (internal::Double(d).Sign()) { - PutReserve(*os_, 9); - PutUnsafe(*os_, '-'); - } - else - PutReserve(*os_, 8); - PutUnsafe(*os_, 'I'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'f'); - PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'y'); - return true; - } - - char *buffer = os_->Push(25); - char* end = internal::dtoa(d, buffer, maxDecimalPlaces_); - os_->Pop(static_cast(25 - (end - buffer))); - return true; -} - -#if defined(CEREAL_RAPIDJSON_SSE2) || defined(CEREAL_RAPIDJSON_SSE42) -template<> -inline bool Writer::ScanWriteUnescapedString(StringStream& is, size_t length) { - if (length < 16) - return CEREAL_RAPIDJSON_LIKELY(is.Tell() < length); - - if (!CEREAL_RAPIDJSON_LIKELY(is.Tell() < length)) - return false; - - const char* p = is.src_; - const char* end = is.head_ + length; - const char* nextAligned = reinterpret_cast((reinterpret_cast(p) + 15) & static_cast(~15)); - const char* endAligned = reinterpret_cast(reinterpret_cast(end) & static_cast(~15)); - if (nextAligned > end) - return true; - - while (p != nextAligned) - if (*p < 0x20 || *p == '\"' || *p == '\\') { - is.src_ = p; - return CEREAL_RAPIDJSON_LIKELY(is.Tell() < length); - } - else - os_->PutUnsafe(*p++); - - // The rest of string using SIMD - static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' }; - static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; - static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F }; - const __m128i dq = _mm_loadu_si128(reinterpret_cast(&dquote[0])); - const __m128i bs = _mm_loadu_si128(reinterpret_cast(&bslash[0])); - const __m128i sp = _mm_loadu_si128(reinterpret_cast(&space[0])); - - for (; p != endAligned; p += 16) { - const __m128i s = _mm_load_si128(reinterpret_cast(p)); - const __m128i t1 = _mm_cmpeq_epi8(s, dq); - const __m128i t2 = _mm_cmpeq_epi8(s, bs); - const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F - const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); - unsigned short r = static_cast(_mm_movemask_epi8(x)); - if (CEREAL_RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped - SizeType len; -#ifdef _MSC_VER // Find the index of first escaped - unsigned long offset; - _BitScanForward(&offset, r); - len = offset; -#else - len = static_cast(__builtin_ffs(r) - 1); -#endif - char* q = reinterpret_cast(os_->PushUnsafe(len)); - for (size_t i = 0; i < len; i++) - q[i] = p[i]; - - p += len; - break; - } - _mm_storeu_si128(reinterpret_cast<__m128i *>(os_->PushUnsafe(16)), s); - } - - is.src_ = p; - return CEREAL_RAPIDJSON_LIKELY(is.Tell() < length); -} -#elif defined(CEREAL_RAPIDJSON_NEON) -template<> -inline bool Writer::ScanWriteUnescapedString(StringStream& is, size_t length) { - if (length < 16) - return CEREAL_RAPIDJSON_LIKELY(is.Tell() < length); - - if (!CEREAL_RAPIDJSON_LIKELY(is.Tell() < length)) - return false; - - const char* p = is.src_; - const char* end = is.head_ + length; - const char* nextAligned = reinterpret_cast((reinterpret_cast(p) + 15) & static_cast(~15)); - const char* endAligned = reinterpret_cast(reinterpret_cast(end) & static_cast(~15)); - if (nextAligned > end) - return true; - - while (p != nextAligned) - if (*p < 0x20 || *p == '\"' || *p == '\\') { - is.src_ = p; - return CEREAL_RAPIDJSON_LIKELY(is.Tell() < length); - } - else - os_->PutUnsafe(*p++); - - // The rest of string using SIMD - const uint8x16_t s0 = vmovq_n_u8('"'); - const uint8x16_t s1 = vmovq_n_u8('\\'); - const uint8x16_t s2 = vmovq_n_u8('\b'); - const uint8x16_t s3 = vmovq_n_u8(32); - - for (; p != endAligned; p += 16) { - const uint8x16_t s = vld1q_u8(reinterpret_cast(p)); - uint8x16_t x = vceqq_u8(s, s0); - x = vorrq_u8(x, vceqq_u8(s, s1)); - x = vorrq_u8(x, vceqq_u8(s, s2)); - x = vorrq_u8(x, vcltq_u8(s, s3)); - - x = vrev64q_u8(x); // Rev in 64 - uint64_t low = vgetq_lane_u64(reinterpret_cast(x), 0); // extract - uint64_t high = vgetq_lane_u64(reinterpret_cast(x), 1); // extract - - SizeType len = 0; - bool escaped = false; - if (low == 0) { - if (high != 0) { - unsigned lz = (unsigned)__builtin_clzll(high); - len = 8 + (lz >> 3); - escaped = true; - } - } else { - unsigned lz = (unsigned)__builtin_clzll(low); - len = lz >> 3; - escaped = true; - } - if (CEREAL_RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped - char* q = reinterpret_cast(os_->PushUnsafe(len)); - for (size_t i = 0; i < len; i++) - q[i] = p[i]; - - p += len; - break; - } - vst1q_u8(reinterpret_cast(os_->PushUnsafe(16)), s); - } - - is.src_ = p; - return CEREAL_RAPIDJSON_LIKELY(is.Tell() < length); -} -#endif // CEREAL_RAPIDJSON_NEON - -CEREAL_RAPIDJSON_NAMESPACE_END - -#if defined(_MSC_VER) || defined(__clang__) -CEREAL_RAPIDJSON_DIAG_POP -#endif - -#endif // CEREAL_RAPIDJSON_CEREAL_RAPIDJSON_H_ diff --git a/include/cereal/external/rapidxml/license.txt b/include/cereal/external/rapidxml/license.txt deleted file mode 100644 index 1409831..0000000 --- a/include/cereal/external/rapidxml/license.txt +++ /dev/null @@ -1,52 +0,0 @@ -Use of this software is granted under one of the following two licenses, -to be chosen freely by the user. - -1. Boost Software License - Version 1.0 - August 17th, 2003 -=============================================================================== - -Copyright (c) 2006, 2007 Marcin Kalicinski - -Permission is hereby granted, free of charge, to any person or organization -obtaining a copy of the software and accompanying documentation covered by -this license (the "Software") to use, reproduce, display, distribute, -execute, and transmit the Software, and to prepare derivative works of the -Software, and to permit third-parties to whom the Software is furnished to -do so, all subject to the following: - -The copyright notices in the Software and this entire statement, including -the above license grant, this restriction and the following disclaimer, -must be included in all copies of the Software, in whole or in part, and -all derivative works of the Software, unless such copies or derivative -works are solely in the form of machine-executable object code generated by -a source language processor. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT -SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE -FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. - -2. The MIT License -=============================================================================== - -Copyright (c) 2006, 2007 Marcin Kalicinski - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL -THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. diff --git a/include/cereal/external/rapidxml/manual.html b/include/cereal/external/rapidxml/manual.html deleted file mode 100644 index 2c42270..0000000 --- a/include/cereal/external/rapidxml/manual.html +++ /dev/null @@ -1,406 +0,0 @@ -

RAPIDXML Manual

Version 1.13

Copyright (C) 2006, 2009 Marcin Kalicinski
See accompanying file
license.txt for license information.

Table of Contents

1. What is RapidXml?
1.1 Dependencies And Compatibility
1.2 Character Types And Encodings
1.3 Error Handling
1.4 Memory Allocation
1.5 W3C Compliance
1.6 API Design
1.7 Reliability
1.8 Acknowledgements
2. Two Minute Tutorial
2.1 Parsing
2.2 Accessing The DOM Tree
2.3 Modifying The DOM Tree
2.4 Printing XML
3. Differences From Regular XML Parsers
3.1 Lifetime Of Source Text
3.2 Ownership Of Strings
3.3 Destructive Vs Non-Destructive Mode
4. Performance
4.1 Comparison With Other Parsers
5. Reference

1. What is RapidXml?

RapidXml is an attempt to create the fastest XML DOM parser possible, while retaining useability, portability and reasonable W3C compatibility. It is an in-situ parser written in C++, with parsing speed approaching that of strlen() function executed on the same data.

- Entire parser is contained in a single header file, so no building or linking is neccesary. To use it you just need to copy rapidxml.hpp file to a convenient place (such as your project directory), and include it where needed. You may also want to use printing functions contained in header rapidxml_print.hpp.

1.1 Dependencies And Compatibility

RapidXml has no dependencies other than a very small subset of standard C++ library (<cassert>, <cstdlib>, <new> and <exception>, unless exceptions are disabled). It should compile on any reasonably conformant compiler, and was tested on Visual C++ 2003, Visual C++ 2005, Visual C++ 2008, gcc 3, gcc 4, and Comeau 4.3.3. Care was taken that no warnings are produced on these compilers, even with highest warning levels enabled.

1.2 Character Types And Encodings

RapidXml is character type agnostic, and can work both with narrow and wide characters. Current version does not fully support UTF-16 or UTF-32, so use of wide characters is somewhat incapacitated. However, it should succesfully parse wchar_t strings containing UTF-16 or UTF-32 if endianness of the data matches that of the machine. UTF-8 is fully supported, including all numeric character references, which are expanded into appropriate UTF-8 byte sequences (unless you enable parse_no_utf8 flag).

- Note that RapidXml performs no decoding - strings returned by name() and value() functions will contain text encoded using the same encoding as source file. Rapidxml understands and expands the following character references: &apos; &amp; &quot; &lt; &gt; &#...; Other character references are not expanded.

1.3 Error Handling

By default, RapidXml uses C++ exceptions to report errors. If this behaviour is undesirable, RAPIDXML_NO_EXCEPTIONS can be defined to suppress exception code. See parse_error class and parse_error_handler() function for more information.

1.4 Memory Allocation

RapidXml uses a special memory pool object to allocate nodes and attributes, because direct allocation using new operator would be far too slow. Underlying memory allocations performed by the pool can be customized by use of memory_pool::set_allocator() function. See class memory_pool for more information.

1.5 W3C Compliance

RapidXml is not a W3C compliant parser, primarily because it ignores DOCTYPE declarations. There is a number of other, minor incompatibilities as well. Still, it can successfully parse and produce complete trees of all valid XML files in W3C conformance suite (over 1000 files specially designed to find flaws in XML processors). In destructive mode it performs whitespace normalization and character entity substitution for a small set of built-in entities.

1.6 API Design

RapidXml API is minimalistic, to reduce code size as much as possible, and facilitate use in embedded environments. Additional convenience functions are provided in separate headers: rapidxml_utils.hpp and rapidxml_print.hpp. Contents of these headers is not an essential part of the library, and is currently not documented (otherwise than with comments in code).

1.7 Reliability

RapidXml is very robust and comes with a large harness of unit tests. Special care has been taken to ensure stability of the parser no matter what source text is thrown at it. One of the unit tests produces 100,000 randomly corrupted variants of XML document, which (when uncorrupted) contains all constructs recognized by RapidXml. RapidXml passes this test when it correctly recognizes that errors have been introduced, and does not crash or loop indefinitely.

- Another unit test puts RapidXml head-to-head with another, well estabilished XML parser, and verifies that their outputs match across a wide variety of small and large documents.

- Yet another test feeds RapidXml with over 1000 test files from W3C compliance suite, and verifies that correct results are obtained. There are also additional tests that verify each API function separately, and test that various parsing modes work as expected.

1.8 Acknowledgements

I would like to thank Arseny Kapoulkine for his work on pugixml, which was an inspiration for this project. Additional thanks go to Kristen Wegner for creating pugxml, from which pugixml was derived. Janusz Wohlfeil kindly ran RapidXml speed tests on hardware that I did not have access to, allowing me to expand performance comparison table.

2. Two Minute Tutorial

2.1 Parsing

The following code causes RapidXml to parse a zero-terminated string named text:
using namespace rapidxml;
-xml_document<> doc;    // character type defaults to char
-doc.parse<0>(text);    // 0 means default parse flags
-
doc object is now a root of DOM tree containing representation of the parsed XML. Because all RapidXml interface is contained inside namespace rapidxml, users must either bring contents of this namespace into scope, or fully qualify all the names. Class xml_document represents a root of the DOM hierarchy. By means of public inheritance, it is also an xml_node and a memory_pool. Template parameter of xml_document::parse() function is used to specify parsing flags, with which you can fine-tune behaviour of the parser. Note that flags must be a compile-time constant.

2.2 Accessing The DOM Tree

To access the DOM tree, use methods of xml_node and xml_attribute classes:
cout << "Name of my first node is: " << doc.first_node()->name() << "\n";
-xml_node<> *node = doc.first_node("foobar");
-cout << "Node foobar has value " << node->value() << "\n";
-for (xml_attribute<> *attr = node->first_attribute();
-     attr; attr = attr->next_attribute())
-{
-    cout << "Node foobar has attribute " << attr->name() << " ";
-    cout << "with value " << attr->value() << "\n";
-}
-

2.3 Modifying The DOM Tree

DOM tree produced by the parser is fully modifiable. Nodes and attributes can be added/removed, and their contents changed. The below example creates a HTML document, whose sole contents is a link to google.com website:
xml_document<> doc;
-xml_node<> *node = doc.allocate_node(node_element, "a", "Google");
-doc.append_node(node);
-xml_attribute<> *attr = doc.allocate_attribute("href", "google.com");
-node->append_attribute(attr);
-
One quirk is that nodes and attributes do not own the text of their names and values. This is because normally they only store pointers to the source text. So, when assigning a new name or value to the node, care must be taken to ensure proper lifetime of the string. The easiest way to achieve it is to allocate the string from the xml_document memory pool. In the above example this is not necessary, because we are only assigning character constants. But the code below uses memory_pool::allocate_string() function to allocate node name (which will have the same lifetime as the document), and assigns it to a new node:
xml_document<> doc;
-char *node_name = doc.allocate_string(name);        // Allocate string and copy name into it
-xml_node<> *node = doc.allocate_node(node_element, node_name);  // Set node name to node_name
-
Check Reference section for description of the entire interface.

2.4 Printing XML

You can print xml_document and xml_node objects into an XML string. Use print() function or operator <<, which are defined in rapidxml_print.hpp header.
using namespace rapidxml;
-xml_document<> doc;    // character type defaults to char
-// ... some code to fill the document
-
-// Print to stream using operator <<
-std::cout << doc;   
-
-// Print to stream using print function, specifying printing flags
-print(std::cout, doc, 0);   // 0 means default printing flags
-
-// Print to string using output iterator
-std::string s;
-print(std::back_inserter(s), doc, 0);
-
-// Print to memory buffer using output iterator
-char buffer[4096];                      // You are responsible for making the buffer large enough!
-char *end = print(buffer, doc, 0);      // end contains pointer to character after last printed character
-*end = 0;                               // Add string terminator after XML
-

3. Differences From Regular XML Parsers

RapidXml is an in-situ parser, which allows it to achieve very high parsing speed. In-situ means that parser does not make copies of strings. Instead, it places pointers to the source text in the DOM hierarchy.

3.1 Lifetime Of Source Text

In-situ parsing requires that source text lives at least as long as the document object. If source text is destroyed, names and values of nodes in DOM tree will become destroyed as well. Additionally, whitespace processing, character entity translation, and zero-termination of strings require that source text be modified during parsing (but see non-destructive mode). This makes the text useless for further processing once it was parsed by RapidXml.

- In many cases however, these are not serious issues.

3.2 Ownership Of Strings

Nodes and attributes produced by RapidXml do not own their name and value strings. They merely hold the pointers to them. This means you have to be careful when setting these values manually, by using xml_base::name(const Ch *) or xml_base::value(const Ch *) functions. Care must be taken to ensure that lifetime of the string passed is at least as long as lifetime of the node/attribute. The easiest way to achieve it is to allocate the string from memory_pool owned by the document. Use memory_pool::allocate_string() function for this purpose.

3.3 Destructive Vs Non-Destructive Mode

By default, the parser modifies source text during the parsing process. This is required to achieve character entity translation, whitespace normalization, and zero-termination of strings.

- In some cases this behaviour may be undesirable, for example if source text resides in read only memory, or is mapped to memory directly from file. By using appropriate parser flags (parse_non_destructive), source text modifications can be disabled. However, because RapidXml does in-situ parsing, it obviously has the following side-effects:

4. Performance

RapidXml achieves its speed through use of several techniques:
  • In-situ parsing. When building DOM tree, RapidXml does not make copies of string data, such as node names and values. Instead, it stores pointers to interior of the source text.
  • Use of template metaprogramming techniques. This allows it to move much of the work to compile time. Through magic of the templates, C++ compiler generates a separate copy of parsing code for any combination of parser flags you use. In each copy, all possible decisions are made at compile time and all unused code is omitted.
  • Extensive use of lookup tables for parsing.
  • Hand-tuned C++ with profiling done on several most popular CPUs.
This results in a very small and fast code: a parser which is custom tailored to exact needs with each invocation.

4.1 Comparison With Other Parsers

The table below compares speed of RapidXml to some other parsers, and to strlen() function executed on the same data. On a modern CPU (as of 2007), you can expect parsing throughput to be close to 1 GB/s. As a rule of thumb, parsing speed is about 50-100x faster than Xerces DOM, 30-60x faster than TinyXml, 3-12x faster than pugxml, and about 5% - 30% faster than pugixml, the fastest XML parser I know of.
  • The test file is a real-world, 50kB large, moderately dense XML file.
  • All timing is done by using RDTSC instruction present in Pentium-compatible CPUs.
  • No profile-guided optimizations are used.
  • All parsers are running in their fastest modes.
  • The results are given in CPU cycles per character, so frequency of CPUs is irrelevant.
  • The results are minimum values from a large number of runs, to minimize effects of operating system activity, task switching, interrupt handling etc.
  • A single parse of the test file takes about 1/10th of a millisecond, so with large number of runs there is a good chance of hitting at least one no-interrupt streak, and obtaining undisturbed results.
Platform
Compiler
strlen() RapidXml pugixml 0.3 pugxml TinyXml
Pentium 4
MSVC 8.0
2.5
5.4
7.0
61.7
298.8
Pentium 4
gcc 4.1.1
0.8
6.1
9.5
67.0
413.2
Core 2
MSVC 8.0
1.0
4.5
5.0
24.6
154.8
Core 2
gcc 4.1.1
0.6
4.6
5.4
28.3
229.3
Athlon XP
MSVC 8.0
3.1
7.7
8.0
25.5
182.6
Athlon XP
gcc 4.1.1
0.9
8.2
9.2
33.7
265.2
Pentium 3
MSVC 8.0
2.0
6.3
7.0
30.9
211.9
Pentium 3
gcc 4.1.1
1.0
6.7
8.9
35.3
316.0
(*) All results are in CPU cycles per character of source text

5. Reference

This section lists all classes, functions, constants etc. and describes them in detail.
class - template - rapidxml::memory_pool
- constructor - memory_pool()
- destructor - ~memory_pool()
function allocate_node(node_type type, const Ch *name=0, const Ch *value=0, std::size_t name_size=0, std::size_t value_size=0)
function allocate_attribute(const Ch *name=0, const Ch *value=0, std::size_t name_size=0, std::size_t value_size=0)
function allocate_string(const Ch *source=0, std::size_t size=0)
function clone_node(const xml_node< Ch > *source, xml_node< Ch > *result=0)
function clear()
function set_allocator(alloc_func *af, free_func *ff)

class rapidxml::parse_error
- constructor - parse_error(const char *what, void *where)
function what() const
function where() const

class - template - rapidxml::xml_attribute
- constructor - xml_attribute()
function document() const
function previous_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function next_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const

class - template - rapidxml::xml_base
- constructor - xml_base()
function name() const
function name_size() const
function value() const
function value_size() const
function name(const Ch *name, std::size_t size)
function name(const Ch *name)
function value(const Ch *value, std::size_t size)
function value(const Ch *value)
function parent() const

class - template - rapidxml::xml_document
- constructor - xml_document()
function parse(Ch *text)
function clear()

class - template - rapidxml::xml_node
- constructor - xml_node(node_type type)
function type() const
function document() const
function first_node(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function last_node(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function previous_sibling(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function next_sibling(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function first_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function last_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const
function type(node_type type)
function prepend_node(xml_node< Ch > *child)
function append_node(xml_node< Ch > *child)
function insert_node(xml_node< Ch > *where, xml_node< Ch > *child)
function remove_first_node()
function remove_last_node()
function remove_node(xml_node< Ch > *where)
function remove_all_nodes()
function prepend_attribute(xml_attribute< Ch > *attribute)
function append_attribute(xml_attribute< Ch > *attribute)
function insert_attribute(xml_attribute< Ch > *where, xml_attribute< Ch > *attribute)
function remove_first_attribute()
function remove_last_attribute()
function remove_attribute(xml_attribute< Ch > *where)
function remove_all_attributes()

namespace rapidxml
enum node_type
function parse_error_handler(const char *what, void *where)
function print(OutIt out, const xml_node< Ch > &node, int flags=0)
function print(std::basic_ostream< Ch > &out, const xml_node< Ch > &node, int flags=0)
function operator<<(std::basic_ostream< Ch > &out, const xml_node< Ch > &node)
- constant - parse_no_data_nodes
- constant - parse_no_element_values
- constant - parse_no_string_terminators
- constant - parse_no_entity_translation
- constant - parse_no_utf8
- constant - parse_declaration_node
- constant - parse_comment_nodes
- constant - parse_doctype_node
- constant - parse_pi_nodes
- constant - parse_validate_closing_tags
- constant - parse_trim_whitespace
- constant - parse_normalize_whitespace
- constant - parse_default
- constant - parse_non_destructive
- constant - parse_fastest
- constant - parse_full
- constant - print_no_indenting


class - template - rapidxml::memory_pool

- - Defined in rapidxml.hpp
- Base class for - xml_document

Description

This class is used by the parser to create new nodes and attributes, without overheads of dynamic memory allocation. In most cases, you will not need to use this class directly. However, if you need to create nodes manually or modify names/values of nodes, you are encouraged to use memory_pool of relevant xml_document to allocate the memory. Not only is this faster than allocating them by using new operator, but also their lifetime will be tied to the lifetime of document, possibly simplyfing memory management.

- Call allocate_node() or allocate_attribute() functions to obtain new nodes or attributes from the pool. You can also call allocate_string() function to allocate strings. Such strings can then be used as names or values of nodes without worrying about their lifetime. Note that there is no free() function -- all allocations are freed at once when clear() function is called, or when the pool is destroyed.

- It is also possible to create a standalone memory_pool, and use it to allocate nodes, whose lifetime will not be tied to any document.

- Pool maintains RAPIDXML_STATIC_POOL_SIZE bytes of statically allocated memory. Until static memory is exhausted, no dynamic memory allocations are done. When static memory is exhausted, pool allocates additional blocks of memory of size RAPIDXML_DYNAMIC_POOL_SIZE each, by using global new[] and delete[] operators. This behaviour can be changed by setting custom allocation routines. Use set_allocator() function to set them.

- Allocations for nodes, attributes and strings are aligned at RAPIDXML_ALIGNMENT bytes. This value defaults to the size of pointer on target architecture.

- To obtain absolutely top performance from the parser, it is important that all nodes are allocated from a single, contiguous block of memory. Otherwise, cache misses when jumping between two (or more) disjoint blocks of memory can slow down parsing quite considerably. If required, you can tweak RAPIDXML_STATIC_POOL_SIZE, RAPIDXML_DYNAMIC_POOL_SIZE and RAPIDXML_ALIGNMENT to obtain best wasted memory to performance compromise. To do it, define their values before rapidxml.hpp file is included.

Parameters

Ch
Character type of created nodes.

- constructor - memory_pool::memory_pool

Synopsis

memory_pool(); -

Description

Constructs empty pool with default allocator functions.

- destructor - memory_pool::~memory_pool

Synopsis

~memory_pool(); -

Description

Destroys pool and frees all the memory. This causes memory occupied by nodes allocated by the pool to be freed. Nodes allocated from the pool are no longer valid.

function memory_pool::allocate_node

Synopsis

xml_node<Ch>* allocate_node(node_type type, const Ch *name=0, const Ch *value=0, std::size_t name_size=0, std::size_t value_size=0); -

Description

Allocates a new node from the pool, and optionally assigns name and value to it. If the allocation request cannot be accomodated, this function will throw std::bad_alloc. If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function will call rapidxml::parse_error_handler() function.

Parameters

type
Type of node to create.
name
Name to assign to the node, or 0 to assign no name.
value
Value to assign to the node, or 0 to assign no value.
name_size
Size of name to assign, or 0 to automatically calculate size from name string.
value_size
Size of value to assign, or 0 to automatically calculate size from value string.

Returns

Pointer to allocated node. This pointer will never be NULL.

function memory_pool::allocate_attribute

Synopsis

xml_attribute<Ch>* allocate_attribute(const Ch *name=0, const Ch *value=0, std::size_t name_size=0, std::size_t value_size=0); -

Description

Allocates a new attribute from the pool, and optionally assigns name and value to it. If the allocation request cannot be accomodated, this function will throw std::bad_alloc. If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function will call rapidxml::parse_error_handler() function.

Parameters

name
Name to assign to the attribute, or 0 to assign no name.
value
Value to assign to the attribute, or 0 to assign no value.
name_size
Size of name to assign, or 0 to automatically calculate size from name string.
value_size
Size of value to assign, or 0 to automatically calculate size from value string.

Returns

Pointer to allocated attribute. This pointer will never be NULL.

function memory_pool::allocate_string

Synopsis

Ch* allocate_string(const Ch *source=0, std::size_t size=0); -

Description

Allocates a char array of given size from the pool, and optionally copies a given string to it. If the allocation request cannot be accomodated, this function will throw std::bad_alloc. If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function will call rapidxml::parse_error_handler() function.

Parameters

source
String to initialize the allocated memory with, or 0 to not initialize it.
size
Number of characters to allocate, or zero to calculate it automatically from source string length; if size is 0, source string must be specified and null terminated.

Returns

Pointer to allocated char array. This pointer will never be NULL.

function memory_pool::clone_node

Synopsis

xml_node<Ch>* clone_node(const xml_node< Ch > *source, xml_node< Ch > *result=0); -

Description

Clones an xml_node and its hierarchy of child nodes and attributes. Nodes and attributes are allocated from this memory pool. Names and values are not cloned, they are shared between the clone and the source. Result node can be optionally specified as a second parameter, in which case its contents will be replaced with cloned source node. This is useful when you want to clone entire document.

Parameters

source
Node to clone.
result
Node to put results in, or 0 to automatically allocate result node

Returns

Pointer to cloned node. This pointer will never be NULL.

function memory_pool::clear

Synopsis

void clear(); -

Description

Clears the pool. This causes memory occupied by nodes allocated by the pool to be freed. Any nodes or strings allocated from the pool will no longer be valid.

function memory_pool::set_allocator

Synopsis

void set_allocator(alloc_func *af, free_func *ff); -

Description

Sets or resets the user-defined memory allocation functions for the pool. This can only be called when no memory is allocated from the pool yet, otherwise results are undefined. Allocation function must not return invalid pointer on failure. It should either throw, stop the program, or use longjmp() function to pass control to other place of program. If it returns invalid pointer, results are undefined.

- User defined allocation functions must have the following forms:

-void *allocate(std::size_t size);
-void free(void *pointer);

Parameters

af
Allocation function, or 0 to restore default function
ff
Free function, or 0 to restore default function

class rapidxml::parse_error

- - Defined in rapidxml.hpp

Description

Parse error exception. This exception is thrown by the parser when an error occurs. Use what() function to get human-readable error message. Use where() function to get a pointer to position within source text where error was detected.

- If throwing exceptions by the parser is undesirable, it can be disabled by defining RAPIDXML_NO_EXCEPTIONS macro before rapidxml.hpp is included. This will cause the parser to call rapidxml::parse_error_handler() function instead of throwing an exception. This function must be defined by the user.

- This class derives from std::exception class.

- constructor - parse_error::parse_error

Synopsis

parse_error(const char *what, void *where); -

Description

Constructs parse error.

function parse_error::what

Synopsis

virtual const char* what() const; -

Description

Gets human readable description of error.

Returns

Pointer to null terminated description of the error.

function parse_error::where

Synopsis

Ch* where() const; -

Description

Gets pointer to character data where error happened. Ch should be the same as char type of xml_document that produced the error.

Returns

Pointer to location within the parsed string where error occured.

class - template - rapidxml::xml_attribute

- - Defined in rapidxml.hpp
- Inherits from - xml_base

Description

Class representing attribute node of XML document. Each attribute has name and value strings, which are available through name() and value() functions (inherited from xml_base). Note that after parse, both name and value of attribute will point to interior of source text used for parsing. Thus, this text must persist in memory for the lifetime of attribute.

Parameters

Ch
Character type to use.

- constructor - xml_attribute::xml_attribute

Synopsis

xml_attribute(); -

Description

Constructs an empty attribute with the specified type. Consider using memory_pool of appropriate xml_document if allocating attributes manually.

function xml_attribute::document

Synopsis

xml_document<Ch>* document() const; -

Description

Gets document of which attribute is a child.

Returns

Pointer to document that contains this attribute, or 0 if there is no parent document.

function xml_attribute::previous_attribute

Synopsis

xml_attribute<Ch>* previous_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; -

Description

Gets previous attribute, optionally matching attribute name.

Parameters

name
Name of attribute to find, or 0 to return previous attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found attribute, or 0 if not found.

function xml_attribute::next_attribute

Synopsis

xml_attribute<Ch>* next_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; -

Description

Gets next attribute, optionally matching attribute name.

Parameters

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
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found attribute, or 0 if not found.

class - template - rapidxml::xml_base

- - Defined in rapidxml.hpp
- Base class for - xml_attribute xml_node

Description

Base class for xml_node and xml_attribute implementing common functions: name(), name_size(), value(), value_size() and parent().

Parameters

Ch
Character type to use

- constructor - xml_base::xml_base

Synopsis

xml_base(); -

function xml_base::name

Synopsis

Ch* name() const; -

Description

Gets name of the node. Interpretation of name depends on type of node. Note that name will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse.

- Use name_size() function to determine length of the name.

Returns

Name of node, or empty string if node has no name.

function xml_base::name_size

Synopsis

std::size_t name_size() const; -

Description

Gets size of node name, not including terminator character. This function works correctly irrespective of whether name is or is not zero terminated.

Returns

Size of node name, in characters.

function xml_base::value

Synopsis

Ch* value() const; -

Description

Gets value of node. Interpretation of value depends on type of node. Note that value will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse.

- Use value_size() function to determine length of the value.

Returns

Value of node, or empty string if node has no value.

function xml_base::value_size

Synopsis

std::size_t value_size() const; -

Description

Gets size of node value, not including terminator character. This function works correctly irrespective of whether value is or is not zero terminated.

Returns

Size of node value, in characters.

function xml_base::name

Synopsis

void name(const Ch *name, std::size_t size); -

Description

Sets name of node to a non zero-terminated string. See Ownership Of Strings .

- Note that node does not own its name or value, it only stores a pointer to it. It will not delete or otherwise free the pointer on destruction. It is reponsibility of the user to properly manage lifetime of the string. The easiest way to achieve it is to use memory_pool of the document to allocate the string - on destruction of the document the string will be automatically freed.

- Size of name must be specified separately, because name does not have to be zero terminated. Use name(const Ch *) function to have the length automatically calculated (string must be zero terminated).

Parameters

name
Name of node to set. Does not have to be zero terminated.
size
Size of name, in characters. This does not include zero terminator, if one is present.

function xml_base::name

Synopsis

void name(const Ch *name); -

Description

Sets name of node to a zero-terminated string. See also Ownership Of Strings and xml_node::name(const Ch *, std::size_t).

Parameters

name
Name of node to set. Must be zero terminated.

function xml_base::value

Synopsis

void value(const Ch *value, std::size_t size); -

Description

Sets value of node to a non zero-terminated string. See Ownership Of Strings .

- Note that node does not own its name or value, it only stores a pointer to it. It will not delete or otherwise free the pointer on destruction. It is reponsibility of the user to properly manage lifetime of the string. The easiest way to achieve it is to use memory_pool of the document to allocate the string - on destruction of the document the string will be automatically freed.

- Size of value must be specified separately, because it does not have to be zero terminated. Use value(const Ch *) function to have the length automatically calculated (string must be zero terminated).

- If an element has a child node of type node_data, it will take precedence over element value when printing. 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.

Parameters

value
value of node to set. Does not have to be zero terminated.
size
Size of value, in characters. This does not include zero terminator, if one is present.

function xml_base::value

Synopsis

void value(const Ch *value); -

Description

Sets value of node to a zero-terminated string. See also Ownership Of Strings and xml_node::value(const Ch *, std::size_t).

Parameters

value
Vame of node to set. Must be zero terminated.

function xml_base::parent

Synopsis

xml_node<Ch>* parent() const; -

Description

Gets node parent.

Returns

Pointer to parent node, or 0 if there is no parent.

class - template - rapidxml::xml_document

- - Defined in rapidxml.hpp
- Inherits from - xml_node memory_pool

Description

This class represents root of the DOM hierarchy. It is also an xml_node and a memory_pool through public inheritance. Use parse() function to build a DOM tree from a zero-terminated XML text string. parse() function allocates memory for nodes and attributes by using functions of xml_document, which are inherited from memory_pool. To access root node of the document, use the document itself, as if it was an xml_node.

Parameters

Ch
Character type to use.

- constructor - xml_document::xml_document

Synopsis

xml_document(); -

Description

Constructs empty XML document.

function xml_document::parse

Synopsis

void parse(Ch *text); -

Description

Parses zero-terminated XML string according to given flags. Passed string will be modified by the parser, unless rapidxml::parse_non_destructive flag is used. The string must persist for the lifetime of the document. In case of error, rapidxml::parse_error exception will be thrown.

- If you want to parse contents of a file, you must first load the file into the memory, and pass pointer to its beginning. Make sure that data is zero-terminated.

- Document can be parsed into multiple times. Each new call to parse removes previous nodes and attributes (if any), but does not clear memory pool.

Parameters

text
XML data to parse; pointer is non-const to denote fact that this data may be modified by the parser.

function xml_document::clear

Synopsis

void clear(); -

Description

Clears the document by deleting all nodes and clearing the memory pool. All nodes owned by document pool are destroyed.

class - template - rapidxml::xml_node

- - Defined in rapidxml.hpp
- Inherits from - xml_base
- Base class for - xml_document

Description

Class representing a node of XML document. Each node may have associated name and value strings, which are available through name() and value() functions. Interpretation of name and value depends on type of the node. Type of node can be determined by using type() function.

- Note that after parse, both name and value of node, if any, will point interior of source text used for parsing. Thus, this text must persist in the memory for the lifetime of node.

Parameters

Ch
Character type to use.

- constructor - xml_node::xml_node

Synopsis

xml_node(node_type type); -

Description

Constructs an empty node with the specified type. Consider using memory_pool of appropriate document to allocate nodes manually.

Parameters

type
Type of node to construct.

function xml_node::type

Synopsis

node_type type() const; -

Description

Gets type of node.

Returns

Type of node.

function xml_node::document

Synopsis

xml_document<Ch>* document() const; -

Description

Gets document of which node is a child.

Returns

Pointer to document that contains this node, or 0 if there is no parent document.

function xml_node::first_node

Synopsis

xml_node<Ch>* first_node(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; -

Description

Gets first child node, optionally matching node name.

Parameters

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
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found child, or 0 if not found.

function xml_node::last_node

Synopsis

xml_node<Ch>* last_node(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; -

Description

Gets last child node, optionally matching node name. Behaviour is undefined if node has no children. Use first_node() to test if node has children.

Parameters

name
Name of child to find, or 0 to return last child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found child, or 0 if not found.

function xml_node::previous_sibling

Synopsis

xml_node<Ch>* previous_sibling(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; -

Description

Gets previous sibling node, optionally matching node name. Behaviour is undefined if node has no parent. Use parent() to test if node has a parent.

Parameters

name
Name of sibling to find, or 0 to return previous sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found sibling, or 0 if not found.

function xml_node::next_sibling

Synopsis

xml_node<Ch>* next_sibling(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; -

Description

Gets next sibling node, optionally matching node name. Behaviour is undefined if node has no parent. Use parent() to test if node has a parent.

Parameters

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
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found sibling, or 0 if not found.

function xml_node::first_attribute

Synopsis

xml_attribute<Ch>* first_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; -

Description

Gets first attribute of node, optionally matching attribute name.

Parameters

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
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found attribute, or 0 if not found.

function xml_node::last_attribute

Synopsis

xml_attribute<Ch>* last_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const; -

Description

Gets last attribute of node, optionally matching attribute name.

Parameters

name
Name of attribute to find, or 0 to return last attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero
name_size
Size of name, in characters, or 0 to have size calculated automatically from string
case_sensitive
Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters

Returns

Pointer to found attribute, or 0 if not found.

function xml_node::type

Synopsis

void type(node_type type); -

Description

Sets type of node.

Parameters

type
Type of node to set.

function xml_node::prepend_node

Synopsis

void prepend_node(xml_node< Ch > *child); -

Description

Prepends a new child node. The prepended child becomes the first child, and all existing children are moved one position back.

Parameters

child
Node to prepend.

function xml_node::append_node

Synopsis

void append_node(xml_node< Ch > *child); -

Description

Appends a new child node. The appended child becomes the last child.

Parameters

child
Node to append.

function xml_node::insert_node

Synopsis

void insert_node(xml_node< Ch > *where, xml_node< Ch > *child); -

Description

Inserts a new child node at specified place inside the node. All children after and including the specified node are moved one position back.

Parameters

where
Place where to insert the child, or 0 to insert at the back.
child
Node to insert.

function xml_node::remove_first_node

Synopsis

void remove_first_node(); -

Description

Removes first child node. If node has no children, behaviour is undefined. Use first_node() to test if node has children.

function xml_node::remove_last_node

Synopsis

void remove_last_node(); -

Description

Removes last child of the node. If node has no children, behaviour is undefined. Use first_node() to test if node has children.

function xml_node::remove_node

Synopsis

void remove_node(xml_node< Ch > *where); -

Description

Removes specified child from the node.

function xml_node::remove_all_nodes

Synopsis

void remove_all_nodes(); -

Description

Removes all child nodes (but not attributes).

function xml_node::prepend_attribute

Synopsis

void prepend_attribute(xml_attribute< Ch > *attribute); -

Description

Prepends a new attribute to the node.

Parameters

attribute
Attribute to prepend.

function xml_node::append_attribute

Synopsis

void append_attribute(xml_attribute< Ch > *attribute); -

Description

Appends a new attribute to the node.

Parameters

attribute
Attribute to append.

function xml_node::insert_attribute

Synopsis

void insert_attribute(xml_attribute< Ch > *where, xml_attribute< Ch > *attribute); -

Description

Inserts a new attribute at specified place inside the node. All attributes after and including the specified attribute are moved one position back.

Parameters

where
Place where to insert the attribute, or 0 to insert at the back.
attribute
Attribute to insert.

function xml_node::remove_first_attribute

Synopsis

void remove_first_attribute(); -

Description

Removes first attribute of the node. If node has no attributes, behaviour is undefined. Use first_attribute() to test if node has attributes.

function xml_node::remove_last_attribute

Synopsis

void remove_last_attribute(); -

Description

Removes last attribute of the node. If node has no attributes, behaviour is undefined. Use first_attribute() to test if node has attributes.

function xml_node::remove_attribute

Synopsis

void remove_attribute(xml_attribute< Ch > *where); -

Description

Removes specified attribute from node.

Parameters

where
Pointer to attribute to be removed.

function xml_node::remove_all_attributes

Synopsis

void remove_all_attributes(); -

Description

Removes all attributes of node.

enum node_type

Description

Enumeration listing all node types produced by the parser. Use xml_node::type() function to query node type.

Values

node_document
A document node. Name and value are empty.
node_element
An element node. Name contains element name. Value contains text of first data node.
node_data
A data node. Name is empty. Value contains data text.
node_cdata
A CDATA node. Name is empty. Value contains data text.
node_comment
A comment node. Name is empty. Value contains comment text.
node_declaration
A declaration node. Name and value are empty. Declaration parameters (version, encoding and standalone) are in node attributes.
node_doctype
A DOCTYPE node. Name is empty. Value contains DOCTYPE text.
node_pi
A PI node. Name contains target. Value contains instructions.

function parse_error_handler

Synopsis

void rapidxml::parse_error_handler(const char *what, void *where); -

Description

When exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function is called to notify user about the error. It must be defined by the user.

- This function cannot return. If it does, the results are undefined.

- A very simple definition might look like that: - void rapidxml::parse_error_handler(const char *what, void *where) - { - std::cout << "Parse error: " << what << "\n"; - std::abort(); - } -

Parameters

what
Human readable description of the error.
where
Pointer to character data where error was detected.

function print

Synopsis

OutIt rapidxml::print(OutIt out, const xml_node< Ch > &node, int flags=0); -

Description

Prints XML to given output iterator.

Parameters

out
Output iterator to print to.
node
Node to be printed. Pass xml_document to print entire document.
flags
Flags controlling how XML is printed.

Returns

Output iterator pointing to position immediately after last character of printed text.

function print

Synopsis

std::basic_ostream<Ch>& rapidxml::print(std::basic_ostream< Ch > &out, const xml_node< Ch > &node, int flags=0); -

Description

Prints XML to given output stream.

Parameters

out
Output stream to print to.
node
Node to be printed. Pass xml_document to print entire document.
flags
Flags controlling how XML is printed.

Returns

Output stream.

function operator<<

Synopsis

std::basic_ostream<Ch>& rapidxml::operator<<(std::basic_ostream< Ch > &out, const xml_node< Ch > &node); -

Description

Prints formatted XML to given output stream. Uses default printing flags. Use print() function to customize printing process.

Parameters

out
Output stream to print to.
node
Node to be printed.

Returns

Output stream.

- constant - parse_no_data_nodes

Synopsis

const int parse_no_data_nodes - = 0x1; -

Description

Parse flag instructing the parser to not create data nodes. Text of first data node will still be placed in value of parent element, unless rapidxml::parse_no_element_values flag is also specified. Can be combined with other flags by use of | operator.

- See xml_document::parse() function.

- constant - parse_no_element_values

Synopsis

const int parse_no_element_values - = 0x2; -

Description

Parse flag instructing the parser to not use text of first data node as a value of parent element. Can be combined with other flags by use of | operator. Note that child data nodes of element node take precendence over its value when printing. That is, if element has one or more child data nodes and a value, the value will be ignored. Use rapidxml::parse_no_data_nodes flag to prevent creation of data nodes if you want to manipulate data using values of elements.

- See xml_document::parse() function.

- constant - parse_no_string_terminators

Synopsis

const int parse_no_string_terminators - = 0x4; -

Description

Parse flag instructing the parser to not place zero terminators after strings in the source text. By default zero terminators are placed, modifying source text. Can be combined with other flags by use of | operator.

- See xml_document::parse() function.

- constant - parse_no_entity_translation

Synopsis

const int parse_no_entity_translation - = 0x8; -

Description

Parse flag instructing the parser to not translate entities in the source text. By default entities are translated, modifying source text. Can be combined with other flags by use of | operator.

- See xml_document::parse() function.

- constant - parse_no_utf8

Synopsis

const int parse_no_utf8 - = 0x10; -

Description

Parse flag instructing the parser to disable UTF-8 handling and assume plain 8 bit characters. By default, UTF-8 handling is enabled. Can be combined with other flags by use of | operator.

- See xml_document::parse() function.

- constant - parse_declaration_node

Synopsis

const int parse_declaration_node - = 0x20; -

Description

Parse flag instructing the parser to create XML declaration node. By default, declaration node is not created. Can be combined with other flags by use of | operator.

- See xml_document::parse() function.

- constant - parse_comment_nodes

Synopsis

const int parse_comment_nodes - = 0x40; -

Description

Parse flag instructing the parser to create comments nodes. By default, comment nodes are not created. Can be combined with other flags by use of | operator.

- See xml_document::parse() function.

- constant - parse_doctype_node

Synopsis

const int parse_doctype_node - = 0x80; -

Description

Parse flag instructing the parser to create DOCTYPE node. By default, doctype node is not created. Although W3C specification allows at most one DOCTYPE node, RapidXml will silently accept documents with more than one. Can be combined with other flags by use of | operator.

- See xml_document::parse() function.

- constant - parse_pi_nodes

Synopsis

const int parse_pi_nodes - = 0x100; -

Description

Parse flag instructing the parser to create PI nodes. By default, PI nodes are not created. Can be combined with other flags by use of | operator.

- See xml_document::parse() function.

- constant - parse_validate_closing_tags

Synopsis

const int parse_validate_closing_tags - = 0x200; -

Description

Parse flag instructing the parser to validate closing tag names. If not set, name inside closing tag is irrelevant to the parser. By default, closing tags are not validated. Can be combined with other flags by use of | operator.

- See xml_document::parse() function.

- constant - parse_trim_whitespace

Synopsis

const int parse_trim_whitespace - = 0x400; -

Description

Parse flag instructing the parser to trim all leading and trailing whitespace of data nodes. By default, whitespace is not trimmed. This flag does not cause the parser to modify source text. Can be combined with other flags by use of | operator.

- See xml_document::parse() function.

- constant - parse_normalize_whitespace

Synopsis

const int parse_normalize_whitespace - = 0x800; -

Description

Parse flag instructing the parser to condense all whitespace runs of data nodes to a single space character. Trimming of leading and trailing whitespace of data is controlled by rapidxml::parse_trim_whitespace flag. By default, whitespace is not normalized. If this flag is specified, source text will be modified. Can be combined with other flags by use of | operator.

- See xml_document::parse() function.

- constant - parse_default

Synopsis

const int parse_default - = 0; -

Description

Parse flags which represent default behaviour of the parser. This is always equal to 0, so that all other flags can be simply ored together. Normally there is no need to inconveniently disable flags by anding with their negated (~) values. This also means that meaning of each flag is a negation of the default setting. For example, if flag name is rapidxml::parse_no_utf8, it means that utf-8 is enabled by default, and using the flag will disable it.

- See xml_document::parse() function.

- constant - parse_non_destructive

Synopsis

const int parse_non_destructive - = parse_no_string_terminators | parse_no_entity_translation; -

Description

A combination of parse flags that forbids any modifications of the source text. This also results in faster parsing. However, note that the following will occur:
  • names and values of nodes will not be zero terminated, you have to use xml_base::name_size() and xml_base::value_size() functions to determine where name and value ends
  • entities will not be translated
  • whitespace will not be normalized
-See xml_document::parse() function.

- constant - parse_fastest

Synopsis

const int parse_fastest - = parse_non_destructive | parse_no_data_nodes; -

Description

A combination of parse flags resulting in fastest possible parsing, without sacrificing important data.

- See xml_document::parse() function.

- constant - parse_full

Synopsis

const int parse_full - = parse_declaration_node | parse_comment_nodes | parse_doctype_node | parse_pi_nodes | parse_validate_closing_tags; -

Description

A combination of parse flags resulting in largest amount of data being extracted. This usually results in slowest parsing.

- See xml_document::parse() function.

- constant - print_no_indenting

Synopsis

const int print_no_indenting - = 0x1; -

Description

Printer flag instructing the printer to suppress indenting of XML. See print() function.

\ No newline at end of file diff --git a/include/cereal/external/rapidxml/rapidxml.hpp b/include/cereal/external/rapidxml/rapidxml.hpp deleted file mode 100644 index d82893a..0000000 --- a/include/cereal/external/rapidxml/rapidxml.hpp +++ /dev/null @@ -1,2624 +0,0 @@ -#ifndef CEREAL_RAPIDXML_HPP_INCLUDED -#define CEREAL_RAPIDXML_HPP_INCLUDED - -// Copyright (C) 2006, 2009 Marcin Kalicinski -// Version 1.13 -// Revision $DateTime: 2009/05/13 01:46:17 $ - -// If standard library is disabled, user must provide implementations of required functions and typedefs -#if !defined(CEREAL_RAPIDXML_NO_STDLIB) - #include // For std::size_t - #include // For assert - #include // For placement new -#endif - -// On MSVC, disable "conditional expression is constant" warning (level 4). -// This warning is almost impossible to avoid with certain types of templated code -#ifdef _MSC_VER - #pragma warning(push) - #pragma warning(disable:4127) // Conditional expression is constant - #pragma warning(disable:4100) // unreferenced formal parameter -#endif - -/////////////////////////////////////////////////////////////////////////// -// CEREAL_RAPIDXML_PARSE_ERROR - -#if defined(CEREAL_RAPIDXML_NO_EXCEPTIONS) - -#define CEREAL_RAPIDXML_PARSE_ERROR(what, where) { parse_error_handler(what, where); assert(0); } - -namespace cereal { -namespace rapidxml -{ - //! When exceptions are disabled by defining CEREAL_RAPIDXML_NO_EXCEPTIONS, - //! this function is called to notify user about the error. - //! It must be defined by the user. - //!

- //! This function cannot return. If it does, the results are undefined. - //!

- //! A very simple definition might look like that: - //!

-    //! void %rapidxml::%parse_error_handler(const char *what, void *where)
-    //! {
-    //!     std::cout << "Parse error: " << what << "\n";
-    //!     std::abort();
-    //! }
-    //! 
- //! \param what Human readable description of the error. - //! \param where Pointer to character data where error was detected. - void parse_error_handler(const char *what, void *where); -} -} // end namespace cereal - -#else - -#include // For std::exception - -#define CEREAL_RAPIDXML_PARSE_ERROR(what, where) throw parse_error(what, where) - -namespace cereal { -namespace rapidxml -{ - - //! Parse error exception. - //! This exception is thrown by the parser when an error occurs. - //! Use what() function to get human-readable error message. - //! Use where() function to get a pointer to position within source text where error was detected. - //!

- //! If throwing exceptions by the parser is undesirable, - //! it can be disabled by defining CEREAL_RAPIDXML_NO_EXCEPTIONS macro before rapidxml.hpp is included. - //! This will cause the parser to call rapidxml::parse_error_handler() function instead of throwing an exception. - //! This function must be defined by the user. - //!

- //! This class derives from std::exception class. - class parse_error: public std::exception - { - - public: - - //! Constructs parse error - parse_error(const char *what_, void *where_) - : m_what(what_) - , m_where(where_) - { - } - - //! Gets human readable description of error. - //! \return Pointer to null terminated description of the error. - virtual const char *what() const CEREAL_NOEXCEPT override - { - return m_what; - } - - //! Gets pointer to character data where error happened. - //! Ch should be the same as char type of xml_document that produced the error. - //! \return Pointer to location within the parsed string where error occured. - template - Ch *where() const - { - return reinterpret_cast(m_where); - } - - private: - - const char *m_what; - void *m_where; - - }; -} -} // end namespace cereal - -#endif - -/////////////////////////////////////////////////////////////////////////// -// Pool sizes - -#ifndef CEREAL_RAPIDXML_STATIC_POOL_SIZE - // Size of static memory block of memory_pool. - // Define CEREAL_RAPIDXML_STATIC_POOL_SIZE before including rapidxml.hpp if you want to override the default value. - // No dynamic memory allocations are performed by memory_pool until static memory is exhausted. - #define CEREAL_RAPIDXML_STATIC_POOL_SIZE (64 * 1024) -#endif - -#ifndef CEREAL_RAPIDXML_DYNAMIC_POOL_SIZE - // Size of dynamic memory block of memory_pool. - // Define CEREAL_RAPIDXML_DYNAMIC_POOL_SIZE before including rapidxml.hpp if you want to override the default value. - // After the static block is exhausted, dynamic blocks with approximately this size are allocated by memory_pool. - #define CEREAL_RAPIDXML_DYNAMIC_POOL_SIZE (64 * 1024) -#endif - -#ifndef CEREAL_RAPIDXML_ALIGNMENT - // Memory allocation alignment. - // Define CEREAL_RAPIDXML_ALIGNMENT before including rapidxml.hpp if you want to override the default value, which is the size of pointer. - // All memory allocations for nodes, attributes and strings will be aligned to this value. - // This must be a power of 2 and at least 1, otherwise memory_pool will not work. - #define CEREAL_RAPIDXML_ALIGNMENT sizeof(void *) -#endif - -namespace cereal { -namespace rapidxml -{ - // Forward declarations - template class xml_node; - template class xml_attribute; - template class xml_document; - - //! Enumeration listing all node types produced by the parser. - //! Use xml_node::type() function to query node type. - enum node_type - { - node_document, //!< A document node. Name and value are empty. - node_element, //!< An element node. Name contains element name. Value contains text of first data node. - node_data, //!< A data node. Name is empty. Value contains data text. - node_cdata, //!< A CDATA node. Name is empty. Value contains data text. - node_comment, //!< A comment node. Name is empty. Value contains comment text. - node_declaration, //!< A declaration node. Name and value are empty. Declaration parameters (version, encoding and standalone) are in node attributes. - node_doctype, //!< A DOCTYPE node. Name is empty. Value contains DOCTYPE text. - node_pi //!< A PI node. Name contains target. Value contains instructions. - }; - - /////////////////////////////////////////////////////////////////////// - // Parsing flags - - //! Parse flag instructing the parser to not create data nodes. - //! Text of first data node will still be placed in value of parent element, unless rapidxml::parse_no_element_values flag is also specified. - //! Can be combined with other flags by use of | operator. - //!

- //! See xml_document::parse() function. - const int parse_no_data_nodes = 0x1; - - //! Parse flag instructing the parser to not use text of first data node as a value of parent element. - //! Can be combined with other flags by use of | operator. - //! Note that child data nodes of element node take precendence over its value when printing. - //! That is, if element has one or more child data nodes and a value, the value will be ignored. - //! Use rapidxml::parse_no_data_nodes flag to prevent creation of data nodes if you want to manipulate data using values of elements. - //!

- //! See xml_document::parse() function. - const int parse_no_element_values = 0x2; - - //! Parse flag instructing the parser to not place zero terminators after strings in the source text. - //! By default zero terminators are placed, modifying source text. - //! Can be combined with other flags by use of | operator. - //!

- //! See xml_document::parse() function. - const int parse_no_string_terminators = 0x4; - - //! Parse flag instructing the parser to not translate entities in the source text. - //! By default entities are translated, modifying source text. - //! Can be combined with other flags by use of | operator. - //!

- //! See xml_document::parse() function. - const int parse_no_entity_translation = 0x8; - - //! Parse flag instructing the parser to disable UTF-8 handling and assume plain 8 bit characters. - //! By default, UTF-8 handling is enabled. - //! Can be combined with other flags by use of | operator. - //!

- //! See xml_document::parse() function. - const int parse_no_utf8 = 0x10; - - //! Parse flag instructing the parser to create XML declaration node. - //! By default, declaration node is not created. - //! Can be combined with other flags by use of | operator. - //!

- //! See xml_document::parse() function. - const int parse_declaration_node = 0x20; - - //! Parse flag instructing the parser to create comments nodes. - //! By default, comment nodes are not created. - //! Can be combined with other flags by use of | operator. - //!

- //! See xml_document::parse() function. - const int parse_comment_nodes = 0x40; - - //! Parse flag instructing the parser to create DOCTYPE node. - //! By default, doctype node is not created. - //! Although W3C specification allows at most one DOCTYPE node, RapidXml will silently accept documents with more than one. - //! Can be combined with other flags by use of | operator. - //!

- //! See xml_document::parse() function. - const int parse_doctype_node = 0x80; - - //! Parse flag instructing the parser to create PI nodes. - //! By default, PI nodes are not created. - //! Can be combined with other flags by use of | operator. - //!

- //! See xml_document::parse() function. - const int parse_pi_nodes = 0x100; - - //! Parse flag instructing the parser to validate closing tag names. - //! If not set, name inside closing tag is irrelevant to the parser. - //! By default, closing tags are not validated. - //! Can be combined with other flags by use of | operator. - //!

- //! See xml_document::parse() function. - const int parse_validate_closing_tags = 0x200; - - //! Parse flag instructing the parser to trim all leading and trailing whitespace of data nodes. - //! By default, whitespace is not trimmed. - //! This flag does not cause the parser to modify source text. - //! Can be combined with other flags by use of | operator. - //!

- //! See xml_document::parse() function. - const int parse_trim_whitespace = 0x400; - - //! Parse flag instructing the parser to condense all whitespace runs of data nodes to a single space character. - //! Trimming of leading and trailing whitespace of data is controlled by rapidxml::parse_trim_whitespace flag. - //! By default, whitespace is not normalized. - //! If this flag is specified, source text will be modified. - //! Can be combined with other flags by use of | operator. - //!

- //! See xml_document::parse() function. - const int parse_normalize_whitespace = 0x800; - - // Compound flags - - //! Parse flags which represent default behaviour of the parser. - //! This is always equal to 0, so that all other flags can be simply ored together. - //! Normally there is no need to inconveniently disable flags by anding with their negated (~) values. - //! This also means that meaning of each flag is a negation of the default setting. - //! For example, if flag name is rapidxml::parse_no_utf8, it means that utf-8 is enabled by default, - //! and using the flag will disable it. - //!

- //! See xml_document::parse() function. - const int parse_default = 0; - - //! A combination of parse flags that forbids any modifications of the source text. - //! This also results in faster parsing. However, note that the following will occur: - //!
    - //!
  • names and values of nodes will not be zero terminated, you have to use xml_base::name_size() and xml_base::value_size() functions to determine where name and value ends
  • - //!
  • entities will not be translated
  • - //!
  • whitespace will not be normalized
  • - //!
- //! See xml_document::parse() function. - const int parse_non_destructive = parse_no_string_terminators | parse_no_entity_translation; - - //! A combination of parse flags resulting in fastest possible parsing, without sacrificing important data. - //!

- //! See xml_document::parse() function. - const int parse_fastest = parse_non_destructive | parse_no_data_nodes; - - //! A combination of parse flags resulting in largest amount of data being extracted. - //! This usually results in slowest parsing. - //!

- //! See xml_document::parse() function. - const int parse_full = parse_declaration_node | parse_comment_nodes | parse_doctype_node | parse_pi_nodes | parse_validate_closing_tags; - - /////////////////////////////////////////////////////////////////////// - // Internals - - //! \cond internal - namespace internal - { - - // Struct that contains lookup tables for the parser - // It must be a template to allow correct linking (because it has static data members, which are defined in a header file). - template - struct lookup_tables - { - static const unsigned char lookup_whitespace[256]; // Whitespace table - static const unsigned char lookup_node_name[256]; // Node name table - static const unsigned char lookup_text[256]; // Text table - static const unsigned char lookup_text_pure_no_ws[256]; // Text table - static const unsigned char lookup_text_pure_with_ws[256]; // Text table - static const unsigned char lookup_attribute_name[256]; // Attribute name table - static const unsigned char lookup_attribute_data_1[256]; // Attribute data table with single quote - static const unsigned char lookup_attribute_data_1_pure[256]; // Attribute data table with single quote - static const unsigned char lookup_attribute_data_2[256]; // Attribute data table with double quotes - static const unsigned char lookup_attribute_data_2_pure[256]; // Attribute data table with double quotes - static const unsigned char lookup_digits[256]; // Digits - static const unsigned char lookup_upcase[256]; // To uppercase conversion table for ASCII characters - }; - - // Find length of the string - template - inline std::size_t measure(const Ch *p) - { - const Ch *tmp = p; - while (*tmp) - ++tmp; - return static_cast(tmp - p); - } - - // Compare strings for equality - template - inline bool compare(const Ch *p1, std::size_t size1, const Ch *p2, std::size_t size2, bool case_sensitive) - { - if (size1 != size2) - return false; - if (case_sensitive) - { - for (const Ch *end = p1 + size1; p1 < end; ++p1, ++p2) - if (*p1 != *p2) - return false; - } - else - { - for (const Ch *end = p1 + size1; p1 < end; ++p1, ++p2) - if (lookup_tables<0>::lookup_upcase[static_cast(*p1)] != lookup_tables<0>::lookup_upcase[static_cast(*p2)]) - return false; - } - return true; - } - - template - inline bool preserve_space(xml_node* node) - { - const Ch preserve_value[] = { Ch('p'), Ch('r'), Ch('e'), Ch('s'), Ch('e'), Ch('r'), Ch('v'), Ch('e') }; - const xml_attribute* space = node->first_attribute("xml:space"); - return space && internal::compare(space->value(), space->value_size(), preserve_value, sizeof(preserve_value) / sizeof(Ch), true); - } - } - //! \endcond - - /////////////////////////////////////////////////////////////////////// - // Memory pool - - //! This class is used by the parser to create new nodes and attributes, without overheads of dynamic memory allocation. - //! In most cases, you will not need to use this class directly. - //! However, if you need to create nodes manually or modify names/values of nodes, - //! you are encouraged to use memory_pool of relevant xml_document to allocate the memory. - //! Not only is this faster than allocating them by using new operator, - //! but also their lifetime will be tied to the lifetime of document, - //! possibly simplyfing memory management. - //!

- //! Call allocate_node() or allocate_attribute() functions to obtain new nodes or attributes from the pool. - //! You can also call allocate_string() function to allocate strings. - //! Such strings can then be used as names or values of nodes without worrying about their lifetime. - //! Note that there is no free() function -- all allocations are freed at once when clear() function is called, - //! or when the pool is destroyed. - //!

- //! It is also possible to create a standalone memory_pool, and use it - //! to allocate nodes, whose lifetime will not be tied to any document. - //!

- //! Pool maintains CEREAL_RAPIDXML_STATIC_POOL_SIZE bytes of statically allocated memory. - //! Until static memory is exhausted, no dynamic memory allocations are done. - //! When static memory is exhausted, pool allocates additional blocks of memory of size CEREAL_RAPIDXML_DYNAMIC_POOL_SIZE each, - //! by using global new[] and delete[] operators. - //! This behaviour can be changed by setting custom allocation routines. - //! Use set_allocator() function to set them. - //!

- //! Allocations for nodes, attributes and strings are aligned at CEREAL_RAPIDXML_ALIGNMENT bytes. - //! This value defaults to the size of pointer on target architecture. - //!

- //! To obtain absolutely top performance from the parser, - //! it is important that all nodes are allocated from a single, contiguous block of memory. - //! Otherwise, cache misses when jumping between two (or more) disjoint blocks of memory can slow down parsing quite considerably. - //! If required, you can tweak CEREAL_RAPIDXML_STATIC_POOL_SIZE, CEREAL_RAPIDXML_DYNAMIC_POOL_SIZE and CEREAL_RAPIDXML_ALIGNMENT - //! to obtain best wasted memory to performance compromise. - //! To do it, define their values before rapidxml.hpp file is included. - //! \tparam Ch Character type of created nodes. - template - class memory_pool - { - - public: - - //! \cond internal - typedef void *(alloc_func)(std::size_t); // Type of user-defined function used to allocate memory - typedef void (free_func)(void *); // Type of user-defined function used to free memory - //! \endcond - - //! Constructs empty pool with default allocator functions. - memory_pool() - : m_alloc_func(0) - , m_free_func(0) - { - init(); - } - - //! Destroys pool and frees all the memory. - //! This causes memory occupied by nodes allocated by the pool to be freed. - //! Nodes allocated from the pool are no longer valid. - ~memory_pool() - { - clear(); - } - - //! Allocates a new node from the pool, and optionally assigns name and value to it. - //! If the allocation request cannot be accomodated, this function will throw std::bad_alloc. - //! If exceptions are disabled by defining CEREAL_RAPIDXML_NO_EXCEPTIONS, this function - //! will call rapidxml::parse_error_handler() function. - //! \param type Type of node to create. - //! \param name Name to assign to the node, or 0 to assign no name. - //! \param value Value to assign to the node, or 0 to assign no value. - //! \param name_size Size of name to assign, or 0 to automatically calculate size from name string. - //! \param value_size Size of value to assign, or 0 to automatically calculate size from value string. - //! \return Pointer to allocated node. This pointer will never be NULL. - xml_node *allocate_node(node_type type, - const Ch *name = 0, const Ch *value = 0, - std::size_t name_size = 0, std::size_t value_size = 0) - { - void *memory = allocate_aligned(sizeof(xml_node)); - xml_node *node = new(memory) xml_node(type); - if (name) - { - if (name_size > 0) - node->name(name, name_size); - else - node->name(name); - } - if (value) - { - if (value_size > 0) - node->value(value, value_size); - else - node->value(value); - } - return node; - } - - //! Allocates a new attribute from the pool, and optionally assigns name and value to it. - //! If the allocation request cannot be accomodated, this function will throw std::bad_alloc. - //! If exceptions are disabled by defining CEREAL_RAPIDXML_NO_EXCEPTIONS, this function - //! will call rapidxml::parse_error_handler() function. - //! \param name Name to assign to the attribute, or 0 to assign no name. - //! \param value Value to assign to the attribute, or 0 to assign no value. - //! \param name_size Size of name to assign, or 0 to automatically calculate size from name string. - //! \param value_size Size of value to assign, or 0 to automatically calculate size from value string. - //! \return Pointer to allocated attribute. This pointer will never be NULL. - xml_attribute *allocate_attribute(const Ch *name = 0, const Ch *value = 0, - std::size_t name_size = 0, std::size_t value_size = 0) - { - void *memory = allocate_aligned(sizeof(xml_attribute)); - xml_attribute *attribute = new(memory) xml_attribute; - if (name) - { - if (name_size > 0) - attribute->name(name, name_size); - else - attribute->name(name); - } - if (value) - { - if (value_size > 0) - attribute->value(value, value_size); - else - attribute->value(value); - } - return attribute; - } - - //! Allocates a char array of given size from the pool, and optionally copies a given string to it. - //! If the allocation request cannot be accomodated, this function will throw std::bad_alloc. - //! If exceptions are disabled by defining CEREAL_RAPIDXML_NO_EXCEPTIONS, this function - //! will call rapidxml::parse_error_handler() function. - //! \param source String to initialize the allocated memory with, or 0 to not initialize it. - //! \param size Number of characters to allocate, or zero to calculate it automatically from source string length; if size is 0, source string must be specified and null terminated. - //! \return Pointer to allocated char array. This pointer will never be NULL. - Ch *allocate_string(const Ch *source = 0, std::size_t size = 0) - { - assert(source || size); // Either source or size (or both) must be specified - if (size == 0) - size = internal::measure(source) + 1; - Ch *result = static_cast(allocate_aligned(size * sizeof(Ch))); - if (source) - for (std::size_t i = 0; i < size; ++i) - result[i] = source[i]; - return result; - } - - //! Clones an xml_node and its hierarchy of child nodes and attributes. - //! Nodes and attributes are allocated from this memory pool. - //! Names and values are not cloned, they are shared between the clone and the source. - //! Result node can be optionally specified as a second parameter, - //! in which case its contents will be replaced with cloned source node. - //! This is useful when you want to clone entire document. - //! \param source Node to clone. - //! \param result Node to put results in, or 0 to automatically allocate result node - //! \return Pointer to cloned node. This pointer will never be NULL. - xml_node *clone_node(const xml_node *source, xml_node *result = 0) - { - // Prepare result node - if (result) - { - result->remove_all_attributes(); - result->remove_all_nodes(); - result->type(source->type()); - } - else - result = allocate_node(source->type()); - - // Clone name and value - result->name(source->name(), source->name_size()); - result->value(source->value(), source->value_size()); - - // Clone child nodes and attributes - for (xml_node *child = source->first_node(); child; child = child->next_sibling()) - result->append_node(clone_node(child)); - for (xml_attribute *attr = source->first_attribute(); attr; attr = attr->next_attribute()) - result->append_attribute(allocate_attribute(attr->name(), attr->value(), attr->name_size(), attr->value_size())); - - return result; - } - - //! Clears the pool. - //! This causes memory occupied by nodes allocated by the pool to be freed. - //! Any nodes or strings allocated from the pool will no longer be valid. - void clear() - { - while (m_begin != m_static_memory) - { - char *previous_begin = reinterpret_cast
(align(m_begin))->previous_begin; - if (m_free_func) - m_free_func(m_begin); - else - delete[] m_begin; - m_begin = previous_begin; - } - init(); - } - - //! Sets or resets the user-defined memory allocation functions for the pool. - //! This can only be called when no memory is allocated from the pool yet, otherwise results are undefined. - //! Allocation function must not return invalid pointer on failure. It should either throw, - //! stop the program, or use longjmp() function to pass control to other place of program. - //! If it returns invalid pointer, results are undefined. - //!

- //! User defined allocation functions must have the following forms: - //!
- //!
void *allocate(std::size_t size); - //!
void free(void *pointer); - //!

- //! \param af Allocation function, or 0 to restore default function - //! \param ff Free function, or 0 to restore default function - void set_allocator(alloc_func *af, free_func *ff) - { - assert(m_begin == m_static_memory && m_ptr == align(m_begin)); // Verify that no memory is allocated yet - m_alloc_func = af; - m_free_func = ff; - } - - private: - - struct header - { - char *previous_begin; - }; - - void init() - { - m_begin = m_static_memory; - m_ptr = align(m_begin); - m_end = m_static_memory + sizeof(m_static_memory); - } - - char *align(char *ptr) - { - std::size_t alignment = ((CEREAL_RAPIDXML_ALIGNMENT - (std::size_t(ptr) & (CEREAL_RAPIDXML_ALIGNMENT - 1))) & (CEREAL_RAPIDXML_ALIGNMENT - 1)); - return ptr + alignment; - } - - char *allocate_raw(std::size_t size) - { - // Allocate - void *memory; - if (m_alloc_func) // Allocate memory using either user-specified allocation function or global operator new[] - { - memory = m_alloc_func(size); - assert(memory); // Allocator is not allowed to return 0, on failure it must either throw, stop the program or use longjmp - } - else - { - memory = new char[size]; -#ifdef CEREAL_RAPIDXML_NO_EXCEPTIONS - if (!memory) // If exceptions are disabled, verify memory allocation, because new will not be able to throw bad_alloc - CEREAL_RAPIDXML_PARSE_ERROR("out of memory", 0); -#endif - } - return static_cast(memory); - } - - void *allocate_aligned(std::size_t size) - { - // Calculate aligned pointer - char *result = align(m_ptr); - - // If not enough memory left in current pool, allocate a new pool - if (result + size > m_end) - { - // Calculate required pool size (may be bigger than CEREAL_RAPIDXML_DYNAMIC_POOL_SIZE) - std::size_t pool_size = CEREAL_RAPIDXML_DYNAMIC_POOL_SIZE; - if (pool_size < size) - pool_size = size; - - // Allocate - std::size_t alloc_size = sizeof(header) + (2 * CEREAL_RAPIDXML_ALIGNMENT - 2) + pool_size; // 2 alignments required in worst case: one for header, one for actual allocation - char *raw_memory = allocate_raw(alloc_size); - - // Setup new pool in allocated memory - char *pool = align(raw_memory); - header *new_header = reinterpret_cast
(pool); - new_header->previous_begin = m_begin; - m_begin = raw_memory; - m_ptr = pool + sizeof(header); - m_end = raw_memory + alloc_size; - - // Calculate aligned pointer again using new pool - result = align(m_ptr); - } - - // Update pool and return aligned pointer - m_ptr = result + size; - return result; - } - - char *m_begin; // Start of raw memory making up current pool - char *m_ptr; // First free byte in current pool - char *m_end; // One past last available byte in current pool - char m_static_memory[CEREAL_RAPIDXML_STATIC_POOL_SIZE]; // Static raw memory - alloc_func *m_alloc_func; // Allocator function, or 0 if default is to be used - free_func *m_free_func; // Free function, or 0 if default is to be used - }; - - /////////////////////////////////////////////////////////////////////////// - // XML base - - //! Base class for xml_node and xml_attribute implementing common functions: - //! name(), name_size(), value(), value_size() and parent(). - //! \tparam Ch Character type to use - template - class xml_base - { - - public: - - /////////////////////////////////////////////////////////////////////////// - // Construction & destruction - - // Construct a base with empty name, value and parent - xml_base() - : m_name(0) - , m_value(0) - , m_parent(0) - { - } - - /////////////////////////////////////////////////////////////////////////// - // Node data access - - //! Gets name of the node. - //! Interpretation of name depends on type of node. - //! Note that name will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse. - //!

- //! Use name_size() function to determine length of the name. - //! \return Name of node, or empty string if node has no name. - Ch *name() const - { - return m_name ? m_name : nullstr(); - } - - //! Gets size of node name, not including terminator character. - //! This function works correctly irrespective of whether name is or is not zero terminated. - //! \return Size of node name, in characters. - std::size_t name_size() const - { - return m_name ? m_name_size : 0; - } - - //! Gets value of node. - //! Interpretation of value depends on type of node. - //! Note that value will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse. - //!

- //! Use value_size() function to determine length of the value. - //! \return Value of node, or empty string if node has no value. - Ch *value() const - { - return m_value ? m_value : nullstr(); - } - - //! Gets size of node value, not including terminator character. - //! This function works correctly irrespective of whether value is or is not zero terminated. - //! \return Size of node value, in characters. - std::size_t value_size() const - { - return m_value ? m_value_size : 0; - } - - /////////////////////////////////////////////////////////////////////////// - // Node modification - - //! Sets name of node to a non zero-terminated string. - //! See \ref ownership_of_strings. - //!

- //! Note that node does not own its name or value, it only stores a pointer to it. - //! It will not delete or otherwise free the pointer on destruction. - //! It is reponsibility of the user to properly manage lifetime of the string. - //! The easiest way to achieve it is to use memory_pool of the document to allocate the string - - //! on destruction of the document the string will be automatically freed. - //!

- //! Size of name must be specified separately, because name does not have to be zero terminated. - //! Use name(const Ch *) function to have the length automatically calculated (string must be zero terminated). - //! \param name_ Name of node to set. Does not have to be zero terminated. - //! \param size Size of name, in characters. This does not include zero terminator, if one is present. - void name(const Ch *name_, std::size_t size) - { - m_name = const_cast(name_); - m_name_size = size; - } - - //! Sets name of node to a zero-terminated string. - //! See also \ref ownership_of_strings and xml_node::name(const Ch *, std::size_t). - //! \param name_ Name of node to set. Must be zero terminated. - void name(const Ch *name_) - { - this->name(name_, internal::measure(name_)); - } - - //! Sets value of node to a non zero-terminated string. - //! See \ref ownership_of_strings. - //!

- //! Note that node does not own its name or value, it only stores a pointer to it. - //! It will not delete or otherwise free the pointer on destruction. - //! It is reponsibility of the user to properly manage lifetime of the string. - //! The easiest way to achieve it is to use memory_pool of the document to allocate the string - - //! on destruction of the document the string will be automatically freed. - //!

- //! Size of value must be specified separately, because it does not have to be zero terminated. - //! Use value(const Ch *) function to have the length automatically calculated (string must be zero terminated). - //!

- //! If an element has a child node of type node_data, it will take precedence over element value when printing. - //! 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. - //! \param value_ value of node to set. Does not have to be zero terminated. - //! \param size Size of value, in characters. This does not include zero terminator, if one is present. - void value(const Ch *value_, std::size_t size) - { - m_value = const_cast(value_); - m_value_size = size; - } - - //! Sets value of node to a zero-terminated string. - //! See also \ref ownership_of_strings and xml_node::value(const Ch *, std::size_t). - //! \param value_ Vame of node to set. Must be zero terminated. - void value(const Ch *value_) - { - this->value(value_, internal::measure(value_)); - } - - /////////////////////////////////////////////////////////////////////////// - // Related nodes access - - //! Gets node parent. - //! \return Pointer to parent node, or 0 if there is no parent. - xml_node *parent() const - { - return m_parent; - } - - protected: - - // Return empty string - static Ch *nullstr() - { - static Ch zero = Ch('\0'); - return &zero; - } - - Ch *m_name; // Name of node, or 0 if no name - Ch *m_value; // Value of node, or 0 if no value - std::size_t m_name_size; // Length of node name, or undefined of no name - std::size_t m_value_size; // Length of node value, or undefined if no value - xml_node *m_parent; // Pointer to parent node, or 0 if none - - }; - - //! Class representing attribute node of XML document. - //! Each attribute has name and value strings, which are available through name() and value() functions (inherited from xml_base). - //! Note that after parse, both name and value of attribute will point to interior of source text used for parsing. - //! Thus, this text must persist in memory for the lifetime of attribute. - //! \tparam Ch Character type to use. - template - class xml_attribute: public xml_base - { - - friend class xml_node; - - public: - - /////////////////////////////////////////////////////////////////////////// - // Construction & destruction - - //! Constructs an empty attribute with the specified type. - //! Consider using memory_pool of appropriate xml_document if allocating attributes manually. - xml_attribute() - { - } - - /////////////////////////////////////////////////////////////////////////// - // Related nodes access - - //! Gets document of which attribute is a child. - //! \return Pointer to document that contains this attribute, or 0 if there is no parent document. - xml_document *document() const - { - if (xml_node *node = this->parent()) - { - while (node->parent()) - node = node->parent(); - return node->type() == node_document ? static_cast *>(node) : 0; - } - else - return 0; - } - - //! Gets previous attribute, optionally matching attribute name. - //! \param name Name of attribute to find, or 0 to return previous attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero - //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string - //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters - //! \return Pointer to found attribute, or 0 if not found. - xml_attribute *previous_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const - { - if (name) - { - if (name_size == 0) - name_size = internal::measure(name); - for (xml_attribute *attribute = m_prev_attribute; attribute; attribute = attribute->m_prev_attribute) - if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive)) - return attribute; - return 0; - } - else - return this->m_parent ? m_prev_attribute : 0; - } - - //! Gets next attribute, optionally matching attribute name. - //! \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 - //! \param name_size_ Size of name, in characters, or 0 to have size calculated automatically from string - //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters - //! \return Pointer to found attribute, or 0 if not found. - xml_attribute *next_attribute(const Ch *name_ = 0, std::size_t name_size_ = 0, bool case_sensitive = true) const - { - if (name_) - { - if (name_size_ == 0) - name_size_ = internal::measure(name_); - for (xml_attribute *attribute = m_next_attribute; attribute; attribute = attribute->m_next_attribute) - if (internal::compare(attribute->name(), attribute->name_size(), name_, name_size_, case_sensitive)) - return attribute; - return 0; - } - else - return this->m_parent ? m_next_attribute : 0; - } - - private: - - xml_attribute *m_prev_attribute; // Pointer to previous sibling of attribute, or 0 if none; only valid if parent is non-zero - xml_attribute *m_next_attribute; // Pointer to next sibling of attribute, or 0 if none; only valid if parent is non-zero - - }; - - /////////////////////////////////////////////////////////////////////////// - // XML node - - //! Class representing a node of XML document. - //! Each node may have associated name and value strings, which are available through name() and value() functions. - //! Interpretation of name and value depends on type of the node. - //! Type of node can be determined by using type() function. - //!

- //! Note that after parse, both name and value of node, if any, will point interior of source text used for parsing. - //! Thus, this text must persist in the memory for the lifetime of node. - //! \tparam Ch Character type to use. - template - class xml_node: public xml_base - { - - public: - - /////////////////////////////////////////////////////////////////////////// - // Construction & destruction - - //! Constructs an empty node with the specified type. - //! Consider using memory_pool of appropriate document to allocate nodes manually. - //! \param type_ Type of node to construct. - xml_node(node_type type_) - : m_type(type_) - , m_first_node(0) - , m_first_attribute(0) - { - } - - /////////////////////////////////////////////////////////////////////////// - // Node data access - - //! Gets type of node. - //! \return Type of node. - node_type type() const - { - return m_type; - } - - /////////////////////////////////////////////////////////////////////////// - // Related nodes access - - //! Gets document of which node is a child. - //! \return Pointer to document that contains this node, or 0 if there is no parent document. - xml_document *document() const - { - xml_node *node = const_cast *>(this); - while (node->parent()) - node = node->parent(); - return node->type() == node_document ? static_cast *>(node) : 0; - } - - //! Gets first child node, optionally matching node name. - //! \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 - //! \param name_size_ Size of name, in characters, or 0 to have size calculated automatically from string - //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters - //! \return Pointer to found child, or 0 if not found. - xml_node *first_node(const Ch *name_ = 0, std::size_t name_size_ = 0, bool case_sensitive = true) const - { - if (name_) - { - if (name_size_ == 0) - name_size_ = internal::measure(name_); - for (xml_node *child = m_first_node; child; child = child->next_sibling()) - if (internal::compare(child->name(), child->name_size(), name_, name_size_, case_sensitive)) - return child; - return 0; - } - else - return m_first_node; - } - - //! Gets last child node, optionally matching node name. - //! Behaviour is undefined if node has no children. - //! Use first_node() to test if node has children. - //! \param name Name of child to find, or 0 to return last child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero - //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string - //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters - //! \return Pointer to found child, or 0 if not found. - xml_node *last_node(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const - { - assert(m_first_node); // Cannot query for last child if node has no children - if (name) - { - if (name_size == 0) - name_size = internal::measure(name); - for (xml_node *child = m_last_node; child; child = child->previous_sibling()) - if (internal::compare(child->name(), child->name_size(), name, name_size, case_sensitive)) - return child; - return 0; - } - else - return m_last_node; - } - - //! Gets previous sibling node, optionally matching node name. - //! Behaviour is undefined if node has no parent. - //! Use parent() to test if node has a parent. - //! \param name Name of sibling to find, or 0 to return previous sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero - //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string - //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters - //! \return Pointer to found sibling, or 0 if not found. - xml_node *previous_sibling(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const - { - assert(this->m_parent); // Cannot query for siblings if node has no parent - if (name) - { - if (name_size == 0) - name_size = internal::measure(name); - for (xml_node *sibling = m_prev_sibling; sibling; sibling = sibling->m_prev_sibling) - if (internal::compare(sibling->name(), sibling->name_size(), name, name_size, case_sensitive)) - return sibling; - return 0; - } - else - return m_prev_sibling; - } - - //! Gets next sibling node, optionally matching node name. - //! Behaviour is undefined if node has no parent. - //! Use parent() to test if node has a parent. - //! \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 - //! \param name_size_ Size of name, in characters, or 0 to have size calculated automatically from string - //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters - //! \return Pointer to found sibling, or 0 if not found. - xml_node *next_sibling(const Ch *name_ = 0, std::size_t name_size_ = 0, bool case_sensitive = true) const - { - assert(this->m_parent); // Cannot query for siblings if node has no parent - if (name_) - { - if (name_size_ == 0) - name_size_ = internal::measure(name_); - for (xml_node *sibling = m_next_sibling; sibling; sibling = sibling->m_next_sibling) - if (internal::compare(sibling->name(), sibling->name_size(), name_, name_size_, case_sensitive)) - return sibling; - return 0; - } - else - return m_next_sibling; - } - - //! Gets first attribute of node, optionally matching attribute name. - //! \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 - //! \param name_size_ Size of name, in characters, or 0 to have size calculated automatically from string - //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters - //! \return Pointer to found attribute, or 0 if not found. - xml_attribute *first_attribute(const Ch *name_ = 0, std::size_t name_size_ = 0, bool case_sensitive = true) const - { - if (name_) - { - if (name_size_ == 0) - name_size_ = internal::measure(name_); - for (xml_attribute *attribute = m_first_attribute; attribute; attribute = attribute->m_next_attribute) - if (internal::compare(attribute->name(), attribute->name_size(), name_, name_size_, case_sensitive)) - return attribute; - return 0; - } - else - return m_first_attribute; - } - - //! Gets last attribute of node, optionally matching attribute name. - //! \param name Name of attribute to find, or 0 to return last attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero - //! \param name_size Size of name, in characters, or 0 to have size calculated automatically from string - //! \param case_sensitive Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters - //! \return Pointer to found attribute, or 0 if not found. - xml_attribute *last_attribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const - { - if (name) - { - if (name_size == 0) - name_size = internal::measure(name); - for (xml_attribute *attribute = m_last_attribute; attribute; attribute = attribute->m_prev_attribute) - if (internal::compare(attribute->name(), attribute->name_size(), name, name_size, case_sensitive)) - return attribute; - return 0; - } - else - return m_first_attribute ? m_last_attribute : 0; - } - - /////////////////////////////////////////////////////////////////////////// - // Node modification - - //! Sets type of node. - //! \param type_ Type of node to set. - void type(node_type type_) - { - m_type = type_; - } - - /////////////////////////////////////////////////////////////////////////// - // Node manipulation - - //! Prepends a new child node. - //! The prepended child becomes the first child, and all existing children are moved one position back. - //! \param child Node to prepend. - void prepend_node(xml_node *child) - { - assert(child && !child->parent() && child->type() != node_document); - if (first_node()) - { - child->m_next_sibling = m_first_node; - m_first_node->m_prev_sibling = child; - } - else - { - child->m_next_sibling = 0; - m_last_node = child; - } - m_first_node = child; - child->m_parent = this; - child->m_prev_sibling = 0; - } - - //! Appends a new child node. - //! The appended child becomes the last child. - //! \param child Node to append. - void append_node(xml_node *child) - { - assert(child && !child->parent() && child->type() != node_document); - if (first_node()) - { - child->m_prev_sibling = m_last_node; - m_last_node->m_next_sibling = child; - } - else - { - child->m_prev_sibling = 0; - m_first_node = child; - } - m_last_node = child; - child->m_parent = this; - child->m_next_sibling = 0; - } - - //! Inserts a new child node at specified place inside the node. - //! All children after and including the specified node are moved one position back. - //! \param where Place where to insert the child, or 0 to insert at the back. - //! \param child Node to insert. - void insert_node(xml_node *where, xml_node *child) - { - assert(!where || where->parent() == this); - assert(child && !child->parent() && child->type() != node_document); - if (where == m_first_node) - prepend_node(child); - else if (where == 0) - append_node(child); - else - { - child->m_prev_sibling = where->m_prev_sibling; - child->m_next_sibling = where; - where->m_prev_sibling->m_next_sibling = child; - where->m_prev_sibling = child; - child->m_parent = this; - } - } - - //! Removes first child node. - //! If node has no children, behaviour is undefined. - //! Use first_node() to test if node has children. - void remove_first_node() - { - assert(first_node()); - xml_node *child = m_first_node; - m_first_node = child->m_next_sibling; - if (child->m_next_sibling) - child->m_next_sibling->m_prev_sibling = 0; - else - m_last_node = 0; - child->m_parent = 0; - } - - //! Removes last child of the node. - //! If node has no children, behaviour is undefined. - //! Use first_node() to test if node has children. - void remove_last_node() - { - assert(first_node()); - xml_node *child = m_last_node; - if (child->m_prev_sibling) - { - m_last_node = child->m_prev_sibling; - child->m_prev_sibling->m_next_sibling = 0; - } - else - m_first_node = 0; - child->m_parent = 0; - } - - //! Removes specified child from the node - // \param where Pointer to child to be removed. - void remove_node(xml_node *where) - { - assert(where && where->parent() == this); - assert(first_node()); - if (where == m_first_node) - remove_first_node(); - else if (where == m_last_node) - remove_last_node(); - else - { - where->m_prev_sibling->m_next_sibling = where->m_next_sibling; - where->m_next_sibling->m_prev_sibling = where->m_prev_sibling; - where->m_parent = 0; - } - } - - //! Removes all child nodes (but not attributes). - void remove_all_nodes() - { - for (xml_node *node = first_node(); node; node = node->m_next_sibling) - node->m_parent = 0; - m_first_node = 0; - } - - //! Prepends a new attribute to the node. - //! \param attribute Attribute to prepend. - void prepend_attribute(xml_attribute *attribute) - { - assert(attribute && !attribute->parent()); - if (first_attribute()) - { - attribute->m_next_attribute = m_first_attribute; - m_first_attribute->m_prev_attribute = attribute; - } - else - { - attribute->m_next_attribute = 0; - m_last_attribute = attribute; - } - m_first_attribute = attribute; - attribute->m_parent = this; - attribute->m_prev_attribute = 0; - } - - //! Appends a new attribute to the node. - //! \param attribute Attribute to append. - void append_attribute(xml_attribute *attribute) - { - assert(attribute && !attribute->parent()); - if (first_attribute()) - { - attribute->m_prev_attribute = m_last_attribute; - m_last_attribute->m_next_attribute = attribute; - } - else - { - attribute->m_prev_attribute = 0; - m_first_attribute = attribute; - } - m_last_attribute = attribute; - attribute->m_parent = this; - attribute->m_next_attribute = 0; - } - - //! Inserts a new attribute at specified place inside the node. - //! All attributes after and including the specified attribute are moved one position back. - //! \param where Place where to insert the attribute, or 0 to insert at the back. - //! \param attribute Attribute to insert. - void insert_attribute(xml_attribute *where, xml_attribute *attribute) - { - assert(!where || where->parent() == this); - assert(attribute && !attribute->parent()); - if (where == m_first_attribute) - prepend_attribute(attribute); - else if (where == 0) - append_attribute(attribute); - else - { - attribute->m_prev_attribute = where->m_prev_attribute; - attribute->m_next_attribute = where; - where->m_prev_attribute->m_next_attribute = attribute; - where->m_prev_attribute = attribute; - attribute->m_parent = this; - } - } - - //! Removes first attribute of the node. - //! If node has no attributes, behaviour is undefined. - //! Use first_attribute() to test if node has attributes. - void remove_first_attribute() - { - assert(first_attribute()); - xml_attribute *attribute = m_first_attribute; - if (attribute->m_next_attribute) - { - attribute->m_next_attribute->m_prev_attribute = 0; - } - else - m_last_attribute = 0; - attribute->m_parent = 0; - m_first_attribute = attribute->m_next_attribute; - } - - //! Removes last attribute of the node. - //! If node has no attributes, behaviour is undefined. - //! Use first_attribute() to test if node has attributes. - void remove_last_attribute() - { - assert(first_attribute()); - xml_attribute *attribute = m_last_attribute; - if (attribute->m_prev_attribute) - { - attribute->m_prev_attribute->m_next_attribute = 0; - m_last_attribute = attribute->m_prev_attribute; - } - else - m_first_attribute = 0; - attribute->m_parent = 0; - } - - //! Removes specified attribute from node. - //! \param where Pointer to attribute to be removed. - void remove_attribute(xml_attribute *where) - { - assert(first_attribute() && where->parent() == this); - if (where == m_first_attribute) - remove_first_attribute(); - else if (where == m_last_attribute) - remove_last_attribute(); - else - { - where->m_prev_attribute->m_next_attribute = where->m_next_attribute; - where->m_next_attribute->m_prev_attribute = where->m_prev_attribute; - where->m_parent = 0; - } - } - - //! Removes all attributes of node. - void remove_all_attributes() - { - for (xml_attribute *attribute = first_attribute(); attribute; attribute = attribute->m_next_attribute) - attribute->m_parent = 0; - m_first_attribute = 0; - } - - private: - - /////////////////////////////////////////////////////////////////////////// - // Restrictions - - // No copying - xml_node(const xml_node &); - void operator =(const xml_node &); - - /////////////////////////////////////////////////////////////////////////// - // Data members - - // Note that some of the pointers below have UNDEFINED values if certain other pointers are 0. - // This is required for maximum performance, as it allows the parser to omit initialization of - // unneded/redundant values. - // - // The rules are as follows: - // 1. first_node and first_attribute contain valid pointers, or 0 if node has no children/attributes respectively - // 2. last_node and last_attribute are valid only if node has at least one child/attribute respectively, otherwise they contain garbage - // 3. prev_sibling and next_sibling are valid only if node has a parent, otherwise they contain garbage - - node_type m_type; // Type of node; always valid - xml_node *m_first_node; // Pointer to first child node, or 0 if none; always valid - xml_node *m_last_node; // Pointer to last child node, or 0 if none; this value is only valid if m_first_node is non-zero - xml_attribute *m_first_attribute; // Pointer to first attribute of node, or 0 if none; always valid - xml_attribute *m_last_attribute; // Pointer to last attribute of node, or 0 if none; this value is only valid if m_first_attribute is non-zero - xml_node *m_prev_sibling; // Pointer to previous sibling of node, or 0 if none; this value is only valid if m_parent is non-zero - xml_node *m_next_sibling; // Pointer to next sibling of node, or 0 if none; this value is only valid if m_parent is non-zero - - }; - - /////////////////////////////////////////////////////////////////////////// - // XML document - - //! This class represents root of the DOM hierarchy. - //! It is also an xml_node and a memory_pool through public inheritance. - //! Use parse() function to build a DOM tree from a zero-terminated XML text string. - //! parse() function allocates memory for nodes and attributes by using functions of xml_document, - //! which are inherited from memory_pool. - //! To access root node of the document, use the document itself, as if it was an xml_node. - //! \tparam Ch Character type to use. - template - class xml_document: public xml_node, public memory_pool - { - - public: - - //! Constructs empty XML document - xml_document() - : xml_node(node_document) - { - } - - //! Parses zero-terminated XML string according to given flags. - //! Passed string will be modified by the parser, unless rapidxml::parse_non_destructive flag is used. - //! The string must persist for the lifetime of the document. - //! In case of error, rapidxml::parse_error exception will be thrown. - //!

- //! If you want to parse contents of a file, you must first load the file into the memory, and pass pointer to its beginning. - //! Make sure that data is zero-terminated. - //!

- //! Document can be parsed into multiple times. - //! Each new call to parse removes previous nodes and attributes (if any), but does not clear memory pool. - //! \param text XML data to parse; pointer is non-const to denote fact that this data may be modified by the parser. - template - void parse(Ch *text) - { - assert(text); - - // Remove current contents - this->remove_all_nodes(); - this->remove_all_attributes(); - - // Parse BOM, if any - parse_bom(text); - - // Parse children - while (1) - { - // Skip whitespace before node - skip(text); - if (*text == 0) - break; - - // Parse and append new child - if (*text == Ch('<')) - { - ++text; // Skip '<' - if (xml_node *node = parse_node(text)) - this->append_node(node); - } - else - CEREAL_RAPIDXML_PARSE_ERROR("expected <", text); - } - - } - - //! Clears the document by deleting all nodes and clearing the memory pool. - //! All nodes owned by document pool are destroyed. - void clear() - { - this->remove_all_nodes(); - this->remove_all_attributes(); - memory_pool::clear(); - } - - private: - - /////////////////////////////////////////////////////////////////////// - // Internal character utility functions - - // Detect whitespace character - struct whitespace_pred - { - static unsigned char test(Ch ch) - { - return internal::lookup_tables<0>::lookup_whitespace[static_cast(ch)]; - } - }; - - // Detect node name character - struct node_name_pred - { - static unsigned char test(Ch ch) - { - return internal::lookup_tables<0>::lookup_node_name[static_cast(ch)]; - } - }; - - // Detect attribute name character - struct attribute_name_pred - { - static unsigned char test(Ch ch) - { - return internal::lookup_tables<0>::lookup_attribute_name[static_cast(ch)]; - } - }; - - // Detect text character (PCDATA) - struct text_pred - { - static unsigned char test(Ch ch) - { - return internal::lookup_tables<0>::lookup_text[static_cast(ch)]; - } - }; - - // Detect text character (PCDATA) that does not require processing - struct text_pure_no_ws_pred - { - static unsigned char test(Ch ch) - { - return internal::lookup_tables<0>::lookup_text_pure_no_ws[static_cast(ch)]; - } - }; - - // Detect text character (PCDATA) that does not require processing - struct text_pure_with_ws_pred - { - static unsigned char test(Ch ch) - { - return internal::lookup_tables<0>::lookup_text_pure_with_ws[static_cast(ch)]; - } - }; - - // Detect attribute value character - template - struct attribute_value_pred - { - static unsigned char test(Ch ch) - { - if (Quote == Ch('\'')) - return internal::lookup_tables<0>::lookup_attribute_data_1[static_cast(ch)]; - if (Quote == Ch('\"')) - return internal::lookup_tables<0>::lookup_attribute_data_2[static_cast(ch)]; - return 0; // Should never be executed, to avoid warnings on Comeau - } - }; - - // Detect attribute value character - template - struct attribute_value_pure_pred - { - static unsigned char test(Ch ch) - { - if (Quote == Ch('\'')) - return internal::lookup_tables<0>::lookup_attribute_data_1_pure[static_cast(ch)]; - if (Quote == Ch('\"')) - return internal::lookup_tables<0>::lookup_attribute_data_2_pure[static_cast(ch)]; - return 0; // Should never be executed, to avoid warnings on Comeau - } - }; - - // Insert coded character, using UTF8 or 8-bit ASCII - template - static void insert_coded_character(Ch *&text, unsigned long code) - { - if (Flags & parse_no_utf8) - { - // Insert 8-bit ASCII character - // Todo: possibly verify that code is less than 256 and use replacement char otherwise? - text[0] = static_cast(code); - text += 1; - } - else - { - // Insert UTF8 sequence - if (code < 0x80) // 1 byte sequence - { - text[0] = static_cast(code); - text += 1; - } - else if (code < 0x800) // 2 byte sequence - { - text[1] = static_cast((code | 0x80) & 0xBF); code >>= 6; - text[0] = static_cast(code | 0xC0); - text += 2; - } - else if (code < 0x10000) // 3 byte sequence - { - text[2] = static_cast((code | 0x80) & 0xBF); code >>= 6; - text[1] = static_cast((code | 0x80) & 0xBF); code >>= 6; - text[0] = static_cast(code | 0xE0); - text += 3; - } - else if (code < 0x110000) // 4 byte sequence - { - text[3] = static_cast((code | 0x80) & 0xBF); code >>= 6; - text[2] = static_cast((code | 0x80) & 0xBF); code >>= 6; - text[1] = static_cast((code | 0x80) & 0xBF); code >>= 6; - text[0] = static_cast(code | 0xF0); - text += 4; - } - else // Invalid, only codes up to 0x10FFFF are allowed in Unicode - { - CEREAL_RAPIDXML_PARSE_ERROR("invalid numeric character entity", text); - } - } - } - - // Skip characters until predicate evaluates to true - template - static void skip(Ch *&text) - { - Ch *tmp = text; - while (StopPred::test(*tmp)) - ++tmp; - text = tmp; - } - - // Skip characters until predicate evaluates to true while doing the following: - // - replacing XML character entity references with proper characters (' & " < > &#...;) - // - condensing whitespace sequences to single space character - template - static Ch *skip_and_expand_character_refs(Ch *&text, bool preserve_space) - { - // If entity translation, whitespace condense and whitespace trimming is disabled, use plain skip - if (Flags & parse_no_entity_translation && - !(Flags & parse_normalize_whitespace) && - !(Flags & parse_trim_whitespace)) - { - skip(text); - return text; - } - - // Use simple skip until first modification is detected - skip(text); - - // Use translation skip - Ch *src = text; - Ch *dest = src; - while (StopPred::test(*src)) - { - // If entity translation is enabled - if (!(Flags & parse_no_entity_translation)) - { - // Test if replacement is needed - if (src[0] == Ch('&')) - { - switch (src[1]) - { - - // & ' - case Ch('a'): - if (src[2] == Ch('m') && src[3] == Ch('p') && src[4] == Ch(';')) - { - *dest = Ch('&'); - ++dest; - src += 5; - continue; - } - if (src[2] == Ch('p') && src[3] == Ch('o') && src[4] == Ch('s') && src[5] == Ch(';')) - { - *dest = Ch('\''); - ++dest; - src += 6; - continue; - } - break; - - // " - case Ch('q'): - if (src[2] == Ch('u') && src[3] == Ch('o') && src[4] == Ch('t') && src[5] == Ch(';')) - { - *dest = Ch('"'); - ++dest; - src += 6; - continue; - } - break; - - // > - case Ch('g'): - if (src[2] == Ch('t') && src[3] == Ch(';')) - { - *dest = Ch('>'); - ++dest; - src += 4; - continue; - } - break; - - // < - case Ch('l'): - if (src[2] == Ch('t') && src[3] == Ch(';')) - { - *dest = Ch('<'); - ++dest; - src += 4; - continue; - } - break; - - // &#...; - assumes ASCII - case Ch('#'): - if (src[2] == Ch('x')) - { - unsigned long code = 0; - src += 3; // Skip &#x - while (1) - { - unsigned char digit = internal::lookup_tables<0>::lookup_digits[static_cast(*src)]; - if (digit == 0xFF) - break; - code = code * 16 + digit; - ++src; - } - insert_coded_character(dest, code); // Put character in output - } - else - { - unsigned long code = 0; - src += 2; // Skip &# - while (1) - { - unsigned char digit = internal::lookup_tables<0>::lookup_digits[static_cast(*src)]; - if (digit == 0xFF) - break; - code = code * 10 + digit; - ++src; - } - insert_coded_character(dest, code); // Put character in output - } - if (*src == Ch(';')) - ++src; - else - CEREAL_RAPIDXML_PARSE_ERROR("expected ;", src); - continue; - - // Something else - default: - // Ignore, just copy '&' verbatim - break; - - } - } - } - - // If whitespace condensing is enabled - if ((Flags & parse_normalize_whitespace) && !preserve_space) - { - // Test if condensing is needed - if (whitespace_pred::test(*src)) - { - *dest = Ch(' '); ++dest; // Put single space in dest - ++src; // Skip first whitespace char - // Skip remaining whitespace chars - while (whitespace_pred::test(*src)) - ++src; - continue; - } - } - - // No replacement, only copy character - *dest++ = *src++; - - } - - // Return new end - text = src; - return dest; - - } - - /////////////////////////////////////////////////////////////////////// - // Internal parsing functions - - // Parse BOM, if any - template - void parse_bom(Ch *&text) - { - // UTF-8? - if (static_cast(text[0]) == 0xEF && - static_cast(text[1]) == 0xBB && - static_cast(text[2]) == 0xBF) - { - text += 3; // Skup utf-8 bom - } - } - - // Parse XML declaration ( - xml_node *parse_xml_declaration(Ch *&text) - { - // If parsing of declaration is disabled - if (!(Flags & parse_declaration_node)) - { - // Skip until end of declaration - while (text[0] != Ch('?') || text[1] != Ch('>')) - { - if (!text[0]) - CEREAL_RAPIDXML_PARSE_ERROR("unexpected end of data", text); - ++text; - } - text += 2; // Skip '?>' - return 0; - } - - // Create declaration - xml_node *declaration = this->allocate_node(node_declaration); - - // Skip whitespace before attributes or ?> - skip(text); - - // Parse declaration attributes - parse_node_attributes(text, declaration); - - // Skip ?> - if (text[0] != Ch('?') || text[1] != Ch('>')) - CEREAL_RAPIDXML_PARSE_ERROR("expected ?>", text); - text += 2; - - return declaration; - } - - // Parse XML comment (' - return 0; // Do not produce comment node - } - - // Remember value start - Ch *value_ = text; - - // Skip until end of comment - while (text[0] != Ch('-') || text[1] != Ch('-') || text[2] != Ch('>')) - { - if (!text[0]) - CEREAL_RAPIDXML_PARSE_ERROR("unexpected end of data", text); - ++text; - } - - // Create comment node - xml_node *comment = this->allocate_node(node_comment); - comment->value(value_, static_cast(text - value_)); - - // Place zero terminator after comment value - if (!(Flags & parse_no_string_terminators)) - *text = Ch('\0'); - - text += 3; // Skip '-->' - return comment; - } - - // Parse DOCTYPE - template - xml_node *parse_doctype(Ch *&text) - { - // Remember value start - Ch *value_ = text; - - // Skip to > - while (*text != Ch('>')) - { - // Determine character type - switch (*text) - { - - // If '[' encountered, scan for matching ending ']' using naive algorithm with depth - // This works for all W3C test files except for 2 most wicked - case Ch('['): - { - ++text; // Skip '[' - int depth = 1; - while (depth > 0) - { - switch (*text) - { - case Ch('['): ++depth; break; - case Ch(']'): --depth; break; - case 0: CEREAL_RAPIDXML_PARSE_ERROR("unexpected end of data", text); - } - ++text; - } - break; - } - - // Error on end of text - case Ch('\0'): - CEREAL_RAPIDXML_PARSE_ERROR("unexpected end of data", text); - - // Other character, skip it - default: - ++text; - - } - } - - // If DOCTYPE nodes enabled - if (Flags & parse_doctype_node) - { - // Create a new doctype node - xml_node *doctype = this->allocate_node(node_doctype); - doctype->value(value_, static_cast(text - value_)); - - // Place zero terminator after value - if (!(Flags & parse_no_string_terminators)) - *text = Ch('\0'); - - text += 1; // skip '>' - return doctype; - } - else - { - text += 1; // skip '>' - return 0; - } - - } - - // Parse PI - template - xml_node *parse_pi(Ch *&text) - { - // If creation of PI nodes is enabled - if (Flags & parse_pi_nodes) - { - // Create pi node - xml_node *pi = this->allocate_node(node_pi); - - // Extract PI target name - Ch *name_ = text; - skip(text); - if (text == name_) - CEREAL_RAPIDXML_PARSE_ERROR("expected PI target", text); - pi->name(name_, static_cast(text - name_)); - - // Skip whitespace between pi target and pi - skip(text); - - // Remember start of pi - Ch *value_ = text; - - // Skip to '?>' - while (text[0] != Ch('?') || text[1] != Ch('>')) - { - if (*text == Ch('\0')) - CEREAL_RAPIDXML_PARSE_ERROR("unexpected end of data", text); - ++text; - } - - // Set pi value (verbatim, no entity expansion or whitespace normalization) - pi->value(value_, static_cast(text - value_)); - - // Place zero terminator after name and value - if (!(Flags & parse_no_string_terminators)) - { - pi->name()[pi->name_size()] = Ch('\0'); - pi->value()[pi->value_size()] = Ch('\0'); - } - - text += 2; // Skip '?>' - return pi; - } - else - { - // Skip to '?>' - while (text[0] != Ch('?') || text[1] != Ch('>')) - { - if (*text == Ch('\0')) - CEREAL_RAPIDXML_PARSE_ERROR("unexpected end of data", text); - ++text; - } - text += 2; // Skip '?>' - return 0; - } - } - - // Parse and append data - // Return character that ends data. - // This is necessary because this character might have been overwritten by a terminating 0 - template - Ch parse_and_append_data(xml_node *node, Ch *&text, Ch *contents_start) - { - // Backup to contents start if whitespace trimming is disabled - if (!(Flags & parse_trim_whitespace)) - text = contents_start; - - const bool preserve_space = internal::preserve_space(node); - - // Skip until end of data - Ch *value_ = text, *end; - if ((Flags & parse_normalize_whitespace) && !preserve_space) - end = skip_and_expand_character_refs(text, false); - else - end = skip_and_expand_character_refs(text, preserve_space); - - // Trim trailing whitespace if flag is set; leading was already trimmed by whitespace skip after > - if ((Flags & parse_trim_whitespace) && !preserve_space) - { - if (Flags & parse_normalize_whitespace) - { - // Whitespace is already condensed to single space characters by skipping function, so just trim 1 char off the end - if (*(end - 1) == Ch(' ')) - --end; - } - else - { - // Backup until non-whitespace character is found - while (whitespace_pred::test(*(end - 1))) - --end; - } - } - - // If characters are still left between end and value (this test is only necessary if normalization is enabled) - // Create new data node - if (!(Flags & parse_no_data_nodes)) - { - xml_node *data = this->allocate_node(node_data); - data->value(value_, static_cast(end - value_)); - node->append_node(data); - } - - // Add data to parent node if no data exists yet - if (!(Flags & parse_no_element_values)) - if (*node->value() == Ch('\0')) - node->value(value_, static_cast(end - value_)); - - // Place zero terminator after value - if (!(Flags & parse_no_string_terminators)) - { - Ch ch = *text; - *end = Ch('\0'); - return ch; // Return character that ends data; this is required because zero terminator overwritten it - } - - // Return character that ends data - return *text; - } - - // Parse CDATA - template - xml_node *parse_cdata(Ch *&text) - { - // If CDATA is disabled - if (Flags & parse_no_data_nodes) - { - // Skip until end of cdata - while (text[0] != Ch(']') || text[1] != Ch(']') || text[2] != Ch('>')) - { - if (!text[0]) - CEREAL_RAPIDXML_PARSE_ERROR("unexpected end of data", text); - ++text; - } - text += 3; // Skip ]]> - return 0; // Do not produce CDATA node - } - - // Skip until end of cdata - Ch *value_ = text; - while (text[0] != Ch(']') || text[1] != Ch(']') || text[2] != Ch('>')) - { - if (!text[0]) - CEREAL_RAPIDXML_PARSE_ERROR("unexpected end of data", text); - ++text; - } - - // Create new cdata node - xml_node *cdata = this->allocate_node(node_cdata); - cdata->value(value_, static_cast(text - value_)); - - // Place zero terminator after value - if (!(Flags & parse_no_string_terminators)) - *text = Ch('\0'); - - text += 3; // Skip ]]> - return cdata; - } - - // Parse element node - template - xml_node *parse_element(Ch *&text) - { - // Create element node - xml_node *element = this->allocate_node(node_element); - - // Extract element name - Ch *name_ = text; - skip(text); - if (text == name_) - CEREAL_RAPIDXML_PARSE_ERROR("expected element name", text); - element->name(name_, static_cast(text - name_)); - - // Skip whitespace between element name and attributes or > - skip(text); - - // Parse attributes, if any - parse_node_attributes(text, element); - - // Determine ending type - if (*text == Ch('>')) - { - ++text; - parse_node_contents(text, element); - } - else if (*text == Ch('/')) - { - ++text; - if (*text != Ch('>')) - CEREAL_RAPIDXML_PARSE_ERROR("expected >", text); - ++text; - } - else - CEREAL_RAPIDXML_PARSE_ERROR("expected >", text); - - // Place zero terminator after name - if (!(Flags & parse_no_string_terminators)) - element->name()[element->name_size()] = Ch('\0'); - - // Return parsed element - return element; - } - - // Determine node type, and parse it - template - xml_node *parse_node(Ch *&text) - { - // Parse proper node type - switch (text[0]) - { - - // <... - default: - // Parse and append element node - return parse_element(text); - - // (text); - } - else - { - // Parse PI - return parse_pi(text); - } - - // (text); - } - break; - - // (text); - } - break; - - // (text); - } - - } // switch - - // Attempt to skip other, unrecognized node types starting with ')) - { - if (*text == 0) - CEREAL_RAPIDXML_PARSE_ERROR("unexpected end of data", text); - ++text; - } - ++text; // Skip '>' - return 0; // No node recognized - - } - } - - // Parse contents of the node - children, data etc. - template - void parse_node_contents(Ch *&text, xml_node *node) - { - // For all children and text - while (1) - { - // Skip whitespace between > and node contents - Ch *contents_start = text; // Store start of node contents before whitespace is skipped - skip(text); - Ch next_char = *text; - - // After data nodes, instead of continuing the loop, control jumps here. - // This is because zero termination inside parse_and_append_data() function - // would wreak havoc with the above code. - // Also, skipping whitespace after data nodes is unnecessary. - after_data_node: - - // Determine what comes next: node closing, child node, data node, or 0? - switch (next_char) - { - - // Node closing or child node - case Ch('<'): - if (text[1] == Ch('/')) - { - Ch *contents_end = 0; - if (internal::preserve_space(node)) - { - contents_end = text; - } - - // Node closing - text += 2; // Skip '(text); - if (!internal::compare(node->name(), node->name_size(), closing_name, static_cast(text - closing_name), true)) - CEREAL_RAPIDXML_PARSE_ERROR("invalid closing tag name", text); - } - else - { - // No validation, just skip name - skip(text); - } - // Skip remaining whitespace after node name - skip(text); - if (*text != Ch('>')) - CEREAL_RAPIDXML_PARSE_ERROR("expected >", text); - ++text; // Skip '>' - - if (contents_end && contents_end != contents_start) - { - node->value(contents_start, static_cast(contents_end - contents_start)); - node->value()[node->value_size()] = Ch('\0'); - } - return; // Node closed, finished parsing contents - } - else - { - // Child node - ++text; // Skip '<' - if (xml_node *child = parse_node(text)) - node->append_node(child); - } - break; - - // End of data - error - case Ch('\0'): - CEREAL_RAPIDXML_PARSE_ERROR("unexpected end of data", text); - - // Data node - default: - next_char = parse_and_append_data(node, text, contents_start); - goto after_data_node; // Bypass regular processing after data nodes - - } - } - } - - // Parse XML attributes of the node - template - void parse_node_attributes(Ch *&text, xml_node *node) - { - // For all attributes - while (attribute_name_pred::test(*text)) - { - // Extract attribute name - Ch *name_ = text; - ++text; // Skip first character of attribute name - skip(text); - if (text == name_) - CEREAL_RAPIDXML_PARSE_ERROR("expected attribute name", name_); - - // Create new attribute - xml_attribute *attribute = this->allocate_attribute(); - attribute->name(name_, static_cast(text - name_)); - node->append_attribute(attribute); - - // Skip whitespace after attribute name - skip(text); - - // Skip = - if (*text != Ch('=')) - CEREAL_RAPIDXML_PARSE_ERROR("expected =", text); - ++text; - - // Add terminating zero after name - if (!(Flags & parse_no_string_terminators)) - attribute->name()[attribute->name_size()] = 0; - - // Skip whitespace after = - skip(text); - - // Skip quote and remember if it was ' or " - Ch quote = *text; - if (quote != Ch('\'') && quote != Ch('"')) - CEREAL_RAPIDXML_PARSE_ERROR("expected ' or \"", text); - ++text; - - // Extract attribute value and expand char refs in it - Ch *value_ = text, *end; - const int AttFlags = Flags & ~parse_normalize_whitespace; // No whitespace normalization in attributes - if (quote == Ch('\'')) - end = skip_and_expand_character_refs, attribute_value_pure_pred, AttFlags>(text, false); - else - end = skip_and_expand_character_refs, attribute_value_pure_pred, AttFlags>(text, false); - - // Set attribute value - attribute->value(value_, static_cast(end - value_)); - - // Make sure that end quote is present - if (*text != quote) - CEREAL_RAPIDXML_PARSE_ERROR("expected ' or \"", text); - ++text; // Skip quote - - // Add terminating zero after value - if (!(Flags & parse_no_string_terminators)) - attribute->value()[attribute->value_size()] = 0; - - // Skip whitespace after attribute value - skip(text); - } - } - - }; - - //! \cond internal - namespace internal - { - - // Whitespace (space \n \r \t) - template - const unsigned char lookup_tables::lookup_whitespace[256] = - { - // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, // 0 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1 - 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 2 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 5 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 7 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // C - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // D - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // E - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // F - }; - - // Node name (anything but space \n \r \t / > ? \0) - template - const unsigned char lookup_tables::lookup_node_name[256] = - { - // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, // 0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, // 2 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, // 3 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F - }; - - // Text (i.e. PCDATA) (anything but < \0) - template - const unsigned char lookup_tables::lookup_text[256] = - { - // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 3 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F - }; - - // Text (i.e. PCDATA) that does not require processing when ws normalization is disabled - // (anything but < \0 &) - template - const unsigned char lookup_tables::lookup_text_pure_no_ws[256] = - { - // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 - 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 3 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F - }; - - // Text (i.e. PCDATA) that does not require processing when ws normalizationis is enabled - // (anything but < \0 & space \n \r \t) - template - const unsigned char lookup_tables::lookup_text_pure_with_ws[256] = - { - // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, // 0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 - 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 3 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F - }; - - // Attribute name (anything but space \n \r \t / < > = ? ! \0) - template - const unsigned char lookup_tables::lookup_attribute_name[256] = - { - // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, // 0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 - 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, // 2 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, // 3 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F - }; - - // Attribute data with single quote (anything but ' \0) - template - const unsigned char lookup_tables::lookup_attribute_data_1[256] = - { - // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 - 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, // 2 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F - }; - - // Attribute data with single quote that does not require processing (anything but ' \0 &) - template - const unsigned char lookup_tables::lookup_attribute_data_1_pure[256] = - { - // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 - 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, // 2 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F - }; - - // Attribute data with double quote (anything but " \0) - template - const unsigned char lookup_tables::lookup_attribute_data_2[256] = - { - // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 - 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F - }; - - // Attribute data with double quote that does not require processing (anything but " \0 &) - template - const unsigned char lookup_tables::lookup_attribute_data_2_pure[256] = - { - // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 1 - 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 3 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 8 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 9 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // C - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // D - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // E - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // F - }; - - // Digits (dec and hex, 255 denotes end of numeric character reference) - template - const unsigned char lookup_tables::lookup_digits[256] = - { - // 0 1 2 3 4 5 6 7 8 9 A B C D E F - 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 0 - 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 1 - 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 2 - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,255,255,255,255,255,255, // 3 - 255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255, // 4 - 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 5 - 255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255, // 6 - 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 7 - 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 8 - 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 9 - 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // A - 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // B - 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // C - 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // D - 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // E - 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255 // F - }; - - // Upper case conversion - template - const unsigned char lookup_tables::lookup_upcase[256] = - { - // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A B C D E F - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, // 0 - 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, // 1 - 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, // 2 - 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // 3 - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, // 4 - 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, // 5 - 96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, // 6 - 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 123,124,125,126,127, // 7 - 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, // 8 - 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, // 9 - 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175, // A - 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, // B - 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207, // C - 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223, // D - 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239, // E - 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255 // F - }; - } - //! \endcond - -} -} // end namespace cereal - -// Undefine internal macros -#undef CEREAL_RAPIDXML_PARSE_ERROR - -// On MSVC, restore warnings state -#ifdef _MSC_VER - #pragma warning(pop) -#endif - -#endif diff --git a/include/cereal/external/rapidxml/rapidxml_iterators.hpp b/include/cereal/external/rapidxml/rapidxml_iterators.hpp deleted file mode 100644 index 736d46c..0000000 --- a/include/cereal/external/rapidxml/rapidxml_iterators.hpp +++ /dev/null @@ -1,175 +0,0 @@ -#ifndef CEREAL_RAPIDXML_ITERATORS_HPP_INCLUDED -#define CEREAL_RAPIDXML_ITERATORS_HPP_INCLUDED - -// Copyright (C) 2006, 2009 Marcin Kalicinski -// Version 1.13 -// Revision $DateTime: 2009/05/13 01:46:17 $ - -#include "rapidxml.hpp" - -namespace cereal { -namespace rapidxml -{ - - //! Iterator of child nodes of xml_node - template - class node_iterator - { - - public: - - typedef typename xml_node value_type; - typedef typename xml_node &reference; - typedef typename xml_node *pointer; - typedef std::ptrdiff_t difference_type; - typedef std::bidirectional_iterator_tag iterator_category; - - node_iterator() - : m_node(0) - { - } - - node_iterator(xml_node *node) - : m_node(node->first_node()) - { - } - - reference operator *() const - { - assert(m_node); - return *m_node; - } - - pointer operator->() const - { - assert(m_node); - return m_node; - } - - node_iterator& operator++() - { - assert(m_node); - m_node = m_node->next_sibling(); - return *this; - } - - node_iterator operator++(int) - { - node_iterator tmp = *this; - ++this; - return tmp; - } - - node_iterator& operator--() - { - assert(m_node && m_node->previous_sibling()); - m_node = m_node->previous_sibling(); - return *this; - } - - node_iterator operator--(int) - { - node_iterator tmp = *this; - ++this; - return tmp; - } - - bool operator ==(const node_iterator &rhs) - { - return m_node == rhs.m_node; - } - - bool operator !=(const node_iterator &rhs) - { - return m_node != rhs.m_node; - } - - private: - - xml_node *m_node; - - }; - - //! Iterator of child attributes of xml_node - template - class attribute_iterator - { - - public: - - typedef typename xml_attribute value_type; - typedef typename xml_attribute &reference; - typedef typename xml_attribute *pointer; - typedef std::ptrdiff_t difference_type; - typedef std::bidirectional_iterator_tag iterator_category; - - attribute_iterator() - : m_attribute(0) - { - } - - attribute_iterator(xml_node *node) - : m_attribute(node->first_attribute()) - { - } - - reference operator *() const - { - assert(m_attribute); - return *m_attribute; - } - - pointer operator->() const - { - assert(m_attribute); - return m_attribute; - } - - attribute_iterator& operator++() - { - assert(m_attribute); - m_attribute = m_attribute->next_attribute(); - return *this; - } - - attribute_iterator operator++(int) - { - attribute_iterator tmp = *this; - ++this; - return tmp; - } - - attribute_iterator& operator--() - { - assert(m_attribute && m_attribute->previous_attribute()); - m_attribute = m_attribute->previous_attribute(); - return *this; - } - - attribute_iterator operator--(int) - { - attribute_iterator tmp = *this; - ++this; - return tmp; - } - - bool operator ==(const attribute_iterator &rhs) - { - return m_attribute == rhs.m_attribute; - } - - bool operator !=(const attribute_iterator &rhs) - { - return m_attribute != rhs.m_attribute; - } - - private: - - xml_attribute *m_attribute; - - }; - -} -} // namespace cereal - -#endif diff --git a/include/cereal/external/rapidxml/rapidxml_print.hpp b/include/cereal/external/rapidxml/rapidxml_print.hpp deleted file mode 100644 index 7fbb962..0000000 --- a/include/cereal/external/rapidxml/rapidxml_print.hpp +++ /dev/null @@ -1,428 +0,0 @@ -#ifndef CEREAL_RAPIDXML_PRINT_HPP_INCLUDED -#define CEREAL_RAPIDXML_PRINT_HPP_INCLUDED - -// Copyright (C) 2006, 2009 Marcin Kalicinski -// Version 1.13 -// Revision $DateTime: 2009/05/13 01:46:17 $ - -#include "rapidxml.hpp" - -// Only include streams if not disabled -#ifndef CEREAL_RAPIDXML_NO_STREAMS - #include - #include -#endif - -namespace cereal { -namespace rapidxml -{ - - /////////////////////////////////////////////////////////////////////// - // Printing flags - - const int print_no_indenting = 0x1; //!< Printer flag instructing the printer to suppress indenting of XML. See print() function. - - /////////////////////////////////////////////////////////////////////// - // Internal - - //! \cond internal - namespace internal - { - - /////////////////////////////////////////////////////////////////////////// - // Internal character operations - - // Copy characters from given range to given output iterator - template - inline OutIt copy_chars(const Ch *begin, const Ch *end, OutIt out) - { - while (begin != end) - *out++ = *begin++; - return out; - } - - // Copy characters from given range to given output iterator and expand - // characters into references (< > ' " &) - template - inline OutIt copy_and_expand_chars(const Ch *begin, const Ch *end, Ch noexpand, OutIt out) - { - while (begin != end) - { - if (*begin == noexpand) - { - *out++ = *begin; // No expansion, copy character - } - else - { - switch (*begin) - { - case Ch('<'): - *out++ = Ch('&'); *out++ = Ch('l'); *out++ = Ch('t'); *out++ = Ch(';'); - break; - case Ch('>'): - *out++ = Ch('&'); *out++ = Ch('g'); *out++ = Ch('t'); *out++ = Ch(';'); - break; - case Ch('\''): - *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('p'); *out++ = Ch('o'); *out++ = Ch('s'); *out++ = Ch(';'); - break; - case Ch('"'): - *out++ = Ch('&'); *out++ = Ch('q'); *out++ = Ch('u'); *out++ = Ch('o'); *out++ = Ch('t'); *out++ = Ch(';'); - break; - case Ch('&'): - *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('m'); *out++ = Ch('p'); *out++ = Ch(';'); - break; - default: - *out++ = *begin; // No expansion, copy character - } - } - ++begin; // Step to next character - } - return out; - } - - // Fill given output iterator with repetitions of the same character - template - inline OutIt fill_chars(OutIt out, int n, Ch ch) - { - for (int i = 0; i < n; ++i) - *out++ = ch; - return out; - } - - // Find character - template - inline bool find_char(const Ch *begin, const Ch *end) - { - while (begin != end) - if (*begin++ == ch) - return true; - return false; - } - - /////////////////////////////////////////////////////////////////////////// - // Internal printing operations - - // Print node - template - inline OutIt print_node(OutIt out, const xml_node *node, int flags, int indent); - - // Print children of the node - template - inline OutIt print_children(OutIt out, const xml_node *node, int flags, int indent) - { - for (xml_node *child = node->first_node(); child; child = child->next_sibling()) - out = print_node(out, child, flags, indent); - return out; - } - - // Print attributes of the node - template - inline OutIt print_attributes(OutIt out, const xml_node *node, int /*flags*/) - { - for (xml_attribute *attribute = node->first_attribute(); attribute; attribute = attribute->next_attribute()) - { - if (attribute->name() && attribute->value()) - { - // Print attribute name - *out = Ch(' '), ++out; - out = copy_chars(attribute->name(), attribute->name() + attribute->name_size(), out); - *out = Ch('='), ++out; - // Print attribute value using appropriate quote type - if (find_char(attribute->value(), attribute->value() + attribute->value_size())) - { - *out = Ch('\''), ++out; - out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('"'), out); - *out = Ch('\''), ++out; - } - else - { - *out = Ch('"'), ++out; - out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('\''), out); - *out = Ch('"'), ++out; - } - } - } - return out; - } - - // Print data node - template - inline OutIt print_data_node(OutIt out, const xml_node *node, int flags, int indent) - { - assert(node->type() == node_data); - if (!(flags & print_no_indenting)) - out = fill_chars(out, indent, Ch('\t')); - out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out); - return out; - } - - // Print data node - template - inline OutIt print_cdata_node(OutIt out, const xml_node *node, int flags, int indent) - { - assert(node->type() == node_cdata); - if (!(flags & print_no_indenting)) - out = fill_chars(out, indent, Ch('\t')); - *out = Ch('<'); ++out; - *out = Ch('!'); ++out; - *out = Ch('['); ++out; - *out = Ch('C'); ++out; - *out = Ch('D'); ++out; - *out = Ch('A'); ++out; - *out = Ch('T'); ++out; - *out = Ch('A'); ++out; - *out = Ch('['); ++out; - out = copy_chars(node->value(), node->value() + node->value_size(), out); - *out = Ch(']'); ++out; - *out = Ch(']'); ++out; - *out = Ch('>'); ++out; - return out; - } - - // Print element node - template - inline OutIt print_element_node(OutIt out, const xml_node *node, int flags, int indent) - { - assert(node->type() == node_element); - - // Print element name and attributes, if any - if (!(flags & print_no_indenting)) - out = fill_chars(out, indent, Ch('\t')); - *out = Ch('<'), ++out; - out = copy_chars(node->name(), node->name() + node->name_size(), out); - out = print_attributes(out, node, flags); - - // If node is childless - if (node->value_size() == 0 && !node->first_node()) - { - // Print childless node tag ending - *out = Ch('/'), ++out; - *out = Ch('>'), ++out; - } - else - { - // Print normal node tag ending - *out = Ch('>'), ++out; - - // Test if node contains a single data node only (and no other nodes) - xml_node *child = node->first_node(); - if (!child) - { - // If node has no children, only print its value without indenting - out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out); - } - else if (child->next_sibling() == 0 && child->type() == node_data) - { - // If node has a sole data child, only print its value without indenting - out = copy_and_expand_chars(child->value(), child->value() + child->value_size(), Ch(0), out); - } - else - { - // Print all children with full indenting - if (!(flags & print_no_indenting)) - *out = Ch('\n'), ++out; - out = print_children(out, node, flags, indent + 1); - if (!(flags & print_no_indenting)) - out = fill_chars(out, indent, Ch('\t')); - } - - // Print node end - *out = Ch('<'), ++out; - *out = Ch('/'), ++out; - out = copy_chars(node->name(), node->name() + node->name_size(), out); - *out = Ch('>'), ++out; - } - return out; - } - - // Print declaration node - template - inline OutIt print_declaration_node(OutIt out, const xml_node *node, int flags, int indent) - { - // Print declaration start - if (!(flags & print_no_indenting)) - out = fill_chars(out, indent, Ch('\t')); - *out = Ch('<'), ++out; - *out = Ch('?'), ++out; - *out = Ch('x'), ++out; - *out = Ch('m'), ++out; - *out = Ch('l'), ++out; - - // Print attributes - out = print_attributes(out, node, flags); - - // Print declaration end - *out = Ch('?'), ++out; - *out = Ch('>'), ++out; - - return out; - } - - // Print comment node - template - inline OutIt print_comment_node(OutIt out, const xml_node *node, int flags, int indent) - { - assert(node->type() == node_comment); - if (!(flags & print_no_indenting)) - out = fill_chars(out, indent, Ch('\t')); - *out = Ch('<'), ++out; - *out = Ch('!'), ++out; - *out = Ch('-'), ++out; - *out = Ch('-'), ++out; - out = copy_chars(node->value(), node->value() + node->value_size(), out); - *out = Ch('-'), ++out; - *out = Ch('-'), ++out; - *out = Ch('>'), ++out; - return out; - } - - // Print doctype node - template - inline OutIt print_doctype_node(OutIt out, const xml_node *node, int flags, int indent) - { - assert(node->type() == node_doctype); - if (!(flags & print_no_indenting)) - out = fill_chars(out, indent, Ch('\t')); - *out = Ch('<'), ++out; - *out = Ch('!'), ++out; - *out = Ch('D'), ++out; - *out = Ch('O'), ++out; - *out = Ch('C'), ++out; - *out = Ch('T'), ++out; - *out = Ch('Y'), ++out; - *out = Ch('P'), ++out; - *out = Ch('E'), ++out; - *out = Ch(' '), ++out; - out = copy_chars(node->value(), node->value() + node->value_size(), out); - *out = Ch('>'), ++out; - return out; - } - - // Print pi node - template - inline OutIt print_pi_node(OutIt out, const xml_node *node, int flags, int indent) - { - assert(node->type() == node_pi); - if (!(flags & print_no_indenting)) - out = fill_chars(out, indent, Ch('\t')); - *out = Ch('<'), ++out; - *out = Ch('?'), ++out; - out = copy_chars(node->name(), node->name() + node->name_size(), out); - *out = Ch(' '), ++out; - out = copy_chars(node->value(), node->value() + node->value_size(), out); - *out = Ch('?'), ++out; - *out = Ch('>'), ++out; - return out; - } - - // Print node - template - inline OutIt print_node(OutIt out, const xml_node *node, int flags, int indent) - { - // Print proper node type - switch (node->type()) - { - - // Document - case node_document: - out = print_children(out, node, flags, indent); - break; - - // Element - case node_element: - out = print_element_node(out, node, flags, indent); - break; - - // Data - case node_data: - out = print_data_node(out, node, flags, indent); - break; - - // CDATA - case node_cdata: - out = print_cdata_node(out, node, flags, indent); - break; - - // Declaration - case node_declaration: - out = print_declaration_node(out, node, flags, indent); - break; - - // Comment - case node_comment: - out = print_comment_node(out, node, flags, indent); - break; - - // Doctype - case node_doctype: - out = print_doctype_node(out, node, flags, indent); - break; - - // Pi - case node_pi: - out = print_pi_node(out, node, flags, indent); - break; - -#ifndef __GNUC__ - // Unknown - default: - assert(0); - break; -#endif - } - - // If indenting not disabled, add line break after node - if (!(flags & print_no_indenting)) - *out = Ch('\n'), ++out; - - // Return modified iterator - return out; - } - - } - //! \endcond - - /////////////////////////////////////////////////////////////////////////// - // Printing - - //! Prints XML to given output iterator. - //! \param out Output iterator to print to. - //! \param node Node to be printed. Pass xml_document to print entire document. - //! \param flags Flags controlling how XML is printed. - //! \return Output iterator pointing to position immediately after last character of printed text. - template - inline OutIt print(OutIt out, const xml_node &node, int flags = 0) - { - return internal::print_node(out, &node, flags, 0); - } - -#ifndef CEREAL_RAPIDXML_NO_STREAMS - - //! Prints XML to given output stream. - //! \param out Output stream to print to. - //! \param node Node to be printed. Pass xml_document to print entire document. - //! \param flags Flags controlling how XML is printed. - //! \return Output stream. - template - inline std::basic_ostream &print(std::basic_ostream &out, const xml_node &node, int flags = 0) - { - print(std::ostream_iterator(out), node, flags); - return out; - } - - //! Prints formatted XML to given output stream. Uses default printing flags. Use print() function to customize printing process. - //! \param out Output stream to print to. - //! \param node Node to be printed. - //! \return Output stream. - template - inline std::basic_ostream &operator <<(std::basic_ostream &out, const xml_node &node) - { - return print(out, node); - } - -#endif - -} -} // namespace cereal - -#endif diff --git a/include/cereal/external/rapidxml/rapidxml_utils.hpp b/include/cereal/external/rapidxml/rapidxml_utils.hpp deleted file mode 100644 index e11ecf3..0000000 --- a/include/cereal/external/rapidxml/rapidxml_utils.hpp +++ /dev/null @@ -1,123 +0,0 @@ -#ifndef CEREAL_RAPIDXML_UTILS_HPP_INCLUDED -#define CEREAL_RAPIDXML_UTILS_HPP_INCLUDED - -// Copyright (C) 2006, 2009 Marcin Kalicinski -// Version 1.13 -// Revision $DateTime: 2009/05/13 01:46:17 $ -//! in certain simple scenarios. They should probably not be used if maximizing performance is the main objective. - -#include "rapidxml.hpp" -#include -#include -#include -#include - -namespace cereal { -namespace rapidxml -{ - - //! Represents data loaded from a file - template - class file - { - - public: - - //! Loads file into the memory. Data will be automatically destroyed by the destructor. - //! \param filename Filename to load. - file(const char *filename) - { - using namespace std; - - // Open stream - basic_ifstream stream(filename, ios::binary); - if (!stream) - throw runtime_error(string("cannot open file ") + filename); - stream.unsetf(ios::skipws); - - // Determine stream size - stream.seekg(0, ios::end); - size_t size = stream.tellg(); - stream.seekg(0); - - // Load data and add terminating 0 - m_data.resize(size + 1); - stream.read(&m_data.front(), static_cast(size)); - m_data[size] = 0; - } - - //! Loads file into the memory. Data will be automatically destroyed by the destructor - //! \param stream Stream to load from - file(std::basic_istream &stream) - { - using namespace std; - - // Load data and add terminating 0 - stream.unsetf(ios::skipws); - m_data.assign(istreambuf_iterator(stream), istreambuf_iterator()); - if (stream.fail() || stream.bad()) - throw runtime_error("error reading stream"); - m_data.push_back(0); - } - - //! Gets file data. - //! \return Pointer to data of file. - Ch *data() - { - return &m_data.front(); - } - - //! Gets file data. - //! \return Pointer to data of file. - const Ch *data() const - { - return &m_data.front(); - } - - //! Gets file data size. - //! \return Size of file data, in characters. - std::size_t size() const - { - return m_data.size(); - } - - private: - - std::vector m_data; // File data - - }; - - //! Counts children of node. Time complexity is O(n). - //! \return Number of children of node - template - inline std::size_t count_children(xml_node *node) - { - xml_node *child = node->first_node(); - std::size_t count = 0; - while (child) - { - ++count; - child = child->next_sibling(); - } - return count; - } - - //! Counts attributes of node. Time complexity is O(n). - //! \return Number of attributes of node - template - inline std::size_t count_attributes(xml_node *node) - { - xml_attribute *attr = node->first_attribute(); - std::size_t count = 0; - while (attr) - { - ++count; - attr = attr->next_attribute(); - } - return count; - } - -} -} // namespace cereal - -#endif diff --git a/include/cereal/macros.hpp b/include/cereal/macros.hpp deleted file mode 100644 index 85cf9b5..0000000 --- a/include/cereal/macros.hpp +++ /dev/null @@ -1,156 +0,0 @@ -/*! \file macros.hpp - \brief Preprocessor macros that can customise the cereal library - - By default, cereal looks for serialization functions with very - specific names, that is: serialize, load, save, load_minimal, - or save_minimal. - - This file allows an advanced user to change these names to conform - to some other style or preference. This is implemented using - preprocessor macros. - - As a result of this, in internal cereal code you will see macros - used for these function names. In user code, you should name - the functions like you normally would and not use the macros - to improve readability. - \ingroup utility */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef CEREAL_MACROS_HPP_ -#define CEREAL_MACROS_HPP_ - -#ifndef CEREAL_THREAD_SAFE -//! Whether cereal should be compiled for a threaded environment -/*! This macro causes cereal to use mutexes to control access to - global internal state in a thread safe manner. - - Note that even with this enabled you must still ensure that - archives are accessed by only one thread at a time; it is safe - to use multiple archives in parallel, but not to access one archive - from many places simultaneously. */ -#define CEREAL_THREAD_SAFE 0 -#endif // CEREAL_THREAD_SAFE - -#ifndef CEREAL_SIZE_TYPE -//! Determines the data type used for size_type -/*! cereal uses size_type to ensure that the serialized size of - dynamic containers is compatible across different architectures - (e.g. 32 vs 64 bit), which may use different underlying types for - std::size_t. - - More information can be found in cereal/details/helpers.hpp. - - If you choose to modify this type, ensure that you use a fixed - size type (e.g. uint32_t). */ -#define CEREAL_SIZE_TYPE uint64_t -#endif // CEREAL_SIZE_TYPE - -// ###################################################################### -#ifndef CEREAL_SERIALIZE_FUNCTION_NAME -//! The serialization/deserialization function name to search for. -/*! You can define @c CEREAL_SERIALIZE_FUNCTION_NAME to be different assuming - you do so before this file is included. */ -#define CEREAL_SERIALIZE_FUNCTION_NAME serialize -#endif // CEREAL_SERIALIZE_FUNCTION_NAME - -#ifndef CEREAL_LOAD_FUNCTION_NAME -//! The deserialization (load) function name to search for. -/*! You can define @c CEREAL_LOAD_FUNCTION_NAME to be different assuming you do so - before this file is included. */ -#define CEREAL_LOAD_FUNCTION_NAME load -#endif // CEREAL_LOAD_FUNCTION_NAME - -#ifndef CEREAL_SAVE_FUNCTION_NAME -//! The serialization (save) function name to search for. -/*! You can define @c CEREAL_SAVE_FUNCTION_NAME to be different assuming you do so - before this file is included. */ -#define CEREAL_SAVE_FUNCTION_NAME save -#endif // CEREAL_SAVE_FUNCTION_NAME - -#ifndef CEREAL_LOAD_MINIMAL_FUNCTION_NAME -//! The deserialization (load_minimal) function name to search for. -/*! You can define @c CEREAL_LOAD_MINIMAL_FUNCTION_NAME to be different assuming you do so - before this file is included. */ -#define CEREAL_LOAD_MINIMAL_FUNCTION_NAME load_minimal -#endif // CEREAL_LOAD_MINIMAL_FUNCTION_NAME - -#ifndef CEREAL_SAVE_MINIMAL_FUNCTION_NAME -//! The serialization (save_minimal) function name to search for. -/*! You can define @c CEREAL_SAVE_MINIMAL_FUNCTION_NAME to be different assuming you do so - before this file is included. */ -#define CEREAL_SAVE_MINIMAL_FUNCTION_NAME save_minimal -#endif // CEREAL_SAVE_MINIMAL_FUNCTION_NAME - -// ###################################################################### -//! Defines the CEREAL_NOEXCEPT macro to use instead of noexcept -/*! If a compiler we support does not support noexcept, this macro - will detect this and define CEREAL_NOEXCEPT as a no-op - @internal */ -#if !defined(CEREAL_HAS_NOEXCEPT) - #if defined(__clang__) - #if __has_feature(cxx_noexcept) - #define CEREAL_HAS_NOEXCEPT - #endif - #else // NOT clang - #if defined(__GXX_EXPERIMENTAL_CXX0X__) && __GNUC__ * 10 + __GNUC_MINOR__ >= 46 || \ - defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 190023026 - #define CEREAL_HAS_NOEXCEPT - #endif // end GCC/MSVC check - #endif // end NOT clang block - - #ifndef CEREAL_NOEXCEPT - #ifdef CEREAL_HAS_NOEXCEPT - #define CEREAL_NOEXCEPT noexcept - #else - #define CEREAL_NOEXCEPT - #endif // end CEREAL_HAS_NOEXCEPT - #endif // end !defined(CEREAL_HAS_NOEXCEPT) -#endif // ifndef CEREAL_NOEXCEPT - -// ###################################################################### -//! Checks if C++17 is available -//! NOTE: clang v5 has a bug with inline variables, so disable C++17 on that compiler -#if (__cplusplus >= 201703L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)) \ - && (!defined(__clang__) || __clang_major__ > 5) -#define CEREAL_HAS_CPP17 -#endif - -//! Checks if C++14 is available -#if __cplusplus >= 201402L -#define CEREAL_HAS_CPP14 -#endif - -// ###################################################################### -//! Defines the CEREAL_ALIGNOF macro to use instead of alignof -#if defined(_MSC_VER) && _MSC_VER < 1900 -#define CEREAL_ALIGNOF __alignof -#else // not MSVC 2013 or older -#define CEREAL_ALIGNOF alignof -#endif // end MSVC check - -#endif // CEREAL_MACROS_HPP_ diff --git a/include/cereal/specialize.hpp b/include/cereal/specialize.hpp deleted file mode 100644 index da9c9a5..0000000 --- a/include/cereal/specialize.hpp +++ /dev/null @@ -1,139 +0,0 @@ -/*! \file specialize.hpp - \brief Serialization disambiguation */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef CEREAL_SPECIALIZE_HPP_ -#define CEREAL_SPECIALIZE_HPP_ - -namespace cereal -{ - // Forward declaration of access class that users can become friends with - class access; - - // ###################################################################### - //! A specifier used in conjunction with cereal::specialize to disambiguate - //! serialization in special cases - /*! @relates specialize - @ingroup Access */ - enum class specialization - { - member_serialize, //!< Force the use of a member serialize function - member_load_save, //!< Force the use of a member load/save pair - member_load_save_minimal, //!< Force the use of a member minimal load/save pair - non_member_serialize, //!< Force the use of a non-member serialize function - non_member_load_save, //!< Force the use of a non-member load/save pair - non_member_load_save_minimal //!< Force the use of a non-member minimal load/save pair - }; - - //! A class used to disambiguate cases where cereal cannot detect a unique way of serializing a class - /*! cereal attempts to figure out which method of serialization (member vs. non-member serialize - or load/save pair) at compile time. If for some reason cereal cannot find a non-ambiguous way - of serializing a type, it will produce a static assertion complaining about this. - - This can happen because you have both a serialize and load/save pair, or even because a base - class has a serialize (public or private with friend access) and a derived class does not - overwrite this due to choosing some other serialization type. - - Specializing this class will tell cereal to explicitly use the serialization type you specify - and it will not complain about ambiguity in its compile time selection. However, if cereal detects - an ambiguity in specializations, it will continue to issue a static assertion. - - @code{.cpp} - class MyParent - { - friend class cereal::access; - template - void serialize( Archive & ar ) {} - }; - - // Although serialize is private in MyParent, to cereal::access it will look public, - // even through MyDerived - class MyDerived : public MyParent - { - public: - template - void load( Archive & ar ) {} - - template - void save( Archive & ar ) {} - }; - - // The load/save pair in MyDerived is ambiguous because serialize in MyParent can - // be accessed from cereal::access. This looks the same as making serialize public - // in MyParent, making it seem as though MyDerived has both a serialize and a load/save pair. - // cereal will complain about this at compile time unless we disambiguate: - - namespace cereal - { - // This struct specialization will tell cereal which is the right way to serialize the ambiguity - template struct specialize {}; - - // If we only had a disambiguation for a specific archive type, it would look something like this - template <> struct specialize {}; - } - @endcode - - You can also choose to use the macros CEREAL_SPECIALIZE_FOR_ALL_ARCHIVES or - CEREAL_SPECIALIZE_FOR_ARCHIVE if you want to type a little bit less. - - @tparam T The type to specialize the serialization for - @tparam S The specialization type to use for T - @ingroup Access */ - template - struct specialize : public std::false_type {}; - - //! Convenient macro for performing specialization for all archive types - /*! This performs specialization for the specific type for all types of archives. - This macro should be placed at the global namespace. - - @code{cpp} - struct MyType {}; - CEREAL_SPECIALIZE_FOR_ALL_ARCHIVES( MyType, cereal::specialization::member_load_save ); - @endcode - - @relates specialize - @ingroup Access */ - #define CEREAL_SPECIALIZE_FOR_ALL_ARCHIVES( Type, Specialization ) \ - namespace cereal { template struct specialize {}; } - - //! Convenient macro for performing specialization for a single archive type - /*! This performs specialization for the specific type for a single type of archive. - This macro should be placed at the global namespace. - - @code{cpp} - struct MyType {}; - CEREAL_SPECIALIZE_FOR_ARCHIVE( cereal::XMLInputArchive, MyType, cereal::specialization::member_load_save ); - @endcode - - @relates specialize - @ingroup Access */ - #define CEREAL_SPECIALIZE_FOR_ARCHIVE( Archive, Type, Specialization ) \ - namespace cereal { template <> struct specialize {}; } -} - -#endif diff --git a/include/cereal/types/array.hpp b/include/cereal/types/array.hpp deleted file mode 100644 index 8ae2a4a..0000000 --- a/include/cereal/types/array.hpp +++ /dev/null @@ -1,79 +0,0 @@ -/*! \file array.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_ARRAY_HPP_ -#define CEREAL_TYPES_ARRAY_HPP_ - -#include "cereal/cereal.hpp" -#include - -namespace cereal -{ - //! Saving for std::array primitive types - //! using binary serialization, if supported - template inline - typename std::enable_if, Archive>::value - && std::is_arithmetic::value, void>::type - CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::array const & array ) - { - ar( binary_data( array.data(), sizeof(array) ) ); - } - - //! Loading for std::array primitive types - //! using binary serialization, if supported - template inline - typename std::enable_if, Archive>::value - && std::is_arithmetic::value, void>::type - CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::array & array ) - { - ar( binary_data( array.data(), sizeof(array) ) ); - } - - //! Saving for std::array all other types - template inline - typename std::enable_if, Archive>::value - || !std::is_arithmetic::value, void>::type - CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::array const & array ) - { - for( auto const & i : array ) - ar( i ); - } - - //! Loading for std::array all other types - template inline - typename std::enable_if, Archive>::value - || !std::is_arithmetic::value, void>::type - CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::array & array ) - { - for( auto & i : array ) - ar( i ); - } -} // namespace cereal - -#endif // CEREAL_TYPES_ARRAY_HPP_ diff --git a/include/cereal/types/atomic.hpp b/include/cereal/types/atomic.hpp deleted file mode 100644 index e5ed5d9..0000000 --- a/include/cereal/types/atomic.hpp +++ /dev/null @@ -1,55 +0,0 @@ -/*! \file atomic.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_ATOMIC_HPP_ -#define CEREAL_TYPES_ATOMIC_HPP_ - -#include -#include - -namespace cereal -{ - //! Serializing (save) for std::atomic - template inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::atomic const & a ) - { - ar( CEREAL_NVP_("atomic_data", a.load()) ); - } - - //! Serializing (load) for std::atomic - template inline - void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::atomic & a ) - { - T tmp; - ar( CEREAL_NVP_("atomic_data", tmp) ); - a.store( tmp ); - } -} // namespace cereal - -#endif // CEREAL_TYPES_ATOMIC_HPP_ diff --git a/include/cereal/types/base_class.hpp b/include/cereal/types/base_class.hpp deleted file mode 100644 index 93275b4..0000000 --- a/include/cereal/types/base_class.hpp +++ /dev/null @@ -1,203 +0,0 @@ -/*! \file base_class.hpp - \brief Support for base classes (virtual and non-virtual) - \ingroup OtherTypes */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_BASE_CLASS_HPP_ -#define CEREAL_TYPES_BASE_CLASS_HPP_ - -#include "cereal/details/traits.hpp" -#include "cereal/details/polymorphic_impl_fwd.hpp" - -namespace cereal -{ - namespace base_class_detail - { - //! Used to register polymorphic relations and avoid the need to include - //! polymorphic.hpp when no polymorphism is used - /*! @internal */ - template ::value> - struct RegisterPolymorphicBaseClass - { - static void bind() - { } - }; - - //! Polymorphic version - /*! @internal */ - template - struct RegisterPolymorphicBaseClass - { - static void bind() - { detail::RegisterPolymorphicCaster::bind(); } - }; - } - - //! Casts a derived class to its non-virtual base class in a way that safely supports abstract classes - /*! This should be used in cases when a derived type needs to serialize its base type. This is better than directly - using static_cast, as it allows for serialization of pure virtual (abstract) base classes. - - This also automatically registers polymorphic relation between the base and derived class, assuming they - are indeed polymorphic. Note this is not the same as polymorphic type registration. For more information - see the documentation on polymorphism. If using a polymorphic class, be sure to include support for - polymorphism (cereal/types/polymorphic.hpp). - - \sa virtual_base_class - - @code{.cpp} - struct MyBase - { - int x; - - virtual void foo() = 0; - - template - void serialize( Archive & ar ) - { - ar( x ); - } - }; - - struct MyDerived : public MyBase //<-- Note non-virtual inheritance - { - int y; - - virtual void foo() {}; - - template - void serialize( Archive & ar ) - { - ar( cereal::base_class(this) ); - ar( y ); - } - }; - @endcode */ - template - struct base_class : private traits::detail::BaseCastBase - { - template - base_class(Derived const * derived) : - base_ptr(const_cast(static_cast(derived))) - { - static_assert( std::is_base_of::value, "Can only use base_class on a valid base class" ); - base_class_detail::RegisterPolymorphicBaseClass::bind(); - } - - Base * base_ptr; - }; - - //! Casts a derived class to its virtual base class in a way that allows cereal to track inheritance - /*! This should be used in cases when a derived type features virtual inheritance from some - base type. This allows cereal to track the inheritance and to avoid making duplicate copies - during serialization. - - It is safe to use virtual_base_class in all circumstances for serializing base classes, even in cases - where virtual inheritance does not take place, though it may be slightly faster to utilize - cereal::base_class<> if you do not need to worry about virtual inheritance. - - This also automatically registers polymorphic relation between the base and derived class, assuming they - are indeed polymorphic. Note this is not the same as polymorphic type registration. For more information - see the documentation on polymorphism. If using a polymorphic class, be sure to include support for - polymorphism (cereal/types/polymorphic.hpp). - - \sa base_class - - @code{.cpp} - struct MyBase - { - int x; - - template - void serialize( Archive & ar ) - { - ar( x ); - } - }; - - struct MyLeft : virtual MyBase //<-- Note the virtual inheritance - { - int y; - - template - void serialize( Archive & ar ) - { - ar( cereal::virtual_base_class( this ) ); - ar( y ); - } - }; - - struct MyRight : virtual MyBase - { - int z; - - template - void serialize( Archive & ar ) - { - ar( cereal::virtual_base_clas( this ) ); - ar( z ); - } - }; - - // diamond virtual inheritance; contains one copy of each base class - struct MyDerived : virtual MyLeft, virtual MyRight - { - int a; - - template - void serialize( Archive & ar ) - { - ar( cereal::virtual_base_class( this ) ); // safely serialize data members in MyLeft - ar( cereal::virtual_base_class( this ) ); // safely serialize data members in MyRight - ar( a ); - - // Because we used virtual_base_class, cereal will ensure that only one instance of MyBase is - // serialized as we traverse the inheritance heirarchy. This means that there will be one copy - // each of the variables x, y, z, and a - - // If we had chosen to use static_cast<> instead, cereal would perform no tracking and - // assume that every base class should be serialized (in this case leading to a duplicate - // serialization of MyBase due to diamond inheritance - }; - } - @endcode */ - template - struct virtual_base_class : private traits::detail::BaseCastBase - { - template - virtual_base_class(Derived const * derived) : - base_ptr(const_cast(static_cast(derived))) - { - static_assert( std::is_base_of::value, "Can only use virtual_base_class on a valid base class" ); - base_class_detail::RegisterPolymorphicBaseClass::bind(); - } - - Base * base_ptr; - }; - -} // namespace cereal - -#endif // CEREAL_TYPES_BASE_CLASS_HPP_ diff --git a/include/cereal/types/bitset.hpp b/include/cereal/types/bitset.hpp deleted file mode 100644 index 6231d6f..0000000 --- a/include/cereal/types/bitset.hpp +++ /dev/null @@ -1,176 +0,0 @@ -/*! \file bitset.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_BITSET_HPP_ -#define CEREAL_TYPES_BITSET_HPP_ - -#include "cereal/cereal.hpp" -#include "cereal/types/string.hpp" -#include - -namespace cereal -{ - namespace bitset_detail - { - //! The type the bitset is encoded with - /*! @internal */ - enum class type : uint8_t - { - ulong, - ullong, - string, - bits - }; - } - - //! Serializing (save) for std::bitset when BinaryData optimization supported - template , Archive>::value> - = traits::sfinae> inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::bitset const & bits ) - { - ar( CEREAL_NVP_("type", bitset_detail::type::bits) ); - - // Serialize 8 bit chunks - std::uint8_t chunk = 0; - std::uint8_t mask = 0x80; - - // Set each chunk using a rotating mask for the current bit - for( std::size_t i = 0; i < N; ++i ) - { - if( bits[i] ) - chunk |= mask; - - mask = static_cast(mask >> 1); - - // output current chunk when mask is empty (8 bits) - if( mask == 0 ) - { - ar( chunk ); - chunk = 0; - mask = 0x80; - } - } - - // serialize remainder, if it exists - if( mask != 0x80 ) - ar( chunk ); - } - - //! Serializing (save) for std::bitset when BinaryData is not supported - template , Archive>::value> - = traits::sfinae> inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::bitset const & bits ) - { - try - { - auto const b = bits.to_ulong(); - ar( CEREAL_NVP_("type", bitset_detail::type::ulong) ); - ar( CEREAL_NVP_("data", b) ); - } - catch( std::overflow_error const & ) - { - try - { - auto const b = bits.to_ullong(); - ar( CEREAL_NVP_("type", bitset_detail::type::ullong) ); - ar( CEREAL_NVP_("data", b) ); - } - catch( std::overflow_error const & ) - { - ar( CEREAL_NVP_("type", bitset_detail::type::string) ); - ar( CEREAL_NVP_("data", bits.to_string()) ); - } - } - } - - //! Serializing (load) for std::bitset - template inline - void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::bitset & bits ) - { - bitset_detail::type t; - ar( CEREAL_NVP_("type", t) ); - - switch( t ) - { - case bitset_detail::type::ulong: - { - unsigned long b; - ar( CEREAL_NVP_("data", b) ); - bits = std::bitset( b ); - break; - } - case bitset_detail::type::ullong: - { - unsigned long long b; - ar( CEREAL_NVP_("data", b) ); - bits = std::bitset( b ); - break; - } - case bitset_detail::type::string: - { - std::string b; - ar( CEREAL_NVP_("data", b) ); - bits = std::bitset( b ); - break; - } - case bitset_detail::type::bits: - { - // Normally we would use BinaryData to route this at compile time, - // but doing this at runtime doesn't break any old serialization - std::uint8_t chunk = 0; - std::uint8_t mask = 0; - - bits.reset(); - - // Load one chunk at a time, rotating through the chunk - // to set bits in the bitset - for( std::size_t i = 0; i < N; ++i ) - { - if( mask == 0 ) - { - ar( chunk ); - mask = 0x80; - } - - if( chunk & mask ) - bits[i] = 1; - - mask = static_cast(mask >> 1); - } - break; - } - default: - throw Exception("Invalid bitset data representation"); - } - } -} // namespace cereal - -#endif // CEREAL_TYPES_BITSET_HPP_ diff --git a/include/cereal/types/boost_variant.hpp b/include/cereal/types/boost_variant.hpp deleted file mode 100644 index 74a339e..0000000 --- a/include/cereal/types/boost_variant.hpp +++ /dev/null @@ -1,164 +0,0 @@ -/*! \file boost_variant.hpp - \brief Support for boost::variant - \ingroup OtherTypes */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_BOOST_VARIANT_HPP_ -#define CEREAL_TYPES_BOOST_VARIANT_HPP_ - -//! @internal -#if defined(_MSC_VER) && _MSC_VER < 1911 -#define CEREAL_CONSTEXPR_LAMBDA -#else // MSVC 2017 or newer, all other compilers -#define CEREAL_CONSTEXPR_LAMBDA constexpr -#endif - -#include "cereal/cereal.hpp" -#include -#include - -namespace cereal -{ - namespace boost_variant_detail - { - //! @internal - template - struct variant_save_visitor : boost::static_visitor<> - { - variant_save_visitor(Archive & ar_) : ar(ar_) {} - - template - void operator()(T const & value) const - { - ar( CEREAL_NVP_("data", value) ); - } - - Archive & ar; - }; - - //! @internal - template - struct LoadAndConstructLoadWrapper - { - using ST = typename std::aligned_storage::type; - - LoadAndConstructLoadWrapper() : - construct( reinterpret_cast( &st ) ) - { } - - ~LoadAndConstructLoadWrapper() - { - if (construct.itsValid) - { - construct->~T(); - } - } - - void CEREAL_SERIALIZE_FUNCTION_NAME( Archive & ar ) - { - ::cereal::detail::Construct::load_andor_construct( ar, construct ); - } - - ST st; - ::cereal::construct construct; - }; - - //! @internal - template struct load_variant_wrapper; - - //! Avoid serializing variant void_ type - /*! @internal */ - template <> - struct load_variant_wrapper - { - template - static void load_variant( Archive &, Variant & ) - { } - }; - - //! @internal - template - struct load_variant_wrapper - { - // default constructible - template - static void load_variant_impl( Archive & ar, Variant & variant, std::true_type ) - { - T value; - ar( CEREAL_NVP_("data", value) ); - variant = std::move(value); - } - - // not default constructible - template - static void load_variant_impl(Archive & ar, Variant & variant, std::false_type ) - { - LoadAndConstructLoadWrapper loadWrapper; - - ar( CEREAL_NVP_("data", loadWrapper) ); - variant = std::move(*loadWrapper.construct.ptr()); - } - - //! @internal - template - static void load_variant(Archive & ar, Variant & variant) - { - load_variant_impl( ar, variant, typename std::is_default_constructible::type() ); - } - }; - } // namespace boost_variant_detail - - //! Saving for boost::variant - template inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, boost::variant const & variant ) - { - int32_t which = variant.which(); - ar( CEREAL_NVP_("which", which) ); - boost_variant_detail::variant_save_visitor visitor(ar); - variant.apply_visitor(visitor); - } - - //! Loading for boost::variant - template inline - void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, boost::variant & variant ) - { - int32_t which; - ar( CEREAL_NVP_("which", which) ); - - using LoadFuncType = void(*)(Archive &, boost::variant &); - CEREAL_CONSTEXPR_LAMBDA LoadFuncType loadFuncArray[] = {&boost_variant_detail::load_variant_wrapper::load_variant...}; - - if(which >= int32_t(sizeof(loadFuncArray)/sizeof(loadFuncArray[0]))) - throw Exception("Invalid 'which' selector when deserializing boost::variant"); - - loadFuncArray[which](ar, variant); - } -} // namespace cereal - -#undef CEREAL_CONSTEXPR_LAMBDA - -#endif // CEREAL_TYPES_BOOST_VARIANT_HPP_ diff --git a/include/cereal/types/chrono.hpp b/include/cereal/types/chrono.hpp deleted file mode 100644 index da1ef42..0000000 --- a/include/cereal/types/chrono.hpp +++ /dev/null @@ -1,72 +0,0 @@ -/*! \file chrono.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_CHRONO_HPP_ -#define CEREAL_TYPES_CHRONO_HPP_ - -#include - -namespace cereal -{ - //! Saving std::chrono::duration - template inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::chrono::duration const & dur ) - { - ar( CEREAL_NVP_("count", dur.count()) ); - } - - //! Loading std::chrono::duration - template inline - void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::chrono::duration & dur ) - { - R count; - ar( CEREAL_NVP_("count", count) ); - - dur = std::chrono::duration{count}; - } - - //! Saving std::chrono::time_point - template inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::chrono::time_point const & dur ) - { - ar( CEREAL_NVP_("time_since_epoch", dur.time_since_epoch()) ); - } - - //! Loading std::chrono::time_point - template inline - void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::chrono::time_point & dur ) - { - D elapsed; - ar( CEREAL_NVP_("time_since_epoch", elapsed) ); - - dur = std::chrono::time_point{elapsed}; - } -} // namespace cereal - -#endif // CEREAL_TYPES_CHRONO_HPP_ diff --git a/include/cereal/types/common.hpp b/include/cereal/types/common.hpp deleted file mode 100644 index 4ea67e2..0000000 --- a/include/cereal/types/common.hpp +++ /dev/null @@ -1,129 +0,0 @@ -/*! \file common.hpp - \brief Support common types - always included automatically - \ingroup OtherTypes */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_COMMON_HPP_ -#define CEREAL_TYPES_COMMON_HPP_ - -#include "cereal/cereal.hpp" - -namespace cereal -{ - namespace common_detail - { - //! Serialization for arrays if BinaryData is supported and we are arithmetic - /*! @internal */ - template inline - void serializeArray( Archive & ar, T & array, std::true_type /* binary_supported */ ) - { - ar( binary_data( array, sizeof(array) ) ); - } - - //! Serialization for arrays if BinaryData is not supported or we are not arithmetic - /*! @internal */ - template inline - void serializeArray( Archive & ar, T & array, std::false_type /* binary_supported */ ) - { - for( auto & i : array ) - ar( i ); - } - - namespace - { - //! Gets the underlying type of an enum - /*! @internal */ - template - struct enum_underlying_type : std::false_type {}; - - //! Gets the underlying type of an enum - /*! Specialization for when we actually have an enum - @internal */ - template - struct enum_underlying_type { using type = typename std::underlying_type::type; }; - } // anon namespace - - //! Checks if a type is an enum - /*! This is needed over simply calling std::is_enum because the type - traits checking at compile time will attempt to call something like - load_minimal with a special NoConvertRef struct that wraps up the true type. - - This will strip away any of that and also expose the true underlying type. - @internal */ - template - class is_enum - { - private: - using DecayedT = typename std::decay::type; - using StrippedT = typename ::cereal::traits::strip_minimal::type; - - public: - static const bool value = std::is_enum::value; - using type = StrippedT; - using base_type = typename enum_underlying_type::type; - }; - } - - //! Saving for enum types - template inline - typename std::enable_if::value, - typename common_detail::is_enum::base_type>::type - CEREAL_SAVE_MINIMAL_FUNCTION_NAME( Archive const &, T const & t ) - { - return static_cast::base_type>(t); - } - - //! Loading for enum types - template inline - typename std::enable_if::value, void>::type - CEREAL_LOAD_MINIMAL_FUNCTION_NAME( Archive const &, T && t, - typename common_detail::is_enum::base_type const & value ) - { - t = reinterpret_cast::type const &>( value ); - } - - //! Serialization for raw pointers - /*! This exists only to throw a static_assert to let users know we don't support raw pointers. */ - template inline - void CEREAL_SERIALIZE_FUNCTION_NAME( Archive &, T * & ) - { - static_assert(cereal::traits::detail::delay_static_assert::value, - "Cereal does not support serializing raw pointers - please use a smart pointer"); - } - - //! Serialization for C style arrays - template inline - typename std::enable_if::value, void>::type - CEREAL_SERIALIZE_FUNCTION_NAME(Archive & ar, T & array) - { - common_detail::serializeArray( ar, array, - std::integral_constant, Archive>::value && - std::is_arithmetic::type>::value>() ); - } -} // namespace cereal - -#endif // CEREAL_TYPES_COMMON_HPP_ diff --git a/include/cereal/types/complex.hpp b/include/cereal/types/complex.hpp deleted file mode 100644 index b9b8691..0000000 --- a/include/cereal/types/complex.hpp +++ /dev/null @@ -1,56 +0,0 @@ -/*! \file complex.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_COMPLEX_HPP_ -#define CEREAL_TYPES_COMPLEX_HPP_ - -#include - -namespace cereal -{ - //! Serializing (save) for std::complex - template inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::complex const & comp ) - { - ar( CEREAL_NVP_("real", comp.real()), - CEREAL_NVP_("imag", comp.imag()) ); - } - - //! Serializing (load) for std::complex - template inline - void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::complex & bits ) - { - T real, imag; - ar( CEREAL_NVP_("real", real), - CEREAL_NVP_("imag", imag) ); - bits = {real, imag}; - } -} // namespace cereal - -#endif // CEREAL_TYPES_COMPLEX_HPP_ diff --git a/include/cereal/types/concepts/pair_associative_container.hpp b/include/cereal/types/concepts/pair_associative_container.hpp deleted file mode 100644 index acfd418..0000000 --- a/include/cereal/types/concepts/pair_associative_container.hpp +++ /dev/null @@ -1,73 +0,0 @@ -/*! \file pair_associative_container.hpp - \brief Support for the PairAssociativeContainer refinement of the - AssociativeContainer concept. - \ingroup TypeConcepts */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_CONCEPTS_PAIR_ASSOCIATIVE_CONTAINER_HPP_ -#define CEREAL_CONCEPTS_PAIR_ASSOCIATIVE_CONTAINER_HPP_ - -#include "cereal/cereal.hpp" - -namespace cereal -{ - //! Saving for std-like pair associative containers - template class Map, typename... Args, typename = typename Map::mapped_type> inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, Map const & map ) - { - ar( make_size_tag( static_cast(map.size()) ) ); - - for( const auto & i : map ) - ar( make_map_item(i.first, i.second) ); - } - - //! Loading for std-like pair associative containers - template class Map, typename... Args, typename = typename Map::mapped_type> inline - void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, Map & map ) - { - size_type size; - ar( make_size_tag( size ) ); - - map.clear(); - - auto hint = map.begin(); - for( size_t i = 0; i < size; ++i ) - { - typename Map::key_type key; - typename Map::mapped_type value; - - ar( make_map_item(key, value) ); - #ifdef CEREAL_OLDER_GCC - hint = map.insert( hint, std::make_pair(std::move(key), std::move(value)) ); - #else // NOT CEREAL_OLDER_GCC - hint = map.emplace_hint( hint, std::move( key ), std::move( value ) ); - #endif // NOT CEREAL_OLDER_GCC - } - } -} // namespace cereal - -#endif // CEREAL_CONCEPTS_PAIR_ASSOCIATIVE_CONTAINER_HPP_ diff --git a/include/cereal/types/deque.hpp b/include/cereal/types/deque.hpp deleted file mode 100644 index 8b101dc..0000000 --- a/include/cereal/types/deque.hpp +++ /dev/null @@ -1,62 +0,0 @@ -/*! \file deque.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_DEQUE_HPP_ -#define CEREAL_TYPES_DEQUE_HPP_ - -#include "cereal/cereal.hpp" -#include - -namespace cereal -{ - //! Saving for std::deque - template inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::deque const & deque ) - { - ar( make_size_tag( static_cast(deque.size()) ) ); - - for( auto const & i : deque ) - ar( i ); - } - - //! Loading for std::deque - template inline - void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::deque & deque ) - { - size_type size; - ar( make_size_tag( size ) ); - - deque.resize( static_cast( size ) ); - - for( auto & i : deque ) - ar( i ); - } -} // namespace cereal - -#endif // CEREAL_TYPES_DEQUE_HPP_ diff --git a/include/cereal/types/forward_list.hpp b/include/cereal/types/forward_list.hpp deleted file mode 100644 index 2370863..0000000 --- a/include/cereal/types/forward_list.hpp +++ /dev/null @@ -1,68 +0,0 @@ -/*! \file forward_list.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_FORWARD_LIST_HPP_ -#define CEREAL_TYPES_FORWARD_LIST_HPP_ - -#include "cereal/cereal.hpp" -#include - -namespace cereal -{ - //! Saving for std::forward_list all other types - template inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::forward_list const & forward_list ) - { - // write the size - note that this is slow because we need to traverse - // the entire list. there are ways we could avoid this but this was chosen - // since it works in the most general fashion with any archive type - size_type const size = std::distance( forward_list.begin(), forward_list.end() ); - - ar( make_size_tag( size ) ); - - // write the list - for( const auto & i : forward_list ) - ar( i ); - } - - //! Loading for std::forward_list all other types from - template - void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::forward_list & forward_list ) - { - size_type size; - ar( make_size_tag( size ) ); - - forward_list.resize( static_cast( size ) ); - - for( auto & i : forward_list ) - ar( i ); - } -} // namespace cereal - -#endif // CEREAL_TYPES_FORWARD_LIST_HPP_ diff --git a/include/cereal/types/functional.hpp b/include/cereal/types/functional.hpp deleted file mode 100644 index 0b9cdf3..0000000 --- a/include/cereal/types/functional.hpp +++ /dev/null @@ -1,43 +0,0 @@ -/*! \file functional.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2016, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_FUNCTIONAL_HPP_ -#define CEREAL_TYPES_FUNCTIONAL_HPP_ - -#include - -namespace cereal -{ - //! Saving for std::less - template inline - void serialize( Archive &, std::less & ) - { } -} // namespace cereal - -#endif // CEREAL_TYPES_FUNCTIONAL_HPP_ diff --git a/include/cereal/types/list.hpp b/include/cereal/types/list.hpp deleted file mode 100644 index 00dd5ef..0000000 --- a/include/cereal/types/list.hpp +++ /dev/null @@ -1,62 +0,0 @@ -/*! \file list.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_LIST_HPP_ -#define CEREAL_TYPES_LIST_HPP_ - -#include "cereal/cereal.hpp" -#include - -namespace cereal -{ - //! Saving for std::list - template inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::list const & list ) - { - ar( make_size_tag( static_cast(list.size()) ) ); - - for( auto const & i : list ) - ar( i ); - } - - //! Loading for std::list - template inline - void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::list & list ) - { - size_type size; - ar( make_size_tag( size ) ); - - list.resize( static_cast( size ) ); - - for( auto & i : list ) - ar( i ); - } -} // namespace cereal - -#endif // CEREAL_TYPES_LIST_HPP_ diff --git a/include/cereal/types/map.hpp b/include/cereal/types/map.hpp deleted file mode 100644 index 329f033..0000000 --- a/include/cereal/types/map.hpp +++ /dev/null @@ -1,36 +0,0 @@ -/*! \file map.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_MAP_HPP_ -#define CEREAL_TYPES_MAP_HPP_ - -#include "cereal/types/concepts/pair_associative_container.hpp" -#include - -#endif // CEREAL_TYPES_MAP_HPP_ diff --git a/include/cereal/types/memory.hpp b/include/cereal/types/memory.hpp deleted file mode 100644 index a32e4c0..0000000 --- a/include/cereal/types/memory.hpp +++ /dev/null @@ -1,425 +0,0 @@ -/*! \file memory.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_SHARED_PTR_HPP_ -#define CEREAL_TYPES_SHARED_PTR_HPP_ - -#include "cereal/cereal.hpp" -#include -#include - -namespace cereal -{ - namespace memory_detail - { - //! A wrapper class to notify cereal that it is ok to serialize the contained pointer - /*! This mechanism allows us to intercept and properly handle polymorphic pointers - @internal */ - template - struct PtrWrapper - { - PtrWrapper(T && p) : ptr(std::forward(p)) {} - T & ptr; - - PtrWrapper( PtrWrapper const & ) = default; - PtrWrapper & operator=( PtrWrapper const & ) = delete; - }; - - //! Make a PtrWrapper - /*! @internal */ - template inline - PtrWrapper make_ptr_wrapper(T && t) - { - return {std::forward(t)}; - } - - //! A struct that acts as a wrapper around calling load_andor_construct - /*! The purpose of this is to allow a load_and_construct call to properly enter into the - 'data' NVP of the ptr_wrapper - @internal */ - template - struct LoadAndConstructLoadWrapper - { - LoadAndConstructLoadWrapper( T * ptr ) : - construct( ptr ) - { } - - //! Constructor for embedding an early call for restoring shared_from_this - template - LoadAndConstructLoadWrapper( T * ptr, F && sharedFromThisFunc ) : - construct( ptr, sharedFromThisFunc ) - { } - - inline void CEREAL_SERIALIZE_FUNCTION_NAME( Archive & ar ) - { - ::cereal::detail::Construct::load_andor_construct( ar, construct ); - } - - ::cereal::construct construct; - }; - - //! A helper struct for saving and restoring the state of types that derive from - //! std::enable_shared_from_this - /*! This special struct is necessary because when a user uses load_and_construct, - the weak_ptr (or whatever implementation defined variant) that allows - enable_shared_from_this to function correctly will not be initialized properly. - - This internal weak_ptr can also be modified by the shared_ptr that is created - during the serialization of a polymorphic pointer, where cereal creates a - wrapper shared_ptr out of a void pointer to the real data. - - In the case of load_and_construct, this happens because it is the allocation - of shared_ptr that perform this initialization, which we let happen on a buffer - of memory (aligned_storage). This buffer is then used for placement new - later on, effectively overwriting any initialized weak_ptr with a default - initialized one, eventually leading to issues when the user calls shared_from_this. - - To get around these issues, we will store the memory for the enable_shared_from_this - portion of the class and replace it after whatever happens to modify it (e.g. the - user performing construction or the wrapper shared_ptr in saving). - - Note that this goes into undefined behavior territory, but as of the initial writing - of this, all standard library implementations of std::enable_shared_from_this are - compatible with this memory manipulation. It is entirely possible that this may someday - break or may not work with convoluted use cases. - - Example usage: - - @code{.cpp} - T * myActualPointer; - { - EnableSharedStateHelper helper( myActualPointer ); // save the state - std::shared_ptr myPtr( myActualPointer ); // modifies the internal weak_ptr - // helper restores state when it goes out of scope - } - @endcode - - When possible, this is designed to be used in an RAII fashion - it will save state on - construction and restore it on destruction. The restore can be done at an earlier time - (e.g. after construct() is called in load_and_construct) in which case the destructor will - do nothing. Performing the restore immediately following construct() allows a user to call - shared_from_this within their load_and_construct function. - - @tparam T Type pointed to by shared_ptr - @internal */ - template - class EnableSharedStateHelper - { - // typedefs for parent type and storage type - using BaseType = typename ::cereal::traits::get_shared_from_this_base::type; - using ParentType = std::enable_shared_from_this; - using StorageType = typename std::aligned_storage::type; - - public: - //! Saves the state of some type inheriting from enable_shared_from_this - /*! @param ptr The raw pointer held by the shared_ptr */ - inline EnableSharedStateHelper( T * ptr ) : - itsPtr( static_cast( ptr ) ), - itsState(), - itsRestored( false ) - { - std::memcpy( &itsState, itsPtr, sizeof(ParentType) ); - } - - //! Restores the state of the held pointer (can only be done once) - inline void restore() - { - if( !itsRestored ) - { - // void * cast needed when type has no trivial copy-assignment - std::memcpy( static_cast(itsPtr), &itsState, sizeof(ParentType) ); - itsRestored = true; - } - } - - //! Restores the state of the held pointer if not done previously - inline ~EnableSharedStateHelper() - { - restore(); - } - - private: - ParentType * itsPtr; - StorageType itsState; - bool itsRestored; - }; // end EnableSharedStateHelper - - //! Performs loading and construction for a shared pointer that is derived from - //! std::enable_shared_from_this - /*! @param ar The archive - @param ptr Raw pointer held by the shared_ptr - @internal */ - template inline - void loadAndConstructSharedPtr( Archive & ar, T * ptr, std::true_type /* has_shared_from_this */ ) - { - memory_detail::EnableSharedStateHelper state( ptr ); - memory_detail::LoadAndConstructLoadWrapper loadWrapper( ptr, [&](){ state.restore(); } ); - - // let the user perform their initialization, shared state will be restored as soon as construct() - // is called - ar( CEREAL_NVP_("data", loadWrapper) ); - } - - //! Performs loading and construction for a shared pointer that is NOT derived from - //! std::enable_shared_from_this - /*! This is the typical case, where we simply pass the load wrapper to the - archive. - - @param ar The archive - @param ptr Raw pointer held by the shared_ptr - @internal */ - template inline - void loadAndConstructSharedPtr( Archive & ar, T * ptr, std::false_type /* has_shared_from_this */ ) - { - memory_detail::LoadAndConstructLoadWrapper loadWrapper( ptr ); - ar( CEREAL_NVP_("data", loadWrapper) ); - } - } // end namespace memory_detail - - //! Saving std::shared_ptr for non polymorphic types - template inline - typename std::enable_if::value, void>::type - CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::shared_ptr const & ptr ) - { - ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper( ptr )) ); - } - - //! Loading std::shared_ptr, case when no user load and construct for non polymorphic types - template inline - typename std::enable_if::value, void>::type - CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::shared_ptr & ptr ) - { - ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper( ptr )) ); - } - - //! Saving std::weak_ptr for non polymorphic types - template inline - typename std::enable_if::value, void>::type - CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::weak_ptr const & ptr ) - { - auto const sptr = ptr.lock(); - ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper( sptr )) ); - } - - //! Loading std::weak_ptr for non polymorphic types - template inline - typename std::enable_if::value, void>::type - CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::weak_ptr & ptr ) - { - std::shared_ptr sptr; - ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper( sptr )) ); - ptr = sptr; - } - - //! Saving std::unique_ptr for non polymorphic types - template inline - typename std::enable_if::value, void>::type - CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::unique_ptr const & ptr ) - { - ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper( ptr )) ); - } - - //! Loading std::unique_ptr, case when user provides load_and_construct for non polymorphic types - template inline - typename std::enable_if::value, void>::type - CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::unique_ptr & ptr ) - { - ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper( ptr )) ); - } - - // ###################################################################### - // Pointer wrapper implementations follow below - - //! Saving std::shared_ptr (wrapper implementation) - /*! @internal */ - template inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, memory_detail::PtrWrapper const &> const & wrapper ) - { - auto & ptr = wrapper.ptr; - - uint32_t id = ar.registerSharedPointer( ptr ); - ar( CEREAL_NVP_("id", id) ); - - if( id & detail::msb_32bit ) - { - ar( CEREAL_NVP_("data", *ptr) ); - } - } - - //! Loading std::shared_ptr, case when user load and construct (wrapper implementation) - /*! @internal */ - template inline - typename std::enable_if::value, void>::type - CEREAL_LOAD_FUNCTION_NAME( Archive & ar, memory_detail::PtrWrapper &> & wrapper ) - { - uint32_t id; - - ar( CEREAL_NVP_("id", id) ); - - if( id & detail::msb_32bit ) - { - // Storage type for the pointer - since we can't default construct this type, - // we'll allocate it using std::aligned_storage and use a custom deleter - using ST = typename std::aligned_storage::type; - - // Valid flag - set to true once construction finishes - // This prevents us from calling the destructor on - // uninitialized data. - auto valid = std::make_shared( false ); - - // Allocate our storage, which we will treat as - // uninitialized until initialized with placement new - using NonConstT = typename std::remove_const::type; - std::shared_ptr ptr(reinterpret_cast(new ST()), - [=]( NonConstT * t ) - { - if( *valid ) - t->~T(); - - delete reinterpret_cast( t ); - } ); - - // Register the pointer - ar.registerSharedPointer( id, ptr ); - - // Perform the actual loading and allocation - memory_detail::loadAndConstructSharedPtr( ar, ptr.get(), typename ::cereal::traits::has_shared_from_this::type() ); - - // Mark pointer as valid (initialized) - *valid = true; - wrapper.ptr = std::move(ptr); - } - else - wrapper.ptr = std::static_pointer_cast(ar.getSharedPointer(id)); - } - - //! Loading std::shared_ptr, case when no user load and construct (wrapper implementation) - /*! @internal */ - template inline - typename std::enable_if::value, void>::type - CEREAL_LOAD_FUNCTION_NAME( Archive & ar, memory_detail::PtrWrapper &> & wrapper ) - { - uint32_t id; - - ar( CEREAL_NVP_("id", id) ); - - if( id & detail::msb_32bit ) - { - using NonConstT = typename std::remove_const::type; - std::shared_ptr ptr( detail::Construct::load_andor_construct() ); - ar.registerSharedPointer( id, ptr ); - ar( CEREAL_NVP_("data", *ptr) ); - wrapper.ptr = std::move(ptr); - } - else - wrapper.ptr = std::static_pointer_cast(ar.getSharedPointer(id)); - } - - //! Saving std::unique_ptr (wrapper implementation) - /*! @internal */ - template inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, memory_detail::PtrWrapper const &> const & wrapper ) - { - auto & ptr = wrapper.ptr; - - // unique_ptr get one byte of metadata which signifies whether they were a nullptr - // 0 == nullptr - // 1 == not null - - if( !ptr ) - ar( CEREAL_NVP_("valid", uint8_t(0)) ); - else - { - ar( CEREAL_NVP_("valid", uint8_t(1)) ); - ar( CEREAL_NVP_("data", *ptr) ); - } - } - - //! Loading std::unique_ptr, case when user provides load_and_construct (wrapper implementation) - /*! @internal */ - template inline - typename std::enable_if::value, void>::type - CEREAL_LOAD_FUNCTION_NAME( Archive & ar, memory_detail::PtrWrapper &> & wrapper ) - { - uint8_t isValid; - ar( CEREAL_NVP_("valid", isValid) ); - - auto & ptr = wrapper.ptr; - - if( isValid ) - { - using NonConstT = typename std::remove_const::type; - // Storage type for the pointer - since we can't default construct this type, - // we'll allocate it using std::aligned_storage - using ST = typename std::aligned_storage::type; - - // Allocate storage - note the ST type so that deleter is correct if - // an exception is thrown before we are initialized - std::unique_ptr stPtr( new ST() ); - - // Use wrapper to enter into "data" nvp of ptr_wrapper - memory_detail::LoadAndConstructLoadWrapper loadWrapper( reinterpret_cast( stPtr.get() ) ); - - // Initialize storage - ar( CEREAL_NVP_("data", loadWrapper) ); - - // Transfer ownership to correct unique_ptr type - ptr.reset( reinterpret_cast( stPtr.release() ) ); - } - else - ptr.reset( nullptr ); - } - - //! Loading std::unique_ptr, case when no load_and_construct (wrapper implementation) - /*! @internal */ - template inline - typename std::enable_if::value, void>::type - CEREAL_LOAD_FUNCTION_NAME( Archive & ar, memory_detail::PtrWrapper &> & wrapper ) - { - uint8_t isValid; - ar( CEREAL_NVP_("valid", isValid) ); - - if( isValid ) - { - using NonConstT = typename std::remove_const::type; - std::unique_ptr ptr( detail::Construct::load_andor_construct() ); - ar( CEREAL_NVP_( "data", *ptr ) ); - wrapper.ptr = std::move(ptr); - } - else - { - wrapper.ptr.reset( nullptr ); - } - } -} // namespace cereal - -// automatically include polymorphic support -#include "cereal/types/polymorphic.hpp" - -#endif // CEREAL_TYPES_SHARED_PTR_HPP_ diff --git a/include/cereal/types/optional.hpp b/include/cereal/types/optional.hpp deleted file mode 100644 index 3d013a6..0000000 --- a/include/cereal/types/optional.hpp +++ /dev/null @@ -1,65 +0,0 @@ -/*! \file optional.hpp - \brief Support for std::optional - \ingroup STLSupport */ -/* - Copyright (c) 2017, Juan Pedro Bolivar Puente - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_STD_OPTIONAL_ -#define CEREAL_TYPES_STD_OPTIONAL_ - -#include "cereal/cereal.hpp" -#include - -namespace cereal { - //! Saving for std::optional - template inline - void CEREAL_SAVE_FUNCTION_NAME(Archive& ar, const std::optional& optional) - { - if(!optional) { - ar(CEREAL_NVP_("nullopt", true)); - } else { - ar(CEREAL_NVP_("nullopt", false), - CEREAL_NVP_("data", *optional)); - } - } - - //! Loading for std::optional - template inline - void CEREAL_LOAD_FUNCTION_NAME(Archive& ar, std::optional& optional) - { - bool nullopt; - ar(CEREAL_NVP_("nullopt", nullopt)); - - if (nullopt) { - optional = std::nullopt; - } else { - optional.emplace(); - ar(CEREAL_NVP_("data", *optional)); - } - } -} // namespace cereal - -#endif // CEREAL_TYPES_STD_OPTIONAL_ diff --git a/include/cereal/types/polymorphic.hpp b/include/cereal/types/polymorphic.hpp deleted file mode 100644 index e4398c8..0000000 --- a/include/cereal/types/polymorphic.hpp +++ /dev/null @@ -1,483 +0,0 @@ -/*! \file polymorphic.hpp - \brief Support for pointers to polymorphic base classes - \ingroup OtherTypes */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_POLYMORPHIC_HPP_ -#define CEREAL_TYPES_POLYMORPHIC_HPP_ - -#include "cereal/cereal.hpp" -#include "cereal/types/memory.hpp" - -#include "cereal/details/util.hpp" -#include "cereal/details/helpers.hpp" -#include "cereal/details/traits.hpp" -#include "cereal/details/polymorphic_impl.hpp" - -#if defined(_MSC_VER) && _MSC_VER < 1916 -#define CEREAL_STATIC_CONSTEXPR static -#else -#define CEREAL_STATIC_CONSTEXPR static constexpr -#endif - -//! Registers a derived polymorphic type with cereal -/*! Polymorphic types must be registered before smart - pointers to them can be serialized. Note that base - classes do not need to be registered. - - Registering a type lets cereal know how to properly - serialize it when a smart pointer to a base object is - used in conjunction with a derived class. - - This assumes that all relevant archives have also - previously been registered. Registration for archives - is usually done in the header file in which they are - defined. This means that type registration needs to - happen after specific archives to be used are included. - - It is recommended that type registration be done in - the header file in which the type is declared. - - Registration can also be placed in a source file, - but this may require the use of the - CEREAL_REGISTER_DYNAMIC_INIT macro (see below). - - Registration may be called repeatedly for the same - type in different translation units to add support - for additional archives if they are not initially - available (included and registered). - - When building serialization support as a DLL on - Windows, registration must happen in the header file. - On Linux and Mac things should still work properly - if placed in a source file, but see the above comments - on registering in source files. - - Polymorphic support in cereal requires RTTI to be - enabled */ -#define CEREAL_REGISTER_TYPE(...) \ - namespace cereal { \ - namespace detail { \ - template <> \ - struct binding_name<__VA_ARGS__> \ - { \ - CEREAL_STATIC_CONSTEXPR char const * name() { return #__VA_ARGS__; } \ - }; \ - } } /* end namespaces */ \ - CEREAL_BIND_TO_ARCHIVES(__VA_ARGS__) - -//! Registers a polymorphic type with cereal, giving it a -//! user defined name -/*! In some cases the default name used with - CEREAL_REGISTER_TYPE (the name of the type) may not be - suitable. This macro allows any name to be associated - with the type. The name should be unique */ -#define CEREAL_REGISTER_TYPE_WITH_NAME(T, Name) \ - namespace cereal { \ - namespace detail { \ - template <> \ - struct binding_name \ - { CEREAL_STATIC_CONSTEXPR char const * name() { return Name; } }; \ - } } /* end namespaces */ \ - CEREAL_BIND_TO_ARCHIVES(T) - -//! Registers the base-derived relationship for a polymorphic type -/*! When polymorphic serialization occurs, cereal needs to know how to - properly cast between derived and base types for the polymorphic - type. Normally this happens automatically whenever cereal::base_class - or cereal::virtual_base_class are used to serialize a base class. In - cases where neither of these is ever called but a base class still - exists, this explicit registration is required. - - The Derived class should be the most derived type that will be serialized, - and the Base type any possible base that has not been covered under a base - class serialization that will be used to store a Derived pointer. - - Placement of this is the same as for CEREAL_REGISTER_TYPE. */ -#define CEREAL_REGISTER_POLYMORPHIC_RELATION(Base, Derived) \ - namespace cereal { \ - namespace detail { \ - template <> \ - struct PolymorphicRelation \ - { static void bind() { RegisterPolymorphicCaster::bind(); } }; \ - } } /* end namespaces */ - -//! Adds a way to force initialization of a translation unit containing -//! calls to CEREAL_REGISTER_TYPE -/*! In C++, dynamic initialization of non-local variables of a translation - unit may be deferred until "the first odr-use of any function or variable - defined in the same translation unit as the variable to be initialized." - - Informally, odr-use means that your program takes the address of or binds - a reference directly to an object, which must have a definition. - - Since polymorphic type support in cereal relies on the dynamic - initialization of certain global objects happening before - serialization is performed, it is important to ensure that something - from files that call CEREAL_REGISTER_TYPE is odr-used before serialization - occurs, otherwise the registration will never take place. This may often - be the case when serialization is built as a shared library external from - your main program. - - This macro, with any name of your choosing, should be placed into the - source file that contains calls to CEREAL_REGISTER_TYPE. - - Its counterpart, CEREAL_FORCE_DYNAMIC_INIT, should be placed in its - associated header file such that it is included in the translation units - (source files) in which you want the registration to appear. - - @relates CEREAL_FORCE_DYNAMIC_INIT - */ -#define CEREAL_REGISTER_DYNAMIC_INIT(LibName) \ - namespace cereal { \ - namespace detail { \ - void CEREAL_DLL_EXPORT dynamic_init_dummy_##LibName() {} \ - } } /* end namespaces */ - -//! Forces dynamic initialization of polymorphic support in a -//! previously registered source file -/*! @sa CEREAL_REGISTER_DYNAMIC_INIT - - See CEREAL_REGISTER_DYNAMIC_INIT for detailed explanation - of how this macro should be used. The name used should - match that for CEREAL_REGISTER_DYNAMIC_INIT. */ -#define CEREAL_FORCE_DYNAMIC_INIT(LibName) \ - namespace cereal { \ - namespace detail { \ - void CEREAL_DLL_EXPORT dynamic_init_dummy_##LibName(); \ - } /* end detail */ \ - } /* end cereal */ \ - namespace { \ - struct dynamic_init_##LibName { \ - dynamic_init_##LibName() { \ - ::cereal::detail::dynamic_init_dummy_##LibName(); \ - } \ - } dynamic_init_instance_##LibName; \ - } /* end anonymous namespace */ - -namespace cereal -{ - namespace polymorphic_detail - { - //! Error message used for unregistered polymorphic types - /*! @internal */ - #define UNREGISTERED_POLYMORPHIC_EXCEPTION(LoadSave, Name) \ - throw cereal::Exception("Trying to " #LoadSave " an unregistered polymorphic type (" + Name + ").\n" \ - "Make sure your type is registered with CEREAL_REGISTER_TYPE and that the archive " \ - "you are using was included (and registered with CEREAL_REGISTER_ARCHIVE) prior to calling CEREAL_REGISTER_TYPE.\n" \ - "If your type is already registered and you still see this error, you may need to use CEREAL_REGISTER_DYNAMIC_INIT."); - - //! Get an input binding from the given archive by deserializing the type meta data - /*! @internal */ - template inline - typename ::cereal::detail::InputBindingMap::Serializers getInputBinding(Archive & ar, std::uint32_t const nameid) - { - // If the nameid is zero, we serialized a null pointer - if(nameid == 0) - { - typename ::cereal::detail::InputBindingMap::Serializers emptySerializers; - emptySerializers.shared_ptr = [](void*, std::shared_ptr & ptr, std::type_info const &) { ptr.reset(); }; - emptySerializers.unique_ptr = [](void*, std::unique_ptr> & ptr, std::type_info const &) { ptr.reset( nullptr ); }; - return emptySerializers; - } - - std::string name; - if(nameid & detail::msb_32bit) - { - ar( CEREAL_NVP_("polymorphic_name", name) ); - ar.registerPolymorphicName(nameid, name); - } - else - name = ar.getPolymorphicName(nameid); - - auto const & bindingMap = detail::StaticObject>::getInstance().map; - - auto binding = bindingMap.find(name); - if(binding == bindingMap.end()) - UNREGISTERED_POLYMORPHIC_EXCEPTION(load, name) - return binding->second; - } - - //! Serialize a shared_ptr if the 2nd msb in the nameid is set, and if we can actually construct the pointee - /*! This check lets us try and skip doing polymorphic machinery if we can get away with - using the derived class serialize function - - Note that on MSVC 2013 preview, is_default_constructible returns true for abstract classes with - default constructors, but on clang/gcc this will return false. So we also need to check for that here. - @internal */ - template inline - typename std::enable_if<(traits::is_default_constructible::value - || traits::has_load_and_construct::value) - && !std::is_abstract::value, bool>::type - serialize_wrapper(Archive & ar, std::shared_ptr & ptr, std::uint32_t const nameid) - { - if(nameid & detail::msb2_32bit) - { - ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper(ptr)) ); - return true; - } - return false; - } - - //! Serialize a unique_ptr if the 2nd msb in the nameid is set, and if we can actually construct the pointee - /*! This check lets us try and skip doing polymorphic machinery if we can get away with - using the derived class serialize function - @internal */ - template inline - typename std::enable_if<(traits::is_default_constructible::value - || traits::has_load_and_construct::value) - && !std::is_abstract::value, bool>::type - serialize_wrapper(Archive & ar, std::unique_ptr & ptr, std::uint32_t const nameid) - { - if(nameid & detail::msb2_32bit) - { - ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper(ptr)) ); - return true; - } - return false; - } - - //! Serialize a shared_ptr if the 2nd msb in the nameid is set, and if we can actually construct the pointee - /*! This case is for when we can't actually construct the shared pointer. Normally this would be caught - as the pointer itself is serialized, but since this is a polymorphic pointer, if we tried to serialize - the pointer we'd end up back here recursively. So we have to catch the error here as well, if - this was a polymorphic type serialized by its proper pointer type - @internal */ - template inline - typename std::enable_if<(!traits::is_default_constructible::value - && !traits::has_load_and_construct::value) - || std::is_abstract::value, bool>::type - serialize_wrapper(Archive &, std::shared_ptr &, std::uint32_t const nameid) - { - if(nameid & detail::msb2_32bit) - throw cereal::Exception("Cannot load a polymorphic type that is not default constructable and does not have a load_and_construct function"); - return false; - } - - //! Serialize a unique_ptr if the 2nd msb in the nameid is set, and if we can actually construct the pointee - /*! This case is for when we can't actually construct the unique pointer. Normally this would be caught - as the pointer itself is serialized, but since this is a polymorphic pointer, if we tried to serialize - the pointer we'd end up back here recursively. So we have to catch the error here as well, if - this was a polymorphic type serialized by its proper pointer type - @internal */ - template inline - typename std::enable_if<(!traits::is_default_constructible::value - && !traits::has_load_and_construct::value) - || std::is_abstract::value, bool>::type - serialize_wrapper(Archive &, std::unique_ptr &, std::uint32_t const nameid) - { - if(nameid & detail::msb2_32bit) - throw cereal::Exception("Cannot load a polymorphic type that is not default constructable and does not have a load_and_construct function"); - return false; - } - } // polymorphic_detail - - // ###################################################################### - // Pointer serialization for polymorphic types - - //! Saving std::shared_ptr for polymorphic types, abstract - template inline - typename std::enable_if::value && std::is_abstract::value, void>::type - CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::shared_ptr const & ptr ) - { - if(!ptr) - { - // same behavior as nullptr in memory implementation - ar( CEREAL_NVP_("polymorphic_id", std::uint32_t(0)) ); - return; - } - - std::type_info const & ptrinfo = typeid(*ptr.get()); - static std::type_info const & tinfo = typeid(T); - // ptrinfo can never be equal to T info since we can't have an instance - // of an abstract object - // this implies we need to do the lookup - - auto const & bindingMap = detail::StaticObject>::getInstance().map; - - auto binding = bindingMap.find(std::type_index(ptrinfo)); - if(binding == bindingMap.end()) - UNREGISTERED_POLYMORPHIC_EXCEPTION(save, cereal::util::demangle(ptrinfo.name())) - - binding->second.shared_ptr(&ar, ptr.get(), tinfo); - } - - //! Saving std::shared_ptr for polymorphic types, not abstract - template inline - typename std::enable_if::value && !std::is_abstract::value, void>::type - CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::shared_ptr const & ptr ) - { - if(!ptr) - { - // same behavior as nullptr in memory implementation - ar( CEREAL_NVP_("polymorphic_id", std::uint32_t(0)) ); - return; - } - - std::type_info const & ptrinfo = typeid(*ptr.get()); - static std::type_info const & tinfo = typeid(T); - - if(ptrinfo == tinfo) - { - // The 2nd msb signals that the following pointer does not need to be - // cast with our polymorphic machinery - ar( CEREAL_NVP_("polymorphic_id", detail::msb2_32bit) ); - - ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper(ptr)) ); - - return; - } - - auto const & bindingMap = detail::StaticObject>::getInstance().map; - - auto binding = bindingMap.find(std::type_index(ptrinfo)); - if(binding == bindingMap.end()) - UNREGISTERED_POLYMORPHIC_EXCEPTION(save, cereal::util::demangle(ptrinfo.name())) - - binding->second.shared_ptr(&ar, ptr.get(), tinfo); - } - - //! Loading std::shared_ptr for polymorphic types - template inline - typename std::enable_if::value, void>::type - CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::shared_ptr & ptr ) - { - std::uint32_t nameid; - ar( CEREAL_NVP_("polymorphic_id", nameid) ); - - // Check to see if we can skip all of this polymorphism business - if(polymorphic_detail::serialize_wrapper(ar, ptr, nameid)) - return; - - auto binding = polymorphic_detail::getInputBinding(ar, nameid); - std::shared_ptr result; - binding.shared_ptr(&ar, result, typeid(T)); - ptr = std::static_pointer_cast(result); - } - - //! Saving std::weak_ptr for polymorphic types - template inline - typename std::enable_if::value, void>::type - CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::weak_ptr const & ptr ) - { - auto const sptr = ptr.lock(); - ar( CEREAL_NVP_("locked_ptr", sptr) ); - } - - //! Loading std::weak_ptr for polymorphic types - template inline - typename std::enable_if::value, void>::type - CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::weak_ptr & ptr ) - { - std::shared_ptr sptr; - ar( CEREAL_NVP_("locked_ptr", sptr) ); - ptr = sptr; - } - - //! Saving std::unique_ptr for polymorphic types that are abstract - template inline - typename std::enable_if::value && std::is_abstract::value, void>::type - CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::unique_ptr const & ptr ) - { - if(!ptr) - { - // same behavior as nullptr in memory implementation - ar( CEREAL_NVP_("polymorphic_id", std::uint32_t(0)) ); - return; - } - - std::type_info const & ptrinfo = typeid(*ptr.get()); - static std::type_info const & tinfo = typeid(T); - // ptrinfo can never be equal to T info since we can't have an instance - // of an abstract object - // this implies we need to do the lookup - - auto const & bindingMap = detail::StaticObject>::getInstance().map; - - auto binding = bindingMap.find(std::type_index(ptrinfo)); - if(binding == bindingMap.end()) - UNREGISTERED_POLYMORPHIC_EXCEPTION(save, cereal::util::demangle(ptrinfo.name())) - - binding->second.unique_ptr(&ar, ptr.get(), tinfo); - } - - //! Saving std::unique_ptr for polymorphic types, not abstract - template inline - typename std::enable_if::value && !std::is_abstract::value, void>::type - CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::unique_ptr const & ptr ) - { - if(!ptr) - { - // same behavior as nullptr in memory implementation - ar( CEREAL_NVP_("polymorphic_id", std::uint32_t(0)) ); - return; - } - - std::type_info const & ptrinfo = typeid(*ptr.get()); - static std::type_info const & tinfo = typeid(T); - - if(ptrinfo == tinfo) - { - // The 2nd msb signals that the following pointer does not need to be - // cast with our polymorphic machinery - ar( CEREAL_NVP_("polymorphic_id", detail::msb2_32bit) ); - - ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper(ptr)) ); - - return; - } - - auto const & bindingMap = detail::StaticObject>::getInstance().map; - - auto binding = bindingMap.find(std::type_index(ptrinfo)); - if(binding == bindingMap.end()) - UNREGISTERED_POLYMORPHIC_EXCEPTION(save, cereal::util::demangle(ptrinfo.name())) - - binding->second.unique_ptr(&ar, ptr.get(), tinfo); - } - - //! Loading std::unique_ptr, case when user provides load_and_construct for polymorphic types - template inline - typename std::enable_if::value, void>::type - CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::unique_ptr & ptr ) - { - std::uint32_t nameid; - ar( CEREAL_NVP_("polymorphic_id", nameid) ); - - // Check to see if we can skip all of this polymorphism business - if(polymorphic_detail::serialize_wrapper(ar, ptr, nameid)) - return; - - auto binding = polymorphic_detail::getInputBinding(ar, nameid); - std::unique_ptr> result; - binding.unique_ptr(&ar, result, typeid(T)); - ptr.reset(static_cast(result.release())); - } - - #undef UNREGISTERED_POLYMORPHIC_EXCEPTION -} // namespace cereal -#endif // CEREAL_TYPES_POLYMORPHIC_HPP_ diff --git a/include/cereal/types/queue.hpp b/include/cereal/types/queue.hpp deleted file mode 100644 index abde445..0000000 --- a/include/cereal/types/queue.hpp +++ /dev/null @@ -1,132 +0,0 @@ -/*! \file queue.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_QUEUE_HPP_ -#define CEREAL_TYPES_QUEUE_HPP_ - -#include "cereal/details/helpers.hpp" -#include - -// The default container for queue is deque, so let's include that too -#include "cereal/types/deque.hpp" -// The default comparator for queue is less -#include "cereal/types/functional.hpp" - -namespace cereal -{ - namespace queue_detail - { - //! Allows access to the protected container in queue - /*! @internal */ - template inline - C const & container( std::queue const & queue ) - { - struct H : public std::queue - { - static C const & get( std::queue const & q ) - { - return q.*(&H::c); - } - }; - - return H::get( queue ); - } - - //! Allows access to the protected container in priority queue - /*! @internal */ - template inline - C const & container( std::priority_queue const & priority_queue ) - { - struct H : public std::priority_queue - { - static C const & get( std::priority_queue const & pq ) - { - return pq.*(&H::c); - } - }; - - return H::get( priority_queue ); - } - - //! Allows access to the protected comparator in priority queue - /*! @internal */ - template inline - Comp const & comparator( std::priority_queue const & priority_queue ) - { - struct H : public std::priority_queue - { - static Comp const & get( std::priority_queue const & pq ) - { - return pq.*(&H::comp); - } - }; - - return H::get( priority_queue ); - } - } - - //! Saving for std::queue - template inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::queue const & queue ) - { - ar( CEREAL_NVP_("container", queue_detail::container( queue )) ); - } - - //! Loading for std::queue - template inline - void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::queue & queue ) - { - C container; - ar( CEREAL_NVP_("container", container) ); - queue = std::queue( std::move( container ) ); - } - - //! Saving for std::priority_queue - template inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::priority_queue const & priority_queue ) - { - ar( CEREAL_NVP_("comparator", queue_detail::comparator( priority_queue )) ); - ar( CEREAL_NVP_("container", queue_detail::container( priority_queue )) ); - } - - //! Loading for std::priority_queue - template inline - void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::priority_queue & priority_queue ) - { - Comp comparator; - ar( CEREAL_NVP_("comparator", comparator) ); - - C container; - ar( CEREAL_NVP_("container", container) ); - - priority_queue = std::priority_queue( comparator, std::move( container ) ); - } -} // namespace cereal - -#endif // CEREAL_TYPES_QUEUE_HPP_ diff --git a/include/cereal/types/set.hpp b/include/cereal/types/set.hpp deleted file mode 100644 index 0f83fbb..0000000 --- a/include/cereal/types/set.hpp +++ /dev/null @@ -1,103 +0,0 @@ -/*! \file set.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_SET_HPP_ -#define CEREAL_TYPES_SET_HPP_ - -#include "cereal/cereal.hpp" -#include - -namespace cereal -{ - namespace set_detail - { - //! @internal - template inline - void save( Archive & ar, SetT const & set ) - { - ar( make_size_tag( static_cast(set.size()) ) ); - - for( const auto & i : set ) - ar( i ); - } - - //! @internal - template inline - void load( Archive & ar, SetT & set ) - { - size_type size; - ar( make_size_tag( size ) ); - - set.clear(); - - auto hint = set.begin(); - for( size_type i = 0; i < size; ++i ) - { - typename SetT::key_type key; - - ar( key ); - #ifdef CEREAL_OLDER_GCC - hint = set.insert( hint, std::move( key ) ); - #else // NOT CEREAL_OLDER_GCC - hint = set.emplace_hint( hint, std::move( key ) ); - #endif // NOT CEREAL_OLDER_GCC - } - } - } - - //! Saving for std::set - template inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::set const & set ) - { - set_detail::save( ar, set ); - } - - //! Loading for std::set - template inline - void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::set & set ) - { - set_detail::load( ar, set ); - } - - //! Saving for std::multiset - template inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::multiset const & multiset ) - { - set_detail::save( ar, multiset ); - } - - //! Loading for std::multiset - template inline - void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::multiset & multiset ) - { - set_detail::load( ar, multiset ); - } -} // namespace cereal - -#endif // CEREAL_TYPES_SET_HPP_ diff --git a/include/cereal/types/stack.hpp b/include/cereal/types/stack.hpp deleted file mode 100644 index 9c08f7d..0000000 --- a/include/cereal/types/stack.hpp +++ /dev/null @@ -1,76 +0,0 @@ -/*! \file stack.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_STACK_HPP_ -#define CEREAL_TYPES_STACK_HPP_ - -#include "cereal/cereal.hpp" -#include - -// The default container for stack is deque, so let's include that too -#include "cereal/types/deque.hpp" - -namespace cereal -{ - namespace stack_detail - { - //! Allows access to the protected container in stack - template inline - C const & container( std::stack const & stack ) - { - struct H : public std::stack - { - static C const & get( std::stack const & s ) - { - return s.*(&H::c); - } - }; - - return H::get( stack ); - } - } - - //! Saving for std::stack - template inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::stack const & stack ) - { - ar( CEREAL_NVP_("container", stack_detail::container( stack )) ); - } - - //! Loading for std::stack - template inline - void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::stack & stack ) - { - C container; - ar( CEREAL_NVP_("container", container) ); - stack = std::stack( std::move( container ) ); - } -} // namespace cereal - -#endif // CEREAL_TYPES_STACK_HPP_ diff --git a/include/cereal/types/string.hpp b/include/cereal/types/string.hpp deleted file mode 100644 index b3d15a6..0000000 --- a/include/cereal/types/string.hpp +++ /dev/null @@ -1,61 +0,0 @@ -/*! \file string.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_STRING_HPP_ -#define CEREAL_TYPES_STRING_HPP_ - -#include "cereal/cereal.hpp" -#include - -namespace cereal -{ - //! Serialization for basic_string types, if binary data is supported - template inline - typename std::enable_if, Archive>::value, void>::type - CEREAL_SAVE_FUNCTION_NAME(Archive & ar, std::basic_string const & str) - { - // Save number of chars + the data - ar( make_size_tag( static_cast(str.size()) ) ); - ar( binary_data( str.data(), str.size() * sizeof(CharT) ) ); - } - - //! Serialization for basic_string types, if binary data is supported - template inline - typename std::enable_if, Archive>::value, void>::type - CEREAL_LOAD_FUNCTION_NAME(Archive & ar, std::basic_string & str) - { - size_type size; - ar( make_size_tag( size ) ); - str.resize(static_cast(size)); - ar( binary_data( const_cast( str.data() ), static_cast(size) * sizeof(CharT) ) ); - } -} // namespace cereal - -#endif // CEREAL_TYPES_STRING_HPP_ - diff --git a/include/cereal/types/tuple.hpp b/include/cereal/types/tuple.hpp deleted file mode 100644 index 80c6807..0000000 --- a/include/cereal/types/tuple.hpp +++ /dev/null @@ -1,123 +0,0 @@ -/*! \file tuple.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_TUPLE_HPP_ -#define CEREAL_TYPES_TUPLE_HPP_ - -#include "cereal/cereal.hpp" -#include - -namespace cereal -{ - namespace tuple_detail - { - //! Creates a c string from a sequence of characters - /*! The c string created will always be prefixed by "tuple_element" - Based on code from: http://stackoverflow/a/20973438/710791 - @internal */ - template - struct char_seq_to_c_str - { - static const int size = 14;// Size of array for the word: tuple_element - typedef const char (&arr_type)[sizeof...(Cs) + size]; - static const char str[sizeof...(Cs) + size]; - }; - - // the word tuple_element plus a number - //! @internal - template - const char char_seq_to_c_str::str[sizeof...(Cs) + size] = - {'t','u','p','l','e','_','e','l','e','m','e','n','t', Cs..., '\0'}; - - //! Converts a number into a sequence of characters - /*! @tparam Q The quotient of dividing the original number by 10 - @tparam R The remainder of dividing the original number by 10 - @tparam C The sequence built so far - @internal */ - template - struct to_string_impl - { - using type = typename to_string_impl(R+std::size_t{'0'}), C...>::type; - }; - - //! Base case with no quotient - /*! @internal */ - template - struct to_string_impl<0, R, C...> - { - using type = char_seq_to_c_str(R+std::size_t{'0'}), C...>; - }; - - //! Generates a c string for a given index of a tuple - /*! Example use: - @code{cpp} - tuple_element_name<3>::c_str();// returns "tuple_element3" - @endcode - @internal */ - template - struct tuple_element_name - { - using type = typename to_string_impl::type; - static const typename type::arr_type c_str(){ return type::str; } - }; - - // unwinds a tuple to save it - //! @internal - template - struct serialize - { - template inline - static void apply( Archive & ar, std::tuple & tuple ) - { - serialize::template apply( ar, tuple ); - ar( CEREAL_NVP_(tuple_element_name::c_str(), - std::get( tuple )) ); - } - }; - - // Zero height specialization - nothing to do here - //! @internal - template <> - struct serialize<0> - { - template inline - static void apply( Archive &, std::tuple & ) - { } - }; - } - - //! Serializing for std::tuple - template inline - void CEREAL_SERIALIZE_FUNCTION_NAME( Archive & ar, std::tuple & tuple ) - { - tuple_detail::serialize>::value>::template apply( ar, tuple ); - } -} // namespace cereal - -#endif // CEREAL_TYPES_TUPLE_HPP_ diff --git a/include/cereal/types/unordered_map.hpp b/include/cereal/types/unordered_map.hpp deleted file mode 100644 index d575593..0000000 --- a/include/cereal/types/unordered_map.hpp +++ /dev/null @@ -1,36 +0,0 @@ -/*! \file unordered_map.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_UNORDERED_MAP_HPP_ -#define CEREAL_TYPES_UNORDERED_MAP_HPP_ - -#include "cereal/types/concepts/pair_associative_container.hpp" -#include - -#endif // CEREAL_TYPES_UNORDERED_MAP_HPP_ diff --git a/include/cereal/types/unordered_set.hpp b/include/cereal/types/unordered_set.hpp deleted file mode 100644 index 2384cdf..0000000 --- a/include/cereal/types/unordered_set.hpp +++ /dev/null @@ -1,99 +0,0 @@ -/*! \file unordered_set.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_UNORDERED_SET_HPP_ -#define CEREAL_TYPES_UNORDERED_SET_HPP_ - -#include "cereal/cereal.hpp" -#include - -namespace cereal -{ - namespace unordered_set_detail - { - //! @internal - template inline - void save( Archive & ar, SetT const & set ) - { - ar( make_size_tag( static_cast(set.size()) ) ); - - for( const auto & i : set ) - ar( i ); - } - - //! @internal - template inline - void load( Archive & ar, SetT & set ) - { - size_type size; - ar( make_size_tag( size ) ); - - set.clear(); - set.reserve( static_cast( size ) ); - - for( size_type i = 0; i < size; ++i ) - { - typename SetT::key_type key; - - ar( key ); - set.emplace( std::move( key ) ); - } - } - } - - //! Saving for std::unordered_set - template inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::unordered_set const & unordered_set ) - { - unordered_set_detail::save( ar, unordered_set ); - } - - //! Loading for std::unordered_set - template inline - void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::unordered_set & unordered_set ) - { - unordered_set_detail::load( ar, unordered_set ); - } - - //! Saving for std::unordered_multiset - template inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::unordered_multiset const & unordered_multiset ) - { - unordered_set_detail::save( ar, unordered_multiset ); - } - - //! Loading for std::unordered_multiset - template inline - void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::unordered_multiset & unordered_multiset ) - { - unordered_set_detail::load( ar, unordered_multiset ); - } -} // namespace cereal - -#endif // CEREAL_TYPES_UNORDERED_SET_HPP_ diff --git a/include/cereal/types/utility.hpp b/include/cereal/types/utility.hpp deleted file mode 100644 index 635aa85..0000000 --- a/include/cereal/types/utility.hpp +++ /dev/null @@ -1,47 +0,0 @@ -/*! \file utility.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_UTILITY_HPP_ -#define CEREAL_TYPES_UTILITY_HPP_ - -#include "cereal/cereal.hpp" -#include - -namespace cereal -{ - //! Serializing for std::pair - template inline - void CEREAL_SERIALIZE_FUNCTION_NAME( Archive & ar, std::pair & pair ) - { - ar( CEREAL_NVP_("first", pair.first), - CEREAL_NVP_("second", pair.second) ); - } -} // namespace cereal - -#endif // CEREAL_TYPES_UTILITY_HPP_ diff --git a/include/cereal/types/valarray.hpp b/include/cereal/types/valarray.hpp deleted file mode 100644 index ed56e22..0000000 --- a/include/cereal/types/valarray.hpp +++ /dev/null @@ -1,89 +0,0 @@ -/*! \file valarray.hpp -\brief Support for types found in \ -\ingroup STLSupport */ - -/* -Copyright (c) 2014, Randolph Voorhies, Shane Grant -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright -notice, this list of conditions and the following disclaimer in the -documentation and/or other materials provided with the distribution. -* Neither the name of cereal nor the -names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef CEREAL_TYPES_VALARRAY_HPP_ -#define CEREAL_TYPES_VALARRAY_HPP_ - -#include "cereal/cereal.hpp" -#include - -namespace cereal -{ - //! Saving for std::valarray arithmetic types, using binary serialization, if supported - template inline - typename std::enable_if, Archive>::value - && std::is_arithmetic::value, void>::type - CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::valarray const & valarray ) - { - ar( make_size_tag( static_cast(valarray.size()) ) ); // number of elements - ar( binary_data( &valarray[0], valarray.size() * sizeof(T) ) ); // &valarray[0] ok since guaranteed contiguous - } - - //! Loading for std::valarray arithmetic types, using binary serialization, if supported - template inline - typename std::enable_if, Archive>::value - && std::is_arithmetic::value, void>::type - CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::valarray & valarray ) - { - size_type valarraySize; - ar( make_size_tag( valarraySize ) ); - - valarray.resize( static_cast( valarraySize ) ); - ar( binary_data( &valarray[0], static_cast( valarraySize ) * sizeof(T) ) ); - } - - //! Saving for std::valarray all other types - template inline - typename std::enable_if, Archive>::value - || !std::is_arithmetic::value, void>::type - CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::valarray const & valarray ) - { - ar( make_size_tag( static_cast(valarray.size()) ) ); // number of elements - for(auto && v : valarray) - ar(v); - } - - //! Loading for std::valarray all other types - template inline - typename std::enable_if, Archive>::value - || !std::is_arithmetic::value, void>::type - CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::valarray & valarray ) - { - size_type valarraySize; - ar( make_size_tag( valarraySize ) ); - - valarray.resize( static_cast( valarraySize ) ); - for(auto && v : valarray) - ar(v); - } -} // namespace cereal - -#endif // CEREAL_TYPES_VALARRAY_HPP_ diff --git a/include/cereal/types/variant.hpp b/include/cereal/types/variant.hpp deleted file mode 100644 index 886b246..0000000 --- a/include/cereal/types/variant.hpp +++ /dev/null @@ -1,108 +0,0 @@ -/*! \file variant.hpp - \brief Support for std::variant - \ingroup STLSupport */ -/* - Copyright (c) 2014, 2017, Randolph Voorhies, Shane Grant, Juan Pedro - Bolivar Puente. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_STD_VARIANT_HPP_ -#define CEREAL_TYPES_STD_VARIANT_HPP_ - -#include "cereal/cereal.hpp" -#include -#include - -namespace cereal -{ - namespace variant_detail - { - //! @internal - template - struct variant_save_visitor - { - variant_save_visitor(Archive & ar_) : ar(ar_) {} - - template - void operator()(T const & value) const - { - ar( CEREAL_NVP_("data", value) ); - } - - Archive & ar; - }; - - //! @internal - template - typename std::enable_if, void>::type - load_variant(Archive & /*ar*/, int /*target*/, Variant & /*variant*/) - { - throw ::cereal::Exception("Error traversing variant during load"); - } - //! @internal - template - typename std::enable_if, void>::type - load_variant(Archive & ar, int target, Variant & variant) - { - if(N == target) - { - variant.template emplace(); - ar( CEREAL_NVP_("data", std::get(variant)) ); - } - else - load_variant(ar, target, variant); - } - - } // namespace variant_detail - - //! Saving for std::variant - template inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::variant const & variant ) - { - std::int32_t index = static_cast(variant.index()); - ar( CEREAL_NVP_("index", index) ); - variant_detail::variant_save_visitor visitor(ar); - std::visit(visitor, variant); - } - - //! Loading for std::variant - template inline - void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::variant & variant ) - { - using variant_t = typename std::variant; - - std::int32_t index; - ar( CEREAL_NVP_("index", index) ); - if(index >= static_cast(std::variant_size_v)) - throw Exception("Invalid 'index' selector when deserializing std::variant"); - - variant_detail::load_variant<0>(ar, index, variant); - } - - //! Serializing a std::monostate - template - void CEREAL_SERIALIZE_FUNCTION_NAME( Archive &, std::monostate const & ) {} -} // namespace cereal - -#endif // CEREAL_TYPES_STD_VARIANT_HPP_ diff --git a/include/cereal/types/vector.hpp b/include/cereal/types/vector.hpp deleted file mode 100644 index aee9e3f..0000000 --- a/include/cereal/types/vector.hpp +++ /dev/null @@ -1,112 +0,0 @@ -/*! \file vector.hpp - \brief Support for types found in \ - \ingroup STLSupport */ -/* - Copyright (c) 2014, Randolph Voorhies, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CEREAL_TYPES_VECTOR_HPP_ -#define CEREAL_TYPES_VECTOR_HPP_ - -#include "cereal/cereal.hpp" -#include - -namespace cereal -{ - //! Serialization for std::vectors of arithmetic (but not bool) using binary serialization, if supported - template inline - typename std::enable_if, Archive>::value - && std::is_arithmetic::value && !std::is_same::value, void>::type - CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::vector const & vector ) - { - ar( make_size_tag( static_cast(vector.size()) ) ); // number of elements - ar( binary_data( vector.data(), vector.size() * sizeof(T) ) ); - } - - //! Serialization for std::vectors of arithmetic (but not bool) using binary serialization, if supported - template inline - typename std::enable_if, Archive>::value - && std::is_arithmetic::value && !std::is_same::value, void>::type - CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::vector & vector ) - { - size_type vectorSize; - ar( make_size_tag( vectorSize ) ); - - vector.resize( static_cast( vectorSize ) ); - ar( binary_data( vector.data(), static_cast( vectorSize ) * sizeof(T) ) ); - } - - //! Serialization for non-arithmetic vector types - template inline - typename std::enable_if<(!traits::is_output_serializable, Archive>::value - || !std::is_arithmetic::value) && !std::is_same::value, void>::type - CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::vector const & vector ) - { - ar( make_size_tag( static_cast(vector.size()) ) ); // number of elements - for(auto && v : vector) - ar( v ); - } - - //! Serialization for non-arithmetic vector types - template inline - typename std::enable_if<(!traits::is_input_serializable, Archive>::value - || !std::is_arithmetic::value) && !std::is_same::value, void>::type - CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::vector & vector ) - { - size_type size; - ar( make_size_tag( size ) ); - - vector.resize( static_cast( size ) ); - for(auto && v : vector) - ar( v ); - } - - //! Serialization for bool vector types - template inline - void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::vector const & vector ) - { - ar( make_size_tag( static_cast(vector.size()) ) ); // number of elements - for(const auto v : vector) - ar( static_cast(v) ); - } - - //! Serialization for bool vector types - template inline - void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::vector & vector ) - { - size_type size; - ar( make_size_tag( size ) ); - - vector.resize( static_cast( size ) ); - for(auto && v : vector) - { - bool b; - ar( b ); - v = b; - } - } -} // namespace cereal - -#endif // CEREAL_TYPES_VECTOR_HPP_ diff --git a/include/cereal/version.hpp b/include/cereal/version.hpp deleted file mode 100644 index 0ad7d41..0000000 --- a/include/cereal/version.hpp +++ /dev/null @@ -1,52 +0,0 @@ -/*! \file version.hpp - \brief Macros to detect cereal version - - These macros can assist in determining the version of cereal. Be - warned that cereal is not guaranteed to be compatible across - different versions. For more information on releases of cereal, - see https://github.com/USCiLab/cereal/releases. - - \ingroup utility */ -/* - Copyright (c) 2018, Shane Grant - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the copyright holder nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef CEREAL_VERSION_HPP_ -#define CEREAL_VERSION_HPP_ - -//! The major version -#define CEREAL_VERSION_MAJOR 1 -//! The minor version -#define CEREAL_VERSION_MINOR 3 -//! The patch version -#define CEREAL_VERSION_PATCH 2 - -//! The full version as a single number -#define CEREAL_VERSION (CEREAL_VERSION_MAJOR * 10000 \ - + CEREAL_VERSION_MINOR * 100 \ - + CEREAL_VERSION_PATCH) - -#endif // CEREAL_VERSION_HPP_ diff --git a/include/collisionsContainer.hpp b/include/collisionsContainer.hpp deleted file mode 100644 index e505b97..0000000 --- a/include/collisionsContainer.hpp +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef _RPGPP_COLLISIONSCONTAINER_H -#define _RPGPP_COLLISIONSCONTAINER_H - -#include -#include - -/** A container of collision tiles to be used by a Room */ -class CollisionsContainer { -private: - /** A vector that contains the tile positions of the collision tiles */ - std::vector vec; -public: - /** Empty constructor */ - CollisionsContainer(); - /** Add a collision tile to this container */ - void addCollisionTile(int x, int y); - /** Remove a collision tile by its tile position */ - void removeCollisionTile(int x, int y); - /** Get a reference to this container's vector. Items are tile positions of the collision tiles. */ - const std::vector& getVector(); -}; - -#endif \ No newline at end of file diff --git a/include/colorRect.hpp b/include/colorRect.hpp deleted file mode 100644 index 7d9c7a1..0000000 --- a/include/colorRect.hpp +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef _RPGPP_COLORRECT_H -#define _RPGPP_COLORRECT_H - -#include -#include "uiElement.hpp" - -class ColorRect : public UIElement { -private: - Rectangle rect; - Color color; -public: - ColorRect(); - ColorRect(Rectangle rect); - void setColor(Color newColor); - void update() override; - void draw() override; -}; - -#endif diff --git a/include/dialogueBalloon.hpp b/include/dialogueBalloon.hpp deleted file mode 100644 index b9c9406..0000000 --- a/include/dialogueBalloon.hpp +++ /dev/null @@ -1,54 +0,0 @@ -#ifndef _RPGPP_DIALOGUEBALLOON_H -#define _RPGPP_DIALOGUEBALLOON_H - -#include -#include -#include - -struct DialogueTextSection { - std::string key; - std::string text; -}; - -struct DialogueLine { - std::string characterName; - std::string text; - bool hasPortrait; - std::string imageId; - std::vector sections; -}; - -struct Dialogue { - std::string title; - std::vector lines; -}; - -class DialogueBalloon { -private: - Rectangle rect; - Rectangle textRect; - Rectangle textPortraitRect; - Dialogue dialogue; - std::string text; - DialogueTextSection sectionText; - bool firstCharTyped; - bool active; - int frameCounter; - int charIndex; - int lineIndex; - int sectionIndex; - Color textColor; - int lastSectionLen; - Vector2 textPos; - void drawPortrait() const; -public: - DialogueBalloon(); - DialogueBalloon(Rectangle rect); - void update(); - void draw(); - void showDialogue(const Dialogue &newDialogue); - void hideDialogue(); - void charP(Vector2 charMeasure, const char* c, Color color); -}; - -#endif diff --git a/include/editor/actorInfoPanel.hpp b/include/editor/actorInfoPanel.hpp deleted file mode 100644 index 3cba444..0000000 --- a/include/editor/actorInfoPanel.hpp +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef _RPGPP_EDITOR_ACTORINFOPANEL_H -#define _RPGPP_EDITOR_ACTORINFOPANEL_H - -#include "worldViewBox.hpp" -#include - -class ActorInfoPanel { -private: - Rectangle rect; - RoomAction action; - std::string actorConcat; - int currentActor; -public: - ActorInfoPanel(); - ActorInfoPanel(Rectangle rect); - void setRect(Rectangle rect); - void setActionMode(RoomAction action); - int getCurrentActorIndex() const; - void update() const; - void draw(); -}; - -#endif diff --git a/include/editor/actorPanelView.hpp b/include/editor/actorPanelView.hpp deleted file mode 100644 index a09a68e..0000000 --- a/include/editor/actorPanelView.hpp +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef _RPGPP_EDITOR_ACTORPANELVIEW_H -#define _RPGPP_EDITOR_ACTORPANELVIEW_H - -#include -#include "actorView.hpp" -#include "propertiesBox.hpp" -#include "animationsView.hpp" - -class ActorPanelView { -private: - Rectangle rect; - ActorView actorView; - PropertiesBox props; - AnimationsView animationsView; -public: - ActorPanelView(); - ActorPanelView(Rectangle rect); - void setRect(Rectangle rect); - void setInitial(); - void update(); - void draw(); -}; - -#endif \ No newline at end of file diff --git a/include/editor/actorPropertiesBox.hpp b/include/editor/actorPropertiesBox.hpp deleted file mode 100644 index c4fc6a5..0000000 --- a/include/editor/actorPropertiesBox.hpp +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef _RPGPP_EDITOR_ACTORPROPERTIESBOX_H -#define _RPGPP_EDITOR_ACTORPROPERTIESBOX_H - -#include "actor.hpp" -#include - -class ActorPropertiesBox { -private: - Rectangle rect; - Vector2 scrollVec; - Rectangle viewRec; - Actor* actor; - bool collisionViewActive; -public: - ActorPropertiesBox(); - ActorPropertiesBox(Rectangle rect); - void setDefaults(); - void update(); - void draw(); - bool getCollisionViewActive(); -}; - -#endif \ No newline at end of file diff --git a/include/editor/actorView.hpp b/include/editor/actorView.hpp deleted file mode 100644 index c111b19..0000000 --- a/include/editor/actorView.hpp +++ /dev/null @@ -1,41 +0,0 @@ -#ifndef _RPGPP_EDITOR_ACTORVIEW_H -#define _RPGPP_EDITOR_ACTORVIEW_H - -#include -#include -#include -#include "mouseInput.hpp" -#include "collisionbox.hpp" - -class ActorView { -private: - int frameCounter; - Rectangle rect; - Rectangle renderRect; - RenderTexture2D renderTexture; - Camera2D camera; - Vector2 mouseWorldPos; - CollisionBox collisionBox; - bool collisionViewActive; - int currentAnim; - int currentFrame; - std::vector currentAnimFrames; - bool animPlaying; - Rectangle actorRect; - void drawActor(); -public: - ActorView(); - ActorView(Rectangle rect); - void setRect(Rectangle rect); - void setInitial(); - void updateData(); - void update(); - void draw(); - void setCollisionActive(bool value); - void setAnimation(int id); - void setAnimPlaying(bool value); - void setFrame(int frame); - int getFrame(); -}; - -#endif diff --git a/include/editor/animationsView.hpp b/include/editor/animationsView.hpp deleted file mode 100644 index 04d767b..0000000 --- a/include/editor/animationsView.hpp +++ /dev/null @@ -1,31 +0,0 @@ -#ifndef _RPGPP_EDITOR_ANIMATIONSVIEW_H -#define _RPGPP_EDITOR_ANIMATIONSVIEW_H - -#include -#include -#include -#include "actor.hpp" -#include "actorView.hpp" - -class AnimationsView { -private: - ActorView* actorView; - Rectangle rect; - bool animDropdownActive; - bool animDropdownEditMode; - int currentAnim; - bool animPlaying; - std::vector animFrames; - std::vector animNames; -public: - AnimationsView(); - AnimationsView(Rectangle rect); - void setRect(Rectangle rect); - void update(); - void draw(); - void setActorView(ActorView* actorView); - int getCurrentAnim(); - bool getAnimPlaying(); -}; - -#endif \ No newline at end of file diff --git a/include/editor/collisionInfoPanel.hpp b/include/editor/collisionInfoPanel.hpp deleted file mode 100644 index 3dc7300..0000000 --- a/include/editor/collisionInfoPanel.hpp +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef _RPGPP_EDITOR_COLLISIONINFOPANEL_H -#define _RPGPP_EDITOR_COLLISIONINFOPANEL_H - -#include -#include "worldViewBox.hpp" - -class CollisionInfoPanel { -private: - Rectangle rect; - RoomAction action; -public: - CollisionInfoPanel(); - CollisionInfoPanel(Rectangle rect); - void setRect(Rectangle rect); - void draw(); - void setActionMode(RoomAction mode); -}; - -#endif \ No newline at end of file diff --git a/include/editor/collisionbox.hpp b/include/editor/collisionbox.hpp deleted file mode 100644 index ca70ee7..0000000 --- a/include/editor/collisionbox.hpp +++ /dev/null @@ -1,34 +0,0 @@ -#ifndef _RPGPP_EDITOR_COLLISIONBOX_H -#define _RPGPP_EDITOR_COLLISIONBOX_H - -#include - -enum ResizeMode { - RESIZE_TOP_LEFT, RESIZE_TOP_RIGHT, RESIZE_BOTTOM_LEFT, RESIZE_BOTTOM_RIGHT, RESIZE_MOVE -}; - -class CollisionBox { -private: - Rectangle rect; - Vector2 mouseWorldPos; - Rectangle topLeft; - Rectangle topRight; - Rectangle bottomLeft; - Rectangle bottomRight; - Vector2 oldMousePos; - Rectangle newRect; - Vector2 mouseOffset; - ResizeMode resizeMode; - Vector2 mouseDelta; - bool holdingMouse; -public: - CollisionBox(); - CollisionBox(Rectangle rect); - void setMouseWorldPos(Vector2 pos); - void setRect(Rectangle rect); - Rectangle getRect(); - void update(); - void draw(); -}; - -#endif \ No newline at end of file diff --git a/include/editor/dialoguePanelView.hpp b/include/editor/dialoguePanelView.hpp deleted file mode 100644 index ad2b2a5..0000000 --- a/include/editor/dialoguePanelView.hpp +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef _RPGPP_EDITOR_DIALOGUEPANELVIEW_H -#define _RPGPP_EDITOR_DIALOGUEPANELVIEW_H - -#include "dialogueViewer.hpp" -#include - -class DialoguePanelView { -private: - Rectangle rect; - DialogueViewer view; -public: - DialoguePanelView(); - DialoguePanelView(Rectangle rect); - void setInitial(); - void setRect(Rectangle rect); - void update(); - void draw(); -}; - -#endif diff --git a/include/editor/dialogueParser.hpp b/include/editor/dialogueParser.hpp deleted file mode 100644 index f36ad18..0000000 --- a/include/editor/dialogueParser.hpp +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef _RPGPP_EDITOR_DIALOGUEPARSER_H -#define _RPGPP_EDITOR_DIALOGUEPARSER_H - -#include -#include -#include -using json = nlohmann::json; - -Dialogue parseDialogueText(std::string text); -json dialogueDumpJson(const Dialogue &diag); - -#endif diff --git a/include/editor/dialogueViewer.hpp b/include/editor/dialogueViewer.hpp deleted file mode 100644 index 7005931..0000000 --- a/include/editor/dialogueViewer.hpp +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef _RPGPP_EDITOR_DIALOGUEVIEWER_H -#define _RPGPP_EDITOR_DIALOGUEVIEWER_H - -#include -#include -#include "dialogueBalloon.hpp" - -class DialogueViewer { -private: - Rectangle rect; - Dialogue* diag; - char newLineName[256]; - std::map images; - bool drawDialogueLine(int idx, std::vector::iterator it); -public: - DialogueViewer(); - DialogueViewer(Rectangle rect); - void setRect(Rectangle rect); - void setDialogue(Dialogue* diag); - void update(); - void draw(); -}; - -#endif diff --git a/include/editor/editor.hpp b/include/editor/editor.hpp deleted file mode 100644 index 5f940d4..0000000 --- a/include/editor/editor.hpp +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef _RPGPP_EDITOR_H -#define _RPGPP_EDITOR_H - -#include -#include "editorInterfaceService.hpp" -#include "fileSystemService.hpp" -#include "resourceService.hpp" - -class Editor { -private: - static Editor *instance_; - static std::unique_ptr ui; - static std::unique_ptr fs; - static std::unique_ptr resources; -public: - Editor(); - static EditorInterfaceService& getUi(); - static FileSystemService& getFileSystem(); - static ResourceService& getResources(); - void init(); - void update(); - void draw(); - void unload(); -}; - -#endif diff --git a/include/editor/editorInterfaceService.hpp b/include/editor/editorInterfaceService.hpp deleted file mode 100644 index a5db270..0000000 --- a/include/editor/editorInterfaceService.hpp +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef _RPGPP_EDITOR_INTERFACE_H -#define _RPGPP_EDITOR_INTERFACE_H - -#include "mainView.hpp" -#include "panelView.hpp" -#include "projectMenuBox.hpp" -#include "resourceViewerBox.hpp" -#include "tabList.hpp" -#include "windowContainer.hpp" -#include "worldViewBox.hpp" -#include -#include -#include -#include - -class MouseInputComponent; - -class EditorInterfaceService { -private: - Font uiFont; - MainView mainView; - ProjectMenuBox projectMenu; - TabList tabList; - WindowContainer windowContainer; - std::unique_ptr worldView; - std::unique_ptr panelView; - ResourceViewerBox resourceView; - Vector2 mousePos; - Vector2 hoverPos; - bool mouseLock; - ViewBoxLayer mouseBoxLayer; - bool demoGuiActive; - void drawMainView(); - void drawProjectView(); - char testStr[256]; - -public: - EditorInterfaceService(); - ~EditorInterfaceService(); - void setInitial(); - void unload() const; - void update(); - void draw(); - Font getFont() const; - void setMouseLock(bool value); - bool getMouseLock() const; - void setMouseBoxLayer(ViewBoxLayer boxLayer); - ViewBoxLayer getMouseBoxLayer() const; - TabList &getTabList(); - WindowContainer &getWindowContainer(); -}; - -#endif diff --git a/include/editor/fileSystemService.hpp b/include/editor/fileSystemService.hpp deleted file mode 100644 index cd5a0bd..0000000 --- a/include/editor/fileSystemService.hpp +++ /dev/null @@ -1,60 +0,0 @@ -#ifndef _RPGPP_EDITOR_FILESYSTEMSERVICE_H -#define _RPGPP_EDITOR_FILESYSTEMSERVICE_H - -#include -#include -#include -#include "projectFile.hpp" -#include "project.hpp" -#include "room.hpp" -#include "tileset.hpp" -#include "actor.hpp" -#include "nfd.h" - -struct FS_Result { - std::string absolutePath; - std::string path; - std::string fileName; - nfdresult_t result; -}; - -class FileSystemService { -private: - bool projectAvailable; - std::unique_ptr project; - std::vector> openedFiles; - int activeIndex; - EngineFileType lastType; - std::string lastOpenPath; - bool isOpen; - TileSet* lastTileSet; - Room* lastRoom; - Actor* lastActor; -public: - FileSystemService(); - ~FileSystemService(); - void unload(); - void promptOpenProject(); - void setProject(const std::string &projectPath); - Project *getProject(); - bool projectIsOpen(); - void openProjectFile(std::string absolutePath); - void setActiveProjectFile(int index); - void closeProjectFile(int index); - void promptOpenFile(); - void saveOpenedFile(); - bool fileIsOpen(); - std::string getOpenedFilePath(); - EngineFileType getType(); - bool isAvailable(EngineFileType type); - ProjectFile* getCurrentFile(); - FS_Result openFile(nfdu8filteritem_t filters[]); - FS_Result openFolder(); - FS_Result openGameData(); - FS_Result openImage(); - FS_Result openTileSetResource(); - FS_Result openDialogueResource(); - FS_Result openMusic(); -}; - -#endif diff --git a/include/editor/interactableInfoPanel.hpp b/include/editor/interactableInfoPanel.hpp deleted file mode 100644 index 308e97a..0000000 --- a/include/editor/interactableInfoPanel.hpp +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef _RPGPP_EDITOR_INTERACTABLEINFOPANEL_H -#define _RPGPP_EDITOR_INTERACTABLEINFOPANEL_H - -#include "worldViewBox.hpp" -#include -#include "interactable.hpp" -#include "interactablePropsState.hpp" -#include - -class InteractableInfoPanel { -private: - Rectangle rect; - RoomAction action; - InteractableType lastType; - InteractableType type; - Vector2 interactableWorldPos; - int typeNumber; - bool typeDropdownEditMode; - IntBaseWrapper* interBase; - InteractablePropsState propsState; - std::unique_ptr diagText; - char diagChars[125]; - bool diagTextEditMode; -public: - InteractableInfoPanel(); - InteractableInfoPanel(Rectangle rect); - void setRect(Rectangle rect); - void setInitial(InteractableType type); - void update(); - void draw(); - void setActionMode(RoomAction mode); - InteractableType getType(); - void setSelected(IntBaseWrapper* inter); - static void drawTypeProps(InteractableType intType, InteractablePropsState* propsState); - static void drawDialogueProps(InteractablePropsState* propsState); - static void drawWarperProps(InteractablePropsState* propsState); -}; - -#endif diff --git a/include/editor/interactablePropsState.hpp b/include/editor/interactablePropsState.hpp deleted file mode 100644 index 18a7977..0000000 --- a/include/editor/interactablePropsState.hpp +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef _RPGPP_EDITOR_INTERACTABLEPROPSSTATE_H -#define _RPGPP_EDITOR_INTERACTABLEPROPSSTATE_H - -#include "interactable.hpp" -#include "dialogueBalloon.hpp" - -class InteractablePropsState { -private: - Dialogue dialogue; -public: - bool onTouch; - std::string diagSource; - InteractablePropsState(); - void setDefaults(IntBaseWrapper* interactable); - void updateProps(IntBaseWrapper* interactable); - void setDialogue(Dialogue dialogue); - Dialogue getDialogue(); -}; - -#endif diff --git a/include/editor/layoutContainer.hpp b/include/editor/layoutContainer.hpp deleted file mode 100644 index fa34f26..0000000 --- a/include/editor/layoutContainer.hpp +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef _RPGPP_EDITOR_LAYOUTCONTAINER_H -#define _RPGPP_EDITOR_LAYOUTCONTAINER_H - -#include -#include - -static bool isLayout; -static ImVec2 layoutOffset; -static ImVec2 lastWindowSize; -static float filledPart; - -void BeginLayout(ImVec2 offset); -void EndLayout(); -void SetWindowLayout(int index, float part); - -#endif \ No newline at end of file diff --git a/include/editor/mainView.hpp b/include/editor/mainView.hpp deleted file mode 100644 index 7c05f64..0000000 --- a/include/editor/mainView.hpp +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef _RPGPP_EDITOR_MAINVIEW_H -#define _RPGPP_EDITOR_MAINVIEW_H - -#include -#include "mainViewPanel.hpp" - -class MainView { -private: - MainViewPanel panel; -public: - MainView(); - void setRect(Rectangle rect); - void update(); - void draw(); -}; - -#endif diff --git a/include/editor/mainViewPanel.hpp b/include/editor/mainViewPanel.hpp deleted file mode 100644 index 05be27d..0000000 --- a/include/editor/mainViewPanel.hpp +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef _RPGPP_EDITOR_MAINVIEWPANEL_H -#define _RPGPP_EDITOR_MAINVIEWPANEL_H - -#include - -class MainViewPanel { -private: - Rectangle rect; - Texture logoTexture; -public: - MainViewPanel(); - MainViewPanel(Rectangle rect); - void setRect(Rectangle rect); - void update(); - void draw(); -}; - -#endif diff --git a/include/editor/mapPanelView.hpp b/include/editor/mapPanelView.hpp deleted file mode 100644 index 6093e61..0000000 --- a/include/editor/mapPanelView.hpp +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef _RPGPP_EDITOR_MAPPANELVIEW_H -#define _RPGPP_EDITOR_MAPPANELVIEW_H - -#include -#include -#include "mapToolsBox.hpp" -#include "collisionInfoPanel.hpp" -#include "interactableInfoPanel.hpp" -#include "propInfoPanel.hpp" -#include "actorInfoPanel.hpp" -#include "worldViewBox.hpp" -#include "propertiesBox.hpp" - -class MapPanelView { -private: - Rectangle rect; - std::unique_ptr worldView; - MapToolsBox toolsBox; - std::unique_ptr tileSetView; - CollisionInfoPanel collisionInfo; - InteractableInfoPanel interactableInfo; - PropInfoPanel propInfo; - ActorInfoPanel actorInfo; - PropertiesBox propBox; - int actionModeToggle; - int layoutModeToggle; - bool layoutDropdownEditMode; -public: - MapPanelView(); - MapPanelView(Rectangle rect); - void setRect(Rectangle rect); - void setInitial(); - void update(); - void draw(); -}; - -#endif diff --git a/include/editor/mapPropertiesBox.hpp b/include/editor/mapPropertiesBox.hpp deleted file mode 100644 index bd6a430..0000000 --- a/include/editor/mapPropertiesBox.hpp +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef _RPGPP_EDITOR_MAPPROPERTIESBOX_H -#define _RPGPP_EDITOR_MAPPROPERTIESBOX_H - -#include -#include "room.hpp" -#include "tilemap.hpp" - -class MapPropertiesBox { -private: - Rectangle rect; - Room *room; - TileMap *map; - int mapHeight; - bool heightEdit; - int mapWidth; - bool widthEdit; - bool musicOn; - Vector2 scrollVec; - Rectangle viewRec; -public: - MapPropertiesBox(); - MapPropertiesBox(Rectangle rect); - void update(); - void draw(); - void setDefaults(); -}; - -#endif diff --git a/include/editor/mapToolsBox.hpp b/include/editor/mapToolsBox.hpp deleted file mode 100644 index 8a04348..0000000 --- a/include/editor/mapToolsBox.hpp +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef _RPGPP_EDITOR_MAPTOOLSBOX_H -#define _RPGPP_EDITOR_MAPTOOLSBOX_H - -#include "worldViewBox.hpp" -#include - -class MapToolsBox { -private: - Rectangle rect; - int actionInt; - RoomAction action; -public: - MapToolsBox(); - MapToolsBox(Rectangle rect); - void setRect(Rectangle rect); - RoomAction getActionMode(); - void update(); - void draw(); -}; - -#endif \ No newline at end of file diff --git a/include/editor/mouseInput.hpp b/include/editor/mouseInput.hpp deleted file mode 100644 index 1e478de..0000000 --- a/include/editor/mouseInput.hpp +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef _RPGPP_EDITOR_MOUSEINPUT_H -#define _RPGPP_EDITOR_MOUSEINPUT_H - -#include - -class MouseInputComponent { -private: - int layer; - Camera2D& camera; - Rectangle cameraRect; - Vector2 offset; - Vector2 mousePos; - Vector2 hoverPos; - Vector2 lastPos; - Vector2 mouseWorldPos; - Vector2 cameraTargetOffset; - bool lock; - int lastMode; -public: - MouseInputComponent(Vector2 offset, Camera2D& camera, Rectangle cameraRect, int layer); - Vector2 getMouseWorldPos(); - Vector2 getMousePos(); - void update(); - bool isInRect(); - void setCameraRect(Rectangle rect); -}; - -#endif diff --git a/include/editor/panelView.hpp b/include/editor/panelView.hpp deleted file mode 100644 index 4686f70..0000000 --- a/include/editor/panelView.hpp +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef _RPGPP_EDITOR_PANELVIEW_H -#define _RPGPP_EDITOR_PANELVIEW_H - -#include -#include "tileSetPanelView.hpp" -#include "mapPanelView.hpp" -#include "actorPanelView.hpp" -#include "dialoguePanelView.hpp" -#include "propPanelView.hpp" - -class PanelView { -private: - Vector2 pos; - Rectangle rect; - TileSetPanelView tileSetPanel; - MapPanelView mapPanel; - ActorPanelView actorPanel; - DialoguePanelView dialoguePanel; - PropPanelView propPanel; -public: - PanelView(); - PanelView(Rectangle rect); - void setRect(Rectangle rect); - void setInitial(); - void update(); - void draw(); -}; - -#endif diff --git a/include/editor/project.hpp b/include/editor/project.hpp deleted file mode 100644 index d646414..0000000 --- a/include/editor/project.hpp +++ /dev/null @@ -1,45 +0,0 @@ -#ifndef _RPGPP_EDITOR_PROJECT_H -#define _RPGPP_EDITOR_PROJECT_H - -#include -#include -#include -#include "gamedata.hpp" -#include "projectFile.hpp" -#include "projectGenerator.hpp" -#include "projectCompiler.hpp" -#include -using json = nlohmann::json; - -class Project { -private: - ProjectGenerator projectGenerator; - ProjectCompiler projectCompiler; - std::string projectBasePath; - std::string projectPath; - std::string projectTitle; - std::string tileSetsPath; - std::string mapsPath; - std::string actorsPath; - std::string dialoguesPath; - std::string imagesPath; - std::string fontsPath; - void generateCmdScript(); - void callCompiler(); - std::vector makePaths(const std::string &dirPath); - std::array, ENGINEFILETYPE_MAX> pathsList; -public: - Project(); - Project(const std::string &filePath); - void reloadPaths(); - static void generateNewProj(const std::string &title, const std::string &path); - GameData generateStruct(); - void compileProject(); - void runProject(); - void cleanCompilation(); - std::string getProjectTitle(); - std::string getProjectBasePath(); - std::vector getTypePaths(EngineFileType type); -}; - -#endif diff --git a/include/editor/projectCompiler.hpp b/include/editor/projectCompiler.hpp deleted file mode 100644 index 808432b..0000000 --- a/include/editor/projectCompiler.hpp +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef _RPGPP_EDITOR_PROJECTCOMPILER_H -#define _RPGPP_EDITOR_PROJECTCOMPILER_H - -#include -#include -#include - -class ProjectCompiler { -public: - ProjectCompiler(); - void generateCmdScript(std::string projectTitle); - void callCompiler(); - void cleanCompilation(const std::string &projectBase); -}; - -#endif \ No newline at end of file diff --git a/include/editor/projectFile.hpp b/include/editor/projectFile.hpp deleted file mode 100644 index aac76e2..0000000 --- a/include/editor/projectFile.hpp +++ /dev/null @@ -1,58 +0,0 @@ -#ifndef _RPGPP_EDITOR_PROJECTFILE_H -#define _RPGPP_EDITOR_PROJECTFILE_H - -#include -#include - -enum EngineFileType { - FILE_TILESET, - FILE_ROOM, - FILE_ACTOR, - FILE_DIALOGUE, - FILE_IMAGE, - FILE_FONT, - FILE_SOUND, - FILE_MUSIC, - FILE_PROP, - FILE_UI, - FILE_SCRIPT -}; - -#define ENGINEFILETYPE_MAX (11) - -class VariantWrapper { -public: - VariantWrapper() {}; - virtual ~VariantWrapper() {}; -}; - -template -class Variant : public VariantWrapper { -public: - std::unique_ptr data; - Variant() {}; - Variant(T* p) { data = std::make_unique(); data.reset(p); }; - void set(T* data) { this->data.reset(data); }; - T* get() { return data.get(); }; -}; - -class ProjectFile { -private: - std::string relativePath; - EngineFileType fileType; - static std::array fileTypeNames; - std::unique_ptr variant; -public: - ProjectFile(); - ProjectFile(const std::string &relativePath, EngineFileType fileType); - static std::array getTypeNames(); - void setFromPath(const std::string &relativePath); - std::string getRelativePath(); - EngineFileType getFileType(); - template - T* getData() { return (static_cast*>(variant.get()))->get(); }; - template - void setData(T* data) { variant.reset(new Variant(data)); }; -}; - -#endif diff --git a/include/editor/projectGenerator.hpp b/include/editor/projectGenerator.hpp deleted file mode 100644 index b8fe0fb..0000000 --- a/include/editor/projectGenerator.hpp +++ /dev/null @@ -1,34 +0,0 @@ -#ifndef _RPGPP_EDITOR_PROJECTGENERATOR_H -#define _RPGPP_EDITOR_PROJECTGENERATOR_H - -#include -#include -#include -#include - -class Project; - -struct ProjectPaths { - std::string tileSetsPath; - std::string mapsPath; - std::string actorsPath; - std::string dialoguesPath; - std::string imagesPath; - std::string fontsPath; - std::vector tileSetPathsList; - std::vector mapPathsList; - std::vector actorPathsList; - std::vector dialoguesPathsList; - std::vector imagesPathsList; - std::vector fontsPathsList; -}; - -class ProjectGenerator { -public: - ProjectGenerator(); - static void generateNewProj(std::string title, const std::string &path); - GameData generateStruct(std::array, ENGINEFILETYPE_MAX>* proj, - std::string title); -}; - -#endif diff --git a/include/editor/projectMenuBox.hpp b/include/editor/projectMenuBox.hpp deleted file mode 100644 index 19fdd0b..0000000 --- a/include/editor/projectMenuBox.hpp +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef _RPGPP_EDITOR_PROJECTMENUBOX_H -#define _RPGPP_EDITOR_PROJECTMENUBOX_H - -#include - -class ProjectMenuBox { -private: - Rectangle rect; -public: - ProjectMenuBox(); - ProjectMenuBox(Rectangle rect); - void setRect(Rectangle rect); - void draw(); -}; - -#endif \ No newline at end of file diff --git a/include/editor/propInfoPanel.hpp b/include/editor/propInfoPanel.hpp deleted file mode 100644 index 1b92bdb..0000000 --- a/include/editor/propInfoPanel.hpp +++ /dev/null @@ -1,27 +0,0 @@ -#ifndef _RPGPP_EDITOR_PROPINFOPANEL_H -#define _RPGPP_EDITOR_PROPINFOPANEL_H - -#include "interactablePropsState.hpp" -#include "worldViewBox.hpp" -#include - -class PropInfoPanel { -private: - Rectangle rect; - RoomAction action; - std::string propConcat; - int currentProp; - InteractablePropsState intPropsState; - Prop* prop; -public: - PropInfoPanel(); - PropInfoPanel(Rectangle rect); - void setRect(Rectangle rect); - void setActionMode(RoomAction action); - int getCurrentPropIndex(); - void setProp(Prop* p); - void update(); - void draw(); -}; - -#endif diff --git a/include/editor/propInitWindow.hpp b/include/editor/propInitWindow.hpp deleted file mode 100644 index f179201..0000000 --- a/include/editor/propInitWindow.hpp +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef _RPGPP_EDITOR_PROPINITWINDOW_H -#define _RPGPP_EDITOR_PROPINITWINDOW_H - -#include -#include "windowPopup.hpp" - -class PropInitWindow : public WindowPopup { -private: - Rectangle rect; - char title[256]; - std::string imageSourcePath; - bool hasSetImageSource; -public: - PropInitWindow(); - PropInitWindow(Rectangle rect); - void openWindow(); - void closeWindow(); - void draw(); -}; - -#endif diff --git a/include/editor/propPanelView.hpp b/include/editor/propPanelView.hpp deleted file mode 100644 index 0b48748..0000000 --- a/include/editor/propPanelView.hpp +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef _RPGPP_EDITOR_PROPPANELVIEW_H -#define _RPGPP_EDITOR_PROPPANELVIEW_H - -#include -#include "propertiesBox.hpp" -#include "propView.hpp" - -class PropPanelView { -private: - Rectangle rect; - PropView propView; - PropertiesBox props; -public: - PropPanelView(); - PropPanelView(Rectangle rect); - void setRect(Rectangle rect); - void setInitial(); - void update(); - void draw(); -}; - -#endif diff --git a/include/editor/propPropertiesBox.hpp b/include/editor/propPropertiesBox.hpp deleted file mode 100644 index b388168..0000000 --- a/include/editor/propPropertiesBox.hpp +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef _RPGPP_EDITOR_PROPPROPERTIESBOX_H -#define _RPGPP_EDITOR_PROPPROPERTIESBOX_H - -#include "interactable.hpp" -#include "prop.hpp" -#include -#include - -class PropPropertiesBox { -private: - Prop* prop; - Rectangle rect; - bool collisionViewActive; - std::array rectPos; - std::array rectSize; - bool propHasInteractable; - int intType; -public: - PropPropertiesBox(); - void setDefaults(); - void update(); - void draw(); - bool getCollisionViewActive(); -}; - -#endif diff --git a/include/editor/propView.hpp b/include/editor/propView.hpp deleted file mode 100644 index ee46e21..0000000 --- a/include/editor/propView.hpp +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef _RPGPP_EDITOR_PROPVIEW_H -#define _RPGPP_EDITOR_PROPVIEW_H - -#include -#include "collisionbox.hpp" - -class PropView { -private: - Rectangle rect; - Rectangle renderRect; - Camera2D camera; - RenderTexture2D renderTexture; - CollisionBox collisionBox; - bool collisionBoxActive; -public: - PropView(); - PropView(Rectangle rect); - void setInitial(); - void setRect(Rectangle rect); - void setCollisionBoxActive(bool value); - void update(); - void draw(); -}; - -#endif diff --git a/include/editor/propertiesBox.hpp b/include/editor/propertiesBox.hpp deleted file mode 100644 index cd85099..0000000 --- a/include/editor/propertiesBox.hpp +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef _RPGPP_EDITOR_PROPERTIESBOX_H -#define _RPGPP_EDITOR_PROPERTIESBOX_H - -#include -#include "tileSetPropertiesBox.hpp" -#include "mapPropertiesBox.hpp" -#include "actorPropertiesBox.hpp" -#include "propPropertiesBox.hpp" - -class PropertiesBox { -private: - Vector2 pos; - Rectangle rect; - TileSetPropertiesBox tileSetProps; - MapPropertiesBox mapProps; - ActorPropertiesBox actorProps; - PropPropertiesBox propProps; -public: - PropertiesBox(); - PropertiesBox(Rectangle rect); - void setRect(Rectangle rect); - void update(); - void draw(); - void setDefaults(); - ActorPropertiesBox& getActorProps(); - PropPropertiesBox& getPropProps(); -}; - -#endif diff --git a/include/editor/resourceViewerBox.hpp b/include/editor/resourceViewerBox.hpp deleted file mode 100644 index 0a748c3..0000000 --- a/include/editor/resourceViewerBox.hpp +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef _RPGPP_EDITOR_RESOURCEVIEWERBOX_H -#define _RPGPP_EDITOR_RESOURCEVIEWERBOX_H - -#include -#include - -class ResourceViewerBox { -private: - Rectangle rect{}; - int dropdownActive; - bool deleteConfirmOpen; - std::string deleteConfirmPath; - void onNewButton() const; - void drawResourcesList(); - void drawContextMenu(const std::string &resPath); - -public: - ResourceViewerBox(); - explicit ResourceViewerBox(Rectangle rect); - void setRect(Rectangle m_rect); - void update() const; - void draw(); -}; - -#endif diff --git a/include/editor/tabList.hpp b/include/editor/tabList.hpp deleted file mode 100644 index f1feddf..0000000 --- a/include/editor/tabList.hpp +++ /dev/null @@ -1,34 +0,0 @@ -#ifndef _RPGPP_EDITOR_TABLIST_H -#define _RPGPP_EDITOR_TABLIST_H - -#include -#include -#include - -struct TabData -{ - std::string title; -}; - -class TabList { -private: - Rectangle rect; - Texture2D closeTexture; - std::vector tabs; - int activeIndex; - float tabWidth; - bool drawOverflow; - Rectangle scissorRect; - Vector2 scissorOffset; - float maxScissorOffset; - int drawTabButton(float offset, const std::string &title, bool active); -public: - TabList(); - TabList(Rectangle rect); - void setRect(Rectangle rect); - void addItem(const std::string &title); - void update(); - void draw(); -}; - -#endif diff --git a/include/editor/tileSetPanelView.hpp b/include/editor/tileSetPanelView.hpp deleted file mode 100644 index 17b3637..0000000 --- a/include/editor/tileSetPanelView.hpp +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef _RPGPP_EDITOR_TILESETPANELVIEW_H -#define _RPGPP_EDITOR_TILESETPANELVIEW_H - -#include -#include "worldViewBox.hpp" -#include "propertiesBox.hpp" - -class TileSetPanelView { -private: - Rectangle rect; - std::unique_ptr worldView; - PropertiesBox propBox; -public: - TileSetPanelView(); - TileSetPanelView(Rectangle rect); - void setRect(Rectangle rect); - void setInitial(); - void update(); - void draw(); -}; - -#endif diff --git a/include/editor/tileSetPropertiesBox.hpp b/include/editor/tileSetPropertiesBox.hpp deleted file mode 100644 index cb52787..0000000 --- a/include/editor/tileSetPropertiesBox.hpp +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef _RPGPP_EDITOR_TILESETPROPERTIESBOX_H -#define _RPGPP_EDITOR_TILESETPROPERTIESBOX_H - -#include -#include -#include "tileset.hpp" - -class TileSetPropertiesBox { -private: - Rectangle rect; - TileSet *tileSet; - int chosenTileSize; - int chosenTileWidth; - int chosenTileHeight; - bool multiSizeCheckBox; - bool chosenTileSizeEditMode; - bool chosenTileWidthEditMode; - bool chosenTileHeightEditMode; - Vector2 scrollVec; - Rectangle viewRec; - std::array tileSizeArr; -public: - TileSetPropertiesBox(); - TileSetPropertiesBox(Rectangle rect); - void update(); - void draw(); - void setDefaults(); -}; - -#endif diff --git a/include/editor/windowContainer.hpp b/include/editor/windowContainer.hpp deleted file mode 100644 index f5a8efc..0000000 --- a/include/editor/windowContainer.hpp +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef _RPGPP_EDITOR_WINDOWCONTAINER_H -#define _RPGPP_EDITOR_WINDOWCONTAINER_H - -#include -#include - -#include "windowPopup.hpp" - -#include "windows/projectBinaryViewWindow.hpp" -#include "windows/tileSetDialogWindow.hpp" - -class WindowContainer { -private: - bool windowOpen; - ProjectBinaryViewWindow projectBinaryView; - TileSetDialogWindow tileSetDialog; - std::map> mapW; -public: - WindowContainer(); - bool isWindowOpen() const; - void setWindowOpen(bool value); - ProjectBinaryViewWindow& openProjectBinaryView(); - TileSetDialogWindow& openTileSetDialog(); - void update(); - void draw(); - void drawTileSetDialog(); - void drawProjectBinaryView(); - WindowPopup& open(const std::string &id); - void drawWindow(const std::string &id); -}; - -#endif diff --git a/include/editor/windowPopup.hpp b/include/editor/windowPopup.hpp deleted file mode 100644 index 75b43df..0000000 --- a/include/editor/windowPopup.hpp +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef _RPGPP_EDITOR_WINDOWPOPUP_H -#define _RPGPP_EDITOR_WINDOWPOPUP_H - -#include -#include - -class WindowPopup { -protected: - Rectangle rect; - bool propExists; - std::string prop; -public: - std::string imPopupId; - virtual ~WindowPopup() {}; - WindowPopup(); - WindowPopup(const std::string &imPopupId, Rectangle rect); - void setProp(const std::string &prop); - std::string getProp(); - bool hasProp(); - void openWindow(); - void closeWindow(); - virtual void update(); - virtual void draw() {}; -}; - -#endif diff --git a/include/editor/windows/aboutWindow.hpp b/include/editor/windows/aboutWindow.hpp deleted file mode 100644 index b42dcf4..0000000 --- a/include/editor/windows/aboutWindow.hpp +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef _RPGPP_ABOUTWINDOW_H -#define _RPGPP_ABOUTWINDOW_H - -#include -#include "windowPopup.hpp" - -class AboutWindow : public WindowPopup { -private: - Rectangle rect; -public: - AboutWindow(); - AboutWindow(Rectangle rect); - void openWindow(); - void closeWindow(); - void draw(); -}; - -#endif diff --git a/include/editor/windows/actorInitWindow.hpp b/include/editor/windows/actorInitWindow.hpp deleted file mode 100644 index 1452177..0000000 --- a/include/editor/windows/actorInitWindow.hpp +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef _RPGPP_EDITOR_ACTORINITWINDOW_H -#define _RPGPP_EDITOR_ACTORINITWINDOW_H - -#include -#include -#include "windowPopup.hpp" - -class ActorInitWindow : public WindowPopup { -private: - Rectangle rect; - bool titleEditMode; - char title[256]; - std::string titleText; - bool hasSetTileSet; - std::string tileSetSource; -public: - ActorInitWindow(); - ActorInitWindow(Rectangle rect); - void closeWindow(); - void openWindow(); - void draw(); -}; - -#endif diff --git a/include/editor/windows/deleteConfirmWindow.hpp b/include/editor/windows/deleteConfirmWindow.hpp deleted file mode 100644 index 986bf59..0000000 --- a/include/editor/windows/deleteConfirmWindow.hpp +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef _RPGPP_DELETECONFIRMWINDOW_H -#define _RPGPP_DELETECONFIRMWINDOW_H - -#include -#include "windowPopup.hpp" - -class DeleteConfirmWindow : public WindowPopup { -private: - Rectangle rect; -public: - DeleteConfirmWindow(); - DeleteConfirmWindow(Rectangle rect); - void openWindow(); - void closeWindow(); - void draw(); -}; - -#endif diff --git a/include/editor/windows/dialogueInitWindow.hpp b/include/editor/windows/dialogueInitWindow.hpp deleted file mode 100644 index 6ec6622..0000000 --- a/include/editor/windows/dialogueInitWindow.hpp +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef _RPGPP_EDITOR_DIALOGUEINITWINDOW_H -#define _RPGPP_EDITOR_DIALOGUEINITWINDOW_H - -#include -#include "windowPopup.hpp" - -class DialogueInitWindow : public WindowPopup { -private: - Rectangle rect; - char title[256]; - std::string titleText; -public: - DialogueInitWindow(); - DialogueInitWindow(Rectangle rect); - void openWindow(); - void closeWindow(); - void draw(); -}; - -#endif diff --git a/include/editor/windows/dialogueLineWindow.hpp b/include/editor/windows/dialogueLineWindow.hpp deleted file mode 100644 index eba38e8..0000000 --- a/include/editor/windows/dialogueLineWindow.hpp +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef _RPGPP_EDITOR_DIALOGUELINEWINDOW_H -#define _RPGPP_EDITOR_DIALOGUELINEWINDOW_H - -#include "windowPopup.hpp" -#include - -class DialogueLineWindow : public WindowPopup { -private: - Rectangle rect; - char lineTitle[256]; -public: - DialogueLineWindow(); - DialogueLineWindow(Rectangle rect); - void openWindow(); - void closeWindow(); - void draw(); -}; - -#endif diff --git a/include/editor/windows/errorWindow.hpp b/include/editor/windows/errorWindow.hpp deleted file mode 100644 index b5fea3d..0000000 --- a/include/editor/windows/errorWindow.hpp +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef _RPGPP_EDITOR_ERRORWINDOW_H -#define _RPGPP_EDITOR_ERRORWINDOW_H - -#include -#include "windowPopup.hpp" - -class ErrorWindow : public WindowPopup { -private: - Rectangle rect; -public: - ErrorWindow(); - ErrorWindow(Rectangle rect); - void openWindow(); - void closeWindow(); - void draw(); -}; - -#endif diff --git a/include/editor/windows/mapInitWindow.hpp b/include/editor/windows/mapInitWindow.hpp deleted file mode 100644 index 207de40..0000000 --- a/include/editor/windows/mapInitWindow.hpp +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef _RPGPP_EDITOR_MAPINITWINDOW_H -#define _RPGPP_EDITOR_MAPINITWINDOW_H - -#include -#include -#include "windowPopup.hpp" - -class MapInitWindow : public WindowPopup { -private: - Rectangle rect; - std::string titleText; - char title[256]; - bool titleEditMode; - std::string tileSetSource; - bool hasSetTileSet; -public: - MapInitWindow(); - MapInitWindow(Rectangle rect); - void openWindow(); - void closeWindow(); - void draw(); -}; - -#endif diff --git a/include/editor/windows/projectBinaryViewWindow.hpp b/include/editor/windows/projectBinaryViewWindow.hpp deleted file mode 100644 index 6379ad9..0000000 --- a/include/editor/windows/projectBinaryViewWindow.hpp +++ /dev/null @@ -1,42 +0,0 @@ -#ifndef _RPGPP_EDITOR_PROJECTBINARYVIEWWINDOW_H -#define _RPGPP_EDITOR_PROJECTBINARYVIEWWINDOW_H - -#include -#include -#include -#include "windowPopup.hpp" - -#include "gamedata.hpp" -#include "imgui.h" -#include "tileset.hpp" -#include "room.hpp" -#include "worldViewBox.hpp" - -class ProjectBinaryViewWindow{ -private: - bool active; - Rectangle rect; - std::unique_ptr tilesView; - std::unique_ptr roomView; - bool dataAvailable; - bool pageEditMode; - int currentPageNum; - EngineFileType currentPage; - std::unique_ptr data; - EngineFileType fileType; - std::unique_ptr tileset; - std::unique_ptr room; - void setTileSet(std::string name); - void setRoom(RoomBin roomBin); - void drawCloseButton(ImDrawList* draw); - void drawResourcesList(); -public: - ProjectBinaryViewWindow(); - ProjectBinaryViewWindow(Rectangle rect); - void setActive(); - void closeWindow(); - void draw(); - void setData(GameData data); -}; - -#endif diff --git a/include/editor/windows/projectInitWindow.hpp b/include/editor/windows/projectInitWindow.hpp deleted file mode 100644 index 70b7142..0000000 --- a/include/editor/windows/projectInitWindow.hpp +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef _RPGPP_EDITOR_PROJECTINITWINDOW_H -#define _RPGPP_EDITOR_PROJECTINITWINDOW_H - -#include -#include - -#include "windowPopup.hpp" - -class ProjectInitWindow : public WindowPopup { -private: - Rectangle rect; - bool titleEditMode; - std::string titleText; - char title[256]; - bool hasSetDirPath; - std::string dirPath; -public: - ProjectInitWindow(); - ProjectInitWindow(Rectangle rect); - void openWindow(); - void closeWindow(); - void draw(); -}; - -#endif diff --git a/include/editor/windows/tileSetDialogWindow.hpp b/include/editor/windows/tileSetDialogWindow.hpp deleted file mode 100644 index 7e616fd..0000000 --- a/include/editor/windows/tileSetDialogWindow.hpp +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef _RPGPP_EDITOR_TILESETDIALOGWINDOW_H -#define _RPGPP_EDITOR_TILESETDIALOGWINDOW_H - -#include -#include -#include -#include "worldViewBox.hpp" - -class TileSetDialogWindow { -private: - bool active; - ViewBoxLayer boxLayer; - Rectangle rect; - Vector2 chosenTile; - std::unique_ptr tileSetView; - std::function callback; -public: - TileSetDialogWindow(); - TileSetDialogWindow(Rectangle rect); - void setActive(); - void closeWindow(); - void update(); - void draw(); - void setTileSet(TileSet* tileSet); - void setSelectedTile(Vector2 atlasTile); - Vector2 getSelectedTile(); - void setCallback(const std::function &func); -}; - -#endif \ No newline at end of file diff --git a/include/editor/windows/tileSetInitWindow.hpp b/include/editor/windows/tileSetInitWindow.hpp deleted file mode 100644 index 0c99643..0000000 --- a/include/editor/windows/tileSetInitWindow.hpp +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef _RPGPP_EDITOR_TILESETINITWINDOW_H -#define _RPGPP_EDITOR_TILESETINITWINDOW_H - -#include -#include -#include "windowPopup.hpp" - -class TileSetInitWindow : public WindowPopup { -private: - Rectangle rect; - bool titleEditMode; - std::string titleText; - char title[256]; - bool hasSetTextureSource; - std::string textureSource; -public: - TileSetInitWindow(); - TileSetInitWindow(Rectangle rect); - void openWindow(); - void closeWindow(); - void draw(); -}; - -#endif diff --git a/include/editor/worldViewBox.hpp b/include/editor/worldViewBox.hpp deleted file mode 100644 index 123198e..0000000 --- a/include/editor/worldViewBox.hpp +++ /dev/null @@ -1,125 +0,0 @@ -#ifndef _RPGPP_EDITOR_WORLDVIEWBOX_H -#define _RPGPP_EDITOR_WORLDVIEWBOX_H - -#include -#include -#include "fileSystemService.hpp" -#include "mouseInput.hpp" -#include "room.hpp" -#include "tileset.hpp" - -class WorldViewBox; - -enum RoomAction { - ACTION_NONE, ACTION_PLACE, ACTION_ERASE, ACTION_EDIT, ACTION_STARTTILE -}; - -enum RoomLayer { - LAYER_TILES, LAYER_COLLISIONS, LAYER_INTERACTABLES, LAYER_PROP, LAYER_ACTOR -}; - -enum ViewBoxLayer { - VIEWBOX_LAYER_BASE = 0, VIEWBOX_LAYER_BINVIEW = 1, VIEWBOX_LAYER_DIALOG = 2, VIEWBOX_LAYER_WINDOW = 3 -}; - -class TileSetViewBox { -private: - TileSet *tileSet; - ViewBoxLayer layer; - WorldViewBox* viewBox; - Vector2 tileAtlasPos; - Vector2 tileWorldPos; - bool hoverValidTile; - bool isSelectingTile; - bool hasSelectedTile; - Vector2 selectedTileAtlasPos; - Vector2 selectedTileWorldPos; -public: - TileSetViewBox(); - TileSetViewBox(WorldViewBox* viewBox, ViewBoxLayer boxLayer); - void unload(); - void setTileSet(TileSet* tileSet); - void setSelectionMode(); - Vector2 getSelectedTile(); - void isHoverOnValidTile(); - void drawGrid(); - void drawTiles(); - void drawMouse(); -}; - -class MapViewBox { -private: - Room *room; - WorldViewBox *viewBox; - ViewBoxLayer layer; - Vector2 tileAtlasPos; - Vector2 tileWorldPos; - bool hoverValidTile; - Vector2 selectedWorldTile; - RoomAction action; - RoomLayer currentLayer; - bool isTileValid; - Vector2 selectedTileAtlasCoords; - InteractableType currentInteractableType; - std::string stringProp; - void drawHoverTile(int atlasTileSize, Vector2 tileWorldPos); -public: - MapViewBox(); - MapViewBox(WorldViewBox *viewBox, ViewBoxLayer boxLayer); - void unload(); - void setMap(Room* map); - void setActionMode(RoomAction mode); - void setLayerMode(RoomLayer mode); - void setSelectedTile(Vector2 tile); - void setCurrentInteractableType(InteractableType type); - void setStringProp(const std::string &str); - Vector2 getSelectedWorldTile(); - void isHoverOnValidTile(); - void drawGrid(); - void drawTiles(); - void drawMouse(); -}; - -class WorldViewBox { - friend class TileSetViewBox; - friend class MapViewBox; -private: - std::string windowTitle; - bool isChild; - Rectangle windowRect; - Rectangle renderRect; - bool mouseLock; - Camera2D camera; - RenderTexture renderTexture; - EngineFileType type; - std::unique_ptr mouseInput; - Vector2 mousePos; - Vector2 hoverPos; - TileSetViewBox tilesView; - MapViewBox mapView; -public: - WorldViewBox(); - WorldViewBox(Rectangle windowRect, EngineFileType type, ViewBoxLayer boxLayer); - ~WorldViewBox(); - void setWindowTitle(const std::string &title); - void asChild(); - Rectangle getWindowRect(); - void setRect(Rectangle rect); - Rectangle getRenderRect(); - void setMouseLock(bool value); - void setTileSet(TileSet* tileSet); - void setRoom(Room* map); - void enableTileSelection(); - Vector2 getSelectedTile(); - void setActionMode(RoomAction mode); - void setLayerMode(RoomLayer mode); - void setCurrentInteractableType(InteractableType type); - void setSelectedTile(Vector2 tile); - void setStringProp(const std::string &str); - Vector2 getSelectedWorldTile(); - void update(); - void draw(); - void unload(); -}; - -#endif diff --git a/include/extras/IconsFontAwesome6.h b/include/extras/IconsFontAwesome6.h deleted file mode 100644 index a56c5f5..0000000 --- a/include/extras/IconsFontAwesome6.h +++ /dev/null @@ -1,1396 +0,0 @@ -// Generated by https://github.com/juliettef/IconFontCppHeaders script GenerateIconFontCppHeaders.py for languages C and C++ -// from https://github.com/FortAwesome/Font-Awesome/raw/6.x/metadata/icons.yml -// for use with https://github.com/FortAwesome/Font-Awesome/blob/6.x/webfonts/fa-regular-400.ttf, https://github.com/FortAwesome/Font-Awesome/blob/6.x/webfonts/fa-solid-900.ttf -#pragma once - -#define FONT_ICON_FILE_NAME_FAR "fa-regular-400.ttf" -#define FONT_ICON_FILE_NAME_FAS "fa-solid-900.ttf" - -#define ICON_MIN_FA 0xe005 -#define ICON_MAX_16_FA 0xf8ff -#define ICON_MAX_FA 0xf8ff -#define ICON_FA_0 "0" // U+0030 -#define ICON_FA_1 "1" // U+0031 -#define ICON_FA_2 "2" // U+0032 -#define ICON_FA_3 "3" // U+0033 -#define ICON_FA_4 "4" // U+0034 -#define ICON_FA_5 "5" // U+0035 -#define ICON_FA_6 "6" // U+0036 -#define ICON_FA_7 "7" // U+0037 -#define ICON_FA_8 "8" // U+0038 -#define ICON_FA_9 "9" // U+0039 -#define ICON_FA_A "A" // U+0041 -#define ICON_FA_ADDRESS_BOOK "\xef\x8a\xb9" // U+f2b9 -#define ICON_FA_ADDRESS_CARD "\xef\x8a\xbb" // U+f2bb -#define ICON_FA_ALIGN_CENTER "\xef\x80\xb7" // U+f037 -#define ICON_FA_ALIGN_JUSTIFY "\xef\x80\xb9" // U+f039 -#define ICON_FA_ALIGN_LEFT "\xef\x80\xb6" // U+f036 -#define ICON_FA_ALIGN_RIGHT "\xef\x80\xb8" // U+f038 -#define ICON_FA_ANCHOR "\xef\x84\xbd" // U+f13d -#define ICON_FA_ANCHOR_CIRCLE_CHECK "\xee\x92\xaa" // U+e4aa -#define ICON_FA_ANCHOR_CIRCLE_EXCLAMATION "\xee\x92\xab" // U+e4ab -#define ICON_FA_ANCHOR_CIRCLE_XMARK "\xee\x92\xac" // U+e4ac -#define ICON_FA_ANCHOR_LOCK "\xee\x92\xad" // U+e4ad -#define ICON_FA_ANGLE_DOWN "\xef\x84\x87" // U+f107 -#define ICON_FA_ANGLE_LEFT "\xef\x84\x84" // U+f104 -#define ICON_FA_ANGLE_RIGHT "\xef\x84\x85" // U+f105 -#define ICON_FA_ANGLE_UP "\xef\x84\x86" // U+f106 -#define ICON_FA_ANGLES_DOWN "\xef\x84\x83" // U+f103 -#define ICON_FA_ANGLES_LEFT "\xef\x84\x80" // U+f100 -#define ICON_FA_ANGLES_RIGHT "\xef\x84\x81" // U+f101 -#define ICON_FA_ANGLES_UP "\xef\x84\x82" // U+f102 -#define ICON_FA_ANKH "\xef\x99\x84" // U+f644 -#define ICON_FA_APPLE_WHOLE "\xef\x97\x91" // U+f5d1 -#define ICON_FA_ARCHWAY "\xef\x95\x97" // U+f557 -#define ICON_FA_ARROW_DOWN "\xef\x81\xa3" // U+f063 -#define ICON_FA_ARROW_DOWN_1_9 "\xef\x85\xa2" // U+f162 -#define ICON_FA_ARROW_DOWN_9_1 "\xef\xa2\x86" // U+f886 -#define ICON_FA_ARROW_DOWN_A_Z "\xef\x85\x9d" // U+f15d -#define ICON_FA_ARROW_DOWN_LONG "\xef\x85\xb5" // U+f175 -#define ICON_FA_ARROW_DOWN_SHORT_WIDE "\xef\xa2\x84" // U+f884 -#define ICON_FA_ARROW_DOWN_UP_ACROSS_LINE "\xee\x92\xaf" // U+e4af -#define ICON_FA_ARROW_DOWN_UP_LOCK "\xee\x92\xb0" // U+e4b0 -#define ICON_FA_ARROW_DOWN_WIDE_SHORT "\xef\x85\xa0" // U+f160 -#define ICON_FA_ARROW_DOWN_Z_A "\xef\xa2\x81" // U+f881 -#define ICON_FA_ARROW_LEFT "\xef\x81\xa0" // U+f060 -#define ICON_FA_ARROW_LEFT_LONG "\xef\x85\xb7" // U+f177 -#define ICON_FA_ARROW_POINTER "\xef\x89\x85" // U+f245 -#define ICON_FA_ARROW_RIGHT "\xef\x81\xa1" // U+f061 -#define ICON_FA_ARROW_RIGHT_ARROW_LEFT "\xef\x83\xac" // U+f0ec -#define ICON_FA_ARROW_RIGHT_FROM_BRACKET "\xef\x82\x8b" // U+f08b -#define ICON_FA_ARROW_RIGHT_LONG "\xef\x85\xb8" // U+f178 -#define ICON_FA_ARROW_RIGHT_TO_BRACKET "\xef\x82\x90" // U+f090 -#define ICON_FA_ARROW_RIGHT_TO_CITY "\xee\x92\xb3" // U+e4b3 -#define ICON_FA_ARROW_ROTATE_LEFT "\xef\x83\xa2" // U+f0e2 -#define ICON_FA_ARROW_ROTATE_RIGHT "\xef\x80\x9e" // U+f01e -#define ICON_FA_ARROW_TREND_DOWN "\xee\x82\x97" // U+e097 -#define ICON_FA_ARROW_TREND_UP "\xee\x82\x98" // U+e098 -#define ICON_FA_ARROW_TURN_DOWN "\xef\x85\x89" // U+f149 -#define ICON_FA_ARROW_TURN_UP "\xef\x85\x88" // U+f148 -#define ICON_FA_ARROW_UP "\xef\x81\xa2" // U+f062 -#define ICON_FA_ARROW_UP_1_9 "\xef\x85\xa3" // U+f163 -#define ICON_FA_ARROW_UP_9_1 "\xef\xa2\x87" // U+f887 -#define ICON_FA_ARROW_UP_A_Z "\xef\x85\x9e" // U+f15e -#define ICON_FA_ARROW_UP_FROM_BRACKET "\xee\x82\x9a" // U+e09a -#define ICON_FA_ARROW_UP_FROM_GROUND_WATER "\xee\x92\xb5" // U+e4b5 -#define ICON_FA_ARROW_UP_FROM_WATER_PUMP "\xee\x92\xb6" // U+e4b6 -#define ICON_FA_ARROW_UP_LONG "\xef\x85\xb6" // U+f176 -#define ICON_FA_ARROW_UP_RIGHT_DOTS "\xee\x92\xb7" // U+e4b7 -#define ICON_FA_ARROW_UP_RIGHT_FROM_SQUARE "\xef\x82\x8e" // U+f08e -#define ICON_FA_ARROW_UP_SHORT_WIDE "\xef\xa2\x85" // U+f885 -#define ICON_FA_ARROW_UP_WIDE_SHORT "\xef\x85\xa1" // U+f161 -#define ICON_FA_ARROW_UP_Z_A "\xef\xa2\x82" // U+f882 -#define ICON_FA_ARROWS_DOWN_TO_LINE "\xee\x92\xb8" // U+e4b8 -#define ICON_FA_ARROWS_DOWN_TO_PEOPLE "\xee\x92\xb9" // U+e4b9 -#define ICON_FA_ARROWS_LEFT_RIGHT "\xef\x81\xbe" // U+f07e -#define ICON_FA_ARROWS_LEFT_RIGHT_TO_LINE "\xee\x92\xba" // U+e4ba -#define ICON_FA_ARROWS_ROTATE "\xef\x80\xa1" // U+f021 -#define ICON_FA_ARROWS_SPIN "\xee\x92\xbb" // U+e4bb -#define ICON_FA_ARROWS_SPLIT_UP_AND_LEFT "\xee\x92\xbc" // U+e4bc -#define ICON_FA_ARROWS_TO_CIRCLE "\xee\x92\xbd" // U+e4bd -#define ICON_FA_ARROWS_TO_DOT "\xee\x92\xbe" // U+e4be -#define ICON_FA_ARROWS_TO_EYE "\xee\x92\xbf" // U+e4bf -#define ICON_FA_ARROWS_TURN_RIGHT "\xee\x93\x80" // U+e4c0 -#define ICON_FA_ARROWS_TURN_TO_DOTS "\xee\x93\x81" // U+e4c1 -#define ICON_FA_ARROWS_UP_DOWN "\xef\x81\xbd" // U+f07d -#define ICON_FA_ARROWS_UP_DOWN_LEFT_RIGHT "\xef\x81\x87" // U+f047 -#define ICON_FA_ARROWS_UP_TO_LINE "\xee\x93\x82" // U+e4c2 -#define ICON_FA_ASTERISK "*" // U+002a -#define ICON_FA_AT "@" // U+0040 -#define ICON_FA_ATOM "\xef\x97\x92" // U+f5d2 -#define ICON_FA_AUDIO_DESCRIPTION "\xef\x8a\x9e" // U+f29e -#define ICON_FA_AUSTRAL_SIGN "\xee\x82\xa9" // U+e0a9 -#define ICON_FA_AWARD "\xef\x95\x99" // U+f559 -#define ICON_FA_B "B" // U+0042 -#define ICON_FA_BABY "\xef\x9d\xbc" // U+f77c -#define ICON_FA_BABY_CARRIAGE "\xef\x9d\xbd" // U+f77d -#define ICON_FA_BACKWARD "\xef\x81\x8a" // U+f04a -#define ICON_FA_BACKWARD_FAST "\xef\x81\x89" // U+f049 -#define ICON_FA_BACKWARD_STEP "\xef\x81\x88" // U+f048 -#define ICON_FA_BACON "\xef\x9f\xa5" // U+f7e5 -#define ICON_FA_BACTERIA "\xee\x81\x99" // U+e059 -#define ICON_FA_BACTERIUM "\xee\x81\x9a" // U+e05a -#define ICON_FA_BAG_SHOPPING "\xef\x8a\x90" // U+f290 -#define ICON_FA_BAHAI "\xef\x99\xa6" // U+f666 -#define ICON_FA_BAHT_SIGN "\xee\x82\xac" // U+e0ac -#define ICON_FA_BAN "\xef\x81\x9e" // U+f05e -#define ICON_FA_BAN_SMOKING "\xef\x95\x8d" // U+f54d -#define ICON_FA_BANDAGE "\xef\x91\xa2" // U+f462 -#define ICON_FA_BARCODE "\xef\x80\xaa" // U+f02a -#define ICON_FA_BARS "\xef\x83\x89" // U+f0c9 -#define ICON_FA_BARS_PROGRESS "\xef\xa0\xa8" // U+f828 -#define ICON_FA_BARS_STAGGERED "\xef\x95\x90" // U+f550 -#define ICON_FA_BASEBALL "\xef\x90\xb3" // U+f433 -#define ICON_FA_BASEBALL_BAT_BALL "\xef\x90\xb2" // U+f432 -#define ICON_FA_BASKET_SHOPPING "\xef\x8a\x91" // U+f291 -#define ICON_FA_BASKETBALL "\xef\x90\xb4" // U+f434 -#define ICON_FA_BATH "\xef\x8b\x8d" // U+f2cd -#define ICON_FA_BATTERY_EMPTY "\xef\x89\x84" // U+f244 -#define ICON_FA_BATTERY_FULL "\xef\x89\x80" // U+f240 -#define ICON_FA_BATTERY_HALF "\xef\x89\x82" // U+f242 -#define ICON_FA_BATTERY_QUARTER "\xef\x89\x83" // U+f243 -#define ICON_FA_BATTERY_THREE_QUARTERS "\xef\x89\x81" // U+f241 -#define ICON_FA_BED "\xef\x88\xb6" // U+f236 -#define ICON_FA_BED_PULSE "\xef\x92\x87" // U+f487 -#define ICON_FA_BEER_MUG_EMPTY "\xef\x83\xbc" // U+f0fc -#define ICON_FA_BELL "\xef\x83\xb3" // U+f0f3 -#define ICON_FA_BELL_CONCIERGE "\xef\x95\xa2" // U+f562 -#define ICON_FA_BELL_SLASH "\xef\x87\xb6" // U+f1f6 -#define ICON_FA_BEZIER_CURVE "\xef\x95\x9b" // U+f55b -#define ICON_FA_BICYCLE "\xef\x88\x86" // U+f206 -#define ICON_FA_BINOCULARS "\xef\x87\xa5" // U+f1e5 -#define ICON_FA_BIOHAZARD "\xef\x9e\x80" // U+f780 -#define ICON_FA_BITCOIN_SIGN "\xee\x82\xb4" // U+e0b4 -#define ICON_FA_BLENDER "\xef\x94\x97" // U+f517 -#define ICON_FA_BLENDER_PHONE "\xef\x9a\xb6" // U+f6b6 -#define ICON_FA_BLOG "\xef\x9e\x81" // U+f781 -#define ICON_FA_BOLD "\xef\x80\xb2" // U+f032 -#define ICON_FA_BOLT "\xef\x83\xa7" // U+f0e7 -#define ICON_FA_BOLT_LIGHTNING "\xee\x82\xb7" // U+e0b7 -#define ICON_FA_BOMB "\xef\x87\xa2" // U+f1e2 -#define ICON_FA_BONE "\xef\x97\x97" // U+f5d7 -#define ICON_FA_BONG "\xef\x95\x9c" // U+f55c -#define ICON_FA_BOOK "\xef\x80\xad" // U+f02d -#define ICON_FA_BOOK_ATLAS "\xef\x95\x98" // U+f558 -#define ICON_FA_BOOK_BIBLE "\xef\x99\x87" // U+f647 -#define ICON_FA_BOOK_BOOKMARK "\xee\x82\xbb" // U+e0bb -#define ICON_FA_BOOK_JOURNAL_WHILLS "\xef\x99\xaa" // U+f66a -#define ICON_FA_BOOK_MEDICAL "\xef\x9f\xa6" // U+f7e6 -#define ICON_FA_BOOK_OPEN "\xef\x94\x98" // U+f518 -#define ICON_FA_BOOK_OPEN_READER "\xef\x97\x9a" // U+f5da -#define ICON_FA_BOOK_QURAN "\xef\x9a\x87" // U+f687 -#define ICON_FA_BOOK_SKULL "\xef\x9a\xb7" // U+f6b7 -#define ICON_FA_BOOKMARK "\xef\x80\xae" // U+f02e -#define ICON_FA_BORDER_ALL "\xef\xa1\x8c" // U+f84c -#define ICON_FA_BORDER_NONE "\xef\xa1\x90" // U+f850 -#define ICON_FA_BORDER_TOP_LEFT "\xef\xa1\x93" // U+f853 -#define ICON_FA_BORE_HOLE "\xee\x93\x83" // U+e4c3 -#define ICON_FA_BOTTLE_DROPLET "\xee\x93\x84" // U+e4c4 -#define ICON_FA_BOTTLE_WATER "\xee\x93\x85" // U+e4c5 -#define ICON_FA_BOWL_FOOD "\xee\x93\x86" // U+e4c6 -#define ICON_FA_BOWL_RICE "\xee\x8b\xab" // U+e2eb -#define ICON_FA_BOWLING_BALL "\xef\x90\xb6" // U+f436 -#define ICON_FA_BOX "\xef\x91\xa6" // U+f466 -#define ICON_FA_BOX_ARCHIVE "\xef\x86\x87" // U+f187 -#define ICON_FA_BOX_OPEN "\xef\x92\x9e" // U+f49e -#define ICON_FA_BOX_TISSUE "\xee\x81\x9b" // U+e05b -#define ICON_FA_BOXES_PACKING "\xee\x93\x87" // U+e4c7 -#define ICON_FA_BOXES_STACKED "\xef\x91\xa8" // U+f468 -#define ICON_FA_BRAILLE "\xef\x8a\xa1" // U+f2a1 -#define ICON_FA_BRAIN "\xef\x97\x9c" // U+f5dc -#define ICON_FA_BRAZILIAN_REAL_SIGN "\xee\x91\xac" // U+e46c -#define ICON_FA_BREAD_SLICE "\xef\x9f\xac" // U+f7ec -#define ICON_FA_BRIDGE "\xee\x93\x88" // U+e4c8 -#define ICON_FA_BRIDGE_CIRCLE_CHECK "\xee\x93\x89" // U+e4c9 -#define ICON_FA_BRIDGE_CIRCLE_EXCLAMATION "\xee\x93\x8a" // U+e4ca -#define ICON_FA_BRIDGE_CIRCLE_XMARK "\xee\x93\x8b" // U+e4cb -#define ICON_FA_BRIDGE_LOCK "\xee\x93\x8c" // U+e4cc -#define ICON_FA_BRIDGE_WATER "\xee\x93\x8e" // U+e4ce -#define ICON_FA_BRIEFCASE "\xef\x82\xb1" // U+f0b1 -#define ICON_FA_BRIEFCASE_MEDICAL "\xef\x91\xa9" // U+f469 -#define ICON_FA_BROOM "\xef\x94\x9a" // U+f51a -#define ICON_FA_BROOM_BALL "\xef\x91\x98" // U+f458 -#define ICON_FA_BRUSH "\xef\x95\x9d" // U+f55d -#define ICON_FA_BUCKET "\xee\x93\x8f" // U+e4cf -#define ICON_FA_BUG "\xef\x86\x88" // U+f188 -#define ICON_FA_BUG_SLASH "\xee\x92\x90" // U+e490 -#define ICON_FA_BUGS "\xee\x93\x90" // U+e4d0 -#define ICON_FA_BUILDING "\xef\x86\xad" // U+f1ad -#define ICON_FA_BUILDING_CIRCLE_ARROW_RIGHT "\xee\x93\x91" // U+e4d1 -#define ICON_FA_BUILDING_CIRCLE_CHECK "\xee\x93\x92" // U+e4d2 -#define ICON_FA_BUILDING_CIRCLE_EXCLAMATION "\xee\x93\x93" // U+e4d3 -#define ICON_FA_BUILDING_CIRCLE_XMARK "\xee\x93\x94" // U+e4d4 -#define ICON_FA_BUILDING_COLUMNS "\xef\x86\x9c" // U+f19c -#define ICON_FA_BUILDING_FLAG "\xee\x93\x95" // U+e4d5 -#define ICON_FA_BUILDING_LOCK "\xee\x93\x96" // U+e4d6 -#define ICON_FA_BUILDING_NGO "\xee\x93\x97" // U+e4d7 -#define ICON_FA_BUILDING_SHIELD "\xee\x93\x98" // U+e4d8 -#define ICON_FA_BUILDING_UN "\xee\x93\x99" // U+e4d9 -#define ICON_FA_BUILDING_USER "\xee\x93\x9a" // U+e4da -#define ICON_FA_BUILDING_WHEAT "\xee\x93\x9b" // U+e4db -#define ICON_FA_BULLHORN "\xef\x82\xa1" // U+f0a1 -#define ICON_FA_BULLSEYE "\xef\x85\x80" // U+f140 -#define ICON_FA_BURGER "\xef\xa0\x85" // U+f805 -#define ICON_FA_BURST "\xee\x93\x9c" // U+e4dc -#define ICON_FA_BUS "\xef\x88\x87" // U+f207 -#define ICON_FA_BUS_SIMPLE "\xef\x95\x9e" // U+f55e -#define ICON_FA_BUSINESS_TIME "\xef\x99\x8a" // U+f64a -#define ICON_FA_C "C" // U+0043 -#define ICON_FA_CAKE_CANDLES "\xef\x87\xbd" // U+f1fd -#define ICON_FA_CALCULATOR "\xef\x87\xac" // U+f1ec -#define ICON_FA_CALENDAR "\xef\x84\xb3" // U+f133 -#define ICON_FA_CALENDAR_CHECK "\xef\x89\xb4" // U+f274 -#define ICON_FA_CALENDAR_DAY "\xef\x9e\x83" // U+f783 -#define ICON_FA_CALENDAR_DAYS "\xef\x81\xb3" // U+f073 -#define ICON_FA_CALENDAR_MINUS "\xef\x89\xb2" // U+f272 -#define ICON_FA_CALENDAR_PLUS "\xef\x89\xb1" // U+f271 -#define ICON_FA_CALENDAR_WEEK "\xef\x9e\x84" // U+f784 -#define ICON_FA_CALENDAR_XMARK "\xef\x89\xb3" // U+f273 -#define ICON_FA_CAMERA "\xef\x80\xb0" // U+f030 -#define ICON_FA_CAMERA_RETRO "\xef\x82\x83" // U+f083 -#define ICON_FA_CAMERA_ROTATE "\xee\x83\x98" // U+e0d8 -#define ICON_FA_CAMPGROUND "\xef\x9a\xbb" // U+f6bb -#define ICON_FA_CANDY_CANE "\xef\x9e\x86" // U+f786 -#define ICON_FA_CANNABIS "\xef\x95\x9f" // U+f55f -#define ICON_FA_CAPSULES "\xef\x91\xab" // U+f46b -#define ICON_FA_CAR "\xef\x86\xb9" // U+f1b9 -#define ICON_FA_CAR_BATTERY "\xef\x97\x9f" // U+f5df -#define ICON_FA_CAR_BURST "\xef\x97\xa1" // U+f5e1 -#define ICON_FA_CAR_ON "\xee\x93\x9d" // U+e4dd -#define ICON_FA_CAR_REAR "\xef\x97\x9e" // U+f5de -#define ICON_FA_CAR_SIDE "\xef\x97\xa4" // U+f5e4 -#define ICON_FA_CAR_TUNNEL "\xee\x93\x9e" // U+e4de -#define ICON_FA_CARAVAN "\xef\xa3\xbf" // U+f8ff -#define ICON_FA_CARET_DOWN "\xef\x83\x97" // U+f0d7 -#define ICON_FA_CARET_LEFT "\xef\x83\x99" // U+f0d9 -#define ICON_FA_CARET_RIGHT "\xef\x83\x9a" // U+f0da -#define ICON_FA_CARET_UP "\xef\x83\x98" // U+f0d8 -#define ICON_FA_CARROT "\xef\x9e\x87" // U+f787 -#define ICON_FA_CART_ARROW_DOWN "\xef\x88\x98" // U+f218 -#define ICON_FA_CART_FLATBED "\xef\x91\xb4" // U+f474 -#define ICON_FA_CART_FLATBED_SUITCASE "\xef\x96\x9d" // U+f59d -#define ICON_FA_CART_PLUS "\xef\x88\x97" // U+f217 -#define ICON_FA_CART_SHOPPING "\xef\x81\xba" // U+f07a -#define ICON_FA_CASH_REGISTER "\xef\x9e\x88" // U+f788 -#define ICON_FA_CAT "\xef\x9a\xbe" // U+f6be -#define ICON_FA_CEDI_SIGN "\xee\x83\x9f" // U+e0df -#define ICON_FA_CENT_SIGN "\xee\x8f\xb5" // U+e3f5 -#define ICON_FA_CERTIFICATE "\xef\x82\xa3" // U+f0a3 -#define ICON_FA_CHAIR "\xef\x9b\x80" // U+f6c0 -#define ICON_FA_CHALKBOARD "\xef\x94\x9b" // U+f51b -#define ICON_FA_CHALKBOARD_USER "\xef\x94\x9c" // U+f51c -#define ICON_FA_CHAMPAGNE_GLASSES "\xef\x9e\x9f" // U+f79f -#define ICON_FA_CHARGING_STATION "\xef\x97\xa7" // U+f5e7 -#define ICON_FA_CHART_AREA "\xef\x87\xbe" // U+f1fe -#define ICON_FA_CHART_BAR "\xef\x82\x80" // U+f080 -#define ICON_FA_CHART_COLUMN "\xee\x83\xa3" // U+e0e3 -#define ICON_FA_CHART_GANTT "\xee\x83\xa4" // U+e0e4 -#define ICON_FA_CHART_LINE "\xef\x88\x81" // U+f201 -#define ICON_FA_CHART_PIE "\xef\x88\x80" // U+f200 -#define ICON_FA_CHART_SIMPLE "\xee\x91\xb3" // U+e473 -#define ICON_FA_CHECK "\xef\x80\x8c" // U+f00c -#define ICON_FA_CHECK_DOUBLE "\xef\x95\xa0" // U+f560 -#define ICON_FA_CHECK_TO_SLOT "\xef\x9d\xb2" // U+f772 -#define ICON_FA_CHEESE "\xef\x9f\xaf" // U+f7ef -#define ICON_FA_CHESS "\xef\x90\xb9" // U+f439 -#define ICON_FA_CHESS_BISHOP "\xef\x90\xba" // U+f43a -#define ICON_FA_CHESS_BOARD "\xef\x90\xbc" // U+f43c -#define ICON_FA_CHESS_KING "\xef\x90\xbf" // U+f43f -#define ICON_FA_CHESS_KNIGHT "\xef\x91\x81" // U+f441 -#define ICON_FA_CHESS_PAWN "\xef\x91\x83" // U+f443 -#define ICON_FA_CHESS_QUEEN "\xef\x91\x85" // U+f445 -#define ICON_FA_CHESS_ROOK "\xef\x91\x87" // U+f447 -#define ICON_FA_CHEVRON_DOWN "\xef\x81\xb8" // U+f078 -#define ICON_FA_CHEVRON_LEFT "\xef\x81\x93" // U+f053 -#define ICON_FA_CHEVRON_RIGHT "\xef\x81\x94" // U+f054 -#define ICON_FA_CHEVRON_UP "\xef\x81\xb7" // U+f077 -#define ICON_FA_CHILD "\xef\x86\xae" // U+f1ae -#define ICON_FA_CHILD_DRESS "\xee\x96\x9c" // U+e59c -#define ICON_FA_CHILD_REACHING "\xee\x96\x9d" // U+e59d -#define ICON_FA_CHILD_RIFLE "\xee\x93\xa0" // U+e4e0 -#define ICON_FA_CHILDREN "\xee\x93\xa1" // U+e4e1 -#define ICON_FA_CHURCH "\xef\x94\x9d" // U+f51d -#define ICON_FA_CIRCLE "\xef\x84\x91" // U+f111 -#define ICON_FA_CIRCLE_ARROW_DOWN "\xef\x82\xab" // U+f0ab -#define ICON_FA_CIRCLE_ARROW_LEFT "\xef\x82\xa8" // U+f0a8 -#define ICON_FA_CIRCLE_ARROW_RIGHT "\xef\x82\xa9" // U+f0a9 -#define ICON_FA_CIRCLE_ARROW_UP "\xef\x82\xaa" // U+f0aa -#define ICON_FA_CIRCLE_CHECK "\xef\x81\x98" // U+f058 -#define ICON_FA_CIRCLE_CHEVRON_DOWN "\xef\x84\xba" // U+f13a -#define ICON_FA_CIRCLE_CHEVRON_LEFT "\xef\x84\xb7" // U+f137 -#define ICON_FA_CIRCLE_CHEVRON_RIGHT "\xef\x84\xb8" // U+f138 -#define ICON_FA_CIRCLE_CHEVRON_UP "\xef\x84\xb9" // U+f139 -#define ICON_FA_CIRCLE_DOLLAR_TO_SLOT "\xef\x92\xb9" // U+f4b9 -#define ICON_FA_CIRCLE_DOT "\xef\x86\x92" // U+f192 -#define ICON_FA_CIRCLE_DOWN "\xef\x8d\x98" // U+f358 -#define ICON_FA_CIRCLE_EXCLAMATION "\xef\x81\xaa" // U+f06a -#define ICON_FA_CIRCLE_H "\xef\x91\xbe" // U+f47e -#define ICON_FA_CIRCLE_HALF_STROKE "\xef\x81\x82" // U+f042 -#define ICON_FA_CIRCLE_INFO "\xef\x81\x9a" // U+f05a -#define ICON_FA_CIRCLE_LEFT "\xef\x8d\x99" // U+f359 -#define ICON_FA_CIRCLE_MINUS "\xef\x81\x96" // U+f056 -#define ICON_FA_CIRCLE_NODES "\xee\x93\xa2" // U+e4e2 -#define ICON_FA_CIRCLE_NOTCH "\xef\x87\x8e" // U+f1ce -#define ICON_FA_CIRCLE_PAUSE "\xef\x8a\x8b" // U+f28b -#define ICON_FA_CIRCLE_PLAY "\xef\x85\x84" // U+f144 -#define ICON_FA_CIRCLE_PLUS "\xef\x81\x95" // U+f055 -#define ICON_FA_CIRCLE_QUESTION "\xef\x81\x99" // U+f059 -#define ICON_FA_CIRCLE_RADIATION "\xef\x9e\xba" // U+f7ba -#define ICON_FA_CIRCLE_RIGHT "\xef\x8d\x9a" // U+f35a -#define ICON_FA_CIRCLE_STOP "\xef\x8a\x8d" // U+f28d -#define ICON_FA_CIRCLE_UP "\xef\x8d\x9b" // U+f35b -#define ICON_FA_CIRCLE_USER "\xef\x8a\xbd" // U+f2bd -#define ICON_FA_CIRCLE_XMARK "\xef\x81\x97" // U+f057 -#define ICON_FA_CITY "\xef\x99\x8f" // U+f64f -#define ICON_FA_CLAPPERBOARD "\xee\x84\xb1" // U+e131 -#define ICON_FA_CLIPBOARD "\xef\x8c\xa8" // U+f328 -#define ICON_FA_CLIPBOARD_CHECK "\xef\x91\xac" // U+f46c -#define ICON_FA_CLIPBOARD_LIST "\xef\x91\xad" // U+f46d -#define ICON_FA_CLIPBOARD_QUESTION "\xee\x93\xa3" // U+e4e3 -#define ICON_FA_CLIPBOARD_USER "\xef\x9f\xb3" // U+f7f3 -#define ICON_FA_CLOCK "\xef\x80\x97" // U+f017 -#define ICON_FA_CLOCK_ROTATE_LEFT "\xef\x87\x9a" // U+f1da -#define ICON_FA_CLONE "\xef\x89\x8d" // U+f24d -#define ICON_FA_CLOSED_CAPTIONING "\xef\x88\x8a" // U+f20a -#define ICON_FA_CLOUD "\xef\x83\x82" // U+f0c2 -#define ICON_FA_CLOUD_ARROW_DOWN "\xef\x83\xad" // U+f0ed -#define ICON_FA_CLOUD_ARROW_UP "\xef\x83\xae" // U+f0ee -#define ICON_FA_CLOUD_BOLT "\xef\x9d\xac" // U+f76c -#define ICON_FA_CLOUD_MEATBALL "\xef\x9c\xbb" // U+f73b -#define ICON_FA_CLOUD_MOON "\xef\x9b\x83" // U+f6c3 -#define ICON_FA_CLOUD_MOON_RAIN "\xef\x9c\xbc" // U+f73c -#define ICON_FA_CLOUD_RAIN "\xef\x9c\xbd" // U+f73d -#define ICON_FA_CLOUD_SHOWERS_HEAVY "\xef\x9d\x80" // U+f740 -#define ICON_FA_CLOUD_SHOWERS_WATER "\xee\x93\xa4" // U+e4e4 -#define ICON_FA_CLOUD_SUN "\xef\x9b\x84" // U+f6c4 -#define ICON_FA_CLOUD_SUN_RAIN "\xef\x9d\x83" // U+f743 -#define ICON_FA_CLOVER "\xee\x84\xb9" // U+e139 -#define ICON_FA_CODE "\xef\x84\xa1" // U+f121 -#define ICON_FA_CODE_BRANCH "\xef\x84\xa6" // U+f126 -#define ICON_FA_CODE_COMMIT "\xef\x8e\x86" // U+f386 -#define ICON_FA_CODE_COMPARE "\xee\x84\xba" // U+e13a -#define ICON_FA_CODE_FORK "\xee\x84\xbb" // U+e13b -#define ICON_FA_CODE_MERGE "\xef\x8e\x87" // U+f387 -#define ICON_FA_CODE_PULL_REQUEST "\xee\x84\xbc" // U+e13c -#define ICON_FA_COINS "\xef\x94\x9e" // U+f51e -#define ICON_FA_COLON_SIGN "\xee\x85\x80" // U+e140 -#define ICON_FA_COMMENT "\xef\x81\xb5" // U+f075 -#define ICON_FA_COMMENT_DOLLAR "\xef\x99\x91" // U+f651 -#define ICON_FA_COMMENT_DOTS "\xef\x92\xad" // U+f4ad -#define ICON_FA_COMMENT_MEDICAL "\xef\x9f\xb5" // U+f7f5 -#define ICON_FA_COMMENT_SLASH "\xef\x92\xb3" // U+f4b3 -#define ICON_FA_COMMENT_SMS "\xef\x9f\x8d" // U+f7cd -#define ICON_FA_COMMENTS "\xef\x82\x86" // U+f086 -#define ICON_FA_COMMENTS_DOLLAR "\xef\x99\x93" // U+f653 -#define ICON_FA_COMPACT_DISC "\xef\x94\x9f" // U+f51f -#define ICON_FA_COMPASS "\xef\x85\x8e" // U+f14e -#define ICON_FA_COMPASS_DRAFTING "\xef\x95\xa8" // U+f568 -#define ICON_FA_COMPRESS "\xef\x81\xa6" // U+f066 -#define ICON_FA_COMPUTER "\xee\x93\xa5" // U+e4e5 -#define ICON_FA_COMPUTER_MOUSE "\xef\xa3\x8c" // U+f8cc -#define ICON_FA_COOKIE "\xef\x95\xa3" // U+f563 -#define ICON_FA_COOKIE_BITE "\xef\x95\xa4" // U+f564 -#define ICON_FA_COPY "\xef\x83\x85" // U+f0c5 -#define ICON_FA_COPYRIGHT "\xef\x87\xb9" // U+f1f9 -#define ICON_FA_COUCH "\xef\x92\xb8" // U+f4b8 -#define ICON_FA_COW "\xef\x9b\x88" // U+f6c8 -#define ICON_FA_CREDIT_CARD "\xef\x82\x9d" // U+f09d -#define ICON_FA_CROP "\xef\x84\xa5" // U+f125 -#define ICON_FA_CROP_SIMPLE "\xef\x95\xa5" // U+f565 -#define ICON_FA_CROSS "\xef\x99\x94" // U+f654 -#define ICON_FA_CROSSHAIRS "\xef\x81\x9b" // U+f05b -#define ICON_FA_CROW "\xef\x94\xa0" // U+f520 -#define ICON_FA_CROWN "\xef\x94\xa1" // U+f521 -#define ICON_FA_CRUTCH "\xef\x9f\xb7" // U+f7f7 -#define ICON_FA_CRUZEIRO_SIGN "\xee\x85\x92" // U+e152 -#define ICON_FA_CUBE "\xef\x86\xb2" // U+f1b2 -#define ICON_FA_CUBES "\xef\x86\xb3" // U+f1b3 -#define ICON_FA_CUBES_STACKED "\xee\x93\xa6" // U+e4e6 -#define ICON_FA_D "D" // U+0044 -#define ICON_FA_DATABASE "\xef\x87\x80" // U+f1c0 -#define ICON_FA_DELETE_LEFT "\xef\x95\x9a" // U+f55a -#define ICON_FA_DEMOCRAT "\xef\x9d\x87" // U+f747 -#define ICON_FA_DESKTOP "\xef\x8e\x90" // U+f390 -#define ICON_FA_DHARMACHAKRA "\xef\x99\x95" // U+f655 -#define ICON_FA_DIAGRAM_NEXT "\xee\x91\xb6" // U+e476 -#define ICON_FA_DIAGRAM_PREDECESSOR "\xee\x91\xb7" // U+e477 -#define ICON_FA_DIAGRAM_PROJECT "\xef\x95\x82" // U+f542 -#define ICON_FA_DIAGRAM_SUCCESSOR "\xee\x91\xba" // U+e47a -#define ICON_FA_DIAMOND "\xef\x88\x99" // U+f219 -#define ICON_FA_DIAMOND_TURN_RIGHT "\xef\x97\xab" // U+f5eb -#define ICON_FA_DICE "\xef\x94\xa2" // U+f522 -#define ICON_FA_DICE_D20 "\xef\x9b\x8f" // U+f6cf -#define ICON_FA_DICE_D6 "\xef\x9b\x91" // U+f6d1 -#define ICON_FA_DICE_FIVE "\xef\x94\xa3" // U+f523 -#define ICON_FA_DICE_FOUR "\xef\x94\xa4" // U+f524 -#define ICON_FA_DICE_ONE "\xef\x94\xa5" // U+f525 -#define ICON_FA_DICE_SIX "\xef\x94\xa6" // U+f526 -#define ICON_FA_DICE_THREE "\xef\x94\xa7" // U+f527 -#define ICON_FA_DICE_TWO "\xef\x94\xa8" // U+f528 -#define ICON_FA_DISEASE "\xef\x9f\xba" // U+f7fa -#define ICON_FA_DISPLAY "\xee\x85\xa3" // U+e163 -#define ICON_FA_DIVIDE "\xef\x94\xa9" // U+f529 -#define ICON_FA_DNA "\xef\x91\xb1" // U+f471 -#define ICON_FA_DOG "\xef\x9b\x93" // U+f6d3 -#define ICON_FA_DOLLAR_SIGN "$" // U+0024 -#define ICON_FA_DOLLY "\xef\x91\xb2" // U+f472 -#define ICON_FA_DONG_SIGN "\xee\x85\xa9" // U+e169 -#define ICON_FA_DOOR_CLOSED "\xef\x94\xaa" // U+f52a -#define ICON_FA_DOOR_OPEN "\xef\x94\xab" // U+f52b -#define ICON_FA_DOVE "\xef\x92\xba" // U+f4ba -#define ICON_FA_DOWN_LEFT_AND_UP_RIGHT_TO_CENTER "\xef\x90\xa2" // U+f422 -#define ICON_FA_DOWN_LONG "\xef\x8c\x89" // U+f309 -#define ICON_FA_DOWNLOAD "\xef\x80\x99" // U+f019 -#define ICON_FA_DRAGON "\xef\x9b\x95" // U+f6d5 -#define ICON_FA_DRAW_POLYGON "\xef\x97\xae" // U+f5ee -#define ICON_FA_DROPLET "\xef\x81\x83" // U+f043 -#define ICON_FA_DROPLET_SLASH "\xef\x97\x87" // U+f5c7 -#define ICON_FA_DRUM "\xef\x95\xa9" // U+f569 -#define ICON_FA_DRUM_STEELPAN "\xef\x95\xaa" // U+f56a -#define ICON_FA_DRUMSTICK_BITE "\xef\x9b\x97" // U+f6d7 -#define ICON_FA_DUMBBELL "\xef\x91\x8b" // U+f44b -#define ICON_FA_DUMPSTER "\xef\x9e\x93" // U+f793 -#define ICON_FA_DUMPSTER_FIRE "\xef\x9e\x94" // U+f794 -#define ICON_FA_DUNGEON "\xef\x9b\x99" // U+f6d9 -#define ICON_FA_E "E" // U+0045 -#define ICON_FA_EAR_DEAF "\xef\x8a\xa4" // U+f2a4 -#define ICON_FA_EAR_LISTEN "\xef\x8a\xa2" // U+f2a2 -#define ICON_FA_EARTH_AFRICA "\xef\x95\xbc" // U+f57c -#define ICON_FA_EARTH_AMERICAS "\xef\x95\xbd" // U+f57d -#define ICON_FA_EARTH_ASIA "\xef\x95\xbe" // U+f57e -#define ICON_FA_EARTH_EUROPE "\xef\x9e\xa2" // U+f7a2 -#define ICON_FA_EARTH_OCEANIA "\xee\x91\xbb" // U+e47b -#define ICON_FA_EGG "\xef\x9f\xbb" // U+f7fb -#define ICON_FA_EJECT "\xef\x81\x92" // U+f052 -#define ICON_FA_ELEVATOR "\xee\x85\xad" // U+e16d -#define ICON_FA_ELLIPSIS "\xef\x85\x81" // U+f141 -#define ICON_FA_ELLIPSIS_VERTICAL "\xef\x85\x82" // U+f142 -#define ICON_FA_ENVELOPE "\xef\x83\xa0" // U+f0e0 -#define ICON_FA_ENVELOPE_CIRCLE_CHECK "\xee\x93\xa8" // U+e4e8 -#define ICON_FA_ENVELOPE_OPEN "\xef\x8a\xb6" // U+f2b6 -#define ICON_FA_ENVELOPE_OPEN_TEXT "\xef\x99\x98" // U+f658 -#define ICON_FA_ENVELOPES_BULK "\xef\x99\xb4" // U+f674 -#define ICON_FA_EQUALS "=" // U+003d -#define ICON_FA_ERASER "\xef\x84\xad" // U+f12d -#define ICON_FA_ETHERNET "\xef\x9e\x96" // U+f796 -#define ICON_FA_EURO_SIGN "\xef\x85\x93" // U+f153 -#define ICON_FA_EXCLAMATION "!" // U+0021 -#define ICON_FA_EXPAND "\xef\x81\xa5" // U+f065 -#define ICON_FA_EXPLOSION "\xee\x93\xa9" // U+e4e9 -#define ICON_FA_EYE "\xef\x81\xae" // U+f06e -#define ICON_FA_EYE_DROPPER "\xef\x87\xbb" // U+f1fb -#define ICON_FA_EYE_LOW_VISION "\xef\x8a\xa8" // U+f2a8 -#define ICON_FA_EYE_SLASH "\xef\x81\xb0" // U+f070 -#define ICON_FA_F "F" // U+0046 -#define ICON_FA_FACE_ANGRY "\xef\x95\x96" // U+f556 -#define ICON_FA_FACE_DIZZY "\xef\x95\xa7" // U+f567 -#define ICON_FA_FACE_FLUSHED "\xef\x95\xb9" // U+f579 -#define ICON_FA_FACE_FROWN "\xef\x84\x99" // U+f119 -#define ICON_FA_FACE_FROWN_OPEN "\xef\x95\xba" // U+f57a -#define ICON_FA_FACE_GRIMACE "\xef\x95\xbf" // U+f57f -#define ICON_FA_FACE_GRIN "\xef\x96\x80" // U+f580 -#define ICON_FA_FACE_GRIN_BEAM "\xef\x96\x82" // U+f582 -#define ICON_FA_FACE_GRIN_BEAM_SWEAT "\xef\x96\x83" // U+f583 -#define ICON_FA_FACE_GRIN_HEARTS "\xef\x96\x84" // U+f584 -#define ICON_FA_FACE_GRIN_SQUINT "\xef\x96\x85" // U+f585 -#define ICON_FA_FACE_GRIN_SQUINT_TEARS "\xef\x96\x86" // U+f586 -#define ICON_FA_FACE_GRIN_STARS "\xef\x96\x87" // U+f587 -#define ICON_FA_FACE_GRIN_TEARS "\xef\x96\x88" // U+f588 -#define ICON_FA_FACE_GRIN_TONGUE "\xef\x96\x89" // U+f589 -#define ICON_FA_FACE_GRIN_TONGUE_SQUINT "\xef\x96\x8a" // U+f58a -#define ICON_FA_FACE_GRIN_TONGUE_WINK "\xef\x96\x8b" // U+f58b -#define ICON_FA_FACE_GRIN_WIDE "\xef\x96\x81" // U+f581 -#define ICON_FA_FACE_GRIN_WINK "\xef\x96\x8c" // U+f58c -#define ICON_FA_FACE_KISS "\xef\x96\x96" // U+f596 -#define ICON_FA_FACE_KISS_BEAM "\xef\x96\x97" // U+f597 -#define ICON_FA_FACE_KISS_WINK_HEART "\xef\x96\x98" // U+f598 -#define ICON_FA_FACE_LAUGH "\xef\x96\x99" // U+f599 -#define ICON_FA_FACE_LAUGH_BEAM "\xef\x96\x9a" // U+f59a -#define ICON_FA_FACE_LAUGH_SQUINT "\xef\x96\x9b" // U+f59b -#define ICON_FA_FACE_LAUGH_WINK "\xef\x96\x9c" // U+f59c -#define ICON_FA_FACE_MEH "\xef\x84\x9a" // U+f11a -#define ICON_FA_FACE_MEH_BLANK "\xef\x96\xa4" // U+f5a4 -#define ICON_FA_FACE_ROLLING_EYES "\xef\x96\xa5" // U+f5a5 -#define ICON_FA_FACE_SAD_CRY "\xef\x96\xb3" // U+f5b3 -#define ICON_FA_FACE_SAD_TEAR "\xef\x96\xb4" // U+f5b4 -#define ICON_FA_FACE_SMILE "\xef\x84\x98" // U+f118 -#define ICON_FA_FACE_SMILE_BEAM "\xef\x96\xb8" // U+f5b8 -#define ICON_FA_FACE_SMILE_WINK "\xef\x93\x9a" // U+f4da -#define ICON_FA_FACE_SURPRISE "\xef\x97\x82" // U+f5c2 -#define ICON_FA_FACE_TIRED "\xef\x97\x88" // U+f5c8 -#define ICON_FA_FAN "\xef\xa1\xa3" // U+f863 -#define ICON_FA_FAUCET "\xee\x80\x85" // U+e005 -#define ICON_FA_FAUCET_DRIP "\xee\x80\x86" // U+e006 -#define ICON_FA_FAX "\xef\x86\xac" // U+f1ac -#define ICON_FA_FEATHER "\xef\x94\xad" // U+f52d -#define ICON_FA_FEATHER_POINTED "\xef\x95\xab" // U+f56b -#define ICON_FA_FERRY "\xee\x93\xaa" // U+e4ea -#define ICON_FA_FILE "\xef\x85\x9b" // U+f15b -#define ICON_FA_FILE_ARROW_DOWN "\xef\x95\xad" // U+f56d -#define ICON_FA_FILE_ARROW_UP "\xef\x95\xb4" // U+f574 -#define ICON_FA_FILE_AUDIO "\xef\x87\x87" // U+f1c7 -#define ICON_FA_FILE_CIRCLE_CHECK "\xee\x92\x93" // U+e493 -#define ICON_FA_FILE_CIRCLE_EXCLAMATION "\xee\x93\xab" // U+e4eb -#define ICON_FA_FILE_CIRCLE_MINUS "\xee\x93\xad" // U+e4ed -#define ICON_FA_FILE_CIRCLE_PLUS "\xee\x93\xae" // U+e4ee -#define ICON_FA_FILE_CIRCLE_QUESTION "\xee\x93\xaf" // U+e4ef -#define ICON_FA_FILE_CIRCLE_XMARK "\xee\x92\x94" // U+e494 -#define ICON_FA_FILE_CODE "\xef\x87\x89" // U+f1c9 -#define ICON_FA_FILE_CONTRACT "\xef\x95\xac" // U+f56c -#define ICON_FA_FILE_CSV "\xef\x9b\x9d" // U+f6dd -#define ICON_FA_FILE_EXCEL "\xef\x87\x83" // U+f1c3 -#define ICON_FA_FILE_EXPORT "\xef\x95\xae" // U+f56e -#define ICON_FA_FILE_IMAGE "\xef\x87\x85" // U+f1c5 -#define ICON_FA_FILE_IMPORT "\xef\x95\xaf" // U+f56f -#define ICON_FA_FILE_INVOICE "\xef\x95\xb0" // U+f570 -#define ICON_FA_FILE_INVOICE_DOLLAR "\xef\x95\xb1" // U+f571 -#define ICON_FA_FILE_LINES "\xef\x85\x9c" // U+f15c -#define ICON_FA_FILE_MEDICAL "\xef\x91\xb7" // U+f477 -#define ICON_FA_FILE_PDF "\xef\x87\x81" // U+f1c1 -#define ICON_FA_FILE_PEN "\xef\x8c\x9c" // U+f31c -#define ICON_FA_FILE_POWERPOINT "\xef\x87\x84" // U+f1c4 -#define ICON_FA_FILE_PRESCRIPTION "\xef\x95\xb2" // U+f572 -#define ICON_FA_FILE_SHIELD "\xee\x93\xb0" // U+e4f0 -#define ICON_FA_FILE_SIGNATURE "\xef\x95\xb3" // U+f573 -#define ICON_FA_FILE_VIDEO "\xef\x87\x88" // U+f1c8 -#define ICON_FA_FILE_WAVEFORM "\xef\x91\xb8" // U+f478 -#define ICON_FA_FILE_WORD "\xef\x87\x82" // U+f1c2 -#define ICON_FA_FILE_ZIPPER "\xef\x87\x86" // U+f1c6 -#define ICON_FA_FILL "\xef\x95\xb5" // U+f575 -#define ICON_FA_FILL_DRIP "\xef\x95\xb6" // U+f576 -#define ICON_FA_FILM "\xef\x80\x88" // U+f008 -#define ICON_FA_FILTER "\xef\x82\xb0" // U+f0b0 -#define ICON_FA_FILTER_CIRCLE_DOLLAR "\xef\x99\xa2" // U+f662 -#define ICON_FA_FILTER_CIRCLE_XMARK "\xee\x85\xbb" // U+e17b -#define ICON_FA_FINGERPRINT "\xef\x95\xb7" // U+f577 -#define ICON_FA_FIRE "\xef\x81\xad" // U+f06d -#define ICON_FA_FIRE_BURNER "\xee\x93\xb1" // U+e4f1 -#define ICON_FA_FIRE_EXTINGUISHER "\xef\x84\xb4" // U+f134 -#define ICON_FA_FIRE_FLAME_CURVED "\xef\x9f\xa4" // U+f7e4 -#define ICON_FA_FIRE_FLAME_SIMPLE "\xef\x91\xaa" // U+f46a -#define ICON_FA_FISH "\xef\x95\xb8" // U+f578 -#define ICON_FA_FISH_FINS "\xee\x93\xb2" // U+e4f2 -#define ICON_FA_FLAG "\xef\x80\xa4" // U+f024 -#define ICON_FA_FLAG_CHECKERED "\xef\x84\x9e" // U+f11e -#define ICON_FA_FLAG_USA "\xef\x9d\x8d" // U+f74d -#define ICON_FA_FLASK "\xef\x83\x83" // U+f0c3 -#define ICON_FA_FLASK_VIAL "\xee\x93\xb3" // U+e4f3 -#define ICON_FA_FLOPPY_DISK "\xef\x83\x87" // U+f0c7 -#define ICON_FA_FLORIN_SIGN "\xee\x86\x84" // U+e184 -#define ICON_FA_FOLDER "\xef\x81\xbb" // U+f07b -#define ICON_FA_FOLDER_CLOSED "\xee\x86\x85" // U+e185 -#define ICON_FA_FOLDER_MINUS "\xef\x99\x9d" // U+f65d -#define ICON_FA_FOLDER_OPEN "\xef\x81\xbc" // U+f07c -#define ICON_FA_FOLDER_PLUS "\xef\x99\x9e" // U+f65e -#define ICON_FA_FOLDER_TREE "\xef\xa0\x82" // U+f802 -#define ICON_FA_FONT "\xef\x80\xb1" // U+f031 -#define ICON_FA_FONT_AWESOME "\xef\x8a\xb4" // U+f2b4 -#define ICON_FA_FOOTBALL "\xef\x91\x8e" // U+f44e -#define ICON_FA_FORWARD "\xef\x81\x8e" // U+f04e -#define ICON_FA_FORWARD_FAST "\xef\x81\x90" // U+f050 -#define ICON_FA_FORWARD_STEP "\xef\x81\x91" // U+f051 -#define ICON_FA_FRANC_SIGN "\xee\x86\x8f" // U+e18f -#define ICON_FA_FROG "\xef\x94\xae" // U+f52e -#define ICON_FA_FUTBOL "\xef\x87\xa3" // U+f1e3 -#define ICON_FA_G "G" // U+0047 -#define ICON_FA_GAMEPAD "\xef\x84\x9b" // U+f11b -#define ICON_FA_GAS_PUMP "\xef\x94\xaf" // U+f52f -#define ICON_FA_GAUGE "\xef\x98\xa4" // U+f624 -#define ICON_FA_GAUGE_HIGH "\xef\x98\xa5" // U+f625 -#define ICON_FA_GAUGE_SIMPLE "\xef\x98\xa9" // U+f629 -#define ICON_FA_GAUGE_SIMPLE_HIGH "\xef\x98\xaa" // U+f62a -#define ICON_FA_GAVEL "\xef\x83\xa3" // U+f0e3 -#define ICON_FA_GEAR "\xef\x80\x93" // U+f013 -#define ICON_FA_GEARS "\xef\x82\x85" // U+f085 -#define ICON_FA_GEM "\xef\x8e\xa5" // U+f3a5 -#define ICON_FA_GENDERLESS "\xef\x88\xad" // U+f22d -#define ICON_FA_GHOST "\xef\x9b\xa2" // U+f6e2 -#define ICON_FA_GIFT "\xef\x81\xab" // U+f06b -#define ICON_FA_GIFTS "\xef\x9e\x9c" // U+f79c -#define ICON_FA_GLASS_WATER "\xee\x93\xb4" // U+e4f4 -#define ICON_FA_GLASS_WATER_DROPLET "\xee\x93\xb5" // U+e4f5 -#define ICON_FA_GLASSES "\xef\x94\xb0" // U+f530 -#define ICON_FA_GLOBE "\xef\x82\xac" // U+f0ac -#define ICON_FA_GOLF_BALL_TEE "\xef\x91\x90" // U+f450 -#define ICON_FA_GOPURAM "\xef\x99\xa4" // U+f664 -#define ICON_FA_GRADUATION_CAP "\xef\x86\x9d" // U+f19d -#define ICON_FA_GREATER_THAN ">" // U+003e -#define ICON_FA_GREATER_THAN_EQUAL "\xef\x94\xb2" // U+f532 -#define ICON_FA_GRIP "\xef\x96\x8d" // U+f58d -#define ICON_FA_GRIP_LINES "\xef\x9e\xa4" // U+f7a4 -#define ICON_FA_GRIP_LINES_VERTICAL "\xef\x9e\xa5" // U+f7a5 -#define ICON_FA_GRIP_VERTICAL "\xef\x96\x8e" // U+f58e -#define ICON_FA_GROUP_ARROWS_ROTATE "\xee\x93\xb6" // U+e4f6 -#define ICON_FA_GUARANI_SIGN "\xee\x86\x9a" // U+e19a -#define ICON_FA_GUITAR "\xef\x9e\xa6" // U+f7a6 -#define ICON_FA_GUN "\xee\x86\x9b" // U+e19b -#define ICON_FA_H "H" // U+0048 -#define ICON_FA_HAMMER "\xef\x9b\xa3" // U+f6e3 -#define ICON_FA_HAMSA "\xef\x99\xa5" // U+f665 -#define ICON_FA_HAND "\xef\x89\x96" // U+f256 -#define ICON_FA_HAND_BACK_FIST "\xef\x89\x95" // U+f255 -#define ICON_FA_HAND_DOTS "\xef\x91\xa1" // U+f461 -#define ICON_FA_HAND_FIST "\xef\x9b\x9e" // U+f6de -#define ICON_FA_HAND_HOLDING "\xef\x92\xbd" // U+f4bd -#define ICON_FA_HAND_HOLDING_DOLLAR "\xef\x93\x80" // U+f4c0 -#define ICON_FA_HAND_HOLDING_DROPLET "\xef\x93\x81" // U+f4c1 -#define ICON_FA_HAND_HOLDING_HAND "\xee\x93\xb7" // U+e4f7 -#define ICON_FA_HAND_HOLDING_HEART "\xef\x92\xbe" // U+f4be -#define ICON_FA_HAND_HOLDING_MEDICAL "\xee\x81\x9c" // U+e05c -#define ICON_FA_HAND_LIZARD "\xef\x89\x98" // U+f258 -#define ICON_FA_HAND_MIDDLE_FINGER "\xef\xa0\x86" // U+f806 -#define ICON_FA_HAND_PEACE "\xef\x89\x9b" // U+f25b -#define ICON_FA_HAND_POINT_DOWN "\xef\x82\xa7" // U+f0a7 -#define ICON_FA_HAND_POINT_LEFT "\xef\x82\xa5" // U+f0a5 -#define ICON_FA_HAND_POINT_RIGHT "\xef\x82\xa4" // U+f0a4 -#define ICON_FA_HAND_POINT_UP "\xef\x82\xa6" // U+f0a6 -#define ICON_FA_HAND_POINTER "\xef\x89\x9a" // U+f25a -#define ICON_FA_HAND_SCISSORS "\xef\x89\x97" // U+f257 -#define ICON_FA_HAND_SPARKLES "\xee\x81\x9d" // U+e05d -#define ICON_FA_HAND_SPOCK "\xef\x89\x99" // U+f259 -#define ICON_FA_HANDCUFFS "\xee\x93\xb8" // U+e4f8 -#define ICON_FA_HANDS "\xef\x8a\xa7" // U+f2a7 -#define ICON_FA_HANDS_ASL_INTERPRETING "\xef\x8a\xa3" // U+f2a3 -#define ICON_FA_HANDS_BOUND "\xee\x93\xb9" // U+e4f9 -#define ICON_FA_HANDS_BUBBLES "\xee\x81\x9e" // U+e05e -#define ICON_FA_HANDS_CLAPPING "\xee\x86\xa8" // U+e1a8 -#define ICON_FA_HANDS_HOLDING "\xef\x93\x82" // U+f4c2 -#define ICON_FA_HANDS_HOLDING_CHILD "\xee\x93\xba" // U+e4fa -#define ICON_FA_HANDS_HOLDING_CIRCLE "\xee\x93\xbb" // U+e4fb -#define ICON_FA_HANDS_PRAYING "\xef\x9a\x84" // U+f684 -#define ICON_FA_HANDSHAKE "\xef\x8a\xb5" // U+f2b5 -#define ICON_FA_HANDSHAKE_ANGLE "\xef\x93\x84" // U+f4c4 -#define ICON_FA_HANDSHAKE_SIMPLE "\xef\x93\x86" // U+f4c6 -#define ICON_FA_HANDSHAKE_SIMPLE_SLASH "\xee\x81\x9f" // U+e05f -#define ICON_FA_HANDSHAKE_SLASH "\xee\x81\xa0" // U+e060 -#define ICON_FA_HANUKIAH "\xef\x9b\xa6" // U+f6e6 -#define ICON_FA_HARD_DRIVE "\xef\x82\xa0" // U+f0a0 -#define ICON_FA_HASHTAG "#" // U+0023 -#define ICON_FA_HAT_COWBOY "\xef\xa3\x80" // U+f8c0 -#define ICON_FA_HAT_COWBOY_SIDE "\xef\xa3\x81" // U+f8c1 -#define ICON_FA_HAT_WIZARD "\xef\x9b\xa8" // U+f6e8 -#define ICON_FA_HEAD_SIDE_COUGH "\xee\x81\xa1" // U+e061 -#define ICON_FA_HEAD_SIDE_COUGH_SLASH "\xee\x81\xa2" // U+e062 -#define ICON_FA_HEAD_SIDE_MASK "\xee\x81\xa3" // U+e063 -#define ICON_FA_HEAD_SIDE_VIRUS "\xee\x81\xa4" // U+e064 -#define ICON_FA_HEADING "\xef\x87\x9c" // U+f1dc -#define ICON_FA_HEADPHONES "\xef\x80\xa5" // U+f025 -#define ICON_FA_HEADPHONES_SIMPLE "\xef\x96\x8f" // U+f58f -#define ICON_FA_HEADSET "\xef\x96\x90" // U+f590 -#define ICON_FA_HEART "\xef\x80\x84" // U+f004 -#define ICON_FA_HEART_CIRCLE_BOLT "\xee\x93\xbc" // U+e4fc -#define ICON_FA_HEART_CIRCLE_CHECK "\xee\x93\xbd" // U+e4fd -#define ICON_FA_HEART_CIRCLE_EXCLAMATION "\xee\x93\xbe" // U+e4fe -#define ICON_FA_HEART_CIRCLE_MINUS "\xee\x93\xbf" // U+e4ff -#define ICON_FA_HEART_CIRCLE_PLUS "\xee\x94\x80" // U+e500 -#define ICON_FA_HEART_CIRCLE_XMARK "\xee\x94\x81" // U+e501 -#define ICON_FA_HEART_CRACK "\xef\x9e\xa9" // U+f7a9 -#define ICON_FA_HEART_PULSE "\xef\x88\x9e" // U+f21e -#define ICON_FA_HELICOPTER "\xef\x94\xb3" // U+f533 -#define ICON_FA_HELICOPTER_SYMBOL "\xee\x94\x82" // U+e502 -#define ICON_FA_HELMET_SAFETY "\xef\xa0\x87" // U+f807 -#define ICON_FA_HELMET_UN "\xee\x94\x83" // U+e503 -#define ICON_FA_HIGHLIGHTER "\xef\x96\x91" // U+f591 -#define ICON_FA_HILL_AVALANCHE "\xee\x94\x87" // U+e507 -#define ICON_FA_HILL_ROCKSLIDE "\xee\x94\x88" // U+e508 -#define ICON_FA_HIPPO "\xef\x9b\xad" // U+f6ed -#define ICON_FA_HOCKEY_PUCK "\xef\x91\x93" // U+f453 -#define ICON_FA_HOLLY_BERRY "\xef\x9e\xaa" // U+f7aa -#define ICON_FA_HORSE "\xef\x9b\xb0" // U+f6f0 -#define ICON_FA_HORSE_HEAD "\xef\x9e\xab" // U+f7ab -#define ICON_FA_HOSPITAL "\xef\x83\xb8" // U+f0f8 -#define ICON_FA_HOSPITAL_USER "\xef\xa0\x8d" // U+f80d -#define ICON_FA_HOT_TUB_PERSON "\xef\x96\x93" // U+f593 -#define ICON_FA_HOTDOG "\xef\xa0\x8f" // U+f80f -#define ICON_FA_HOTEL "\xef\x96\x94" // U+f594 -#define ICON_FA_HOURGLASS "\xef\x89\x94" // U+f254 -#define ICON_FA_HOURGLASS_EMPTY "\xef\x89\x92" // U+f252 -#define ICON_FA_HOURGLASS_END "\xef\x89\x93" // U+f253 -#define ICON_FA_HOURGLASS_START "\xef\x89\x91" // U+f251 -#define ICON_FA_HOUSE "\xef\x80\x95" // U+f015 -#define ICON_FA_HOUSE_CHIMNEY "\xee\x8e\xaf" // U+e3af -#define ICON_FA_HOUSE_CHIMNEY_CRACK "\xef\x9b\xb1" // U+f6f1 -#define ICON_FA_HOUSE_CHIMNEY_MEDICAL "\xef\x9f\xb2" // U+f7f2 -#define ICON_FA_HOUSE_CHIMNEY_USER "\xee\x81\xa5" // U+e065 -#define ICON_FA_HOUSE_CHIMNEY_WINDOW "\xee\x80\x8d" // U+e00d -#define ICON_FA_HOUSE_CIRCLE_CHECK "\xee\x94\x89" // U+e509 -#define ICON_FA_HOUSE_CIRCLE_EXCLAMATION "\xee\x94\x8a" // U+e50a -#define ICON_FA_HOUSE_CIRCLE_XMARK "\xee\x94\x8b" // U+e50b -#define ICON_FA_HOUSE_CRACK "\xee\x8e\xb1" // U+e3b1 -#define ICON_FA_HOUSE_FIRE "\xee\x94\x8c" // U+e50c -#define ICON_FA_HOUSE_FLAG "\xee\x94\x8d" // U+e50d -#define ICON_FA_HOUSE_FLOOD_WATER "\xee\x94\x8e" // U+e50e -#define ICON_FA_HOUSE_FLOOD_WATER_CIRCLE_ARROW_RIGHT "\xee\x94\x8f" // U+e50f -#define ICON_FA_HOUSE_LAPTOP "\xee\x81\xa6" // U+e066 -#define ICON_FA_HOUSE_LOCK "\xee\x94\x90" // U+e510 -#define ICON_FA_HOUSE_MEDICAL "\xee\x8e\xb2" // U+e3b2 -#define ICON_FA_HOUSE_MEDICAL_CIRCLE_CHECK "\xee\x94\x91" // U+e511 -#define ICON_FA_HOUSE_MEDICAL_CIRCLE_EXCLAMATION "\xee\x94\x92" // U+e512 -#define ICON_FA_HOUSE_MEDICAL_CIRCLE_XMARK "\xee\x94\x93" // U+e513 -#define ICON_FA_HOUSE_MEDICAL_FLAG "\xee\x94\x94" // U+e514 -#define ICON_FA_HOUSE_SIGNAL "\xee\x80\x92" // U+e012 -#define ICON_FA_HOUSE_TSUNAMI "\xee\x94\x95" // U+e515 -#define ICON_FA_HOUSE_USER "\xee\x86\xb0" // U+e1b0 -#define ICON_FA_HRYVNIA_SIGN "\xef\x9b\xb2" // U+f6f2 -#define ICON_FA_HURRICANE "\xef\x9d\x91" // U+f751 -#define ICON_FA_I "I" // U+0049 -#define ICON_FA_I_CURSOR "\xef\x89\x86" // U+f246 -#define ICON_FA_ICE_CREAM "\xef\xa0\x90" // U+f810 -#define ICON_FA_ICICLES "\xef\x9e\xad" // U+f7ad -#define ICON_FA_ICONS "\xef\xa1\xad" // U+f86d -#define ICON_FA_ID_BADGE "\xef\x8b\x81" // U+f2c1 -#define ICON_FA_ID_CARD "\xef\x8b\x82" // U+f2c2 -#define ICON_FA_ID_CARD_CLIP "\xef\x91\xbf" // U+f47f -#define ICON_FA_IGLOO "\xef\x9e\xae" // U+f7ae -#define ICON_FA_IMAGE "\xef\x80\xbe" // U+f03e -#define ICON_FA_IMAGE_PORTRAIT "\xef\x8f\xa0" // U+f3e0 -#define ICON_FA_IMAGES "\xef\x8c\x82" // U+f302 -#define ICON_FA_INBOX "\xef\x80\x9c" // U+f01c -#define ICON_FA_INDENT "\xef\x80\xbc" // U+f03c -#define ICON_FA_INDIAN_RUPEE_SIGN "\xee\x86\xbc" // U+e1bc -#define ICON_FA_INDUSTRY "\xef\x89\xb5" // U+f275 -#define ICON_FA_INFINITY "\xef\x94\xb4" // U+f534 -#define ICON_FA_INFO "\xef\x84\xa9" // U+f129 -#define ICON_FA_ITALIC "\xef\x80\xb3" // U+f033 -#define ICON_FA_J "J" // U+004a -#define ICON_FA_JAR "\xee\x94\x96" // U+e516 -#define ICON_FA_JAR_WHEAT "\xee\x94\x97" // U+e517 -#define ICON_FA_JEDI "\xef\x99\xa9" // U+f669 -#define ICON_FA_JET_FIGHTER "\xef\x83\xbb" // U+f0fb -#define ICON_FA_JET_FIGHTER_UP "\xee\x94\x98" // U+e518 -#define ICON_FA_JOINT "\xef\x96\x95" // U+f595 -#define ICON_FA_JUG_DETERGENT "\xee\x94\x99" // U+e519 -#define ICON_FA_K "K" // U+004b -#define ICON_FA_KAABA "\xef\x99\xab" // U+f66b -#define ICON_FA_KEY "\xef\x82\x84" // U+f084 -#define ICON_FA_KEYBOARD "\xef\x84\x9c" // U+f11c -#define ICON_FA_KHANDA "\xef\x99\xad" // U+f66d -#define ICON_FA_KIP_SIGN "\xee\x87\x84" // U+e1c4 -#define ICON_FA_KIT_MEDICAL "\xef\x91\xb9" // U+f479 -#define ICON_FA_KITCHEN_SET "\xee\x94\x9a" // U+e51a -#define ICON_FA_KIWI_BIRD "\xef\x94\xb5" // U+f535 -#define ICON_FA_L "L" // U+004c -#define ICON_FA_LAND_MINE_ON "\xee\x94\x9b" // U+e51b -#define ICON_FA_LANDMARK "\xef\x99\xaf" // U+f66f -#define ICON_FA_LANDMARK_DOME "\xef\x9d\x92" // U+f752 -#define ICON_FA_LANDMARK_FLAG "\xee\x94\x9c" // U+e51c -#define ICON_FA_LANGUAGE "\xef\x86\xab" // U+f1ab -#define ICON_FA_LAPTOP "\xef\x84\x89" // U+f109 -#define ICON_FA_LAPTOP_CODE "\xef\x97\xbc" // U+f5fc -#define ICON_FA_LAPTOP_FILE "\xee\x94\x9d" // U+e51d -#define ICON_FA_LAPTOP_MEDICAL "\xef\xa0\x92" // U+f812 -#define ICON_FA_LARI_SIGN "\xee\x87\x88" // U+e1c8 -#define ICON_FA_LAYER_GROUP "\xef\x97\xbd" // U+f5fd -#define ICON_FA_LEAF "\xef\x81\xac" // U+f06c -#define ICON_FA_LEFT_LONG "\xef\x8c\x8a" // U+f30a -#define ICON_FA_LEFT_RIGHT "\xef\x8c\xb7" // U+f337 -#define ICON_FA_LEMON "\xef\x82\x94" // U+f094 -#define ICON_FA_LESS_THAN "<" // U+003c -#define ICON_FA_LESS_THAN_EQUAL "\xef\x94\xb7" // U+f537 -#define ICON_FA_LIFE_RING "\xef\x87\x8d" // U+f1cd -#define ICON_FA_LIGHTBULB "\xef\x83\xab" // U+f0eb -#define ICON_FA_LINES_LEANING "\xee\x94\x9e" // U+e51e -#define ICON_FA_LINK "\xef\x83\x81" // U+f0c1 -#define ICON_FA_LINK_SLASH "\xef\x84\xa7" // U+f127 -#define ICON_FA_LIRA_SIGN "\xef\x86\x95" // U+f195 -#define ICON_FA_LIST "\xef\x80\xba" // U+f03a -#define ICON_FA_LIST_CHECK "\xef\x82\xae" // U+f0ae -#define ICON_FA_LIST_OL "\xef\x83\x8b" // U+f0cb -#define ICON_FA_LIST_UL "\xef\x83\x8a" // U+f0ca -#define ICON_FA_LITECOIN_SIGN "\xee\x87\x93" // U+e1d3 -#define ICON_FA_LOCATION_ARROW "\xef\x84\xa4" // U+f124 -#define ICON_FA_LOCATION_CROSSHAIRS "\xef\x98\x81" // U+f601 -#define ICON_FA_LOCATION_DOT "\xef\x8f\x85" // U+f3c5 -#define ICON_FA_LOCATION_PIN "\xef\x81\x81" // U+f041 -#define ICON_FA_LOCATION_PIN_LOCK "\xee\x94\x9f" // U+e51f -#define ICON_FA_LOCK "\xef\x80\xa3" // U+f023 -#define ICON_FA_LOCK_OPEN "\xef\x8f\x81" // U+f3c1 -#define ICON_FA_LOCUST "\xee\x94\xa0" // U+e520 -#define ICON_FA_LUNGS "\xef\x98\x84" // U+f604 -#define ICON_FA_LUNGS_VIRUS "\xee\x81\xa7" // U+e067 -#define ICON_FA_M "M" // U+004d -#define ICON_FA_MAGNET "\xef\x81\xb6" // U+f076 -#define ICON_FA_MAGNIFYING_GLASS "\xef\x80\x82" // U+f002 -#define ICON_FA_MAGNIFYING_GLASS_ARROW_RIGHT "\xee\x94\xa1" // U+e521 -#define ICON_FA_MAGNIFYING_GLASS_CHART "\xee\x94\xa2" // U+e522 -#define ICON_FA_MAGNIFYING_GLASS_DOLLAR "\xef\x9a\x88" // U+f688 -#define ICON_FA_MAGNIFYING_GLASS_LOCATION "\xef\x9a\x89" // U+f689 -#define ICON_FA_MAGNIFYING_GLASS_MINUS "\xef\x80\x90" // U+f010 -#define ICON_FA_MAGNIFYING_GLASS_PLUS "\xef\x80\x8e" // U+f00e -#define ICON_FA_MANAT_SIGN "\xee\x87\x95" // U+e1d5 -#define ICON_FA_MAP "\xef\x89\xb9" // U+f279 -#define ICON_FA_MAP_LOCATION "\xef\x96\x9f" // U+f59f -#define ICON_FA_MAP_LOCATION_DOT "\xef\x96\xa0" // U+f5a0 -#define ICON_FA_MAP_PIN "\xef\x89\xb6" // U+f276 -#define ICON_FA_MARKER "\xef\x96\xa1" // U+f5a1 -#define ICON_FA_MARS "\xef\x88\xa2" // U+f222 -#define ICON_FA_MARS_AND_VENUS "\xef\x88\xa4" // U+f224 -#define ICON_FA_MARS_AND_VENUS_BURST "\xee\x94\xa3" // U+e523 -#define ICON_FA_MARS_DOUBLE "\xef\x88\xa7" // U+f227 -#define ICON_FA_MARS_STROKE "\xef\x88\xa9" // U+f229 -#define ICON_FA_MARS_STROKE_RIGHT "\xef\x88\xab" // U+f22b -#define ICON_FA_MARS_STROKE_UP "\xef\x88\xaa" // U+f22a -#define ICON_FA_MARTINI_GLASS "\xef\x95\xbb" // U+f57b -#define ICON_FA_MARTINI_GLASS_CITRUS "\xef\x95\xa1" // U+f561 -#define ICON_FA_MARTINI_GLASS_EMPTY "\xef\x80\x80" // U+f000 -#define ICON_FA_MASK "\xef\x9b\xba" // U+f6fa -#define ICON_FA_MASK_FACE "\xee\x87\x97" // U+e1d7 -#define ICON_FA_MASK_VENTILATOR "\xee\x94\xa4" // U+e524 -#define ICON_FA_MASKS_THEATER "\xef\x98\xb0" // U+f630 -#define ICON_FA_MATTRESS_PILLOW "\xee\x94\xa5" // U+e525 -#define ICON_FA_MAXIMIZE "\xef\x8c\x9e" // U+f31e -#define ICON_FA_MEDAL "\xef\x96\xa2" // U+f5a2 -#define ICON_FA_MEMORY "\xef\x94\xb8" // U+f538 -#define ICON_FA_MENORAH "\xef\x99\xb6" // U+f676 -#define ICON_FA_MERCURY "\xef\x88\xa3" // U+f223 -#define ICON_FA_MESSAGE "\xef\x89\xba" // U+f27a -#define ICON_FA_METEOR "\xef\x9d\x93" // U+f753 -#define ICON_FA_MICROCHIP "\xef\x8b\x9b" // U+f2db -#define ICON_FA_MICROPHONE "\xef\x84\xb0" // U+f130 -#define ICON_FA_MICROPHONE_LINES "\xef\x8f\x89" // U+f3c9 -#define ICON_FA_MICROPHONE_LINES_SLASH "\xef\x94\xb9" // U+f539 -#define ICON_FA_MICROPHONE_SLASH "\xef\x84\xb1" // U+f131 -#define ICON_FA_MICROSCOPE "\xef\x98\x90" // U+f610 -#define ICON_FA_MILL_SIGN "\xee\x87\xad" // U+e1ed -#define ICON_FA_MINIMIZE "\xef\x9e\x8c" // U+f78c -#define ICON_FA_MINUS "\xef\x81\xa8" // U+f068 -#define ICON_FA_MITTEN "\xef\x9e\xb5" // U+f7b5 -#define ICON_FA_MOBILE "\xef\x8f\x8e" // U+f3ce -#define ICON_FA_MOBILE_BUTTON "\xef\x84\x8b" // U+f10b -#define ICON_FA_MOBILE_RETRO "\xee\x94\xa7" // U+e527 -#define ICON_FA_MOBILE_SCREEN "\xef\x8f\x8f" // U+f3cf -#define ICON_FA_MOBILE_SCREEN_BUTTON "\xef\x8f\x8d" // U+f3cd -#define ICON_FA_MONEY_BILL "\xef\x83\x96" // U+f0d6 -#define ICON_FA_MONEY_BILL_1 "\xef\x8f\x91" // U+f3d1 -#define ICON_FA_MONEY_BILL_1_WAVE "\xef\x94\xbb" // U+f53b -#define ICON_FA_MONEY_BILL_TRANSFER "\xee\x94\xa8" // U+e528 -#define ICON_FA_MONEY_BILL_TREND_UP "\xee\x94\xa9" // U+e529 -#define ICON_FA_MONEY_BILL_WAVE "\xef\x94\xba" // U+f53a -#define ICON_FA_MONEY_BILL_WHEAT "\xee\x94\xaa" // U+e52a -#define ICON_FA_MONEY_BILLS "\xee\x87\xb3" // U+e1f3 -#define ICON_FA_MONEY_CHECK "\xef\x94\xbc" // U+f53c -#define ICON_FA_MONEY_CHECK_DOLLAR "\xef\x94\xbd" // U+f53d -#define ICON_FA_MONUMENT "\xef\x96\xa6" // U+f5a6 -#define ICON_FA_MOON "\xef\x86\x86" // U+f186 -#define ICON_FA_MORTAR_PESTLE "\xef\x96\xa7" // U+f5a7 -#define ICON_FA_MOSQUE "\xef\x99\xb8" // U+f678 -#define ICON_FA_MOSQUITO "\xee\x94\xab" // U+e52b -#define ICON_FA_MOSQUITO_NET "\xee\x94\xac" // U+e52c -#define ICON_FA_MOTORCYCLE "\xef\x88\x9c" // U+f21c -#define ICON_FA_MOUND "\xee\x94\xad" // U+e52d -#define ICON_FA_MOUNTAIN "\xef\x9b\xbc" // U+f6fc -#define ICON_FA_MOUNTAIN_CITY "\xee\x94\xae" // U+e52e -#define ICON_FA_MOUNTAIN_SUN "\xee\x94\xaf" // U+e52f -#define ICON_FA_MUG_HOT "\xef\x9e\xb6" // U+f7b6 -#define ICON_FA_MUG_SAUCER "\xef\x83\xb4" // U+f0f4 -#define ICON_FA_MUSIC "\xef\x80\x81" // U+f001 -#define ICON_FA_N "N" // U+004e -#define ICON_FA_NAIRA_SIGN "\xee\x87\xb6" // U+e1f6 -#define ICON_FA_NETWORK_WIRED "\xef\x9b\xbf" // U+f6ff -#define ICON_FA_NEUTER "\xef\x88\xac" // U+f22c -#define ICON_FA_NEWSPAPER "\xef\x87\xaa" // U+f1ea -#define ICON_FA_NOT_EQUAL "\xef\x94\xbe" // U+f53e -#define ICON_FA_NOTE_STICKY "\xef\x89\x89" // U+f249 -#define ICON_FA_NOTES_MEDICAL "\xef\x92\x81" // U+f481 -#define ICON_FA_O "O" // U+004f -#define ICON_FA_OBJECT_GROUP "\xef\x89\x87" // U+f247 -#define ICON_FA_OBJECT_UNGROUP "\xef\x89\x88" // U+f248 -#define ICON_FA_OIL_CAN "\xef\x98\x93" // U+f613 -#define ICON_FA_OIL_WELL "\xee\x94\xb2" // U+e532 -#define ICON_FA_OM "\xef\x99\xb9" // U+f679 -#define ICON_FA_OTTER "\xef\x9c\x80" // U+f700 -#define ICON_FA_OUTDENT "\xef\x80\xbb" // U+f03b -#define ICON_FA_P "P" // U+0050 -#define ICON_FA_PAGER "\xef\xa0\x95" // U+f815 -#define ICON_FA_PAINT_ROLLER "\xef\x96\xaa" // U+f5aa -#define ICON_FA_PAINTBRUSH "\xef\x87\xbc" // U+f1fc -#define ICON_FA_PALETTE "\xef\x94\xbf" // U+f53f -#define ICON_FA_PALLET "\xef\x92\x82" // U+f482 -#define ICON_FA_PANORAMA "\xee\x88\x89" // U+e209 -#define ICON_FA_PAPER_PLANE "\xef\x87\x98" // U+f1d8 -#define ICON_FA_PAPERCLIP "\xef\x83\x86" // U+f0c6 -#define ICON_FA_PARACHUTE_BOX "\xef\x93\x8d" // U+f4cd -#define ICON_FA_PARAGRAPH "\xef\x87\x9d" // U+f1dd -#define ICON_FA_PASSPORT "\xef\x96\xab" // U+f5ab -#define ICON_FA_PASTE "\xef\x83\xaa" // U+f0ea -#define ICON_FA_PAUSE "\xef\x81\x8c" // U+f04c -#define ICON_FA_PAW "\xef\x86\xb0" // U+f1b0 -#define ICON_FA_PEACE "\xef\x99\xbc" // U+f67c -#define ICON_FA_PEN "\xef\x8c\x84" // U+f304 -#define ICON_FA_PEN_CLIP "\xef\x8c\x85" // U+f305 -#define ICON_FA_PEN_FANCY "\xef\x96\xac" // U+f5ac -#define ICON_FA_PEN_NIB "\xef\x96\xad" // U+f5ad -#define ICON_FA_PEN_RULER "\xef\x96\xae" // U+f5ae -#define ICON_FA_PEN_TO_SQUARE "\xef\x81\x84" // U+f044 -#define ICON_FA_PENCIL "\xef\x8c\x83" // U+f303 -#define ICON_FA_PEOPLE_ARROWS_LEFT_RIGHT "\xee\x81\xa8" // U+e068 -#define ICON_FA_PEOPLE_CARRY_BOX "\xef\x93\x8e" // U+f4ce -#define ICON_FA_PEOPLE_GROUP "\xee\x94\xb3" // U+e533 -#define ICON_FA_PEOPLE_LINE "\xee\x94\xb4" // U+e534 -#define ICON_FA_PEOPLE_PULLING "\xee\x94\xb5" // U+e535 -#define ICON_FA_PEOPLE_ROBBERY "\xee\x94\xb6" // U+e536 -#define ICON_FA_PEOPLE_ROOF "\xee\x94\xb7" // U+e537 -#define ICON_FA_PEPPER_HOT "\xef\xa0\x96" // U+f816 -#define ICON_FA_PERCENT "%" // U+0025 -#define ICON_FA_PERSON "\xef\x86\x83" // U+f183 -#define ICON_FA_PERSON_ARROW_DOWN_TO_LINE "\xee\x94\xb8" // U+e538 -#define ICON_FA_PERSON_ARROW_UP_FROM_LINE "\xee\x94\xb9" // U+e539 -#define ICON_FA_PERSON_BIKING "\xef\xa1\x8a" // U+f84a -#define ICON_FA_PERSON_BOOTH "\xef\x9d\x96" // U+f756 -#define ICON_FA_PERSON_BREASTFEEDING "\xee\x94\xba" // U+e53a -#define ICON_FA_PERSON_BURST "\xee\x94\xbb" // U+e53b -#define ICON_FA_PERSON_CANE "\xee\x94\xbc" // U+e53c -#define ICON_FA_PERSON_CHALKBOARD "\xee\x94\xbd" // U+e53d -#define ICON_FA_PERSON_CIRCLE_CHECK "\xee\x94\xbe" // U+e53e -#define ICON_FA_PERSON_CIRCLE_EXCLAMATION "\xee\x94\xbf" // U+e53f -#define ICON_FA_PERSON_CIRCLE_MINUS "\xee\x95\x80" // U+e540 -#define ICON_FA_PERSON_CIRCLE_PLUS "\xee\x95\x81" // U+e541 -#define ICON_FA_PERSON_CIRCLE_QUESTION "\xee\x95\x82" // U+e542 -#define ICON_FA_PERSON_CIRCLE_XMARK "\xee\x95\x83" // U+e543 -#define ICON_FA_PERSON_DIGGING "\xef\xa1\x9e" // U+f85e -#define ICON_FA_PERSON_DOTS_FROM_LINE "\xef\x91\xb0" // U+f470 -#define ICON_FA_PERSON_DRESS "\xef\x86\x82" // U+f182 -#define ICON_FA_PERSON_DRESS_BURST "\xee\x95\x84" // U+e544 -#define ICON_FA_PERSON_DROWNING "\xee\x95\x85" // U+e545 -#define ICON_FA_PERSON_FALLING "\xee\x95\x86" // U+e546 -#define ICON_FA_PERSON_FALLING_BURST "\xee\x95\x87" // U+e547 -#define ICON_FA_PERSON_HALF_DRESS "\xee\x95\x88" // U+e548 -#define ICON_FA_PERSON_HARASSING "\xee\x95\x89" // U+e549 -#define ICON_FA_PERSON_HIKING "\xef\x9b\xac" // U+f6ec -#define ICON_FA_PERSON_MILITARY_POINTING "\xee\x95\x8a" // U+e54a -#define ICON_FA_PERSON_MILITARY_RIFLE "\xee\x95\x8b" // U+e54b -#define ICON_FA_PERSON_MILITARY_TO_PERSON "\xee\x95\x8c" // U+e54c -#define ICON_FA_PERSON_PRAYING "\xef\x9a\x83" // U+f683 -#define ICON_FA_PERSON_PREGNANT "\xee\x8c\x9e" // U+e31e -#define ICON_FA_PERSON_RAYS "\xee\x95\x8d" // U+e54d -#define ICON_FA_PERSON_RIFLE "\xee\x95\x8e" // U+e54e -#define ICON_FA_PERSON_RUNNING "\xef\x9c\x8c" // U+f70c -#define ICON_FA_PERSON_SHELTER "\xee\x95\x8f" // U+e54f -#define ICON_FA_PERSON_SKATING "\xef\x9f\x85" // U+f7c5 -#define ICON_FA_PERSON_SKIING "\xef\x9f\x89" // U+f7c9 -#define ICON_FA_PERSON_SKIING_NORDIC "\xef\x9f\x8a" // U+f7ca -#define ICON_FA_PERSON_SNOWBOARDING "\xef\x9f\x8e" // U+f7ce -#define ICON_FA_PERSON_SWIMMING "\xef\x97\x84" // U+f5c4 -#define ICON_FA_PERSON_THROUGH_WINDOW "\xee\x90\xb3" // U+e433 -#define ICON_FA_PERSON_WALKING "\xef\x95\x94" // U+f554 -#define ICON_FA_PERSON_WALKING_ARROW_LOOP_LEFT "\xee\x95\x91" // U+e551 -#define ICON_FA_PERSON_WALKING_ARROW_RIGHT "\xee\x95\x92" // U+e552 -#define ICON_FA_PERSON_WALKING_DASHED_LINE_ARROW_RIGHT "\xee\x95\x93" // U+e553 -#define ICON_FA_PERSON_WALKING_LUGGAGE "\xee\x95\x94" // U+e554 -#define ICON_FA_PERSON_WALKING_WITH_CANE "\xef\x8a\x9d" // U+f29d -#define ICON_FA_PESETA_SIGN "\xee\x88\xa1" // U+e221 -#define ICON_FA_PESO_SIGN "\xee\x88\xa2" // U+e222 -#define ICON_FA_PHONE "\xef\x82\x95" // U+f095 -#define ICON_FA_PHONE_FLIP "\xef\xa1\xb9" // U+f879 -#define ICON_FA_PHONE_SLASH "\xef\x8f\x9d" // U+f3dd -#define ICON_FA_PHONE_VOLUME "\xef\x8a\xa0" // U+f2a0 -#define ICON_FA_PHOTO_FILM "\xef\xa1\xbc" // U+f87c -#define ICON_FA_PIGGY_BANK "\xef\x93\x93" // U+f4d3 -#define ICON_FA_PILLS "\xef\x92\x84" // U+f484 -#define ICON_FA_PIZZA_SLICE "\xef\xa0\x98" // U+f818 -#define ICON_FA_PLACE_OF_WORSHIP "\xef\x99\xbf" // U+f67f -#define ICON_FA_PLANE "\xef\x81\xb2" // U+f072 -#define ICON_FA_PLANE_ARRIVAL "\xef\x96\xaf" // U+f5af -#define ICON_FA_PLANE_CIRCLE_CHECK "\xee\x95\x95" // U+e555 -#define ICON_FA_PLANE_CIRCLE_EXCLAMATION "\xee\x95\x96" // U+e556 -#define ICON_FA_PLANE_CIRCLE_XMARK "\xee\x95\x97" // U+e557 -#define ICON_FA_PLANE_DEPARTURE "\xef\x96\xb0" // U+f5b0 -#define ICON_FA_PLANE_LOCK "\xee\x95\x98" // U+e558 -#define ICON_FA_PLANE_SLASH "\xee\x81\xa9" // U+e069 -#define ICON_FA_PLANE_UP "\xee\x88\xad" // U+e22d -#define ICON_FA_PLANT_WILT "\xee\x90\xbb" // U+e43b -#define ICON_FA_PLATE_WHEAT "\xee\x95\x9a" // U+e55a -#define ICON_FA_PLAY "\xef\x81\x8b" // U+f04b -#define ICON_FA_PLUG "\xef\x87\xa6" // U+f1e6 -#define ICON_FA_PLUG_CIRCLE_BOLT "\xee\x95\x9b" // U+e55b -#define ICON_FA_PLUG_CIRCLE_CHECK "\xee\x95\x9c" // U+e55c -#define ICON_FA_PLUG_CIRCLE_EXCLAMATION "\xee\x95\x9d" // U+e55d -#define ICON_FA_PLUG_CIRCLE_MINUS "\xee\x95\x9e" // U+e55e -#define ICON_FA_PLUG_CIRCLE_PLUS "\xee\x95\x9f" // U+e55f -#define ICON_FA_PLUG_CIRCLE_XMARK "\xee\x95\xa0" // U+e560 -#define ICON_FA_PLUS "+" // U+002b -#define ICON_FA_PLUS_MINUS "\xee\x90\xbc" // U+e43c -#define ICON_FA_PODCAST "\xef\x8b\x8e" // U+f2ce -#define ICON_FA_POO "\xef\x8b\xbe" // U+f2fe -#define ICON_FA_POO_STORM "\xef\x9d\x9a" // U+f75a -#define ICON_FA_POOP "\xef\x98\x99" // U+f619 -#define ICON_FA_POWER_OFF "\xef\x80\x91" // U+f011 -#define ICON_FA_PRESCRIPTION "\xef\x96\xb1" // U+f5b1 -#define ICON_FA_PRESCRIPTION_BOTTLE "\xef\x92\x85" // U+f485 -#define ICON_FA_PRESCRIPTION_BOTTLE_MEDICAL "\xef\x92\x86" // U+f486 -#define ICON_FA_PRINT "\xef\x80\xaf" // U+f02f -#define ICON_FA_PUMP_MEDICAL "\xee\x81\xaa" // U+e06a -#define ICON_FA_PUMP_SOAP "\xee\x81\xab" // U+e06b -#define ICON_FA_PUZZLE_PIECE "\xef\x84\xae" // U+f12e -#define ICON_FA_Q "Q" // U+0051 -#define ICON_FA_QRCODE "\xef\x80\xa9" // U+f029 -#define ICON_FA_QUESTION "?" // U+003f -#define ICON_FA_QUOTE_LEFT "\xef\x84\x8d" // U+f10d -#define ICON_FA_QUOTE_RIGHT "\xef\x84\x8e" // U+f10e -#define ICON_FA_R "R" // U+0052 -#define ICON_FA_RADIATION "\xef\x9e\xb9" // U+f7b9 -#define ICON_FA_RADIO "\xef\xa3\x97" // U+f8d7 -#define ICON_FA_RAINBOW "\xef\x9d\x9b" // U+f75b -#define ICON_FA_RANKING_STAR "\xee\x95\xa1" // U+e561 -#define ICON_FA_RECEIPT "\xef\x95\x83" // U+f543 -#define ICON_FA_RECORD_VINYL "\xef\xa3\x99" // U+f8d9 -#define ICON_FA_RECTANGLE_AD "\xef\x99\x81" // U+f641 -#define ICON_FA_RECTANGLE_LIST "\xef\x80\xa2" // U+f022 -#define ICON_FA_RECTANGLE_XMARK "\xef\x90\x90" // U+f410 -#define ICON_FA_RECYCLE "\xef\x86\xb8" // U+f1b8 -#define ICON_FA_REGISTERED "\xef\x89\x9d" // U+f25d -#define ICON_FA_REPEAT "\xef\x8d\xa3" // U+f363 -#define ICON_FA_REPLY "\xef\x8f\xa5" // U+f3e5 -#define ICON_FA_REPLY_ALL "\xef\x84\xa2" // U+f122 -#define ICON_FA_REPUBLICAN "\xef\x9d\x9e" // U+f75e -#define ICON_FA_RESTROOM "\xef\x9e\xbd" // U+f7bd -#define ICON_FA_RETWEET "\xef\x81\xb9" // U+f079 -#define ICON_FA_RIBBON "\xef\x93\x96" // U+f4d6 -#define ICON_FA_RIGHT_FROM_BRACKET "\xef\x8b\xb5" // U+f2f5 -#define ICON_FA_RIGHT_LEFT "\xef\x8d\xa2" // U+f362 -#define ICON_FA_RIGHT_LONG "\xef\x8c\x8b" // U+f30b -#define ICON_FA_RIGHT_TO_BRACKET "\xef\x8b\xb6" // U+f2f6 -#define ICON_FA_RING "\xef\x9c\x8b" // U+f70b -#define ICON_FA_ROAD "\xef\x80\x98" // U+f018 -#define ICON_FA_ROAD_BARRIER "\xee\x95\xa2" // U+e562 -#define ICON_FA_ROAD_BRIDGE "\xee\x95\xa3" // U+e563 -#define ICON_FA_ROAD_CIRCLE_CHECK "\xee\x95\xa4" // U+e564 -#define ICON_FA_ROAD_CIRCLE_EXCLAMATION "\xee\x95\xa5" // U+e565 -#define ICON_FA_ROAD_CIRCLE_XMARK "\xee\x95\xa6" // U+e566 -#define ICON_FA_ROAD_LOCK "\xee\x95\xa7" // U+e567 -#define ICON_FA_ROAD_SPIKES "\xee\x95\xa8" // U+e568 -#define ICON_FA_ROBOT "\xef\x95\x84" // U+f544 -#define ICON_FA_ROCKET "\xef\x84\xb5" // U+f135 -#define ICON_FA_ROTATE "\xef\x8b\xb1" // U+f2f1 -#define ICON_FA_ROTATE_LEFT "\xef\x8b\xaa" // U+f2ea -#define ICON_FA_ROTATE_RIGHT "\xef\x8b\xb9" // U+f2f9 -#define ICON_FA_ROUTE "\xef\x93\x97" // U+f4d7 -#define ICON_FA_RSS "\xef\x82\x9e" // U+f09e -#define ICON_FA_RUBLE_SIGN "\xef\x85\x98" // U+f158 -#define ICON_FA_RUG "\xee\x95\xa9" // U+e569 -#define ICON_FA_RULER "\xef\x95\x85" // U+f545 -#define ICON_FA_RULER_COMBINED "\xef\x95\x86" // U+f546 -#define ICON_FA_RULER_HORIZONTAL "\xef\x95\x87" // U+f547 -#define ICON_FA_RULER_VERTICAL "\xef\x95\x88" // U+f548 -#define ICON_FA_RUPEE_SIGN "\xef\x85\x96" // U+f156 -#define ICON_FA_RUPIAH_SIGN "\xee\x88\xbd" // U+e23d -#define ICON_FA_S "S" // U+0053 -#define ICON_FA_SACK_DOLLAR "\xef\xa0\x9d" // U+f81d -#define ICON_FA_SACK_XMARK "\xee\x95\xaa" // U+e56a -#define ICON_FA_SAILBOAT "\xee\x91\x85" // U+e445 -#define ICON_FA_SATELLITE "\xef\x9e\xbf" // U+f7bf -#define ICON_FA_SATELLITE_DISH "\xef\x9f\x80" // U+f7c0 -#define ICON_FA_SCALE_BALANCED "\xef\x89\x8e" // U+f24e -#define ICON_FA_SCALE_UNBALANCED "\xef\x94\x95" // U+f515 -#define ICON_FA_SCALE_UNBALANCED_FLIP "\xef\x94\x96" // U+f516 -#define ICON_FA_SCHOOL "\xef\x95\x89" // U+f549 -#define ICON_FA_SCHOOL_CIRCLE_CHECK "\xee\x95\xab" // U+e56b -#define ICON_FA_SCHOOL_CIRCLE_EXCLAMATION "\xee\x95\xac" // U+e56c -#define ICON_FA_SCHOOL_CIRCLE_XMARK "\xee\x95\xad" // U+e56d -#define ICON_FA_SCHOOL_FLAG "\xee\x95\xae" // U+e56e -#define ICON_FA_SCHOOL_LOCK "\xee\x95\xaf" // U+e56f -#define ICON_FA_SCISSORS "\xef\x83\x84" // U+f0c4 -#define ICON_FA_SCREWDRIVER "\xef\x95\x8a" // U+f54a -#define ICON_FA_SCREWDRIVER_WRENCH "\xef\x9f\x99" // U+f7d9 -#define ICON_FA_SCROLL "\xef\x9c\x8e" // U+f70e -#define ICON_FA_SCROLL_TORAH "\xef\x9a\xa0" // U+f6a0 -#define ICON_FA_SD_CARD "\xef\x9f\x82" // U+f7c2 -#define ICON_FA_SECTION "\xee\x91\x87" // U+e447 -#define ICON_FA_SEEDLING "\xef\x93\x98" // U+f4d8 -#define ICON_FA_SERVER "\xef\x88\xb3" // U+f233 -#define ICON_FA_SHAPES "\xef\x98\x9f" // U+f61f -#define ICON_FA_SHARE "\xef\x81\xa4" // U+f064 -#define ICON_FA_SHARE_FROM_SQUARE "\xef\x85\x8d" // U+f14d -#define ICON_FA_SHARE_NODES "\xef\x87\xa0" // U+f1e0 -#define ICON_FA_SHEET_PLASTIC "\xee\x95\xb1" // U+e571 -#define ICON_FA_SHEKEL_SIGN "\xef\x88\x8b" // U+f20b -#define ICON_FA_SHIELD "\xef\x84\xb2" // U+f132 -#define ICON_FA_SHIELD_CAT "\xee\x95\xb2" // U+e572 -#define ICON_FA_SHIELD_DOG "\xee\x95\xb3" // U+e573 -#define ICON_FA_SHIELD_HALVED "\xef\x8f\xad" // U+f3ed -#define ICON_FA_SHIELD_HEART "\xee\x95\xb4" // U+e574 -#define ICON_FA_SHIELD_VIRUS "\xee\x81\xac" // U+e06c -#define ICON_FA_SHIP "\xef\x88\x9a" // U+f21a -#define ICON_FA_SHIRT "\xef\x95\x93" // U+f553 -#define ICON_FA_SHOE_PRINTS "\xef\x95\x8b" // U+f54b -#define ICON_FA_SHOP "\xef\x95\x8f" // U+f54f -#define ICON_FA_SHOP_LOCK "\xee\x92\xa5" // U+e4a5 -#define ICON_FA_SHOP_SLASH "\xee\x81\xb0" // U+e070 -#define ICON_FA_SHOWER "\xef\x8b\x8c" // U+f2cc -#define ICON_FA_SHRIMP "\xee\x91\x88" // U+e448 -#define ICON_FA_SHUFFLE "\xef\x81\xb4" // U+f074 -#define ICON_FA_SHUTTLE_SPACE "\xef\x86\x97" // U+f197 -#define ICON_FA_SIGN_HANGING "\xef\x93\x99" // U+f4d9 -#define ICON_FA_SIGNAL "\xef\x80\x92" // U+f012 -#define ICON_FA_SIGNATURE "\xef\x96\xb7" // U+f5b7 -#define ICON_FA_SIGNS_POST "\xef\x89\xb7" // U+f277 -#define ICON_FA_SIM_CARD "\xef\x9f\x84" // U+f7c4 -#define ICON_FA_SINK "\xee\x81\xad" // U+e06d -#define ICON_FA_SITEMAP "\xef\x83\xa8" // U+f0e8 -#define ICON_FA_SKULL "\xef\x95\x8c" // U+f54c -#define ICON_FA_SKULL_CROSSBONES "\xef\x9c\x94" // U+f714 -#define ICON_FA_SLASH "\xef\x9c\x95" // U+f715 -#define ICON_FA_SLEIGH "\xef\x9f\x8c" // U+f7cc -#define ICON_FA_SLIDERS "\xef\x87\x9e" // U+f1de -#define ICON_FA_SMOG "\xef\x9d\x9f" // U+f75f -#define ICON_FA_SMOKING "\xef\x92\x8d" // U+f48d -#define ICON_FA_SNOWFLAKE "\xef\x8b\x9c" // U+f2dc -#define ICON_FA_SNOWMAN "\xef\x9f\x90" // U+f7d0 -#define ICON_FA_SNOWPLOW "\xef\x9f\x92" // U+f7d2 -#define ICON_FA_SOAP "\xee\x81\xae" // U+e06e -#define ICON_FA_SOCKS "\xef\x9a\x96" // U+f696 -#define ICON_FA_SOLAR_PANEL "\xef\x96\xba" // U+f5ba -#define ICON_FA_SORT "\xef\x83\x9c" // U+f0dc -#define ICON_FA_SORT_DOWN "\xef\x83\x9d" // U+f0dd -#define ICON_FA_SORT_UP "\xef\x83\x9e" // U+f0de -#define ICON_FA_SPA "\xef\x96\xbb" // U+f5bb -#define ICON_FA_SPAGHETTI_MONSTER_FLYING "\xef\x99\xbb" // U+f67b -#define ICON_FA_SPELL_CHECK "\xef\xa2\x91" // U+f891 -#define ICON_FA_SPIDER "\xef\x9c\x97" // U+f717 -#define ICON_FA_SPINNER "\xef\x84\x90" // U+f110 -#define ICON_FA_SPLOTCH "\xef\x96\xbc" // U+f5bc -#define ICON_FA_SPOON "\xef\x8b\xa5" // U+f2e5 -#define ICON_FA_SPRAY_CAN "\xef\x96\xbd" // U+f5bd -#define ICON_FA_SPRAY_CAN_SPARKLES "\xef\x97\x90" // U+f5d0 -#define ICON_FA_SQUARE "\xef\x83\x88" // U+f0c8 -#define ICON_FA_SQUARE_ARROW_UP_RIGHT "\xef\x85\x8c" // U+f14c -#define ICON_FA_SQUARE_CARET_DOWN "\xef\x85\x90" // U+f150 -#define ICON_FA_SQUARE_CARET_LEFT "\xef\x86\x91" // U+f191 -#define ICON_FA_SQUARE_CARET_RIGHT "\xef\x85\x92" // U+f152 -#define ICON_FA_SQUARE_CARET_UP "\xef\x85\x91" // U+f151 -#define ICON_FA_SQUARE_CHECK "\xef\x85\x8a" // U+f14a -#define ICON_FA_SQUARE_ENVELOPE "\xef\x86\x99" // U+f199 -#define ICON_FA_SQUARE_FULL "\xef\x91\x9c" // U+f45c -#define ICON_FA_SQUARE_H "\xef\x83\xbd" // U+f0fd -#define ICON_FA_SQUARE_MINUS "\xef\x85\x86" // U+f146 -#define ICON_FA_SQUARE_NFI "\xee\x95\xb6" // U+e576 -#define ICON_FA_SQUARE_PARKING "\xef\x95\x80" // U+f540 -#define ICON_FA_SQUARE_PEN "\xef\x85\x8b" // U+f14b -#define ICON_FA_SQUARE_PERSON_CONFINED "\xee\x95\xb7" // U+e577 -#define ICON_FA_SQUARE_PHONE "\xef\x82\x98" // U+f098 -#define ICON_FA_SQUARE_PHONE_FLIP "\xef\xa1\xbb" // U+f87b -#define ICON_FA_SQUARE_PLUS "\xef\x83\xbe" // U+f0fe -#define ICON_FA_SQUARE_POLL_HORIZONTAL "\xef\x9a\x82" // U+f682 -#define ICON_FA_SQUARE_POLL_VERTICAL "\xef\x9a\x81" // U+f681 -#define ICON_FA_SQUARE_ROOT_VARIABLE "\xef\x9a\x98" // U+f698 -#define ICON_FA_SQUARE_RSS "\xef\x85\x83" // U+f143 -#define ICON_FA_SQUARE_SHARE_NODES "\xef\x87\xa1" // U+f1e1 -#define ICON_FA_SQUARE_UP_RIGHT "\xef\x8d\xa0" // U+f360 -#define ICON_FA_SQUARE_VIRUS "\xee\x95\xb8" // U+e578 -#define ICON_FA_SQUARE_XMARK "\xef\x8b\x93" // U+f2d3 -#define ICON_FA_STAFF_AESCULAPIUS "\xee\x95\xb9" // U+e579 -#define ICON_FA_STAIRS "\xee\x8a\x89" // U+e289 -#define ICON_FA_STAMP "\xef\x96\xbf" // U+f5bf -#define ICON_FA_STAR "\xef\x80\x85" // U+f005 -#define ICON_FA_STAR_AND_CRESCENT "\xef\x9a\x99" // U+f699 -#define ICON_FA_STAR_HALF "\xef\x82\x89" // U+f089 -#define ICON_FA_STAR_HALF_STROKE "\xef\x97\x80" // U+f5c0 -#define ICON_FA_STAR_OF_DAVID "\xef\x9a\x9a" // U+f69a -#define ICON_FA_STAR_OF_LIFE "\xef\x98\xa1" // U+f621 -#define ICON_FA_STERLING_SIGN "\xef\x85\x94" // U+f154 -#define ICON_FA_STETHOSCOPE "\xef\x83\xb1" // U+f0f1 -#define ICON_FA_STOP "\xef\x81\x8d" // U+f04d -#define ICON_FA_STOPWATCH "\xef\x8b\xb2" // U+f2f2 -#define ICON_FA_STOPWATCH_20 "\xee\x81\xaf" // U+e06f -#define ICON_FA_STORE "\xef\x95\x8e" // U+f54e -#define ICON_FA_STORE_SLASH "\xee\x81\xb1" // U+e071 -#define ICON_FA_STREET_VIEW "\xef\x88\x9d" // U+f21d -#define ICON_FA_STRIKETHROUGH "\xef\x83\x8c" // U+f0cc -#define ICON_FA_STROOPWAFEL "\xef\x95\x91" // U+f551 -#define ICON_FA_SUBSCRIPT "\xef\x84\xac" // U+f12c -#define ICON_FA_SUITCASE "\xef\x83\xb2" // U+f0f2 -#define ICON_FA_SUITCASE_MEDICAL "\xef\x83\xba" // U+f0fa -#define ICON_FA_SUITCASE_ROLLING "\xef\x97\x81" // U+f5c1 -#define ICON_FA_SUN "\xef\x86\x85" // U+f185 -#define ICON_FA_SUN_PLANT_WILT "\xee\x95\xba" // U+e57a -#define ICON_FA_SUPERSCRIPT "\xef\x84\xab" // U+f12b -#define ICON_FA_SWATCHBOOK "\xef\x97\x83" // U+f5c3 -#define ICON_FA_SYNAGOGUE "\xef\x9a\x9b" // U+f69b -#define ICON_FA_SYRINGE "\xef\x92\x8e" // U+f48e -#define ICON_FA_T "T" // U+0054 -#define ICON_FA_TABLE "\xef\x83\x8e" // U+f0ce -#define ICON_FA_TABLE_CELLS "\xef\x80\x8a" // U+f00a -#define ICON_FA_TABLE_CELLS_LARGE "\xef\x80\x89" // U+f009 -#define ICON_FA_TABLE_COLUMNS "\xef\x83\x9b" // U+f0db -#define ICON_FA_TABLE_LIST "\xef\x80\x8b" // U+f00b -#define ICON_FA_TABLE_TENNIS_PADDLE_BALL "\xef\x91\x9d" // U+f45d -#define ICON_FA_TABLET "\xef\x8f\xbb" // U+f3fb -#define ICON_FA_TABLET_BUTTON "\xef\x84\x8a" // U+f10a -#define ICON_FA_TABLET_SCREEN_BUTTON "\xef\x8f\xba" // U+f3fa -#define ICON_FA_TABLETS "\xef\x92\x90" // U+f490 -#define ICON_FA_TACHOGRAPH_DIGITAL "\xef\x95\xa6" // U+f566 -#define ICON_FA_TAG "\xef\x80\xab" // U+f02b -#define ICON_FA_TAGS "\xef\x80\xac" // U+f02c -#define ICON_FA_TAPE "\xef\x93\x9b" // U+f4db -#define ICON_FA_TARP "\xee\x95\xbb" // U+e57b -#define ICON_FA_TARP_DROPLET "\xee\x95\xbc" // U+e57c -#define ICON_FA_TAXI "\xef\x86\xba" // U+f1ba -#define ICON_FA_TEETH "\xef\x98\xae" // U+f62e -#define ICON_FA_TEETH_OPEN "\xef\x98\xaf" // U+f62f -#define ICON_FA_TEMPERATURE_ARROW_DOWN "\xee\x80\xbf" // U+e03f -#define ICON_FA_TEMPERATURE_ARROW_UP "\xee\x81\x80" // U+e040 -#define ICON_FA_TEMPERATURE_EMPTY "\xef\x8b\x8b" // U+f2cb -#define ICON_FA_TEMPERATURE_FULL "\xef\x8b\x87" // U+f2c7 -#define ICON_FA_TEMPERATURE_HALF "\xef\x8b\x89" // U+f2c9 -#define ICON_FA_TEMPERATURE_HIGH "\xef\x9d\xa9" // U+f769 -#define ICON_FA_TEMPERATURE_LOW "\xef\x9d\xab" // U+f76b -#define ICON_FA_TEMPERATURE_QUARTER "\xef\x8b\x8a" // U+f2ca -#define ICON_FA_TEMPERATURE_THREE_QUARTERS "\xef\x8b\x88" // U+f2c8 -#define ICON_FA_TENGE_SIGN "\xef\x9f\x97" // U+f7d7 -#define ICON_FA_TENT "\xee\x95\xbd" // U+e57d -#define ICON_FA_TENT_ARROW_DOWN_TO_LINE "\xee\x95\xbe" // U+e57e -#define ICON_FA_TENT_ARROW_LEFT_RIGHT "\xee\x95\xbf" // U+e57f -#define ICON_FA_TENT_ARROW_TURN_LEFT "\xee\x96\x80" // U+e580 -#define ICON_FA_TENT_ARROWS_DOWN "\xee\x96\x81" // U+e581 -#define ICON_FA_TENTS "\xee\x96\x82" // U+e582 -#define ICON_FA_TERMINAL "\xef\x84\xa0" // U+f120 -#define ICON_FA_TEXT_HEIGHT "\xef\x80\xb4" // U+f034 -#define ICON_FA_TEXT_SLASH "\xef\xa1\xbd" // U+f87d -#define ICON_FA_TEXT_WIDTH "\xef\x80\xb5" // U+f035 -#define ICON_FA_THERMOMETER "\xef\x92\x91" // U+f491 -#define ICON_FA_THUMBS_DOWN "\xef\x85\xa5" // U+f165 -#define ICON_FA_THUMBS_UP "\xef\x85\xa4" // U+f164 -#define ICON_FA_THUMBTACK "\xef\x82\x8d" // U+f08d -#define ICON_FA_TICKET "\xef\x85\x85" // U+f145 -#define ICON_FA_TICKET_SIMPLE "\xef\x8f\xbf" // U+f3ff -#define ICON_FA_TIMELINE "\xee\x8a\x9c" // U+e29c -#define ICON_FA_TOGGLE_OFF "\xef\x88\x84" // U+f204 -#define ICON_FA_TOGGLE_ON "\xef\x88\x85" // U+f205 -#define ICON_FA_TOILET "\xef\x9f\x98" // U+f7d8 -#define ICON_FA_TOILET_PAPER "\xef\x9c\x9e" // U+f71e -#define ICON_FA_TOILET_PAPER_SLASH "\xee\x81\xb2" // U+e072 -#define ICON_FA_TOILET_PORTABLE "\xee\x96\x83" // U+e583 -#define ICON_FA_TOILETS_PORTABLE "\xee\x96\x84" // U+e584 -#define ICON_FA_TOOLBOX "\xef\x95\x92" // U+f552 -#define ICON_FA_TOOTH "\xef\x97\x89" // U+f5c9 -#define ICON_FA_TORII_GATE "\xef\x9a\xa1" // U+f6a1 -#define ICON_FA_TORNADO "\xef\x9d\xaf" // U+f76f -#define ICON_FA_TOWER_BROADCAST "\xef\x94\x99" // U+f519 -#define ICON_FA_TOWER_CELL "\xee\x96\x85" // U+e585 -#define ICON_FA_TOWER_OBSERVATION "\xee\x96\x86" // U+e586 -#define ICON_FA_TRACTOR "\xef\x9c\xa2" // U+f722 -#define ICON_FA_TRADEMARK "\xef\x89\x9c" // U+f25c -#define ICON_FA_TRAFFIC_LIGHT "\xef\x98\xb7" // U+f637 -#define ICON_FA_TRAILER "\xee\x81\x81" // U+e041 -#define ICON_FA_TRAIN "\xef\x88\xb8" // U+f238 -#define ICON_FA_TRAIN_SUBWAY "\xef\x88\xb9" // U+f239 -#define ICON_FA_TRAIN_TRAM "\xef\x9f\x9a" // U+f7da -#define ICON_FA_TRANSGENDER "\xef\x88\xa5" // U+f225 -#define ICON_FA_TRASH "\xef\x87\xb8" // U+f1f8 -#define ICON_FA_TRASH_ARROW_UP "\xef\xa0\xa9" // U+f829 -#define ICON_FA_TRASH_CAN "\xef\x8b\xad" // U+f2ed -#define ICON_FA_TRASH_CAN_ARROW_UP "\xef\xa0\xaa" // U+f82a -#define ICON_FA_TREE "\xef\x86\xbb" // U+f1bb -#define ICON_FA_TREE_CITY "\xee\x96\x87" // U+e587 -#define ICON_FA_TRIANGLE_EXCLAMATION "\xef\x81\xb1" // U+f071 -#define ICON_FA_TROPHY "\xef\x82\x91" // U+f091 -#define ICON_FA_TROWEL "\xee\x96\x89" // U+e589 -#define ICON_FA_TROWEL_BRICKS "\xee\x96\x8a" // U+e58a -#define ICON_FA_TRUCK "\xef\x83\x91" // U+f0d1 -#define ICON_FA_TRUCK_ARROW_RIGHT "\xee\x96\x8b" // U+e58b -#define ICON_FA_TRUCK_DROPLET "\xee\x96\x8c" // U+e58c -#define ICON_FA_TRUCK_FAST "\xef\x92\x8b" // U+f48b -#define ICON_FA_TRUCK_FIELD "\xee\x96\x8d" // U+e58d -#define ICON_FA_TRUCK_FIELD_UN "\xee\x96\x8e" // U+e58e -#define ICON_FA_TRUCK_FRONT "\xee\x8a\xb7" // U+e2b7 -#define ICON_FA_TRUCK_MEDICAL "\xef\x83\xb9" // U+f0f9 -#define ICON_FA_TRUCK_MONSTER "\xef\x98\xbb" // U+f63b -#define ICON_FA_TRUCK_MOVING "\xef\x93\x9f" // U+f4df -#define ICON_FA_TRUCK_PICKUP "\xef\x98\xbc" // U+f63c -#define ICON_FA_TRUCK_PLANE "\xee\x96\x8f" // U+e58f -#define ICON_FA_TRUCK_RAMP_BOX "\xef\x93\x9e" // U+f4de -#define ICON_FA_TTY "\xef\x87\xa4" // U+f1e4 -#define ICON_FA_TURKISH_LIRA_SIGN "\xee\x8a\xbb" // U+e2bb -#define ICON_FA_TURN_DOWN "\xef\x8e\xbe" // U+f3be -#define ICON_FA_TURN_UP "\xef\x8e\xbf" // U+f3bf -#define ICON_FA_TV "\xef\x89\xac" // U+f26c -#define ICON_FA_U "U" // U+0055 -#define ICON_FA_UMBRELLA "\xef\x83\xa9" // U+f0e9 -#define ICON_FA_UMBRELLA_BEACH "\xef\x97\x8a" // U+f5ca -#define ICON_FA_UNDERLINE "\xef\x83\x8d" // U+f0cd -#define ICON_FA_UNIVERSAL_ACCESS "\xef\x8a\x9a" // U+f29a -#define ICON_FA_UNLOCK "\xef\x82\x9c" // U+f09c -#define ICON_FA_UNLOCK_KEYHOLE "\xef\x84\xbe" // U+f13e -#define ICON_FA_UP_DOWN "\xef\x8c\xb8" // U+f338 -#define ICON_FA_UP_DOWN_LEFT_RIGHT "\xef\x82\xb2" // U+f0b2 -#define ICON_FA_UP_LONG "\xef\x8c\x8c" // U+f30c -#define ICON_FA_UP_RIGHT_AND_DOWN_LEFT_FROM_CENTER "\xef\x90\xa4" // U+f424 -#define ICON_FA_UP_RIGHT_FROM_SQUARE "\xef\x8d\x9d" // U+f35d -#define ICON_FA_UPLOAD "\xef\x82\x93" // U+f093 -#define ICON_FA_USER "\xef\x80\x87" // U+f007 -#define ICON_FA_USER_ASTRONAUT "\xef\x93\xbb" // U+f4fb -#define ICON_FA_USER_CHECK "\xef\x93\xbc" // U+f4fc -#define ICON_FA_USER_CLOCK "\xef\x93\xbd" // U+f4fd -#define ICON_FA_USER_DOCTOR "\xef\x83\xb0" // U+f0f0 -#define ICON_FA_USER_GEAR "\xef\x93\xbe" // U+f4fe -#define ICON_FA_USER_GRADUATE "\xef\x94\x81" // U+f501 -#define ICON_FA_USER_GROUP "\xef\x94\x80" // U+f500 -#define ICON_FA_USER_INJURED "\xef\x9c\xa8" // U+f728 -#define ICON_FA_USER_LARGE "\xef\x90\x86" // U+f406 -#define ICON_FA_USER_LARGE_SLASH "\xef\x93\xba" // U+f4fa -#define ICON_FA_USER_LOCK "\xef\x94\x82" // U+f502 -#define ICON_FA_USER_MINUS "\xef\x94\x83" // U+f503 -#define ICON_FA_USER_NINJA "\xef\x94\x84" // U+f504 -#define ICON_FA_USER_NURSE "\xef\xa0\xaf" // U+f82f -#define ICON_FA_USER_PEN "\xef\x93\xbf" // U+f4ff -#define ICON_FA_USER_PLUS "\xef\x88\xb4" // U+f234 -#define ICON_FA_USER_SECRET "\xef\x88\x9b" // U+f21b -#define ICON_FA_USER_SHIELD "\xef\x94\x85" // U+f505 -#define ICON_FA_USER_SLASH "\xef\x94\x86" // U+f506 -#define ICON_FA_USER_TAG "\xef\x94\x87" // U+f507 -#define ICON_FA_USER_TIE "\xef\x94\x88" // U+f508 -#define ICON_FA_USER_XMARK "\xef\x88\xb5" // U+f235 -#define ICON_FA_USERS "\xef\x83\x80" // U+f0c0 -#define ICON_FA_USERS_BETWEEN_LINES "\xee\x96\x91" // U+e591 -#define ICON_FA_USERS_GEAR "\xef\x94\x89" // U+f509 -#define ICON_FA_USERS_LINE "\xee\x96\x92" // U+e592 -#define ICON_FA_USERS_RAYS "\xee\x96\x93" // U+e593 -#define ICON_FA_USERS_RECTANGLE "\xee\x96\x94" // U+e594 -#define ICON_FA_USERS_SLASH "\xee\x81\xb3" // U+e073 -#define ICON_FA_USERS_VIEWFINDER "\xee\x96\x95" // U+e595 -#define ICON_FA_UTENSILS "\xef\x8b\xa7" // U+f2e7 -#define ICON_FA_V "V" // U+0056 -#define ICON_FA_VAN_SHUTTLE "\xef\x96\xb6" // U+f5b6 -#define ICON_FA_VAULT "\xee\x8b\x85" // U+e2c5 -#define ICON_FA_VECTOR_SQUARE "\xef\x97\x8b" // U+f5cb -#define ICON_FA_VENUS "\xef\x88\xa1" // U+f221 -#define ICON_FA_VENUS_DOUBLE "\xef\x88\xa6" // U+f226 -#define ICON_FA_VENUS_MARS "\xef\x88\xa8" // U+f228 -#define ICON_FA_VEST "\xee\x82\x85" // U+e085 -#define ICON_FA_VEST_PATCHES "\xee\x82\x86" // U+e086 -#define ICON_FA_VIAL "\xef\x92\x92" // U+f492 -#define ICON_FA_VIAL_CIRCLE_CHECK "\xee\x96\x96" // U+e596 -#define ICON_FA_VIAL_VIRUS "\xee\x96\x97" // U+e597 -#define ICON_FA_VIALS "\xef\x92\x93" // U+f493 -#define ICON_FA_VIDEO "\xef\x80\xbd" // U+f03d -#define ICON_FA_VIDEO_SLASH "\xef\x93\xa2" // U+f4e2 -#define ICON_FA_VIHARA "\xef\x9a\xa7" // U+f6a7 -#define ICON_FA_VIRUS "\xee\x81\xb4" // U+e074 -#define ICON_FA_VIRUS_COVID "\xee\x92\xa8" // U+e4a8 -#define ICON_FA_VIRUS_COVID_SLASH "\xee\x92\xa9" // U+e4a9 -#define ICON_FA_VIRUS_SLASH "\xee\x81\xb5" // U+e075 -#define ICON_FA_VIRUSES "\xee\x81\xb6" // U+e076 -#define ICON_FA_VOICEMAIL "\xef\xa2\x97" // U+f897 -#define ICON_FA_VOLCANO "\xef\x9d\xb0" // U+f770 -#define ICON_FA_VOLLEYBALL "\xef\x91\x9f" // U+f45f -#define ICON_FA_VOLUME_HIGH "\xef\x80\xa8" // U+f028 -#define ICON_FA_VOLUME_LOW "\xef\x80\xa7" // U+f027 -#define ICON_FA_VOLUME_OFF "\xef\x80\xa6" // U+f026 -#define ICON_FA_VOLUME_XMARK "\xef\x9a\xa9" // U+f6a9 -#define ICON_FA_VR_CARDBOARD "\xef\x9c\xa9" // U+f729 -#define ICON_FA_W "W" // U+0057 -#define ICON_FA_WALKIE_TALKIE "\xef\xa3\xaf" // U+f8ef -#define ICON_FA_WALLET "\xef\x95\x95" // U+f555 -#define ICON_FA_WAND_MAGIC "\xef\x83\x90" // U+f0d0 -#define ICON_FA_WAND_MAGIC_SPARKLES "\xee\x8b\x8a" // U+e2ca -#define ICON_FA_WAND_SPARKLES "\xef\x9c\xab" // U+f72b -#define ICON_FA_WAREHOUSE "\xef\x92\x94" // U+f494 -#define ICON_FA_WATER "\xef\x9d\xb3" // U+f773 -#define ICON_FA_WATER_LADDER "\xef\x97\x85" // U+f5c5 -#define ICON_FA_WAVE_SQUARE "\xef\xa0\xbe" // U+f83e -#define ICON_FA_WEIGHT_HANGING "\xef\x97\x8d" // U+f5cd -#define ICON_FA_WEIGHT_SCALE "\xef\x92\x96" // U+f496 -#define ICON_FA_WHEAT_AWN "\xee\x8b\x8d" // U+e2cd -#define ICON_FA_WHEAT_AWN_CIRCLE_EXCLAMATION "\xee\x96\x98" // U+e598 -#define ICON_FA_WHEELCHAIR "\xef\x86\x93" // U+f193 -#define ICON_FA_WHEELCHAIR_MOVE "\xee\x8b\x8e" // U+e2ce -#define ICON_FA_WHISKEY_GLASS "\xef\x9e\xa0" // U+f7a0 -#define ICON_FA_WIFI "\xef\x87\xab" // U+f1eb -#define ICON_FA_WIND "\xef\x9c\xae" // U+f72e -#define ICON_FA_WINDOW_MAXIMIZE "\xef\x8b\x90" // U+f2d0 -#define ICON_FA_WINDOW_MINIMIZE "\xef\x8b\x91" // U+f2d1 -#define ICON_FA_WINDOW_RESTORE "\xef\x8b\x92" // U+f2d2 -#define ICON_FA_WINE_BOTTLE "\xef\x9c\xaf" // U+f72f -#define ICON_FA_WINE_GLASS "\xef\x93\xa3" // U+f4e3 -#define ICON_FA_WINE_GLASS_EMPTY "\xef\x97\x8e" // U+f5ce -#define ICON_FA_WON_SIGN "\xef\x85\x99" // U+f159 -#define ICON_FA_WORM "\xee\x96\x99" // U+e599 -#define ICON_FA_WRENCH "\xef\x82\xad" // U+f0ad -#define ICON_FA_X "X" // U+0058 -#define ICON_FA_X_RAY "\xef\x92\x97" // U+f497 -#define ICON_FA_XMARK "\xef\x80\x8d" // U+f00d -#define ICON_FA_XMARKS_LINES "\xee\x96\x9a" // U+e59a -#define ICON_FA_Y "Y" // U+0059 -#define ICON_FA_YEN_SIGN "\xef\x85\x97" // U+f157 -#define ICON_FA_YIN_YANG "\xef\x9a\xad" // U+f6ad -#define ICON_FA_Z "Z" // U+005a diff --git a/include/game.hpp b/include/game.hpp deleted file mode 100644 index d59d295..0000000 --- a/include/game.hpp +++ /dev/null @@ -1,45 +0,0 @@ -#ifndef _RPGPP_GAME_H -#define _RPGPP_GAME_H - -class WorldService; - -#include -#include -#include "gamedata.hpp" -#include "stateService.hpp" -#include "worldService.hpp" -#include "interfaceService.hpp" -#include "resourceService.hpp" -#include "soundService.hpp" - -#define RPGPP_VER "0.1" - -class Game { -private: - static Game *instance_; - static std::unique_ptr gameData; - static bool usesBin; - static std::unique_ptr state; - static std::unique_ptr world; - static std::unique_ptr ui; - static std::unique_ptr resources; - static std::unique_ptr sounds; -public: - Game(); - static Game& instance(); - static void useBin(const std::string &filePath); - static GameData& getBin(); - static StateService& getState(); - static WorldService& getWorld(); - static InterfaceService& getUi(); - static ResourceService& getResources(); - static SoundService& getSounds(); - - static void init(); - - static void update(); - static void draw(); - static void unload(); -}; - -#endif diff --git a/include/gamedata.hpp b/include/gamedata.hpp deleted file mode 100644 index b07490e..0000000 --- a/include/gamedata.hpp +++ /dev/null @@ -1,123 +0,0 @@ -#ifndef _RPGPP_GAMEDATA_H -#define _RPGPP_GAMEDATA_H - -#include -#include -#include -#include -#include -#include - -#include "dialogueBalloon.hpp" - -#define RPGPP_DRAW_MULTIPLIER (3) - -struct IVector { - int x; - int y; -}; - -struct IRect { - int x; - int y; - int width; - int height; -}; - -struct ActorBin { - std::string name; - std::string tileSetName; - IRect collision; - std::array, 8> animations; -}; - -struct ActorInRoomBin { - std::string name; - IVector tilePos; -}; - -struct TileBin { - IVector atlasPos; - IVector worldPos; -}; - -struct InteractableBin { - int x; - int y; - int type; - bool onTouch; - std::string dialogue; -}; - -struct PropInRoomBin { - std::string name; - IVector tilePos; - bool onTouch; - std::string dialogue; -}; - -struct TileSetBin { - std::string name; - std::string extension; - IVector tileSize; - std::vector image; - int dataSize; -}; - -struct ImageBin { - std::vector data; - int dataSize; -}; - -struct MusicBin { - std::string relativePath; - bool isSound; -}; - -struct PropBin { - std::string name; - IRect atlasRect; - IRect collisionRect; - std::string imagePath; - bool hasInteractable; - int intType; -}; - -struct RoomBin { - std::string name; - std::string tileSetName; - int width; - int height; - IVector startPoint; - std::vector collisions; - std::vector interactables; - std::vector props; - std::vector actors; - std::vector> tiles; - std::string musicSource; -}; - -struct GameBinSettings { - std::string playerActor; -}; - -struct GameData { - std::string title; - std::map images; - std::map tilesets; - std::vector rooms; - std::vector actors; - std::vector props; - std::map dialogues; - std::map music; -}; - -struct DataSerialization { - std::vector bytes; - int count; -}; - -void serializeDataToFile(std::string fileName, GameData data); -GameData deserializeFile(std::string fileName); - -#endif diff --git a/include/imageRect.hpp b/include/imageRect.hpp deleted file mode 100644 index f18ea59..0000000 --- a/include/imageRect.hpp +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef _RPGPP_IMAGERECT_H -#define _RPGPP_IMAGERECT_H - -#include -#include "uiElement.hpp" -#include - -class ImageRect : public UIElement { -private: - Rectangle rect; - std::string source; - Texture2D texture; -public: - ImageRect(); - ImageRect(Rectangle rect); - void setSource(const std::string &source); - void setTexture(Texture2D texture); - void update(); - void draw(); -}; - -#endif diff --git a/include/imgui/IconsFontAwesome6.h b/include/imgui/IconsFontAwesome6.h deleted file mode 100644 index a56c5f5..0000000 --- a/include/imgui/IconsFontAwesome6.h +++ /dev/null @@ -1,1396 +0,0 @@ -// Generated by https://github.com/juliettef/IconFontCppHeaders script GenerateIconFontCppHeaders.py for languages C and C++ -// from https://github.com/FortAwesome/Font-Awesome/raw/6.x/metadata/icons.yml -// for use with https://github.com/FortAwesome/Font-Awesome/blob/6.x/webfonts/fa-regular-400.ttf, https://github.com/FortAwesome/Font-Awesome/blob/6.x/webfonts/fa-solid-900.ttf -#pragma once - -#define FONT_ICON_FILE_NAME_FAR "fa-regular-400.ttf" -#define FONT_ICON_FILE_NAME_FAS "fa-solid-900.ttf" - -#define ICON_MIN_FA 0xe005 -#define ICON_MAX_16_FA 0xf8ff -#define ICON_MAX_FA 0xf8ff -#define ICON_FA_0 "0" // U+0030 -#define ICON_FA_1 "1" // U+0031 -#define ICON_FA_2 "2" // U+0032 -#define ICON_FA_3 "3" // U+0033 -#define ICON_FA_4 "4" // U+0034 -#define ICON_FA_5 "5" // U+0035 -#define ICON_FA_6 "6" // U+0036 -#define ICON_FA_7 "7" // U+0037 -#define ICON_FA_8 "8" // U+0038 -#define ICON_FA_9 "9" // U+0039 -#define ICON_FA_A "A" // U+0041 -#define ICON_FA_ADDRESS_BOOK "\xef\x8a\xb9" // U+f2b9 -#define ICON_FA_ADDRESS_CARD "\xef\x8a\xbb" // U+f2bb -#define ICON_FA_ALIGN_CENTER "\xef\x80\xb7" // U+f037 -#define ICON_FA_ALIGN_JUSTIFY "\xef\x80\xb9" // U+f039 -#define ICON_FA_ALIGN_LEFT "\xef\x80\xb6" // U+f036 -#define ICON_FA_ALIGN_RIGHT "\xef\x80\xb8" // U+f038 -#define ICON_FA_ANCHOR "\xef\x84\xbd" // U+f13d -#define ICON_FA_ANCHOR_CIRCLE_CHECK "\xee\x92\xaa" // U+e4aa -#define ICON_FA_ANCHOR_CIRCLE_EXCLAMATION "\xee\x92\xab" // U+e4ab -#define ICON_FA_ANCHOR_CIRCLE_XMARK "\xee\x92\xac" // U+e4ac -#define ICON_FA_ANCHOR_LOCK "\xee\x92\xad" // U+e4ad -#define ICON_FA_ANGLE_DOWN "\xef\x84\x87" // U+f107 -#define ICON_FA_ANGLE_LEFT "\xef\x84\x84" // U+f104 -#define ICON_FA_ANGLE_RIGHT "\xef\x84\x85" // U+f105 -#define ICON_FA_ANGLE_UP "\xef\x84\x86" // U+f106 -#define ICON_FA_ANGLES_DOWN "\xef\x84\x83" // U+f103 -#define ICON_FA_ANGLES_LEFT "\xef\x84\x80" // U+f100 -#define ICON_FA_ANGLES_RIGHT "\xef\x84\x81" // U+f101 -#define ICON_FA_ANGLES_UP "\xef\x84\x82" // U+f102 -#define ICON_FA_ANKH "\xef\x99\x84" // U+f644 -#define ICON_FA_APPLE_WHOLE "\xef\x97\x91" // U+f5d1 -#define ICON_FA_ARCHWAY "\xef\x95\x97" // U+f557 -#define ICON_FA_ARROW_DOWN "\xef\x81\xa3" // U+f063 -#define ICON_FA_ARROW_DOWN_1_9 "\xef\x85\xa2" // U+f162 -#define ICON_FA_ARROW_DOWN_9_1 "\xef\xa2\x86" // U+f886 -#define ICON_FA_ARROW_DOWN_A_Z "\xef\x85\x9d" // U+f15d -#define ICON_FA_ARROW_DOWN_LONG "\xef\x85\xb5" // U+f175 -#define ICON_FA_ARROW_DOWN_SHORT_WIDE "\xef\xa2\x84" // U+f884 -#define ICON_FA_ARROW_DOWN_UP_ACROSS_LINE "\xee\x92\xaf" // U+e4af -#define ICON_FA_ARROW_DOWN_UP_LOCK "\xee\x92\xb0" // U+e4b0 -#define ICON_FA_ARROW_DOWN_WIDE_SHORT "\xef\x85\xa0" // U+f160 -#define ICON_FA_ARROW_DOWN_Z_A "\xef\xa2\x81" // U+f881 -#define ICON_FA_ARROW_LEFT "\xef\x81\xa0" // U+f060 -#define ICON_FA_ARROW_LEFT_LONG "\xef\x85\xb7" // U+f177 -#define ICON_FA_ARROW_POINTER "\xef\x89\x85" // U+f245 -#define ICON_FA_ARROW_RIGHT "\xef\x81\xa1" // U+f061 -#define ICON_FA_ARROW_RIGHT_ARROW_LEFT "\xef\x83\xac" // U+f0ec -#define ICON_FA_ARROW_RIGHT_FROM_BRACKET "\xef\x82\x8b" // U+f08b -#define ICON_FA_ARROW_RIGHT_LONG "\xef\x85\xb8" // U+f178 -#define ICON_FA_ARROW_RIGHT_TO_BRACKET "\xef\x82\x90" // U+f090 -#define ICON_FA_ARROW_RIGHT_TO_CITY "\xee\x92\xb3" // U+e4b3 -#define ICON_FA_ARROW_ROTATE_LEFT "\xef\x83\xa2" // U+f0e2 -#define ICON_FA_ARROW_ROTATE_RIGHT "\xef\x80\x9e" // U+f01e -#define ICON_FA_ARROW_TREND_DOWN "\xee\x82\x97" // U+e097 -#define ICON_FA_ARROW_TREND_UP "\xee\x82\x98" // U+e098 -#define ICON_FA_ARROW_TURN_DOWN "\xef\x85\x89" // U+f149 -#define ICON_FA_ARROW_TURN_UP "\xef\x85\x88" // U+f148 -#define ICON_FA_ARROW_UP "\xef\x81\xa2" // U+f062 -#define ICON_FA_ARROW_UP_1_9 "\xef\x85\xa3" // U+f163 -#define ICON_FA_ARROW_UP_9_1 "\xef\xa2\x87" // U+f887 -#define ICON_FA_ARROW_UP_A_Z "\xef\x85\x9e" // U+f15e -#define ICON_FA_ARROW_UP_FROM_BRACKET "\xee\x82\x9a" // U+e09a -#define ICON_FA_ARROW_UP_FROM_GROUND_WATER "\xee\x92\xb5" // U+e4b5 -#define ICON_FA_ARROW_UP_FROM_WATER_PUMP "\xee\x92\xb6" // U+e4b6 -#define ICON_FA_ARROW_UP_LONG "\xef\x85\xb6" // U+f176 -#define ICON_FA_ARROW_UP_RIGHT_DOTS "\xee\x92\xb7" // U+e4b7 -#define ICON_FA_ARROW_UP_RIGHT_FROM_SQUARE "\xef\x82\x8e" // U+f08e -#define ICON_FA_ARROW_UP_SHORT_WIDE "\xef\xa2\x85" // U+f885 -#define ICON_FA_ARROW_UP_WIDE_SHORT "\xef\x85\xa1" // U+f161 -#define ICON_FA_ARROW_UP_Z_A "\xef\xa2\x82" // U+f882 -#define ICON_FA_ARROWS_DOWN_TO_LINE "\xee\x92\xb8" // U+e4b8 -#define ICON_FA_ARROWS_DOWN_TO_PEOPLE "\xee\x92\xb9" // U+e4b9 -#define ICON_FA_ARROWS_LEFT_RIGHT "\xef\x81\xbe" // U+f07e -#define ICON_FA_ARROWS_LEFT_RIGHT_TO_LINE "\xee\x92\xba" // U+e4ba -#define ICON_FA_ARROWS_ROTATE "\xef\x80\xa1" // U+f021 -#define ICON_FA_ARROWS_SPIN "\xee\x92\xbb" // U+e4bb -#define ICON_FA_ARROWS_SPLIT_UP_AND_LEFT "\xee\x92\xbc" // U+e4bc -#define ICON_FA_ARROWS_TO_CIRCLE "\xee\x92\xbd" // U+e4bd -#define ICON_FA_ARROWS_TO_DOT "\xee\x92\xbe" // U+e4be -#define ICON_FA_ARROWS_TO_EYE "\xee\x92\xbf" // U+e4bf -#define ICON_FA_ARROWS_TURN_RIGHT "\xee\x93\x80" // U+e4c0 -#define ICON_FA_ARROWS_TURN_TO_DOTS "\xee\x93\x81" // U+e4c1 -#define ICON_FA_ARROWS_UP_DOWN "\xef\x81\xbd" // U+f07d -#define ICON_FA_ARROWS_UP_DOWN_LEFT_RIGHT "\xef\x81\x87" // U+f047 -#define ICON_FA_ARROWS_UP_TO_LINE "\xee\x93\x82" // U+e4c2 -#define ICON_FA_ASTERISK "*" // U+002a -#define ICON_FA_AT "@" // U+0040 -#define ICON_FA_ATOM "\xef\x97\x92" // U+f5d2 -#define ICON_FA_AUDIO_DESCRIPTION "\xef\x8a\x9e" // U+f29e -#define ICON_FA_AUSTRAL_SIGN "\xee\x82\xa9" // U+e0a9 -#define ICON_FA_AWARD "\xef\x95\x99" // U+f559 -#define ICON_FA_B "B" // U+0042 -#define ICON_FA_BABY "\xef\x9d\xbc" // U+f77c -#define ICON_FA_BABY_CARRIAGE "\xef\x9d\xbd" // U+f77d -#define ICON_FA_BACKWARD "\xef\x81\x8a" // U+f04a -#define ICON_FA_BACKWARD_FAST "\xef\x81\x89" // U+f049 -#define ICON_FA_BACKWARD_STEP "\xef\x81\x88" // U+f048 -#define ICON_FA_BACON "\xef\x9f\xa5" // U+f7e5 -#define ICON_FA_BACTERIA "\xee\x81\x99" // U+e059 -#define ICON_FA_BACTERIUM "\xee\x81\x9a" // U+e05a -#define ICON_FA_BAG_SHOPPING "\xef\x8a\x90" // U+f290 -#define ICON_FA_BAHAI "\xef\x99\xa6" // U+f666 -#define ICON_FA_BAHT_SIGN "\xee\x82\xac" // U+e0ac -#define ICON_FA_BAN "\xef\x81\x9e" // U+f05e -#define ICON_FA_BAN_SMOKING "\xef\x95\x8d" // U+f54d -#define ICON_FA_BANDAGE "\xef\x91\xa2" // U+f462 -#define ICON_FA_BARCODE "\xef\x80\xaa" // U+f02a -#define ICON_FA_BARS "\xef\x83\x89" // U+f0c9 -#define ICON_FA_BARS_PROGRESS "\xef\xa0\xa8" // U+f828 -#define ICON_FA_BARS_STAGGERED "\xef\x95\x90" // U+f550 -#define ICON_FA_BASEBALL "\xef\x90\xb3" // U+f433 -#define ICON_FA_BASEBALL_BAT_BALL "\xef\x90\xb2" // U+f432 -#define ICON_FA_BASKET_SHOPPING "\xef\x8a\x91" // U+f291 -#define ICON_FA_BASKETBALL "\xef\x90\xb4" // U+f434 -#define ICON_FA_BATH "\xef\x8b\x8d" // U+f2cd -#define ICON_FA_BATTERY_EMPTY "\xef\x89\x84" // U+f244 -#define ICON_FA_BATTERY_FULL "\xef\x89\x80" // U+f240 -#define ICON_FA_BATTERY_HALF "\xef\x89\x82" // U+f242 -#define ICON_FA_BATTERY_QUARTER "\xef\x89\x83" // U+f243 -#define ICON_FA_BATTERY_THREE_QUARTERS "\xef\x89\x81" // U+f241 -#define ICON_FA_BED "\xef\x88\xb6" // U+f236 -#define ICON_FA_BED_PULSE "\xef\x92\x87" // U+f487 -#define ICON_FA_BEER_MUG_EMPTY "\xef\x83\xbc" // U+f0fc -#define ICON_FA_BELL "\xef\x83\xb3" // U+f0f3 -#define ICON_FA_BELL_CONCIERGE "\xef\x95\xa2" // U+f562 -#define ICON_FA_BELL_SLASH "\xef\x87\xb6" // U+f1f6 -#define ICON_FA_BEZIER_CURVE "\xef\x95\x9b" // U+f55b -#define ICON_FA_BICYCLE "\xef\x88\x86" // U+f206 -#define ICON_FA_BINOCULARS "\xef\x87\xa5" // U+f1e5 -#define ICON_FA_BIOHAZARD "\xef\x9e\x80" // U+f780 -#define ICON_FA_BITCOIN_SIGN "\xee\x82\xb4" // U+e0b4 -#define ICON_FA_BLENDER "\xef\x94\x97" // U+f517 -#define ICON_FA_BLENDER_PHONE "\xef\x9a\xb6" // U+f6b6 -#define ICON_FA_BLOG "\xef\x9e\x81" // U+f781 -#define ICON_FA_BOLD "\xef\x80\xb2" // U+f032 -#define ICON_FA_BOLT "\xef\x83\xa7" // U+f0e7 -#define ICON_FA_BOLT_LIGHTNING "\xee\x82\xb7" // U+e0b7 -#define ICON_FA_BOMB "\xef\x87\xa2" // U+f1e2 -#define ICON_FA_BONE "\xef\x97\x97" // U+f5d7 -#define ICON_FA_BONG "\xef\x95\x9c" // U+f55c -#define ICON_FA_BOOK "\xef\x80\xad" // U+f02d -#define ICON_FA_BOOK_ATLAS "\xef\x95\x98" // U+f558 -#define ICON_FA_BOOK_BIBLE "\xef\x99\x87" // U+f647 -#define ICON_FA_BOOK_BOOKMARK "\xee\x82\xbb" // U+e0bb -#define ICON_FA_BOOK_JOURNAL_WHILLS "\xef\x99\xaa" // U+f66a -#define ICON_FA_BOOK_MEDICAL "\xef\x9f\xa6" // U+f7e6 -#define ICON_FA_BOOK_OPEN "\xef\x94\x98" // U+f518 -#define ICON_FA_BOOK_OPEN_READER "\xef\x97\x9a" // U+f5da -#define ICON_FA_BOOK_QURAN "\xef\x9a\x87" // U+f687 -#define ICON_FA_BOOK_SKULL "\xef\x9a\xb7" // U+f6b7 -#define ICON_FA_BOOKMARK "\xef\x80\xae" // U+f02e -#define ICON_FA_BORDER_ALL "\xef\xa1\x8c" // U+f84c -#define ICON_FA_BORDER_NONE "\xef\xa1\x90" // U+f850 -#define ICON_FA_BORDER_TOP_LEFT "\xef\xa1\x93" // U+f853 -#define ICON_FA_BORE_HOLE "\xee\x93\x83" // U+e4c3 -#define ICON_FA_BOTTLE_DROPLET "\xee\x93\x84" // U+e4c4 -#define ICON_FA_BOTTLE_WATER "\xee\x93\x85" // U+e4c5 -#define ICON_FA_BOWL_FOOD "\xee\x93\x86" // U+e4c6 -#define ICON_FA_BOWL_RICE "\xee\x8b\xab" // U+e2eb -#define ICON_FA_BOWLING_BALL "\xef\x90\xb6" // U+f436 -#define ICON_FA_BOX "\xef\x91\xa6" // U+f466 -#define ICON_FA_BOX_ARCHIVE "\xef\x86\x87" // U+f187 -#define ICON_FA_BOX_OPEN "\xef\x92\x9e" // U+f49e -#define ICON_FA_BOX_TISSUE "\xee\x81\x9b" // U+e05b -#define ICON_FA_BOXES_PACKING "\xee\x93\x87" // U+e4c7 -#define ICON_FA_BOXES_STACKED "\xef\x91\xa8" // U+f468 -#define ICON_FA_BRAILLE "\xef\x8a\xa1" // U+f2a1 -#define ICON_FA_BRAIN "\xef\x97\x9c" // U+f5dc -#define ICON_FA_BRAZILIAN_REAL_SIGN "\xee\x91\xac" // U+e46c -#define ICON_FA_BREAD_SLICE "\xef\x9f\xac" // U+f7ec -#define ICON_FA_BRIDGE "\xee\x93\x88" // U+e4c8 -#define ICON_FA_BRIDGE_CIRCLE_CHECK "\xee\x93\x89" // U+e4c9 -#define ICON_FA_BRIDGE_CIRCLE_EXCLAMATION "\xee\x93\x8a" // U+e4ca -#define ICON_FA_BRIDGE_CIRCLE_XMARK "\xee\x93\x8b" // U+e4cb -#define ICON_FA_BRIDGE_LOCK "\xee\x93\x8c" // U+e4cc -#define ICON_FA_BRIDGE_WATER "\xee\x93\x8e" // U+e4ce -#define ICON_FA_BRIEFCASE "\xef\x82\xb1" // U+f0b1 -#define ICON_FA_BRIEFCASE_MEDICAL "\xef\x91\xa9" // U+f469 -#define ICON_FA_BROOM "\xef\x94\x9a" // U+f51a -#define ICON_FA_BROOM_BALL "\xef\x91\x98" // U+f458 -#define ICON_FA_BRUSH "\xef\x95\x9d" // U+f55d -#define ICON_FA_BUCKET "\xee\x93\x8f" // U+e4cf -#define ICON_FA_BUG "\xef\x86\x88" // U+f188 -#define ICON_FA_BUG_SLASH "\xee\x92\x90" // U+e490 -#define ICON_FA_BUGS "\xee\x93\x90" // U+e4d0 -#define ICON_FA_BUILDING "\xef\x86\xad" // U+f1ad -#define ICON_FA_BUILDING_CIRCLE_ARROW_RIGHT "\xee\x93\x91" // U+e4d1 -#define ICON_FA_BUILDING_CIRCLE_CHECK "\xee\x93\x92" // U+e4d2 -#define ICON_FA_BUILDING_CIRCLE_EXCLAMATION "\xee\x93\x93" // U+e4d3 -#define ICON_FA_BUILDING_CIRCLE_XMARK "\xee\x93\x94" // U+e4d4 -#define ICON_FA_BUILDING_COLUMNS "\xef\x86\x9c" // U+f19c -#define ICON_FA_BUILDING_FLAG "\xee\x93\x95" // U+e4d5 -#define ICON_FA_BUILDING_LOCK "\xee\x93\x96" // U+e4d6 -#define ICON_FA_BUILDING_NGO "\xee\x93\x97" // U+e4d7 -#define ICON_FA_BUILDING_SHIELD "\xee\x93\x98" // U+e4d8 -#define ICON_FA_BUILDING_UN "\xee\x93\x99" // U+e4d9 -#define ICON_FA_BUILDING_USER "\xee\x93\x9a" // U+e4da -#define ICON_FA_BUILDING_WHEAT "\xee\x93\x9b" // U+e4db -#define ICON_FA_BULLHORN "\xef\x82\xa1" // U+f0a1 -#define ICON_FA_BULLSEYE "\xef\x85\x80" // U+f140 -#define ICON_FA_BURGER "\xef\xa0\x85" // U+f805 -#define ICON_FA_BURST "\xee\x93\x9c" // U+e4dc -#define ICON_FA_BUS "\xef\x88\x87" // U+f207 -#define ICON_FA_BUS_SIMPLE "\xef\x95\x9e" // U+f55e -#define ICON_FA_BUSINESS_TIME "\xef\x99\x8a" // U+f64a -#define ICON_FA_C "C" // U+0043 -#define ICON_FA_CAKE_CANDLES "\xef\x87\xbd" // U+f1fd -#define ICON_FA_CALCULATOR "\xef\x87\xac" // U+f1ec -#define ICON_FA_CALENDAR "\xef\x84\xb3" // U+f133 -#define ICON_FA_CALENDAR_CHECK "\xef\x89\xb4" // U+f274 -#define ICON_FA_CALENDAR_DAY "\xef\x9e\x83" // U+f783 -#define ICON_FA_CALENDAR_DAYS "\xef\x81\xb3" // U+f073 -#define ICON_FA_CALENDAR_MINUS "\xef\x89\xb2" // U+f272 -#define ICON_FA_CALENDAR_PLUS "\xef\x89\xb1" // U+f271 -#define ICON_FA_CALENDAR_WEEK "\xef\x9e\x84" // U+f784 -#define ICON_FA_CALENDAR_XMARK "\xef\x89\xb3" // U+f273 -#define ICON_FA_CAMERA "\xef\x80\xb0" // U+f030 -#define ICON_FA_CAMERA_RETRO "\xef\x82\x83" // U+f083 -#define ICON_FA_CAMERA_ROTATE "\xee\x83\x98" // U+e0d8 -#define ICON_FA_CAMPGROUND "\xef\x9a\xbb" // U+f6bb -#define ICON_FA_CANDY_CANE "\xef\x9e\x86" // U+f786 -#define ICON_FA_CANNABIS "\xef\x95\x9f" // U+f55f -#define ICON_FA_CAPSULES "\xef\x91\xab" // U+f46b -#define ICON_FA_CAR "\xef\x86\xb9" // U+f1b9 -#define ICON_FA_CAR_BATTERY "\xef\x97\x9f" // U+f5df -#define ICON_FA_CAR_BURST "\xef\x97\xa1" // U+f5e1 -#define ICON_FA_CAR_ON "\xee\x93\x9d" // U+e4dd -#define ICON_FA_CAR_REAR "\xef\x97\x9e" // U+f5de -#define ICON_FA_CAR_SIDE "\xef\x97\xa4" // U+f5e4 -#define ICON_FA_CAR_TUNNEL "\xee\x93\x9e" // U+e4de -#define ICON_FA_CARAVAN "\xef\xa3\xbf" // U+f8ff -#define ICON_FA_CARET_DOWN "\xef\x83\x97" // U+f0d7 -#define ICON_FA_CARET_LEFT "\xef\x83\x99" // U+f0d9 -#define ICON_FA_CARET_RIGHT "\xef\x83\x9a" // U+f0da -#define ICON_FA_CARET_UP "\xef\x83\x98" // U+f0d8 -#define ICON_FA_CARROT "\xef\x9e\x87" // U+f787 -#define ICON_FA_CART_ARROW_DOWN "\xef\x88\x98" // U+f218 -#define ICON_FA_CART_FLATBED "\xef\x91\xb4" // U+f474 -#define ICON_FA_CART_FLATBED_SUITCASE "\xef\x96\x9d" // U+f59d -#define ICON_FA_CART_PLUS "\xef\x88\x97" // U+f217 -#define ICON_FA_CART_SHOPPING "\xef\x81\xba" // U+f07a -#define ICON_FA_CASH_REGISTER "\xef\x9e\x88" // U+f788 -#define ICON_FA_CAT "\xef\x9a\xbe" // U+f6be -#define ICON_FA_CEDI_SIGN "\xee\x83\x9f" // U+e0df -#define ICON_FA_CENT_SIGN "\xee\x8f\xb5" // U+e3f5 -#define ICON_FA_CERTIFICATE "\xef\x82\xa3" // U+f0a3 -#define ICON_FA_CHAIR "\xef\x9b\x80" // U+f6c0 -#define ICON_FA_CHALKBOARD "\xef\x94\x9b" // U+f51b -#define ICON_FA_CHALKBOARD_USER "\xef\x94\x9c" // U+f51c -#define ICON_FA_CHAMPAGNE_GLASSES "\xef\x9e\x9f" // U+f79f -#define ICON_FA_CHARGING_STATION "\xef\x97\xa7" // U+f5e7 -#define ICON_FA_CHART_AREA "\xef\x87\xbe" // U+f1fe -#define ICON_FA_CHART_BAR "\xef\x82\x80" // U+f080 -#define ICON_FA_CHART_COLUMN "\xee\x83\xa3" // U+e0e3 -#define ICON_FA_CHART_GANTT "\xee\x83\xa4" // U+e0e4 -#define ICON_FA_CHART_LINE "\xef\x88\x81" // U+f201 -#define ICON_FA_CHART_PIE "\xef\x88\x80" // U+f200 -#define ICON_FA_CHART_SIMPLE "\xee\x91\xb3" // U+e473 -#define ICON_FA_CHECK "\xef\x80\x8c" // U+f00c -#define ICON_FA_CHECK_DOUBLE "\xef\x95\xa0" // U+f560 -#define ICON_FA_CHECK_TO_SLOT "\xef\x9d\xb2" // U+f772 -#define ICON_FA_CHEESE "\xef\x9f\xaf" // U+f7ef -#define ICON_FA_CHESS "\xef\x90\xb9" // U+f439 -#define ICON_FA_CHESS_BISHOP "\xef\x90\xba" // U+f43a -#define ICON_FA_CHESS_BOARD "\xef\x90\xbc" // U+f43c -#define ICON_FA_CHESS_KING "\xef\x90\xbf" // U+f43f -#define ICON_FA_CHESS_KNIGHT "\xef\x91\x81" // U+f441 -#define ICON_FA_CHESS_PAWN "\xef\x91\x83" // U+f443 -#define ICON_FA_CHESS_QUEEN "\xef\x91\x85" // U+f445 -#define ICON_FA_CHESS_ROOK "\xef\x91\x87" // U+f447 -#define ICON_FA_CHEVRON_DOWN "\xef\x81\xb8" // U+f078 -#define ICON_FA_CHEVRON_LEFT "\xef\x81\x93" // U+f053 -#define ICON_FA_CHEVRON_RIGHT "\xef\x81\x94" // U+f054 -#define ICON_FA_CHEVRON_UP "\xef\x81\xb7" // U+f077 -#define ICON_FA_CHILD "\xef\x86\xae" // U+f1ae -#define ICON_FA_CHILD_DRESS "\xee\x96\x9c" // U+e59c -#define ICON_FA_CHILD_REACHING "\xee\x96\x9d" // U+e59d -#define ICON_FA_CHILD_RIFLE "\xee\x93\xa0" // U+e4e0 -#define ICON_FA_CHILDREN "\xee\x93\xa1" // U+e4e1 -#define ICON_FA_CHURCH "\xef\x94\x9d" // U+f51d -#define ICON_FA_CIRCLE "\xef\x84\x91" // U+f111 -#define ICON_FA_CIRCLE_ARROW_DOWN "\xef\x82\xab" // U+f0ab -#define ICON_FA_CIRCLE_ARROW_LEFT "\xef\x82\xa8" // U+f0a8 -#define ICON_FA_CIRCLE_ARROW_RIGHT "\xef\x82\xa9" // U+f0a9 -#define ICON_FA_CIRCLE_ARROW_UP "\xef\x82\xaa" // U+f0aa -#define ICON_FA_CIRCLE_CHECK "\xef\x81\x98" // U+f058 -#define ICON_FA_CIRCLE_CHEVRON_DOWN "\xef\x84\xba" // U+f13a -#define ICON_FA_CIRCLE_CHEVRON_LEFT "\xef\x84\xb7" // U+f137 -#define ICON_FA_CIRCLE_CHEVRON_RIGHT "\xef\x84\xb8" // U+f138 -#define ICON_FA_CIRCLE_CHEVRON_UP "\xef\x84\xb9" // U+f139 -#define ICON_FA_CIRCLE_DOLLAR_TO_SLOT "\xef\x92\xb9" // U+f4b9 -#define ICON_FA_CIRCLE_DOT "\xef\x86\x92" // U+f192 -#define ICON_FA_CIRCLE_DOWN "\xef\x8d\x98" // U+f358 -#define ICON_FA_CIRCLE_EXCLAMATION "\xef\x81\xaa" // U+f06a -#define ICON_FA_CIRCLE_H "\xef\x91\xbe" // U+f47e -#define ICON_FA_CIRCLE_HALF_STROKE "\xef\x81\x82" // U+f042 -#define ICON_FA_CIRCLE_INFO "\xef\x81\x9a" // U+f05a -#define ICON_FA_CIRCLE_LEFT "\xef\x8d\x99" // U+f359 -#define ICON_FA_CIRCLE_MINUS "\xef\x81\x96" // U+f056 -#define ICON_FA_CIRCLE_NODES "\xee\x93\xa2" // U+e4e2 -#define ICON_FA_CIRCLE_NOTCH "\xef\x87\x8e" // U+f1ce -#define ICON_FA_CIRCLE_PAUSE "\xef\x8a\x8b" // U+f28b -#define ICON_FA_CIRCLE_PLAY "\xef\x85\x84" // U+f144 -#define ICON_FA_CIRCLE_PLUS "\xef\x81\x95" // U+f055 -#define ICON_FA_CIRCLE_QUESTION "\xef\x81\x99" // U+f059 -#define ICON_FA_CIRCLE_RADIATION "\xef\x9e\xba" // U+f7ba -#define ICON_FA_CIRCLE_RIGHT "\xef\x8d\x9a" // U+f35a -#define ICON_FA_CIRCLE_STOP "\xef\x8a\x8d" // U+f28d -#define ICON_FA_CIRCLE_UP "\xef\x8d\x9b" // U+f35b -#define ICON_FA_CIRCLE_USER "\xef\x8a\xbd" // U+f2bd -#define ICON_FA_CIRCLE_XMARK "\xef\x81\x97" // U+f057 -#define ICON_FA_CITY "\xef\x99\x8f" // U+f64f -#define ICON_FA_CLAPPERBOARD "\xee\x84\xb1" // U+e131 -#define ICON_FA_CLIPBOARD "\xef\x8c\xa8" // U+f328 -#define ICON_FA_CLIPBOARD_CHECK "\xef\x91\xac" // U+f46c -#define ICON_FA_CLIPBOARD_LIST "\xef\x91\xad" // U+f46d -#define ICON_FA_CLIPBOARD_QUESTION "\xee\x93\xa3" // U+e4e3 -#define ICON_FA_CLIPBOARD_USER "\xef\x9f\xb3" // U+f7f3 -#define ICON_FA_CLOCK "\xef\x80\x97" // U+f017 -#define ICON_FA_CLOCK_ROTATE_LEFT "\xef\x87\x9a" // U+f1da -#define ICON_FA_CLONE "\xef\x89\x8d" // U+f24d -#define ICON_FA_CLOSED_CAPTIONING "\xef\x88\x8a" // U+f20a -#define ICON_FA_CLOUD "\xef\x83\x82" // U+f0c2 -#define ICON_FA_CLOUD_ARROW_DOWN "\xef\x83\xad" // U+f0ed -#define ICON_FA_CLOUD_ARROW_UP "\xef\x83\xae" // U+f0ee -#define ICON_FA_CLOUD_BOLT "\xef\x9d\xac" // U+f76c -#define ICON_FA_CLOUD_MEATBALL "\xef\x9c\xbb" // U+f73b -#define ICON_FA_CLOUD_MOON "\xef\x9b\x83" // U+f6c3 -#define ICON_FA_CLOUD_MOON_RAIN "\xef\x9c\xbc" // U+f73c -#define ICON_FA_CLOUD_RAIN "\xef\x9c\xbd" // U+f73d -#define ICON_FA_CLOUD_SHOWERS_HEAVY "\xef\x9d\x80" // U+f740 -#define ICON_FA_CLOUD_SHOWERS_WATER "\xee\x93\xa4" // U+e4e4 -#define ICON_FA_CLOUD_SUN "\xef\x9b\x84" // U+f6c4 -#define ICON_FA_CLOUD_SUN_RAIN "\xef\x9d\x83" // U+f743 -#define ICON_FA_CLOVER "\xee\x84\xb9" // U+e139 -#define ICON_FA_CODE "\xef\x84\xa1" // U+f121 -#define ICON_FA_CODE_BRANCH "\xef\x84\xa6" // U+f126 -#define ICON_FA_CODE_COMMIT "\xef\x8e\x86" // U+f386 -#define ICON_FA_CODE_COMPARE "\xee\x84\xba" // U+e13a -#define ICON_FA_CODE_FORK "\xee\x84\xbb" // U+e13b -#define ICON_FA_CODE_MERGE "\xef\x8e\x87" // U+f387 -#define ICON_FA_CODE_PULL_REQUEST "\xee\x84\xbc" // U+e13c -#define ICON_FA_COINS "\xef\x94\x9e" // U+f51e -#define ICON_FA_COLON_SIGN "\xee\x85\x80" // U+e140 -#define ICON_FA_COMMENT "\xef\x81\xb5" // U+f075 -#define ICON_FA_COMMENT_DOLLAR "\xef\x99\x91" // U+f651 -#define ICON_FA_COMMENT_DOTS "\xef\x92\xad" // U+f4ad -#define ICON_FA_COMMENT_MEDICAL "\xef\x9f\xb5" // U+f7f5 -#define ICON_FA_COMMENT_SLASH "\xef\x92\xb3" // U+f4b3 -#define ICON_FA_COMMENT_SMS "\xef\x9f\x8d" // U+f7cd -#define ICON_FA_COMMENTS "\xef\x82\x86" // U+f086 -#define ICON_FA_COMMENTS_DOLLAR "\xef\x99\x93" // U+f653 -#define ICON_FA_COMPACT_DISC "\xef\x94\x9f" // U+f51f -#define ICON_FA_COMPASS "\xef\x85\x8e" // U+f14e -#define ICON_FA_COMPASS_DRAFTING "\xef\x95\xa8" // U+f568 -#define ICON_FA_COMPRESS "\xef\x81\xa6" // U+f066 -#define ICON_FA_COMPUTER "\xee\x93\xa5" // U+e4e5 -#define ICON_FA_COMPUTER_MOUSE "\xef\xa3\x8c" // U+f8cc -#define ICON_FA_COOKIE "\xef\x95\xa3" // U+f563 -#define ICON_FA_COOKIE_BITE "\xef\x95\xa4" // U+f564 -#define ICON_FA_COPY "\xef\x83\x85" // U+f0c5 -#define ICON_FA_COPYRIGHT "\xef\x87\xb9" // U+f1f9 -#define ICON_FA_COUCH "\xef\x92\xb8" // U+f4b8 -#define ICON_FA_COW "\xef\x9b\x88" // U+f6c8 -#define ICON_FA_CREDIT_CARD "\xef\x82\x9d" // U+f09d -#define ICON_FA_CROP "\xef\x84\xa5" // U+f125 -#define ICON_FA_CROP_SIMPLE "\xef\x95\xa5" // U+f565 -#define ICON_FA_CROSS "\xef\x99\x94" // U+f654 -#define ICON_FA_CROSSHAIRS "\xef\x81\x9b" // U+f05b -#define ICON_FA_CROW "\xef\x94\xa0" // U+f520 -#define ICON_FA_CROWN "\xef\x94\xa1" // U+f521 -#define ICON_FA_CRUTCH "\xef\x9f\xb7" // U+f7f7 -#define ICON_FA_CRUZEIRO_SIGN "\xee\x85\x92" // U+e152 -#define ICON_FA_CUBE "\xef\x86\xb2" // U+f1b2 -#define ICON_FA_CUBES "\xef\x86\xb3" // U+f1b3 -#define ICON_FA_CUBES_STACKED "\xee\x93\xa6" // U+e4e6 -#define ICON_FA_D "D" // U+0044 -#define ICON_FA_DATABASE "\xef\x87\x80" // U+f1c0 -#define ICON_FA_DELETE_LEFT "\xef\x95\x9a" // U+f55a -#define ICON_FA_DEMOCRAT "\xef\x9d\x87" // U+f747 -#define ICON_FA_DESKTOP "\xef\x8e\x90" // U+f390 -#define ICON_FA_DHARMACHAKRA "\xef\x99\x95" // U+f655 -#define ICON_FA_DIAGRAM_NEXT "\xee\x91\xb6" // U+e476 -#define ICON_FA_DIAGRAM_PREDECESSOR "\xee\x91\xb7" // U+e477 -#define ICON_FA_DIAGRAM_PROJECT "\xef\x95\x82" // U+f542 -#define ICON_FA_DIAGRAM_SUCCESSOR "\xee\x91\xba" // U+e47a -#define ICON_FA_DIAMOND "\xef\x88\x99" // U+f219 -#define ICON_FA_DIAMOND_TURN_RIGHT "\xef\x97\xab" // U+f5eb -#define ICON_FA_DICE "\xef\x94\xa2" // U+f522 -#define ICON_FA_DICE_D20 "\xef\x9b\x8f" // U+f6cf -#define ICON_FA_DICE_D6 "\xef\x9b\x91" // U+f6d1 -#define ICON_FA_DICE_FIVE "\xef\x94\xa3" // U+f523 -#define ICON_FA_DICE_FOUR "\xef\x94\xa4" // U+f524 -#define ICON_FA_DICE_ONE "\xef\x94\xa5" // U+f525 -#define ICON_FA_DICE_SIX "\xef\x94\xa6" // U+f526 -#define ICON_FA_DICE_THREE "\xef\x94\xa7" // U+f527 -#define ICON_FA_DICE_TWO "\xef\x94\xa8" // U+f528 -#define ICON_FA_DISEASE "\xef\x9f\xba" // U+f7fa -#define ICON_FA_DISPLAY "\xee\x85\xa3" // U+e163 -#define ICON_FA_DIVIDE "\xef\x94\xa9" // U+f529 -#define ICON_FA_DNA "\xef\x91\xb1" // U+f471 -#define ICON_FA_DOG "\xef\x9b\x93" // U+f6d3 -#define ICON_FA_DOLLAR_SIGN "$" // U+0024 -#define ICON_FA_DOLLY "\xef\x91\xb2" // U+f472 -#define ICON_FA_DONG_SIGN "\xee\x85\xa9" // U+e169 -#define ICON_FA_DOOR_CLOSED "\xef\x94\xaa" // U+f52a -#define ICON_FA_DOOR_OPEN "\xef\x94\xab" // U+f52b -#define ICON_FA_DOVE "\xef\x92\xba" // U+f4ba -#define ICON_FA_DOWN_LEFT_AND_UP_RIGHT_TO_CENTER "\xef\x90\xa2" // U+f422 -#define ICON_FA_DOWN_LONG "\xef\x8c\x89" // U+f309 -#define ICON_FA_DOWNLOAD "\xef\x80\x99" // U+f019 -#define ICON_FA_DRAGON "\xef\x9b\x95" // U+f6d5 -#define ICON_FA_DRAW_POLYGON "\xef\x97\xae" // U+f5ee -#define ICON_FA_DROPLET "\xef\x81\x83" // U+f043 -#define ICON_FA_DROPLET_SLASH "\xef\x97\x87" // U+f5c7 -#define ICON_FA_DRUM "\xef\x95\xa9" // U+f569 -#define ICON_FA_DRUM_STEELPAN "\xef\x95\xaa" // U+f56a -#define ICON_FA_DRUMSTICK_BITE "\xef\x9b\x97" // U+f6d7 -#define ICON_FA_DUMBBELL "\xef\x91\x8b" // U+f44b -#define ICON_FA_DUMPSTER "\xef\x9e\x93" // U+f793 -#define ICON_FA_DUMPSTER_FIRE "\xef\x9e\x94" // U+f794 -#define ICON_FA_DUNGEON "\xef\x9b\x99" // U+f6d9 -#define ICON_FA_E "E" // U+0045 -#define ICON_FA_EAR_DEAF "\xef\x8a\xa4" // U+f2a4 -#define ICON_FA_EAR_LISTEN "\xef\x8a\xa2" // U+f2a2 -#define ICON_FA_EARTH_AFRICA "\xef\x95\xbc" // U+f57c -#define ICON_FA_EARTH_AMERICAS "\xef\x95\xbd" // U+f57d -#define ICON_FA_EARTH_ASIA "\xef\x95\xbe" // U+f57e -#define ICON_FA_EARTH_EUROPE "\xef\x9e\xa2" // U+f7a2 -#define ICON_FA_EARTH_OCEANIA "\xee\x91\xbb" // U+e47b -#define ICON_FA_EGG "\xef\x9f\xbb" // U+f7fb -#define ICON_FA_EJECT "\xef\x81\x92" // U+f052 -#define ICON_FA_ELEVATOR "\xee\x85\xad" // U+e16d -#define ICON_FA_ELLIPSIS "\xef\x85\x81" // U+f141 -#define ICON_FA_ELLIPSIS_VERTICAL "\xef\x85\x82" // U+f142 -#define ICON_FA_ENVELOPE "\xef\x83\xa0" // U+f0e0 -#define ICON_FA_ENVELOPE_CIRCLE_CHECK "\xee\x93\xa8" // U+e4e8 -#define ICON_FA_ENVELOPE_OPEN "\xef\x8a\xb6" // U+f2b6 -#define ICON_FA_ENVELOPE_OPEN_TEXT "\xef\x99\x98" // U+f658 -#define ICON_FA_ENVELOPES_BULK "\xef\x99\xb4" // U+f674 -#define ICON_FA_EQUALS "=" // U+003d -#define ICON_FA_ERASER "\xef\x84\xad" // U+f12d -#define ICON_FA_ETHERNET "\xef\x9e\x96" // U+f796 -#define ICON_FA_EURO_SIGN "\xef\x85\x93" // U+f153 -#define ICON_FA_EXCLAMATION "!" // U+0021 -#define ICON_FA_EXPAND "\xef\x81\xa5" // U+f065 -#define ICON_FA_EXPLOSION "\xee\x93\xa9" // U+e4e9 -#define ICON_FA_EYE "\xef\x81\xae" // U+f06e -#define ICON_FA_EYE_DROPPER "\xef\x87\xbb" // U+f1fb -#define ICON_FA_EYE_LOW_VISION "\xef\x8a\xa8" // U+f2a8 -#define ICON_FA_EYE_SLASH "\xef\x81\xb0" // U+f070 -#define ICON_FA_F "F" // U+0046 -#define ICON_FA_FACE_ANGRY "\xef\x95\x96" // U+f556 -#define ICON_FA_FACE_DIZZY "\xef\x95\xa7" // U+f567 -#define ICON_FA_FACE_FLUSHED "\xef\x95\xb9" // U+f579 -#define ICON_FA_FACE_FROWN "\xef\x84\x99" // U+f119 -#define ICON_FA_FACE_FROWN_OPEN "\xef\x95\xba" // U+f57a -#define ICON_FA_FACE_GRIMACE "\xef\x95\xbf" // U+f57f -#define ICON_FA_FACE_GRIN "\xef\x96\x80" // U+f580 -#define ICON_FA_FACE_GRIN_BEAM "\xef\x96\x82" // U+f582 -#define ICON_FA_FACE_GRIN_BEAM_SWEAT "\xef\x96\x83" // U+f583 -#define ICON_FA_FACE_GRIN_HEARTS "\xef\x96\x84" // U+f584 -#define ICON_FA_FACE_GRIN_SQUINT "\xef\x96\x85" // U+f585 -#define ICON_FA_FACE_GRIN_SQUINT_TEARS "\xef\x96\x86" // U+f586 -#define ICON_FA_FACE_GRIN_STARS "\xef\x96\x87" // U+f587 -#define ICON_FA_FACE_GRIN_TEARS "\xef\x96\x88" // U+f588 -#define ICON_FA_FACE_GRIN_TONGUE "\xef\x96\x89" // U+f589 -#define ICON_FA_FACE_GRIN_TONGUE_SQUINT "\xef\x96\x8a" // U+f58a -#define ICON_FA_FACE_GRIN_TONGUE_WINK "\xef\x96\x8b" // U+f58b -#define ICON_FA_FACE_GRIN_WIDE "\xef\x96\x81" // U+f581 -#define ICON_FA_FACE_GRIN_WINK "\xef\x96\x8c" // U+f58c -#define ICON_FA_FACE_KISS "\xef\x96\x96" // U+f596 -#define ICON_FA_FACE_KISS_BEAM "\xef\x96\x97" // U+f597 -#define ICON_FA_FACE_KISS_WINK_HEART "\xef\x96\x98" // U+f598 -#define ICON_FA_FACE_LAUGH "\xef\x96\x99" // U+f599 -#define ICON_FA_FACE_LAUGH_BEAM "\xef\x96\x9a" // U+f59a -#define ICON_FA_FACE_LAUGH_SQUINT "\xef\x96\x9b" // U+f59b -#define ICON_FA_FACE_LAUGH_WINK "\xef\x96\x9c" // U+f59c -#define ICON_FA_FACE_MEH "\xef\x84\x9a" // U+f11a -#define ICON_FA_FACE_MEH_BLANK "\xef\x96\xa4" // U+f5a4 -#define ICON_FA_FACE_ROLLING_EYES "\xef\x96\xa5" // U+f5a5 -#define ICON_FA_FACE_SAD_CRY "\xef\x96\xb3" // U+f5b3 -#define ICON_FA_FACE_SAD_TEAR "\xef\x96\xb4" // U+f5b4 -#define ICON_FA_FACE_SMILE "\xef\x84\x98" // U+f118 -#define ICON_FA_FACE_SMILE_BEAM "\xef\x96\xb8" // U+f5b8 -#define ICON_FA_FACE_SMILE_WINK "\xef\x93\x9a" // U+f4da -#define ICON_FA_FACE_SURPRISE "\xef\x97\x82" // U+f5c2 -#define ICON_FA_FACE_TIRED "\xef\x97\x88" // U+f5c8 -#define ICON_FA_FAN "\xef\xa1\xa3" // U+f863 -#define ICON_FA_FAUCET "\xee\x80\x85" // U+e005 -#define ICON_FA_FAUCET_DRIP "\xee\x80\x86" // U+e006 -#define ICON_FA_FAX "\xef\x86\xac" // U+f1ac -#define ICON_FA_FEATHER "\xef\x94\xad" // U+f52d -#define ICON_FA_FEATHER_POINTED "\xef\x95\xab" // U+f56b -#define ICON_FA_FERRY "\xee\x93\xaa" // U+e4ea -#define ICON_FA_FILE "\xef\x85\x9b" // U+f15b -#define ICON_FA_FILE_ARROW_DOWN "\xef\x95\xad" // U+f56d -#define ICON_FA_FILE_ARROW_UP "\xef\x95\xb4" // U+f574 -#define ICON_FA_FILE_AUDIO "\xef\x87\x87" // U+f1c7 -#define ICON_FA_FILE_CIRCLE_CHECK "\xee\x92\x93" // U+e493 -#define ICON_FA_FILE_CIRCLE_EXCLAMATION "\xee\x93\xab" // U+e4eb -#define ICON_FA_FILE_CIRCLE_MINUS "\xee\x93\xad" // U+e4ed -#define ICON_FA_FILE_CIRCLE_PLUS "\xee\x93\xae" // U+e4ee -#define ICON_FA_FILE_CIRCLE_QUESTION "\xee\x93\xaf" // U+e4ef -#define ICON_FA_FILE_CIRCLE_XMARK "\xee\x92\x94" // U+e494 -#define ICON_FA_FILE_CODE "\xef\x87\x89" // U+f1c9 -#define ICON_FA_FILE_CONTRACT "\xef\x95\xac" // U+f56c -#define ICON_FA_FILE_CSV "\xef\x9b\x9d" // U+f6dd -#define ICON_FA_FILE_EXCEL "\xef\x87\x83" // U+f1c3 -#define ICON_FA_FILE_EXPORT "\xef\x95\xae" // U+f56e -#define ICON_FA_FILE_IMAGE "\xef\x87\x85" // U+f1c5 -#define ICON_FA_FILE_IMPORT "\xef\x95\xaf" // U+f56f -#define ICON_FA_FILE_INVOICE "\xef\x95\xb0" // U+f570 -#define ICON_FA_FILE_INVOICE_DOLLAR "\xef\x95\xb1" // U+f571 -#define ICON_FA_FILE_LINES "\xef\x85\x9c" // U+f15c -#define ICON_FA_FILE_MEDICAL "\xef\x91\xb7" // U+f477 -#define ICON_FA_FILE_PDF "\xef\x87\x81" // U+f1c1 -#define ICON_FA_FILE_PEN "\xef\x8c\x9c" // U+f31c -#define ICON_FA_FILE_POWERPOINT "\xef\x87\x84" // U+f1c4 -#define ICON_FA_FILE_PRESCRIPTION "\xef\x95\xb2" // U+f572 -#define ICON_FA_FILE_SHIELD "\xee\x93\xb0" // U+e4f0 -#define ICON_FA_FILE_SIGNATURE "\xef\x95\xb3" // U+f573 -#define ICON_FA_FILE_VIDEO "\xef\x87\x88" // U+f1c8 -#define ICON_FA_FILE_WAVEFORM "\xef\x91\xb8" // U+f478 -#define ICON_FA_FILE_WORD "\xef\x87\x82" // U+f1c2 -#define ICON_FA_FILE_ZIPPER "\xef\x87\x86" // U+f1c6 -#define ICON_FA_FILL "\xef\x95\xb5" // U+f575 -#define ICON_FA_FILL_DRIP "\xef\x95\xb6" // U+f576 -#define ICON_FA_FILM "\xef\x80\x88" // U+f008 -#define ICON_FA_FILTER "\xef\x82\xb0" // U+f0b0 -#define ICON_FA_FILTER_CIRCLE_DOLLAR "\xef\x99\xa2" // U+f662 -#define ICON_FA_FILTER_CIRCLE_XMARK "\xee\x85\xbb" // U+e17b -#define ICON_FA_FINGERPRINT "\xef\x95\xb7" // U+f577 -#define ICON_FA_FIRE "\xef\x81\xad" // U+f06d -#define ICON_FA_FIRE_BURNER "\xee\x93\xb1" // U+e4f1 -#define ICON_FA_FIRE_EXTINGUISHER "\xef\x84\xb4" // U+f134 -#define ICON_FA_FIRE_FLAME_CURVED "\xef\x9f\xa4" // U+f7e4 -#define ICON_FA_FIRE_FLAME_SIMPLE "\xef\x91\xaa" // U+f46a -#define ICON_FA_FISH "\xef\x95\xb8" // U+f578 -#define ICON_FA_FISH_FINS "\xee\x93\xb2" // U+e4f2 -#define ICON_FA_FLAG "\xef\x80\xa4" // U+f024 -#define ICON_FA_FLAG_CHECKERED "\xef\x84\x9e" // U+f11e -#define ICON_FA_FLAG_USA "\xef\x9d\x8d" // U+f74d -#define ICON_FA_FLASK "\xef\x83\x83" // U+f0c3 -#define ICON_FA_FLASK_VIAL "\xee\x93\xb3" // U+e4f3 -#define ICON_FA_FLOPPY_DISK "\xef\x83\x87" // U+f0c7 -#define ICON_FA_FLORIN_SIGN "\xee\x86\x84" // U+e184 -#define ICON_FA_FOLDER "\xef\x81\xbb" // U+f07b -#define ICON_FA_FOLDER_CLOSED "\xee\x86\x85" // U+e185 -#define ICON_FA_FOLDER_MINUS "\xef\x99\x9d" // U+f65d -#define ICON_FA_FOLDER_OPEN "\xef\x81\xbc" // U+f07c -#define ICON_FA_FOLDER_PLUS "\xef\x99\x9e" // U+f65e -#define ICON_FA_FOLDER_TREE "\xef\xa0\x82" // U+f802 -#define ICON_FA_FONT "\xef\x80\xb1" // U+f031 -#define ICON_FA_FONT_AWESOME "\xef\x8a\xb4" // U+f2b4 -#define ICON_FA_FOOTBALL "\xef\x91\x8e" // U+f44e -#define ICON_FA_FORWARD "\xef\x81\x8e" // U+f04e -#define ICON_FA_FORWARD_FAST "\xef\x81\x90" // U+f050 -#define ICON_FA_FORWARD_STEP "\xef\x81\x91" // U+f051 -#define ICON_FA_FRANC_SIGN "\xee\x86\x8f" // U+e18f -#define ICON_FA_FROG "\xef\x94\xae" // U+f52e -#define ICON_FA_FUTBOL "\xef\x87\xa3" // U+f1e3 -#define ICON_FA_G "G" // U+0047 -#define ICON_FA_GAMEPAD "\xef\x84\x9b" // U+f11b -#define ICON_FA_GAS_PUMP "\xef\x94\xaf" // U+f52f -#define ICON_FA_GAUGE "\xef\x98\xa4" // U+f624 -#define ICON_FA_GAUGE_HIGH "\xef\x98\xa5" // U+f625 -#define ICON_FA_GAUGE_SIMPLE "\xef\x98\xa9" // U+f629 -#define ICON_FA_GAUGE_SIMPLE_HIGH "\xef\x98\xaa" // U+f62a -#define ICON_FA_GAVEL "\xef\x83\xa3" // U+f0e3 -#define ICON_FA_GEAR "\xef\x80\x93" // U+f013 -#define ICON_FA_GEARS "\xef\x82\x85" // U+f085 -#define ICON_FA_GEM "\xef\x8e\xa5" // U+f3a5 -#define ICON_FA_GENDERLESS "\xef\x88\xad" // U+f22d -#define ICON_FA_GHOST "\xef\x9b\xa2" // U+f6e2 -#define ICON_FA_GIFT "\xef\x81\xab" // U+f06b -#define ICON_FA_GIFTS "\xef\x9e\x9c" // U+f79c -#define ICON_FA_GLASS_WATER "\xee\x93\xb4" // U+e4f4 -#define ICON_FA_GLASS_WATER_DROPLET "\xee\x93\xb5" // U+e4f5 -#define ICON_FA_GLASSES "\xef\x94\xb0" // U+f530 -#define ICON_FA_GLOBE "\xef\x82\xac" // U+f0ac -#define ICON_FA_GOLF_BALL_TEE "\xef\x91\x90" // U+f450 -#define ICON_FA_GOPURAM "\xef\x99\xa4" // U+f664 -#define ICON_FA_GRADUATION_CAP "\xef\x86\x9d" // U+f19d -#define ICON_FA_GREATER_THAN ">" // U+003e -#define ICON_FA_GREATER_THAN_EQUAL "\xef\x94\xb2" // U+f532 -#define ICON_FA_GRIP "\xef\x96\x8d" // U+f58d -#define ICON_FA_GRIP_LINES "\xef\x9e\xa4" // U+f7a4 -#define ICON_FA_GRIP_LINES_VERTICAL "\xef\x9e\xa5" // U+f7a5 -#define ICON_FA_GRIP_VERTICAL "\xef\x96\x8e" // U+f58e -#define ICON_FA_GROUP_ARROWS_ROTATE "\xee\x93\xb6" // U+e4f6 -#define ICON_FA_GUARANI_SIGN "\xee\x86\x9a" // U+e19a -#define ICON_FA_GUITAR "\xef\x9e\xa6" // U+f7a6 -#define ICON_FA_GUN "\xee\x86\x9b" // U+e19b -#define ICON_FA_H "H" // U+0048 -#define ICON_FA_HAMMER "\xef\x9b\xa3" // U+f6e3 -#define ICON_FA_HAMSA "\xef\x99\xa5" // U+f665 -#define ICON_FA_HAND "\xef\x89\x96" // U+f256 -#define ICON_FA_HAND_BACK_FIST "\xef\x89\x95" // U+f255 -#define ICON_FA_HAND_DOTS "\xef\x91\xa1" // U+f461 -#define ICON_FA_HAND_FIST "\xef\x9b\x9e" // U+f6de -#define ICON_FA_HAND_HOLDING "\xef\x92\xbd" // U+f4bd -#define ICON_FA_HAND_HOLDING_DOLLAR "\xef\x93\x80" // U+f4c0 -#define ICON_FA_HAND_HOLDING_DROPLET "\xef\x93\x81" // U+f4c1 -#define ICON_FA_HAND_HOLDING_HAND "\xee\x93\xb7" // U+e4f7 -#define ICON_FA_HAND_HOLDING_HEART "\xef\x92\xbe" // U+f4be -#define ICON_FA_HAND_HOLDING_MEDICAL "\xee\x81\x9c" // U+e05c -#define ICON_FA_HAND_LIZARD "\xef\x89\x98" // U+f258 -#define ICON_FA_HAND_MIDDLE_FINGER "\xef\xa0\x86" // U+f806 -#define ICON_FA_HAND_PEACE "\xef\x89\x9b" // U+f25b -#define ICON_FA_HAND_POINT_DOWN "\xef\x82\xa7" // U+f0a7 -#define ICON_FA_HAND_POINT_LEFT "\xef\x82\xa5" // U+f0a5 -#define ICON_FA_HAND_POINT_RIGHT "\xef\x82\xa4" // U+f0a4 -#define ICON_FA_HAND_POINT_UP "\xef\x82\xa6" // U+f0a6 -#define ICON_FA_HAND_POINTER "\xef\x89\x9a" // U+f25a -#define ICON_FA_HAND_SCISSORS "\xef\x89\x97" // U+f257 -#define ICON_FA_HAND_SPARKLES "\xee\x81\x9d" // U+e05d -#define ICON_FA_HAND_SPOCK "\xef\x89\x99" // U+f259 -#define ICON_FA_HANDCUFFS "\xee\x93\xb8" // U+e4f8 -#define ICON_FA_HANDS "\xef\x8a\xa7" // U+f2a7 -#define ICON_FA_HANDS_ASL_INTERPRETING "\xef\x8a\xa3" // U+f2a3 -#define ICON_FA_HANDS_BOUND "\xee\x93\xb9" // U+e4f9 -#define ICON_FA_HANDS_BUBBLES "\xee\x81\x9e" // U+e05e -#define ICON_FA_HANDS_CLAPPING "\xee\x86\xa8" // U+e1a8 -#define ICON_FA_HANDS_HOLDING "\xef\x93\x82" // U+f4c2 -#define ICON_FA_HANDS_HOLDING_CHILD "\xee\x93\xba" // U+e4fa -#define ICON_FA_HANDS_HOLDING_CIRCLE "\xee\x93\xbb" // U+e4fb -#define ICON_FA_HANDS_PRAYING "\xef\x9a\x84" // U+f684 -#define ICON_FA_HANDSHAKE "\xef\x8a\xb5" // U+f2b5 -#define ICON_FA_HANDSHAKE_ANGLE "\xef\x93\x84" // U+f4c4 -#define ICON_FA_HANDSHAKE_SIMPLE "\xef\x93\x86" // U+f4c6 -#define ICON_FA_HANDSHAKE_SIMPLE_SLASH "\xee\x81\x9f" // U+e05f -#define ICON_FA_HANDSHAKE_SLASH "\xee\x81\xa0" // U+e060 -#define ICON_FA_HANUKIAH "\xef\x9b\xa6" // U+f6e6 -#define ICON_FA_HARD_DRIVE "\xef\x82\xa0" // U+f0a0 -#define ICON_FA_HASHTAG "#" // U+0023 -#define ICON_FA_HAT_COWBOY "\xef\xa3\x80" // U+f8c0 -#define ICON_FA_HAT_COWBOY_SIDE "\xef\xa3\x81" // U+f8c1 -#define ICON_FA_HAT_WIZARD "\xef\x9b\xa8" // U+f6e8 -#define ICON_FA_HEAD_SIDE_COUGH "\xee\x81\xa1" // U+e061 -#define ICON_FA_HEAD_SIDE_COUGH_SLASH "\xee\x81\xa2" // U+e062 -#define ICON_FA_HEAD_SIDE_MASK "\xee\x81\xa3" // U+e063 -#define ICON_FA_HEAD_SIDE_VIRUS "\xee\x81\xa4" // U+e064 -#define ICON_FA_HEADING "\xef\x87\x9c" // U+f1dc -#define ICON_FA_HEADPHONES "\xef\x80\xa5" // U+f025 -#define ICON_FA_HEADPHONES_SIMPLE "\xef\x96\x8f" // U+f58f -#define ICON_FA_HEADSET "\xef\x96\x90" // U+f590 -#define ICON_FA_HEART "\xef\x80\x84" // U+f004 -#define ICON_FA_HEART_CIRCLE_BOLT "\xee\x93\xbc" // U+e4fc -#define ICON_FA_HEART_CIRCLE_CHECK "\xee\x93\xbd" // U+e4fd -#define ICON_FA_HEART_CIRCLE_EXCLAMATION "\xee\x93\xbe" // U+e4fe -#define ICON_FA_HEART_CIRCLE_MINUS "\xee\x93\xbf" // U+e4ff -#define ICON_FA_HEART_CIRCLE_PLUS "\xee\x94\x80" // U+e500 -#define ICON_FA_HEART_CIRCLE_XMARK "\xee\x94\x81" // U+e501 -#define ICON_FA_HEART_CRACK "\xef\x9e\xa9" // U+f7a9 -#define ICON_FA_HEART_PULSE "\xef\x88\x9e" // U+f21e -#define ICON_FA_HELICOPTER "\xef\x94\xb3" // U+f533 -#define ICON_FA_HELICOPTER_SYMBOL "\xee\x94\x82" // U+e502 -#define ICON_FA_HELMET_SAFETY "\xef\xa0\x87" // U+f807 -#define ICON_FA_HELMET_UN "\xee\x94\x83" // U+e503 -#define ICON_FA_HIGHLIGHTER "\xef\x96\x91" // U+f591 -#define ICON_FA_HILL_AVALANCHE "\xee\x94\x87" // U+e507 -#define ICON_FA_HILL_ROCKSLIDE "\xee\x94\x88" // U+e508 -#define ICON_FA_HIPPO "\xef\x9b\xad" // U+f6ed -#define ICON_FA_HOCKEY_PUCK "\xef\x91\x93" // U+f453 -#define ICON_FA_HOLLY_BERRY "\xef\x9e\xaa" // U+f7aa -#define ICON_FA_HORSE "\xef\x9b\xb0" // U+f6f0 -#define ICON_FA_HORSE_HEAD "\xef\x9e\xab" // U+f7ab -#define ICON_FA_HOSPITAL "\xef\x83\xb8" // U+f0f8 -#define ICON_FA_HOSPITAL_USER "\xef\xa0\x8d" // U+f80d -#define ICON_FA_HOT_TUB_PERSON "\xef\x96\x93" // U+f593 -#define ICON_FA_HOTDOG "\xef\xa0\x8f" // U+f80f -#define ICON_FA_HOTEL "\xef\x96\x94" // U+f594 -#define ICON_FA_HOURGLASS "\xef\x89\x94" // U+f254 -#define ICON_FA_HOURGLASS_EMPTY "\xef\x89\x92" // U+f252 -#define ICON_FA_HOURGLASS_END "\xef\x89\x93" // U+f253 -#define ICON_FA_HOURGLASS_START "\xef\x89\x91" // U+f251 -#define ICON_FA_HOUSE "\xef\x80\x95" // U+f015 -#define ICON_FA_HOUSE_CHIMNEY "\xee\x8e\xaf" // U+e3af -#define ICON_FA_HOUSE_CHIMNEY_CRACK "\xef\x9b\xb1" // U+f6f1 -#define ICON_FA_HOUSE_CHIMNEY_MEDICAL "\xef\x9f\xb2" // U+f7f2 -#define ICON_FA_HOUSE_CHIMNEY_USER "\xee\x81\xa5" // U+e065 -#define ICON_FA_HOUSE_CHIMNEY_WINDOW "\xee\x80\x8d" // U+e00d -#define ICON_FA_HOUSE_CIRCLE_CHECK "\xee\x94\x89" // U+e509 -#define ICON_FA_HOUSE_CIRCLE_EXCLAMATION "\xee\x94\x8a" // U+e50a -#define ICON_FA_HOUSE_CIRCLE_XMARK "\xee\x94\x8b" // U+e50b -#define ICON_FA_HOUSE_CRACK "\xee\x8e\xb1" // U+e3b1 -#define ICON_FA_HOUSE_FIRE "\xee\x94\x8c" // U+e50c -#define ICON_FA_HOUSE_FLAG "\xee\x94\x8d" // U+e50d -#define ICON_FA_HOUSE_FLOOD_WATER "\xee\x94\x8e" // U+e50e -#define ICON_FA_HOUSE_FLOOD_WATER_CIRCLE_ARROW_RIGHT "\xee\x94\x8f" // U+e50f -#define ICON_FA_HOUSE_LAPTOP "\xee\x81\xa6" // U+e066 -#define ICON_FA_HOUSE_LOCK "\xee\x94\x90" // U+e510 -#define ICON_FA_HOUSE_MEDICAL "\xee\x8e\xb2" // U+e3b2 -#define ICON_FA_HOUSE_MEDICAL_CIRCLE_CHECK "\xee\x94\x91" // U+e511 -#define ICON_FA_HOUSE_MEDICAL_CIRCLE_EXCLAMATION "\xee\x94\x92" // U+e512 -#define ICON_FA_HOUSE_MEDICAL_CIRCLE_XMARK "\xee\x94\x93" // U+e513 -#define ICON_FA_HOUSE_MEDICAL_FLAG "\xee\x94\x94" // U+e514 -#define ICON_FA_HOUSE_SIGNAL "\xee\x80\x92" // U+e012 -#define ICON_FA_HOUSE_TSUNAMI "\xee\x94\x95" // U+e515 -#define ICON_FA_HOUSE_USER "\xee\x86\xb0" // U+e1b0 -#define ICON_FA_HRYVNIA_SIGN "\xef\x9b\xb2" // U+f6f2 -#define ICON_FA_HURRICANE "\xef\x9d\x91" // U+f751 -#define ICON_FA_I "I" // U+0049 -#define ICON_FA_I_CURSOR "\xef\x89\x86" // U+f246 -#define ICON_FA_ICE_CREAM "\xef\xa0\x90" // U+f810 -#define ICON_FA_ICICLES "\xef\x9e\xad" // U+f7ad -#define ICON_FA_ICONS "\xef\xa1\xad" // U+f86d -#define ICON_FA_ID_BADGE "\xef\x8b\x81" // U+f2c1 -#define ICON_FA_ID_CARD "\xef\x8b\x82" // U+f2c2 -#define ICON_FA_ID_CARD_CLIP "\xef\x91\xbf" // U+f47f -#define ICON_FA_IGLOO "\xef\x9e\xae" // U+f7ae -#define ICON_FA_IMAGE "\xef\x80\xbe" // U+f03e -#define ICON_FA_IMAGE_PORTRAIT "\xef\x8f\xa0" // U+f3e0 -#define ICON_FA_IMAGES "\xef\x8c\x82" // U+f302 -#define ICON_FA_INBOX "\xef\x80\x9c" // U+f01c -#define ICON_FA_INDENT "\xef\x80\xbc" // U+f03c -#define ICON_FA_INDIAN_RUPEE_SIGN "\xee\x86\xbc" // U+e1bc -#define ICON_FA_INDUSTRY "\xef\x89\xb5" // U+f275 -#define ICON_FA_INFINITY "\xef\x94\xb4" // U+f534 -#define ICON_FA_INFO "\xef\x84\xa9" // U+f129 -#define ICON_FA_ITALIC "\xef\x80\xb3" // U+f033 -#define ICON_FA_J "J" // U+004a -#define ICON_FA_JAR "\xee\x94\x96" // U+e516 -#define ICON_FA_JAR_WHEAT "\xee\x94\x97" // U+e517 -#define ICON_FA_JEDI "\xef\x99\xa9" // U+f669 -#define ICON_FA_JET_FIGHTER "\xef\x83\xbb" // U+f0fb -#define ICON_FA_JET_FIGHTER_UP "\xee\x94\x98" // U+e518 -#define ICON_FA_JOINT "\xef\x96\x95" // U+f595 -#define ICON_FA_JUG_DETERGENT "\xee\x94\x99" // U+e519 -#define ICON_FA_K "K" // U+004b -#define ICON_FA_KAABA "\xef\x99\xab" // U+f66b -#define ICON_FA_KEY "\xef\x82\x84" // U+f084 -#define ICON_FA_KEYBOARD "\xef\x84\x9c" // U+f11c -#define ICON_FA_KHANDA "\xef\x99\xad" // U+f66d -#define ICON_FA_KIP_SIGN "\xee\x87\x84" // U+e1c4 -#define ICON_FA_KIT_MEDICAL "\xef\x91\xb9" // U+f479 -#define ICON_FA_KITCHEN_SET "\xee\x94\x9a" // U+e51a -#define ICON_FA_KIWI_BIRD "\xef\x94\xb5" // U+f535 -#define ICON_FA_L "L" // U+004c -#define ICON_FA_LAND_MINE_ON "\xee\x94\x9b" // U+e51b -#define ICON_FA_LANDMARK "\xef\x99\xaf" // U+f66f -#define ICON_FA_LANDMARK_DOME "\xef\x9d\x92" // U+f752 -#define ICON_FA_LANDMARK_FLAG "\xee\x94\x9c" // U+e51c -#define ICON_FA_LANGUAGE "\xef\x86\xab" // U+f1ab -#define ICON_FA_LAPTOP "\xef\x84\x89" // U+f109 -#define ICON_FA_LAPTOP_CODE "\xef\x97\xbc" // U+f5fc -#define ICON_FA_LAPTOP_FILE "\xee\x94\x9d" // U+e51d -#define ICON_FA_LAPTOP_MEDICAL "\xef\xa0\x92" // U+f812 -#define ICON_FA_LARI_SIGN "\xee\x87\x88" // U+e1c8 -#define ICON_FA_LAYER_GROUP "\xef\x97\xbd" // U+f5fd -#define ICON_FA_LEAF "\xef\x81\xac" // U+f06c -#define ICON_FA_LEFT_LONG "\xef\x8c\x8a" // U+f30a -#define ICON_FA_LEFT_RIGHT "\xef\x8c\xb7" // U+f337 -#define ICON_FA_LEMON "\xef\x82\x94" // U+f094 -#define ICON_FA_LESS_THAN "<" // U+003c -#define ICON_FA_LESS_THAN_EQUAL "\xef\x94\xb7" // U+f537 -#define ICON_FA_LIFE_RING "\xef\x87\x8d" // U+f1cd -#define ICON_FA_LIGHTBULB "\xef\x83\xab" // U+f0eb -#define ICON_FA_LINES_LEANING "\xee\x94\x9e" // U+e51e -#define ICON_FA_LINK "\xef\x83\x81" // U+f0c1 -#define ICON_FA_LINK_SLASH "\xef\x84\xa7" // U+f127 -#define ICON_FA_LIRA_SIGN "\xef\x86\x95" // U+f195 -#define ICON_FA_LIST "\xef\x80\xba" // U+f03a -#define ICON_FA_LIST_CHECK "\xef\x82\xae" // U+f0ae -#define ICON_FA_LIST_OL "\xef\x83\x8b" // U+f0cb -#define ICON_FA_LIST_UL "\xef\x83\x8a" // U+f0ca -#define ICON_FA_LITECOIN_SIGN "\xee\x87\x93" // U+e1d3 -#define ICON_FA_LOCATION_ARROW "\xef\x84\xa4" // U+f124 -#define ICON_FA_LOCATION_CROSSHAIRS "\xef\x98\x81" // U+f601 -#define ICON_FA_LOCATION_DOT "\xef\x8f\x85" // U+f3c5 -#define ICON_FA_LOCATION_PIN "\xef\x81\x81" // U+f041 -#define ICON_FA_LOCATION_PIN_LOCK "\xee\x94\x9f" // U+e51f -#define ICON_FA_LOCK "\xef\x80\xa3" // U+f023 -#define ICON_FA_LOCK_OPEN "\xef\x8f\x81" // U+f3c1 -#define ICON_FA_LOCUST "\xee\x94\xa0" // U+e520 -#define ICON_FA_LUNGS "\xef\x98\x84" // U+f604 -#define ICON_FA_LUNGS_VIRUS "\xee\x81\xa7" // U+e067 -#define ICON_FA_M "M" // U+004d -#define ICON_FA_MAGNET "\xef\x81\xb6" // U+f076 -#define ICON_FA_MAGNIFYING_GLASS "\xef\x80\x82" // U+f002 -#define ICON_FA_MAGNIFYING_GLASS_ARROW_RIGHT "\xee\x94\xa1" // U+e521 -#define ICON_FA_MAGNIFYING_GLASS_CHART "\xee\x94\xa2" // U+e522 -#define ICON_FA_MAGNIFYING_GLASS_DOLLAR "\xef\x9a\x88" // U+f688 -#define ICON_FA_MAGNIFYING_GLASS_LOCATION "\xef\x9a\x89" // U+f689 -#define ICON_FA_MAGNIFYING_GLASS_MINUS "\xef\x80\x90" // U+f010 -#define ICON_FA_MAGNIFYING_GLASS_PLUS "\xef\x80\x8e" // U+f00e -#define ICON_FA_MANAT_SIGN "\xee\x87\x95" // U+e1d5 -#define ICON_FA_MAP "\xef\x89\xb9" // U+f279 -#define ICON_FA_MAP_LOCATION "\xef\x96\x9f" // U+f59f -#define ICON_FA_MAP_LOCATION_DOT "\xef\x96\xa0" // U+f5a0 -#define ICON_FA_MAP_PIN "\xef\x89\xb6" // U+f276 -#define ICON_FA_MARKER "\xef\x96\xa1" // U+f5a1 -#define ICON_FA_MARS "\xef\x88\xa2" // U+f222 -#define ICON_FA_MARS_AND_VENUS "\xef\x88\xa4" // U+f224 -#define ICON_FA_MARS_AND_VENUS_BURST "\xee\x94\xa3" // U+e523 -#define ICON_FA_MARS_DOUBLE "\xef\x88\xa7" // U+f227 -#define ICON_FA_MARS_STROKE "\xef\x88\xa9" // U+f229 -#define ICON_FA_MARS_STROKE_RIGHT "\xef\x88\xab" // U+f22b -#define ICON_FA_MARS_STROKE_UP "\xef\x88\xaa" // U+f22a -#define ICON_FA_MARTINI_GLASS "\xef\x95\xbb" // U+f57b -#define ICON_FA_MARTINI_GLASS_CITRUS "\xef\x95\xa1" // U+f561 -#define ICON_FA_MARTINI_GLASS_EMPTY "\xef\x80\x80" // U+f000 -#define ICON_FA_MASK "\xef\x9b\xba" // U+f6fa -#define ICON_FA_MASK_FACE "\xee\x87\x97" // U+e1d7 -#define ICON_FA_MASK_VENTILATOR "\xee\x94\xa4" // U+e524 -#define ICON_FA_MASKS_THEATER "\xef\x98\xb0" // U+f630 -#define ICON_FA_MATTRESS_PILLOW "\xee\x94\xa5" // U+e525 -#define ICON_FA_MAXIMIZE "\xef\x8c\x9e" // U+f31e -#define ICON_FA_MEDAL "\xef\x96\xa2" // U+f5a2 -#define ICON_FA_MEMORY "\xef\x94\xb8" // U+f538 -#define ICON_FA_MENORAH "\xef\x99\xb6" // U+f676 -#define ICON_FA_MERCURY "\xef\x88\xa3" // U+f223 -#define ICON_FA_MESSAGE "\xef\x89\xba" // U+f27a -#define ICON_FA_METEOR "\xef\x9d\x93" // U+f753 -#define ICON_FA_MICROCHIP "\xef\x8b\x9b" // U+f2db -#define ICON_FA_MICROPHONE "\xef\x84\xb0" // U+f130 -#define ICON_FA_MICROPHONE_LINES "\xef\x8f\x89" // U+f3c9 -#define ICON_FA_MICROPHONE_LINES_SLASH "\xef\x94\xb9" // U+f539 -#define ICON_FA_MICROPHONE_SLASH "\xef\x84\xb1" // U+f131 -#define ICON_FA_MICROSCOPE "\xef\x98\x90" // U+f610 -#define ICON_FA_MILL_SIGN "\xee\x87\xad" // U+e1ed -#define ICON_FA_MINIMIZE "\xef\x9e\x8c" // U+f78c -#define ICON_FA_MINUS "\xef\x81\xa8" // U+f068 -#define ICON_FA_MITTEN "\xef\x9e\xb5" // U+f7b5 -#define ICON_FA_MOBILE "\xef\x8f\x8e" // U+f3ce -#define ICON_FA_MOBILE_BUTTON "\xef\x84\x8b" // U+f10b -#define ICON_FA_MOBILE_RETRO "\xee\x94\xa7" // U+e527 -#define ICON_FA_MOBILE_SCREEN "\xef\x8f\x8f" // U+f3cf -#define ICON_FA_MOBILE_SCREEN_BUTTON "\xef\x8f\x8d" // U+f3cd -#define ICON_FA_MONEY_BILL "\xef\x83\x96" // U+f0d6 -#define ICON_FA_MONEY_BILL_1 "\xef\x8f\x91" // U+f3d1 -#define ICON_FA_MONEY_BILL_1_WAVE "\xef\x94\xbb" // U+f53b -#define ICON_FA_MONEY_BILL_TRANSFER "\xee\x94\xa8" // U+e528 -#define ICON_FA_MONEY_BILL_TREND_UP "\xee\x94\xa9" // U+e529 -#define ICON_FA_MONEY_BILL_WAVE "\xef\x94\xba" // U+f53a -#define ICON_FA_MONEY_BILL_WHEAT "\xee\x94\xaa" // U+e52a -#define ICON_FA_MONEY_BILLS "\xee\x87\xb3" // U+e1f3 -#define ICON_FA_MONEY_CHECK "\xef\x94\xbc" // U+f53c -#define ICON_FA_MONEY_CHECK_DOLLAR "\xef\x94\xbd" // U+f53d -#define ICON_FA_MONUMENT "\xef\x96\xa6" // U+f5a6 -#define ICON_FA_MOON "\xef\x86\x86" // U+f186 -#define ICON_FA_MORTAR_PESTLE "\xef\x96\xa7" // U+f5a7 -#define ICON_FA_MOSQUE "\xef\x99\xb8" // U+f678 -#define ICON_FA_MOSQUITO "\xee\x94\xab" // U+e52b -#define ICON_FA_MOSQUITO_NET "\xee\x94\xac" // U+e52c -#define ICON_FA_MOTORCYCLE "\xef\x88\x9c" // U+f21c -#define ICON_FA_MOUND "\xee\x94\xad" // U+e52d -#define ICON_FA_MOUNTAIN "\xef\x9b\xbc" // U+f6fc -#define ICON_FA_MOUNTAIN_CITY "\xee\x94\xae" // U+e52e -#define ICON_FA_MOUNTAIN_SUN "\xee\x94\xaf" // U+e52f -#define ICON_FA_MUG_HOT "\xef\x9e\xb6" // U+f7b6 -#define ICON_FA_MUG_SAUCER "\xef\x83\xb4" // U+f0f4 -#define ICON_FA_MUSIC "\xef\x80\x81" // U+f001 -#define ICON_FA_N "N" // U+004e -#define ICON_FA_NAIRA_SIGN "\xee\x87\xb6" // U+e1f6 -#define ICON_FA_NETWORK_WIRED "\xef\x9b\xbf" // U+f6ff -#define ICON_FA_NEUTER "\xef\x88\xac" // U+f22c -#define ICON_FA_NEWSPAPER "\xef\x87\xaa" // U+f1ea -#define ICON_FA_NOT_EQUAL "\xef\x94\xbe" // U+f53e -#define ICON_FA_NOTE_STICKY "\xef\x89\x89" // U+f249 -#define ICON_FA_NOTES_MEDICAL "\xef\x92\x81" // U+f481 -#define ICON_FA_O "O" // U+004f -#define ICON_FA_OBJECT_GROUP "\xef\x89\x87" // U+f247 -#define ICON_FA_OBJECT_UNGROUP "\xef\x89\x88" // U+f248 -#define ICON_FA_OIL_CAN "\xef\x98\x93" // U+f613 -#define ICON_FA_OIL_WELL "\xee\x94\xb2" // U+e532 -#define ICON_FA_OM "\xef\x99\xb9" // U+f679 -#define ICON_FA_OTTER "\xef\x9c\x80" // U+f700 -#define ICON_FA_OUTDENT "\xef\x80\xbb" // U+f03b -#define ICON_FA_P "P" // U+0050 -#define ICON_FA_PAGER "\xef\xa0\x95" // U+f815 -#define ICON_FA_PAINT_ROLLER "\xef\x96\xaa" // U+f5aa -#define ICON_FA_PAINTBRUSH "\xef\x87\xbc" // U+f1fc -#define ICON_FA_PALETTE "\xef\x94\xbf" // U+f53f -#define ICON_FA_PALLET "\xef\x92\x82" // U+f482 -#define ICON_FA_PANORAMA "\xee\x88\x89" // U+e209 -#define ICON_FA_PAPER_PLANE "\xef\x87\x98" // U+f1d8 -#define ICON_FA_PAPERCLIP "\xef\x83\x86" // U+f0c6 -#define ICON_FA_PARACHUTE_BOX "\xef\x93\x8d" // U+f4cd -#define ICON_FA_PARAGRAPH "\xef\x87\x9d" // U+f1dd -#define ICON_FA_PASSPORT "\xef\x96\xab" // U+f5ab -#define ICON_FA_PASTE "\xef\x83\xaa" // U+f0ea -#define ICON_FA_PAUSE "\xef\x81\x8c" // U+f04c -#define ICON_FA_PAW "\xef\x86\xb0" // U+f1b0 -#define ICON_FA_PEACE "\xef\x99\xbc" // U+f67c -#define ICON_FA_PEN "\xef\x8c\x84" // U+f304 -#define ICON_FA_PEN_CLIP "\xef\x8c\x85" // U+f305 -#define ICON_FA_PEN_FANCY "\xef\x96\xac" // U+f5ac -#define ICON_FA_PEN_NIB "\xef\x96\xad" // U+f5ad -#define ICON_FA_PEN_RULER "\xef\x96\xae" // U+f5ae -#define ICON_FA_PEN_TO_SQUARE "\xef\x81\x84" // U+f044 -#define ICON_FA_PENCIL "\xef\x8c\x83" // U+f303 -#define ICON_FA_PEOPLE_ARROWS_LEFT_RIGHT "\xee\x81\xa8" // U+e068 -#define ICON_FA_PEOPLE_CARRY_BOX "\xef\x93\x8e" // U+f4ce -#define ICON_FA_PEOPLE_GROUP "\xee\x94\xb3" // U+e533 -#define ICON_FA_PEOPLE_LINE "\xee\x94\xb4" // U+e534 -#define ICON_FA_PEOPLE_PULLING "\xee\x94\xb5" // U+e535 -#define ICON_FA_PEOPLE_ROBBERY "\xee\x94\xb6" // U+e536 -#define ICON_FA_PEOPLE_ROOF "\xee\x94\xb7" // U+e537 -#define ICON_FA_PEPPER_HOT "\xef\xa0\x96" // U+f816 -#define ICON_FA_PERCENT "%" // U+0025 -#define ICON_FA_PERSON "\xef\x86\x83" // U+f183 -#define ICON_FA_PERSON_ARROW_DOWN_TO_LINE "\xee\x94\xb8" // U+e538 -#define ICON_FA_PERSON_ARROW_UP_FROM_LINE "\xee\x94\xb9" // U+e539 -#define ICON_FA_PERSON_BIKING "\xef\xa1\x8a" // U+f84a -#define ICON_FA_PERSON_BOOTH "\xef\x9d\x96" // U+f756 -#define ICON_FA_PERSON_BREASTFEEDING "\xee\x94\xba" // U+e53a -#define ICON_FA_PERSON_BURST "\xee\x94\xbb" // U+e53b -#define ICON_FA_PERSON_CANE "\xee\x94\xbc" // U+e53c -#define ICON_FA_PERSON_CHALKBOARD "\xee\x94\xbd" // U+e53d -#define ICON_FA_PERSON_CIRCLE_CHECK "\xee\x94\xbe" // U+e53e -#define ICON_FA_PERSON_CIRCLE_EXCLAMATION "\xee\x94\xbf" // U+e53f -#define ICON_FA_PERSON_CIRCLE_MINUS "\xee\x95\x80" // U+e540 -#define ICON_FA_PERSON_CIRCLE_PLUS "\xee\x95\x81" // U+e541 -#define ICON_FA_PERSON_CIRCLE_QUESTION "\xee\x95\x82" // U+e542 -#define ICON_FA_PERSON_CIRCLE_XMARK "\xee\x95\x83" // U+e543 -#define ICON_FA_PERSON_DIGGING "\xef\xa1\x9e" // U+f85e -#define ICON_FA_PERSON_DOTS_FROM_LINE "\xef\x91\xb0" // U+f470 -#define ICON_FA_PERSON_DRESS "\xef\x86\x82" // U+f182 -#define ICON_FA_PERSON_DRESS_BURST "\xee\x95\x84" // U+e544 -#define ICON_FA_PERSON_DROWNING "\xee\x95\x85" // U+e545 -#define ICON_FA_PERSON_FALLING "\xee\x95\x86" // U+e546 -#define ICON_FA_PERSON_FALLING_BURST "\xee\x95\x87" // U+e547 -#define ICON_FA_PERSON_HALF_DRESS "\xee\x95\x88" // U+e548 -#define ICON_FA_PERSON_HARASSING "\xee\x95\x89" // U+e549 -#define ICON_FA_PERSON_HIKING "\xef\x9b\xac" // U+f6ec -#define ICON_FA_PERSON_MILITARY_POINTING "\xee\x95\x8a" // U+e54a -#define ICON_FA_PERSON_MILITARY_RIFLE "\xee\x95\x8b" // U+e54b -#define ICON_FA_PERSON_MILITARY_TO_PERSON "\xee\x95\x8c" // U+e54c -#define ICON_FA_PERSON_PRAYING "\xef\x9a\x83" // U+f683 -#define ICON_FA_PERSON_PREGNANT "\xee\x8c\x9e" // U+e31e -#define ICON_FA_PERSON_RAYS "\xee\x95\x8d" // U+e54d -#define ICON_FA_PERSON_RIFLE "\xee\x95\x8e" // U+e54e -#define ICON_FA_PERSON_RUNNING "\xef\x9c\x8c" // U+f70c -#define ICON_FA_PERSON_SHELTER "\xee\x95\x8f" // U+e54f -#define ICON_FA_PERSON_SKATING "\xef\x9f\x85" // U+f7c5 -#define ICON_FA_PERSON_SKIING "\xef\x9f\x89" // U+f7c9 -#define ICON_FA_PERSON_SKIING_NORDIC "\xef\x9f\x8a" // U+f7ca -#define ICON_FA_PERSON_SNOWBOARDING "\xef\x9f\x8e" // U+f7ce -#define ICON_FA_PERSON_SWIMMING "\xef\x97\x84" // U+f5c4 -#define ICON_FA_PERSON_THROUGH_WINDOW "\xee\x90\xb3" // U+e433 -#define ICON_FA_PERSON_WALKING "\xef\x95\x94" // U+f554 -#define ICON_FA_PERSON_WALKING_ARROW_LOOP_LEFT "\xee\x95\x91" // U+e551 -#define ICON_FA_PERSON_WALKING_ARROW_RIGHT "\xee\x95\x92" // U+e552 -#define ICON_FA_PERSON_WALKING_DASHED_LINE_ARROW_RIGHT "\xee\x95\x93" // U+e553 -#define ICON_FA_PERSON_WALKING_LUGGAGE "\xee\x95\x94" // U+e554 -#define ICON_FA_PERSON_WALKING_WITH_CANE "\xef\x8a\x9d" // U+f29d -#define ICON_FA_PESETA_SIGN "\xee\x88\xa1" // U+e221 -#define ICON_FA_PESO_SIGN "\xee\x88\xa2" // U+e222 -#define ICON_FA_PHONE "\xef\x82\x95" // U+f095 -#define ICON_FA_PHONE_FLIP "\xef\xa1\xb9" // U+f879 -#define ICON_FA_PHONE_SLASH "\xef\x8f\x9d" // U+f3dd -#define ICON_FA_PHONE_VOLUME "\xef\x8a\xa0" // U+f2a0 -#define ICON_FA_PHOTO_FILM "\xef\xa1\xbc" // U+f87c -#define ICON_FA_PIGGY_BANK "\xef\x93\x93" // U+f4d3 -#define ICON_FA_PILLS "\xef\x92\x84" // U+f484 -#define ICON_FA_PIZZA_SLICE "\xef\xa0\x98" // U+f818 -#define ICON_FA_PLACE_OF_WORSHIP "\xef\x99\xbf" // U+f67f -#define ICON_FA_PLANE "\xef\x81\xb2" // U+f072 -#define ICON_FA_PLANE_ARRIVAL "\xef\x96\xaf" // U+f5af -#define ICON_FA_PLANE_CIRCLE_CHECK "\xee\x95\x95" // U+e555 -#define ICON_FA_PLANE_CIRCLE_EXCLAMATION "\xee\x95\x96" // U+e556 -#define ICON_FA_PLANE_CIRCLE_XMARK "\xee\x95\x97" // U+e557 -#define ICON_FA_PLANE_DEPARTURE "\xef\x96\xb0" // U+f5b0 -#define ICON_FA_PLANE_LOCK "\xee\x95\x98" // U+e558 -#define ICON_FA_PLANE_SLASH "\xee\x81\xa9" // U+e069 -#define ICON_FA_PLANE_UP "\xee\x88\xad" // U+e22d -#define ICON_FA_PLANT_WILT "\xee\x90\xbb" // U+e43b -#define ICON_FA_PLATE_WHEAT "\xee\x95\x9a" // U+e55a -#define ICON_FA_PLAY "\xef\x81\x8b" // U+f04b -#define ICON_FA_PLUG "\xef\x87\xa6" // U+f1e6 -#define ICON_FA_PLUG_CIRCLE_BOLT "\xee\x95\x9b" // U+e55b -#define ICON_FA_PLUG_CIRCLE_CHECK "\xee\x95\x9c" // U+e55c -#define ICON_FA_PLUG_CIRCLE_EXCLAMATION "\xee\x95\x9d" // U+e55d -#define ICON_FA_PLUG_CIRCLE_MINUS "\xee\x95\x9e" // U+e55e -#define ICON_FA_PLUG_CIRCLE_PLUS "\xee\x95\x9f" // U+e55f -#define ICON_FA_PLUG_CIRCLE_XMARK "\xee\x95\xa0" // U+e560 -#define ICON_FA_PLUS "+" // U+002b -#define ICON_FA_PLUS_MINUS "\xee\x90\xbc" // U+e43c -#define ICON_FA_PODCAST "\xef\x8b\x8e" // U+f2ce -#define ICON_FA_POO "\xef\x8b\xbe" // U+f2fe -#define ICON_FA_POO_STORM "\xef\x9d\x9a" // U+f75a -#define ICON_FA_POOP "\xef\x98\x99" // U+f619 -#define ICON_FA_POWER_OFF "\xef\x80\x91" // U+f011 -#define ICON_FA_PRESCRIPTION "\xef\x96\xb1" // U+f5b1 -#define ICON_FA_PRESCRIPTION_BOTTLE "\xef\x92\x85" // U+f485 -#define ICON_FA_PRESCRIPTION_BOTTLE_MEDICAL "\xef\x92\x86" // U+f486 -#define ICON_FA_PRINT "\xef\x80\xaf" // U+f02f -#define ICON_FA_PUMP_MEDICAL "\xee\x81\xaa" // U+e06a -#define ICON_FA_PUMP_SOAP "\xee\x81\xab" // U+e06b -#define ICON_FA_PUZZLE_PIECE "\xef\x84\xae" // U+f12e -#define ICON_FA_Q "Q" // U+0051 -#define ICON_FA_QRCODE "\xef\x80\xa9" // U+f029 -#define ICON_FA_QUESTION "?" // U+003f -#define ICON_FA_QUOTE_LEFT "\xef\x84\x8d" // U+f10d -#define ICON_FA_QUOTE_RIGHT "\xef\x84\x8e" // U+f10e -#define ICON_FA_R "R" // U+0052 -#define ICON_FA_RADIATION "\xef\x9e\xb9" // U+f7b9 -#define ICON_FA_RADIO "\xef\xa3\x97" // U+f8d7 -#define ICON_FA_RAINBOW "\xef\x9d\x9b" // U+f75b -#define ICON_FA_RANKING_STAR "\xee\x95\xa1" // U+e561 -#define ICON_FA_RECEIPT "\xef\x95\x83" // U+f543 -#define ICON_FA_RECORD_VINYL "\xef\xa3\x99" // U+f8d9 -#define ICON_FA_RECTANGLE_AD "\xef\x99\x81" // U+f641 -#define ICON_FA_RECTANGLE_LIST "\xef\x80\xa2" // U+f022 -#define ICON_FA_RECTANGLE_XMARK "\xef\x90\x90" // U+f410 -#define ICON_FA_RECYCLE "\xef\x86\xb8" // U+f1b8 -#define ICON_FA_REGISTERED "\xef\x89\x9d" // U+f25d -#define ICON_FA_REPEAT "\xef\x8d\xa3" // U+f363 -#define ICON_FA_REPLY "\xef\x8f\xa5" // U+f3e5 -#define ICON_FA_REPLY_ALL "\xef\x84\xa2" // U+f122 -#define ICON_FA_REPUBLICAN "\xef\x9d\x9e" // U+f75e -#define ICON_FA_RESTROOM "\xef\x9e\xbd" // U+f7bd -#define ICON_FA_RETWEET "\xef\x81\xb9" // U+f079 -#define ICON_FA_RIBBON "\xef\x93\x96" // U+f4d6 -#define ICON_FA_RIGHT_FROM_BRACKET "\xef\x8b\xb5" // U+f2f5 -#define ICON_FA_RIGHT_LEFT "\xef\x8d\xa2" // U+f362 -#define ICON_FA_RIGHT_LONG "\xef\x8c\x8b" // U+f30b -#define ICON_FA_RIGHT_TO_BRACKET "\xef\x8b\xb6" // U+f2f6 -#define ICON_FA_RING "\xef\x9c\x8b" // U+f70b -#define ICON_FA_ROAD "\xef\x80\x98" // U+f018 -#define ICON_FA_ROAD_BARRIER "\xee\x95\xa2" // U+e562 -#define ICON_FA_ROAD_BRIDGE "\xee\x95\xa3" // U+e563 -#define ICON_FA_ROAD_CIRCLE_CHECK "\xee\x95\xa4" // U+e564 -#define ICON_FA_ROAD_CIRCLE_EXCLAMATION "\xee\x95\xa5" // U+e565 -#define ICON_FA_ROAD_CIRCLE_XMARK "\xee\x95\xa6" // U+e566 -#define ICON_FA_ROAD_LOCK "\xee\x95\xa7" // U+e567 -#define ICON_FA_ROAD_SPIKES "\xee\x95\xa8" // U+e568 -#define ICON_FA_ROBOT "\xef\x95\x84" // U+f544 -#define ICON_FA_ROCKET "\xef\x84\xb5" // U+f135 -#define ICON_FA_ROTATE "\xef\x8b\xb1" // U+f2f1 -#define ICON_FA_ROTATE_LEFT "\xef\x8b\xaa" // U+f2ea -#define ICON_FA_ROTATE_RIGHT "\xef\x8b\xb9" // U+f2f9 -#define ICON_FA_ROUTE "\xef\x93\x97" // U+f4d7 -#define ICON_FA_RSS "\xef\x82\x9e" // U+f09e -#define ICON_FA_RUBLE_SIGN "\xef\x85\x98" // U+f158 -#define ICON_FA_RUG "\xee\x95\xa9" // U+e569 -#define ICON_FA_RULER "\xef\x95\x85" // U+f545 -#define ICON_FA_RULER_COMBINED "\xef\x95\x86" // U+f546 -#define ICON_FA_RULER_HORIZONTAL "\xef\x95\x87" // U+f547 -#define ICON_FA_RULER_VERTICAL "\xef\x95\x88" // U+f548 -#define ICON_FA_RUPEE_SIGN "\xef\x85\x96" // U+f156 -#define ICON_FA_RUPIAH_SIGN "\xee\x88\xbd" // U+e23d -#define ICON_FA_S "S" // U+0053 -#define ICON_FA_SACK_DOLLAR "\xef\xa0\x9d" // U+f81d -#define ICON_FA_SACK_XMARK "\xee\x95\xaa" // U+e56a -#define ICON_FA_SAILBOAT "\xee\x91\x85" // U+e445 -#define ICON_FA_SATELLITE "\xef\x9e\xbf" // U+f7bf -#define ICON_FA_SATELLITE_DISH "\xef\x9f\x80" // U+f7c0 -#define ICON_FA_SCALE_BALANCED "\xef\x89\x8e" // U+f24e -#define ICON_FA_SCALE_UNBALANCED "\xef\x94\x95" // U+f515 -#define ICON_FA_SCALE_UNBALANCED_FLIP "\xef\x94\x96" // U+f516 -#define ICON_FA_SCHOOL "\xef\x95\x89" // U+f549 -#define ICON_FA_SCHOOL_CIRCLE_CHECK "\xee\x95\xab" // U+e56b -#define ICON_FA_SCHOOL_CIRCLE_EXCLAMATION "\xee\x95\xac" // U+e56c -#define ICON_FA_SCHOOL_CIRCLE_XMARK "\xee\x95\xad" // U+e56d -#define ICON_FA_SCHOOL_FLAG "\xee\x95\xae" // U+e56e -#define ICON_FA_SCHOOL_LOCK "\xee\x95\xaf" // U+e56f -#define ICON_FA_SCISSORS "\xef\x83\x84" // U+f0c4 -#define ICON_FA_SCREWDRIVER "\xef\x95\x8a" // U+f54a -#define ICON_FA_SCREWDRIVER_WRENCH "\xef\x9f\x99" // U+f7d9 -#define ICON_FA_SCROLL "\xef\x9c\x8e" // U+f70e -#define ICON_FA_SCROLL_TORAH "\xef\x9a\xa0" // U+f6a0 -#define ICON_FA_SD_CARD "\xef\x9f\x82" // U+f7c2 -#define ICON_FA_SECTION "\xee\x91\x87" // U+e447 -#define ICON_FA_SEEDLING "\xef\x93\x98" // U+f4d8 -#define ICON_FA_SERVER "\xef\x88\xb3" // U+f233 -#define ICON_FA_SHAPES "\xef\x98\x9f" // U+f61f -#define ICON_FA_SHARE "\xef\x81\xa4" // U+f064 -#define ICON_FA_SHARE_FROM_SQUARE "\xef\x85\x8d" // U+f14d -#define ICON_FA_SHARE_NODES "\xef\x87\xa0" // U+f1e0 -#define ICON_FA_SHEET_PLASTIC "\xee\x95\xb1" // U+e571 -#define ICON_FA_SHEKEL_SIGN "\xef\x88\x8b" // U+f20b -#define ICON_FA_SHIELD "\xef\x84\xb2" // U+f132 -#define ICON_FA_SHIELD_CAT "\xee\x95\xb2" // U+e572 -#define ICON_FA_SHIELD_DOG "\xee\x95\xb3" // U+e573 -#define ICON_FA_SHIELD_HALVED "\xef\x8f\xad" // U+f3ed -#define ICON_FA_SHIELD_HEART "\xee\x95\xb4" // U+e574 -#define ICON_FA_SHIELD_VIRUS "\xee\x81\xac" // U+e06c -#define ICON_FA_SHIP "\xef\x88\x9a" // U+f21a -#define ICON_FA_SHIRT "\xef\x95\x93" // U+f553 -#define ICON_FA_SHOE_PRINTS "\xef\x95\x8b" // U+f54b -#define ICON_FA_SHOP "\xef\x95\x8f" // U+f54f -#define ICON_FA_SHOP_LOCK "\xee\x92\xa5" // U+e4a5 -#define ICON_FA_SHOP_SLASH "\xee\x81\xb0" // U+e070 -#define ICON_FA_SHOWER "\xef\x8b\x8c" // U+f2cc -#define ICON_FA_SHRIMP "\xee\x91\x88" // U+e448 -#define ICON_FA_SHUFFLE "\xef\x81\xb4" // U+f074 -#define ICON_FA_SHUTTLE_SPACE "\xef\x86\x97" // U+f197 -#define ICON_FA_SIGN_HANGING "\xef\x93\x99" // U+f4d9 -#define ICON_FA_SIGNAL "\xef\x80\x92" // U+f012 -#define ICON_FA_SIGNATURE "\xef\x96\xb7" // U+f5b7 -#define ICON_FA_SIGNS_POST "\xef\x89\xb7" // U+f277 -#define ICON_FA_SIM_CARD "\xef\x9f\x84" // U+f7c4 -#define ICON_FA_SINK "\xee\x81\xad" // U+e06d -#define ICON_FA_SITEMAP "\xef\x83\xa8" // U+f0e8 -#define ICON_FA_SKULL "\xef\x95\x8c" // U+f54c -#define ICON_FA_SKULL_CROSSBONES "\xef\x9c\x94" // U+f714 -#define ICON_FA_SLASH "\xef\x9c\x95" // U+f715 -#define ICON_FA_SLEIGH "\xef\x9f\x8c" // U+f7cc -#define ICON_FA_SLIDERS "\xef\x87\x9e" // U+f1de -#define ICON_FA_SMOG "\xef\x9d\x9f" // U+f75f -#define ICON_FA_SMOKING "\xef\x92\x8d" // U+f48d -#define ICON_FA_SNOWFLAKE "\xef\x8b\x9c" // U+f2dc -#define ICON_FA_SNOWMAN "\xef\x9f\x90" // U+f7d0 -#define ICON_FA_SNOWPLOW "\xef\x9f\x92" // U+f7d2 -#define ICON_FA_SOAP "\xee\x81\xae" // U+e06e -#define ICON_FA_SOCKS "\xef\x9a\x96" // U+f696 -#define ICON_FA_SOLAR_PANEL "\xef\x96\xba" // U+f5ba -#define ICON_FA_SORT "\xef\x83\x9c" // U+f0dc -#define ICON_FA_SORT_DOWN "\xef\x83\x9d" // U+f0dd -#define ICON_FA_SORT_UP "\xef\x83\x9e" // U+f0de -#define ICON_FA_SPA "\xef\x96\xbb" // U+f5bb -#define ICON_FA_SPAGHETTI_MONSTER_FLYING "\xef\x99\xbb" // U+f67b -#define ICON_FA_SPELL_CHECK "\xef\xa2\x91" // U+f891 -#define ICON_FA_SPIDER "\xef\x9c\x97" // U+f717 -#define ICON_FA_SPINNER "\xef\x84\x90" // U+f110 -#define ICON_FA_SPLOTCH "\xef\x96\xbc" // U+f5bc -#define ICON_FA_SPOON "\xef\x8b\xa5" // U+f2e5 -#define ICON_FA_SPRAY_CAN "\xef\x96\xbd" // U+f5bd -#define ICON_FA_SPRAY_CAN_SPARKLES "\xef\x97\x90" // U+f5d0 -#define ICON_FA_SQUARE "\xef\x83\x88" // U+f0c8 -#define ICON_FA_SQUARE_ARROW_UP_RIGHT "\xef\x85\x8c" // U+f14c -#define ICON_FA_SQUARE_CARET_DOWN "\xef\x85\x90" // U+f150 -#define ICON_FA_SQUARE_CARET_LEFT "\xef\x86\x91" // U+f191 -#define ICON_FA_SQUARE_CARET_RIGHT "\xef\x85\x92" // U+f152 -#define ICON_FA_SQUARE_CARET_UP "\xef\x85\x91" // U+f151 -#define ICON_FA_SQUARE_CHECK "\xef\x85\x8a" // U+f14a -#define ICON_FA_SQUARE_ENVELOPE "\xef\x86\x99" // U+f199 -#define ICON_FA_SQUARE_FULL "\xef\x91\x9c" // U+f45c -#define ICON_FA_SQUARE_H "\xef\x83\xbd" // U+f0fd -#define ICON_FA_SQUARE_MINUS "\xef\x85\x86" // U+f146 -#define ICON_FA_SQUARE_NFI "\xee\x95\xb6" // U+e576 -#define ICON_FA_SQUARE_PARKING "\xef\x95\x80" // U+f540 -#define ICON_FA_SQUARE_PEN "\xef\x85\x8b" // U+f14b -#define ICON_FA_SQUARE_PERSON_CONFINED "\xee\x95\xb7" // U+e577 -#define ICON_FA_SQUARE_PHONE "\xef\x82\x98" // U+f098 -#define ICON_FA_SQUARE_PHONE_FLIP "\xef\xa1\xbb" // U+f87b -#define ICON_FA_SQUARE_PLUS "\xef\x83\xbe" // U+f0fe -#define ICON_FA_SQUARE_POLL_HORIZONTAL "\xef\x9a\x82" // U+f682 -#define ICON_FA_SQUARE_POLL_VERTICAL "\xef\x9a\x81" // U+f681 -#define ICON_FA_SQUARE_ROOT_VARIABLE "\xef\x9a\x98" // U+f698 -#define ICON_FA_SQUARE_RSS "\xef\x85\x83" // U+f143 -#define ICON_FA_SQUARE_SHARE_NODES "\xef\x87\xa1" // U+f1e1 -#define ICON_FA_SQUARE_UP_RIGHT "\xef\x8d\xa0" // U+f360 -#define ICON_FA_SQUARE_VIRUS "\xee\x95\xb8" // U+e578 -#define ICON_FA_SQUARE_XMARK "\xef\x8b\x93" // U+f2d3 -#define ICON_FA_STAFF_AESCULAPIUS "\xee\x95\xb9" // U+e579 -#define ICON_FA_STAIRS "\xee\x8a\x89" // U+e289 -#define ICON_FA_STAMP "\xef\x96\xbf" // U+f5bf -#define ICON_FA_STAR "\xef\x80\x85" // U+f005 -#define ICON_FA_STAR_AND_CRESCENT "\xef\x9a\x99" // U+f699 -#define ICON_FA_STAR_HALF "\xef\x82\x89" // U+f089 -#define ICON_FA_STAR_HALF_STROKE "\xef\x97\x80" // U+f5c0 -#define ICON_FA_STAR_OF_DAVID "\xef\x9a\x9a" // U+f69a -#define ICON_FA_STAR_OF_LIFE "\xef\x98\xa1" // U+f621 -#define ICON_FA_STERLING_SIGN "\xef\x85\x94" // U+f154 -#define ICON_FA_STETHOSCOPE "\xef\x83\xb1" // U+f0f1 -#define ICON_FA_STOP "\xef\x81\x8d" // U+f04d -#define ICON_FA_STOPWATCH "\xef\x8b\xb2" // U+f2f2 -#define ICON_FA_STOPWATCH_20 "\xee\x81\xaf" // U+e06f -#define ICON_FA_STORE "\xef\x95\x8e" // U+f54e -#define ICON_FA_STORE_SLASH "\xee\x81\xb1" // U+e071 -#define ICON_FA_STREET_VIEW "\xef\x88\x9d" // U+f21d -#define ICON_FA_STRIKETHROUGH "\xef\x83\x8c" // U+f0cc -#define ICON_FA_STROOPWAFEL "\xef\x95\x91" // U+f551 -#define ICON_FA_SUBSCRIPT "\xef\x84\xac" // U+f12c -#define ICON_FA_SUITCASE "\xef\x83\xb2" // U+f0f2 -#define ICON_FA_SUITCASE_MEDICAL "\xef\x83\xba" // U+f0fa -#define ICON_FA_SUITCASE_ROLLING "\xef\x97\x81" // U+f5c1 -#define ICON_FA_SUN "\xef\x86\x85" // U+f185 -#define ICON_FA_SUN_PLANT_WILT "\xee\x95\xba" // U+e57a -#define ICON_FA_SUPERSCRIPT "\xef\x84\xab" // U+f12b -#define ICON_FA_SWATCHBOOK "\xef\x97\x83" // U+f5c3 -#define ICON_FA_SYNAGOGUE "\xef\x9a\x9b" // U+f69b -#define ICON_FA_SYRINGE "\xef\x92\x8e" // U+f48e -#define ICON_FA_T "T" // U+0054 -#define ICON_FA_TABLE "\xef\x83\x8e" // U+f0ce -#define ICON_FA_TABLE_CELLS "\xef\x80\x8a" // U+f00a -#define ICON_FA_TABLE_CELLS_LARGE "\xef\x80\x89" // U+f009 -#define ICON_FA_TABLE_COLUMNS "\xef\x83\x9b" // U+f0db -#define ICON_FA_TABLE_LIST "\xef\x80\x8b" // U+f00b -#define ICON_FA_TABLE_TENNIS_PADDLE_BALL "\xef\x91\x9d" // U+f45d -#define ICON_FA_TABLET "\xef\x8f\xbb" // U+f3fb -#define ICON_FA_TABLET_BUTTON "\xef\x84\x8a" // U+f10a -#define ICON_FA_TABLET_SCREEN_BUTTON "\xef\x8f\xba" // U+f3fa -#define ICON_FA_TABLETS "\xef\x92\x90" // U+f490 -#define ICON_FA_TACHOGRAPH_DIGITAL "\xef\x95\xa6" // U+f566 -#define ICON_FA_TAG "\xef\x80\xab" // U+f02b -#define ICON_FA_TAGS "\xef\x80\xac" // U+f02c -#define ICON_FA_TAPE "\xef\x93\x9b" // U+f4db -#define ICON_FA_TARP "\xee\x95\xbb" // U+e57b -#define ICON_FA_TARP_DROPLET "\xee\x95\xbc" // U+e57c -#define ICON_FA_TAXI "\xef\x86\xba" // U+f1ba -#define ICON_FA_TEETH "\xef\x98\xae" // U+f62e -#define ICON_FA_TEETH_OPEN "\xef\x98\xaf" // U+f62f -#define ICON_FA_TEMPERATURE_ARROW_DOWN "\xee\x80\xbf" // U+e03f -#define ICON_FA_TEMPERATURE_ARROW_UP "\xee\x81\x80" // U+e040 -#define ICON_FA_TEMPERATURE_EMPTY "\xef\x8b\x8b" // U+f2cb -#define ICON_FA_TEMPERATURE_FULL "\xef\x8b\x87" // U+f2c7 -#define ICON_FA_TEMPERATURE_HALF "\xef\x8b\x89" // U+f2c9 -#define ICON_FA_TEMPERATURE_HIGH "\xef\x9d\xa9" // U+f769 -#define ICON_FA_TEMPERATURE_LOW "\xef\x9d\xab" // U+f76b -#define ICON_FA_TEMPERATURE_QUARTER "\xef\x8b\x8a" // U+f2ca -#define ICON_FA_TEMPERATURE_THREE_QUARTERS "\xef\x8b\x88" // U+f2c8 -#define ICON_FA_TENGE_SIGN "\xef\x9f\x97" // U+f7d7 -#define ICON_FA_TENT "\xee\x95\xbd" // U+e57d -#define ICON_FA_TENT_ARROW_DOWN_TO_LINE "\xee\x95\xbe" // U+e57e -#define ICON_FA_TENT_ARROW_LEFT_RIGHT "\xee\x95\xbf" // U+e57f -#define ICON_FA_TENT_ARROW_TURN_LEFT "\xee\x96\x80" // U+e580 -#define ICON_FA_TENT_ARROWS_DOWN "\xee\x96\x81" // U+e581 -#define ICON_FA_TENTS "\xee\x96\x82" // U+e582 -#define ICON_FA_TERMINAL "\xef\x84\xa0" // U+f120 -#define ICON_FA_TEXT_HEIGHT "\xef\x80\xb4" // U+f034 -#define ICON_FA_TEXT_SLASH "\xef\xa1\xbd" // U+f87d -#define ICON_FA_TEXT_WIDTH "\xef\x80\xb5" // U+f035 -#define ICON_FA_THERMOMETER "\xef\x92\x91" // U+f491 -#define ICON_FA_THUMBS_DOWN "\xef\x85\xa5" // U+f165 -#define ICON_FA_THUMBS_UP "\xef\x85\xa4" // U+f164 -#define ICON_FA_THUMBTACK "\xef\x82\x8d" // U+f08d -#define ICON_FA_TICKET "\xef\x85\x85" // U+f145 -#define ICON_FA_TICKET_SIMPLE "\xef\x8f\xbf" // U+f3ff -#define ICON_FA_TIMELINE "\xee\x8a\x9c" // U+e29c -#define ICON_FA_TOGGLE_OFF "\xef\x88\x84" // U+f204 -#define ICON_FA_TOGGLE_ON "\xef\x88\x85" // U+f205 -#define ICON_FA_TOILET "\xef\x9f\x98" // U+f7d8 -#define ICON_FA_TOILET_PAPER "\xef\x9c\x9e" // U+f71e -#define ICON_FA_TOILET_PAPER_SLASH "\xee\x81\xb2" // U+e072 -#define ICON_FA_TOILET_PORTABLE "\xee\x96\x83" // U+e583 -#define ICON_FA_TOILETS_PORTABLE "\xee\x96\x84" // U+e584 -#define ICON_FA_TOOLBOX "\xef\x95\x92" // U+f552 -#define ICON_FA_TOOTH "\xef\x97\x89" // U+f5c9 -#define ICON_FA_TORII_GATE "\xef\x9a\xa1" // U+f6a1 -#define ICON_FA_TORNADO "\xef\x9d\xaf" // U+f76f -#define ICON_FA_TOWER_BROADCAST "\xef\x94\x99" // U+f519 -#define ICON_FA_TOWER_CELL "\xee\x96\x85" // U+e585 -#define ICON_FA_TOWER_OBSERVATION "\xee\x96\x86" // U+e586 -#define ICON_FA_TRACTOR "\xef\x9c\xa2" // U+f722 -#define ICON_FA_TRADEMARK "\xef\x89\x9c" // U+f25c -#define ICON_FA_TRAFFIC_LIGHT "\xef\x98\xb7" // U+f637 -#define ICON_FA_TRAILER "\xee\x81\x81" // U+e041 -#define ICON_FA_TRAIN "\xef\x88\xb8" // U+f238 -#define ICON_FA_TRAIN_SUBWAY "\xef\x88\xb9" // U+f239 -#define ICON_FA_TRAIN_TRAM "\xef\x9f\x9a" // U+f7da -#define ICON_FA_TRANSGENDER "\xef\x88\xa5" // U+f225 -#define ICON_FA_TRASH "\xef\x87\xb8" // U+f1f8 -#define ICON_FA_TRASH_ARROW_UP "\xef\xa0\xa9" // U+f829 -#define ICON_FA_TRASH_CAN "\xef\x8b\xad" // U+f2ed -#define ICON_FA_TRASH_CAN_ARROW_UP "\xef\xa0\xaa" // U+f82a -#define ICON_FA_TREE "\xef\x86\xbb" // U+f1bb -#define ICON_FA_TREE_CITY "\xee\x96\x87" // U+e587 -#define ICON_FA_TRIANGLE_EXCLAMATION "\xef\x81\xb1" // U+f071 -#define ICON_FA_TROPHY "\xef\x82\x91" // U+f091 -#define ICON_FA_TROWEL "\xee\x96\x89" // U+e589 -#define ICON_FA_TROWEL_BRICKS "\xee\x96\x8a" // U+e58a -#define ICON_FA_TRUCK "\xef\x83\x91" // U+f0d1 -#define ICON_FA_TRUCK_ARROW_RIGHT "\xee\x96\x8b" // U+e58b -#define ICON_FA_TRUCK_DROPLET "\xee\x96\x8c" // U+e58c -#define ICON_FA_TRUCK_FAST "\xef\x92\x8b" // U+f48b -#define ICON_FA_TRUCK_FIELD "\xee\x96\x8d" // U+e58d -#define ICON_FA_TRUCK_FIELD_UN "\xee\x96\x8e" // U+e58e -#define ICON_FA_TRUCK_FRONT "\xee\x8a\xb7" // U+e2b7 -#define ICON_FA_TRUCK_MEDICAL "\xef\x83\xb9" // U+f0f9 -#define ICON_FA_TRUCK_MONSTER "\xef\x98\xbb" // U+f63b -#define ICON_FA_TRUCK_MOVING "\xef\x93\x9f" // U+f4df -#define ICON_FA_TRUCK_PICKUP "\xef\x98\xbc" // U+f63c -#define ICON_FA_TRUCK_PLANE "\xee\x96\x8f" // U+e58f -#define ICON_FA_TRUCK_RAMP_BOX "\xef\x93\x9e" // U+f4de -#define ICON_FA_TTY "\xef\x87\xa4" // U+f1e4 -#define ICON_FA_TURKISH_LIRA_SIGN "\xee\x8a\xbb" // U+e2bb -#define ICON_FA_TURN_DOWN "\xef\x8e\xbe" // U+f3be -#define ICON_FA_TURN_UP "\xef\x8e\xbf" // U+f3bf -#define ICON_FA_TV "\xef\x89\xac" // U+f26c -#define ICON_FA_U "U" // U+0055 -#define ICON_FA_UMBRELLA "\xef\x83\xa9" // U+f0e9 -#define ICON_FA_UMBRELLA_BEACH "\xef\x97\x8a" // U+f5ca -#define ICON_FA_UNDERLINE "\xef\x83\x8d" // U+f0cd -#define ICON_FA_UNIVERSAL_ACCESS "\xef\x8a\x9a" // U+f29a -#define ICON_FA_UNLOCK "\xef\x82\x9c" // U+f09c -#define ICON_FA_UNLOCK_KEYHOLE "\xef\x84\xbe" // U+f13e -#define ICON_FA_UP_DOWN "\xef\x8c\xb8" // U+f338 -#define ICON_FA_UP_DOWN_LEFT_RIGHT "\xef\x82\xb2" // U+f0b2 -#define ICON_FA_UP_LONG "\xef\x8c\x8c" // U+f30c -#define ICON_FA_UP_RIGHT_AND_DOWN_LEFT_FROM_CENTER "\xef\x90\xa4" // U+f424 -#define ICON_FA_UP_RIGHT_FROM_SQUARE "\xef\x8d\x9d" // U+f35d -#define ICON_FA_UPLOAD "\xef\x82\x93" // U+f093 -#define ICON_FA_USER "\xef\x80\x87" // U+f007 -#define ICON_FA_USER_ASTRONAUT "\xef\x93\xbb" // U+f4fb -#define ICON_FA_USER_CHECK "\xef\x93\xbc" // U+f4fc -#define ICON_FA_USER_CLOCK "\xef\x93\xbd" // U+f4fd -#define ICON_FA_USER_DOCTOR "\xef\x83\xb0" // U+f0f0 -#define ICON_FA_USER_GEAR "\xef\x93\xbe" // U+f4fe -#define ICON_FA_USER_GRADUATE "\xef\x94\x81" // U+f501 -#define ICON_FA_USER_GROUP "\xef\x94\x80" // U+f500 -#define ICON_FA_USER_INJURED "\xef\x9c\xa8" // U+f728 -#define ICON_FA_USER_LARGE "\xef\x90\x86" // U+f406 -#define ICON_FA_USER_LARGE_SLASH "\xef\x93\xba" // U+f4fa -#define ICON_FA_USER_LOCK "\xef\x94\x82" // U+f502 -#define ICON_FA_USER_MINUS "\xef\x94\x83" // U+f503 -#define ICON_FA_USER_NINJA "\xef\x94\x84" // U+f504 -#define ICON_FA_USER_NURSE "\xef\xa0\xaf" // U+f82f -#define ICON_FA_USER_PEN "\xef\x93\xbf" // U+f4ff -#define ICON_FA_USER_PLUS "\xef\x88\xb4" // U+f234 -#define ICON_FA_USER_SECRET "\xef\x88\x9b" // U+f21b -#define ICON_FA_USER_SHIELD "\xef\x94\x85" // U+f505 -#define ICON_FA_USER_SLASH "\xef\x94\x86" // U+f506 -#define ICON_FA_USER_TAG "\xef\x94\x87" // U+f507 -#define ICON_FA_USER_TIE "\xef\x94\x88" // U+f508 -#define ICON_FA_USER_XMARK "\xef\x88\xb5" // U+f235 -#define ICON_FA_USERS "\xef\x83\x80" // U+f0c0 -#define ICON_FA_USERS_BETWEEN_LINES "\xee\x96\x91" // U+e591 -#define ICON_FA_USERS_GEAR "\xef\x94\x89" // U+f509 -#define ICON_FA_USERS_LINE "\xee\x96\x92" // U+e592 -#define ICON_FA_USERS_RAYS "\xee\x96\x93" // U+e593 -#define ICON_FA_USERS_RECTANGLE "\xee\x96\x94" // U+e594 -#define ICON_FA_USERS_SLASH "\xee\x81\xb3" // U+e073 -#define ICON_FA_USERS_VIEWFINDER "\xee\x96\x95" // U+e595 -#define ICON_FA_UTENSILS "\xef\x8b\xa7" // U+f2e7 -#define ICON_FA_V "V" // U+0056 -#define ICON_FA_VAN_SHUTTLE "\xef\x96\xb6" // U+f5b6 -#define ICON_FA_VAULT "\xee\x8b\x85" // U+e2c5 -#define ICON_FA_VECTOR_SQUARE "\xef\x97\x8b" // U+f5cb -#define ICON_FA_VENUS "\xef\x88\xa1" // U+f221 -#define ICON_FA_VENUS_DOUBLE "\xef\x88\xa6" // U+f226 -#define ICON_FA_VENUS_MARS "\xef\x88\xa8" // U+f228 -#define ICON_FA_VEST "\xee\x82\x85" // U+e085 -#define ICON_FA_VEST_PATCHES "\xee\x82\x86" // U+e086 -#define ICON_FA_VIAL "\xef\x92\x92" // U+f492 -#define ICON_FA_VIAL_CIRCLE_CHECK "\xee\x96\x96" // U+e596 -#define ICON_FA_VIAL_VIRUS "\xee\x96\x97" // U+e597 -#define ICON_FA_VIALS "\xef\x92\x93" // U+f493 -#define ICON_FA_VIDEO "\xef\x80\xbd" // U+f03d -#define ICON_FA_VIDEO_SLASH "\xef\x93\xa2" // U+f4e2 -#define ICON_FA_VIHARA "\xef\x9a\xa7" // U+f6a7 -#define ICON_FA_VIRUS "\xee\x81\xb4" // U+e074 -#define ICON_FA_VIRUS_COVID "\xee\x92\xa8" // U+e4a8 -#define ICON_FA_VIRUS_COVID_SLASH "\xee\x92\xa9" // U+e4a9 -#define ICON_FA_VIRUS_SLASH "\xee\x81\xb5" // U+e075 -#define ICON_FA_VIRUSES "\xee\x81\xb6" // U+e076 -#define ICON_FA_VOICEMAIL "\xef\xa2\x97" // U+f897 -#define ICON_FA_VOLCANO "\xef\x9d\xb0" // U+f770 -#define ICON_FA_VOLLEYBALL "\xef\x91\x9f" // U+f45f -#define ICON_FA_VOLUME_HIGH "\xef\x80\xa8" // U+f028 -#define ICON_FA_VOLUME_LOW "\xef\x80\xa7" // U+f027 -#define ICON_FA_VOLUME_OFF "\xef\x80\xa6" // U+f026 -#define ICON_FA_VOLUME_XMARK "\xef\x9a\xa9" // U+f6a9 -#define ICON_FA_VR_CARDBOARD "\xef\x9c\xa9" // U+f729 -#define ICON_FA_W "W" // U+0057 -#define ICON_FA_WALKIE_TALKIE "\xef\xa3\xaf" // U+f8ef -#define ICON_FA_WALLET "\xef\x95\x95" // U+f555 -#define ICON_FA_WAND_MAGIC "\xef\x83\x90" // U+f0d0 -#define ICON_FA_WAND_MAGIC_SPARKLES "\xee\x8b\x8a" // U+e2ca -#define ICON_FA_WAND_SPARKLES "\xef\x9c\xab" // U+f72b -#define ICON_FA_WAREHOUSE "\xef\x92\x94" // U+f494 -#define ICON_FA_WATER "\xef\x9d\xb3" // U+f773 -#define ICON_FA_WATER_LADDER "\xef\x97\x85" // U+f5c5 -#define ICON_FA_WAVE_SQUARE "\xef\xa0\xbe" // U+f83e -#define ICON_FA_WEIGHT_HANGING "\xef\x97\x8d" // U+f5cd -#define ICON_FA_WEIGHT_SCALE "\xef\x92\x96" // U+f496 -#define ICON_FA_WHEAT_AWN "\xee\x8b\x8d" // U+e2cd -#define ICON_FA_WHEAT_AWN_CIRCLE_EXCLAMATION "\xee\x96\x98" // U+e598 -#define ICON_FA_WHEELCHAIR "\xef\x86\x93" // U+f193 -#define ICON_FA_WHEELCHAIR_MOVE "\xee\x8b\x8e" // U+e2ce -#define ICON_FA_WHISKEY_GLASS "\xef\x9e\xa0" // U+f7a0 -#define ICON_FA_WIFI "\xef\x87\xab" // U+f1eb -#define ICON_FA_WIND "\xef\x9c\xae" // U+f72e -#define ICON_FA_WINDOW_MAXIMIZE "\xef\x8b\x90" // U+f2d0 -#define ICON_FA_WINDOW_MINIMIZE "\xef\x8b\x91" // U+f2d1 -#define ICON_FA_WINDOW_RESTORE "\xef\x8b\x92" // U+f2d2 -#define ICON_FA_WINE_BOTTLE "\xef\x9c\xaf" // U+f72f -#define ICON_FA_WINE_GLASS "\xef\x93\xa3" // U+f4e3 -#define ICON_FA_WINE_GLASS_EMPTY "\xef\x97\x8e" // U+f5ce -#define ICON_FA_WON_SIGN "\xef\x85\x99" // U+f159 -#define ICON_FA_WORM "\xee\x96\x99" // U+e599 -#define ICON_FA_WRENCH "\xef\x82\xad" // U+f0ad -#define ICON_FA_X "X" // U+0058 -#define ICON_FA_X_RAY "\xef\x92\x97" // U+f497 -#define ICON_FA_XMARK "\xef\x80\x8d" // U+f00d -#define ICON_FA_XMARKS_LINES "\xee\x96\x9a" // U+e59a -#define ICON_FA_Y "Y" // U+0059 -#define ICON_FA_YEN_SIGN "\xef\x85\x97" // U+f157 -#define ICON_FA_YIN_YANG "\xef\x9a\xad" // U+f6ad -#define ICON_FA_Z "Z" // U+005a diff --git a/include/imgui/IconsKenney.h b/include/imgui/IconsKenney.h deleted file mode 100644 index 0e07940..0000000 --- a/include/imgui/IconsKenney.h +++ /dev/null @@ -1,242 +0,0 @@ -// Generated by https://github.com/juliettef/IconFontCppHeaders script GenerateIconFontCppHeaders.py -// for C and C++ -// from codepoints https://github.com/nicodinh/kenney-icon-font/raw/master/css/kenney-icons.css -// for use with font https://github.com/nicodinh/kenney-icon-font/blob/master/fonts/kenney-icon-font.ttf - -#pragma once - -#define FONT_ICON_FILE_NAME_KI "kenney-icon-font.ttf" - -#define ICON_MIN_KI 0xe900 -#define ICON_MAX_16_KI 0xe9e4 -#define ICON_MAX_KI 0xe9e4 - -#define ICON_KI_HOME "\xee\xa4\x80" // U+e900 -#define ICON_KI_ADJUST "\xee\xa4\x81" // U+e901 -#define ICON_KI_WRENCH "\xee\xa4\x82" // U+e902 -#define ICON_KI_COG "\xee\xa4\x83" // U+e903 -#define ICON_KI_OFF "\xee\xa4\x84" // U+e904 -#define ICON_KI_EXPAND "\xee\xa4\x85" // U+e905 -#define ICON_KI_REDUCE "\xee\xa4\x86" // U+e906 -#define ICON_KI_MOVIE "\xee\xa4\x87" // U+e907 -#define ICON_KI_FLAP "\xee\xa4\x88" // U+e908 -#define ICON_KI_SHOPPING_CART "\xee\xa4\x89" // U+e909 -#define ICON_KI_SHOPPING_CASE "\xee\xa4\x8a" // U+e90a -#define ICON_KI_EXTERNAL "\xee\xa4\x8b" // U+e90b -#define ICON_KI_NETWORK "\xee\xa4\x8c" // U+e90c -#define ICON_KI_CHECK "\xee\xa4\x8d" // U+e90d -#define ICON_KI_TIMES "\xee\xa4\x8e" // U+e90e -#define ICON_KI_TIMES_CIRCLE "\xee\xa4\x8f" // U+e90f -#define ICON_KI_PLUS "\xee\xa4\x90" // U+e910 -#define ICON_KI_PLUS_CIRCLE "\xee\xa4\x91" // U+e911 -#define ICON_KI_MINUS "\xee\xa4\x92" // U+e912 -#define ICON_KI_MINUS_CIRCLE "\xee\xa4\x93" // U+e913 -#define ICON_KI_INFO "\xee\xa4\x94" // U+e914 -#define ICON_KI_INFO_CIRCLE "\xee\xa4\x95" // U+e915 -#define ICON_KI_QUESTION "\xee\xa4\x96" // U+e916 -#define ICON_KI_QUESTION_CIRCLE "\xee\xa4\x97" // U+e917 -#define ICON_KI_EXLAMATION "\xee\xa4\x98" // U+e918 -#define ICON_KI_EXCLAMATION_CIRCLE "\xee\xa4\x99" // U+e919 -#define ICON_KI_EXCLAMATION_TRIANGLE "\xee\xa4\x9a" // U+e91a -#define ICON_KI_PAINT_BRUSH "\xee\xa4\x9b" // U+e91b -#define ICON_KI_PENCIL "\xee\xa4\x9c" // U+e91c -#define ICON_KI_CHECKBOX "\xee\xa4\x9d" // U+e91d -#define ICON_KI_CHECKBOX_CHECKED "\xee\xa4\x9e" // U+e91e -#define ICON_KI_RADIO "\xee\xa4\x9f" // U+e91f -#define ICON_KI_RADIO_CHECKED "\xee\xa4\xa0" // U+e920 -#define ICON_KI_SORT_VERTICAL "\xee\xa4\xa1" // U+e921 -#define ICON_KI_SORT_HORIZONTAL "\xee\xa4\xa2" // U+e922 -#define ICON_KI_GRID "\xee\xa4\xa3" // U+e923 -#define ICON_KI_LIST "\xee\xa4\xa4" // U+e924 -#define ICON_KI_ROWS "\xee\xa4\xa5" // U+e925 -#define ICON_KI_CELLS "\xee\xa4\xa6" // U+e926 -#define ICON_KI_SIGNAL_LOW "\xee\xa4\xa7" // U+e927 -#define ICON_KI_SIGNAL_MEDIUM "\xee\xa4\xa8" // U+e928 -#define ICON_KI_SIGNAL_HIGH "\xee\xa4\xa9" // U+e929 -#define ICON_KI_TRASH "\xee\xa4\xaa" // U+e92a -#define ICON_KI_TRASH_ALT "\xee\xa4\xab" // U+e92b -#define ICON_KI_RELOAD_INVERSE "\xee\xa4\xac" // U+e92c -#define ICON_KI_RELOAD "\xee\xa4\xad" // U+e92d -#define ICON_KI_TOP "\xee\xa4\xae" // U+e92e -#define ICON_KI_BOTTOM "\xee\xa4\xaf" // U+e92f -#define ICON_KI_UPLOAD "\xee\xa4\xb0" // U+e930 -#define ICON_KI_DOWNLOAD "\xee\xa4\xb1" // U+e931 -#define ICON_KI_CLOUD "\xee\xa4\xb2" // U+e932 -#define ICON_KI_CLOUD_UPLOAD "\xee\xa4\xb3" // U+e933 -#define ICON_KI_CLOUD_DOWNLOAD "\xee\xa4\xb4" // U+e934 -#define ICON_KI_SEARCH "\xee\xa4\xb5" // U+e935 -#define ICON_KI_SEARCH_PLUS "\xee\xa4\xb6" // U+e936 -#define ICON_KI_SEARCH_MINUS "\xee\xa4\xb7" // U+e937 -#define ICON_KI_SEARCH_EQUAL "\xee\xa4\xb8" // U+e938 -#define ICON_KI_LOCK "\xee\xa4\xb9" // U+e939 -#define ICON_KI_UNLOCK "\xee\xa4\xba" // U+e93a -#define ICON_KI_USER "\xee\xa4\xbb" // U+e93b -#define ICON_KI_USERS "\xee\xa4\xbc" // U+e93c -#define ICON_KI_USERS_ALT "\xee\xa4\xbd" // U+e93d -#define ICON_KI_SIGN_IN "\xee\xa4\xbe" // U+e93e -#define ICON_KI_SIGN_IN_INVERSE "\xee\xa4\xbf" // U+e93f -#define ICON_KI_SIGN_OUT "\xee\xa5\x80" // U+e940 -#define ICON_KI_SIGN_OUT_INVERSE "\xee\xa5\x81" // U+e941 -#define ICON_KI_ARROW_TOP "\xee\xa5\x82" // U+e942 -#define ICON_KI_ARROW_RIGHT "\xee\xa5\x83" // U+e943 -#define ICON_KI_ARROW_BOTTOM "\xee\xa5\x84" // U+e944 -#define ICON_KI_ARROW_LEFT "\xee\xa5\x85" // U+e945 -#define ICON_KI_ARROW_TOP_LEFT "\xee\xa5\x86" // U+e946 -#define ICON_KI_ARROW_TOP_RIGHT "\xee\xa5\x87" // U+e947 -#define ICON_KI_ARROW_BOTTOM_RIGHT "\xee\xa5\x88" // U+e948 -#define ICON_KI_ARROW_BOTTOM_LEFT "\xee\xa5\x89" // U+e949 -#define ICON_KI_CARET_TOP "\xee\xa5\x8a" // U+e94a -#define ICON_KI_CARET_RIGHT "\xee\xa5\x8b" // U+e94b -#define ICON_KI_CARET_BOTTOM "\xee\xa5\x8c" // U+e94c -#define ICON_KI_CARET_LEFT "\xee\xa5\x8d" // U+e94d -#define ICON_KI_NEXT_ALT "\xee\xa5\x8e" // U+e94e -#define ICON_KI_NEXT "\xee\xa5\x8f" // U+e94f -#define ICON_KI_PREVIOUS "\xee\xa5\x90" // U+e950 -#define ICON_KI_PREVIOUS_ALT "\xee\xa5\x91" // U+e951 -#define ICON_KI_FILL "\xee\xa5\x92" // U+e952 -#define ICON_KI_ERASER "\xee\xa5\x93" // U+e953 -#define ICON_KI_SAVE "\xee\xa5\x94" // U+e954 -#define ICON_KI_STEP_BACKWARD "\xee\xa5\x95" // U+e955 -#define ICON_KI_BACKWARD "\xee\xa5\x96" // U+e956 -#define ICON_KI_PAUSE "\xee\xa5\x97" // U+e957 -#define ICON_KI_FORWARD "\xee\xa5\x98" // U+e958 -#define ICON_KI_STEP_FORWARD "\xee\xa5\x99" // U+e959 -#define ICON_KI_STOP "\xee\xa5\x9a" // U+e95a -#define ICON_KI_REC "\xee\xa5\x9b" // U+e95b -#define ICON_KI_CURSOR "\xee\xa5\x9c" // U+e95c -#define ICON_KI_POINTER "\xee\xa5\x9d" // U+e95d -#define ICON_KI_EXIT "\xee\xa5\x9e" // U+e95e -#define ICON_KI_FIGURE "\xee\xa5\x9f" // U+e95f -#define ICON_KI_CAR "\xee\xa5\xa0" // U+e960 -#define ICON_KI_COIN "\xee\xa5\xa1" // U+e961 -#define ICON_KI_KEY "\xee\xa5\xa2" // U+e962 -#define ICON_KI_CUB "\xee\xa5\xa3" // U+e963 -#define ICON_KI_DIAMOND "\xee\xa5\xa4" // U+e964 -#define ICON_KI_BADGE "\xee\xa5\xa5" // U+e965 -#define ICON_KI_BADGE_ALT "\xee\xa5\xa6" // U+e966 -#define ICON_KI_PODIUM "\xee\xa5\xa7" // U+e967 -#define ICON_KI_PODIUM_ALT "\xee\xa5\xa8" // U+e968 -#define ICON_KI_FLAG "\xee\xa5\xa9" // U+e969 -#define ICON_KI_FIST "\xee\xa5\xaa" // U+e96a -#define ICON_KI_FIST_CIRCLE "\xee\xa5\xab" // U+e96b -#define ICON_KI_HEART "\xee\xa5\xac" // U+e96c -#define ICON_KI_HEART_HALF "\xee\xa5\xad" // U+e96d -#define ICON_KI_HEART_HALF_O "\xee\xa5\xae" // U+e96e -#define ICON_KI_HEART_O "\xee\xa5\xaf" // U+e96f -#define ICON_KI_STAR "\xee\xa5\xb0" // U+e970 -#define ICON_KI_STAR_HALF "\xee\xa5\xb1" // U+e971 -#define ICON_KI_STAR_HALF_O "\xee\xa5\xb2" // U+e972 -#define ICON_KI_STAR_O "\xee\xa5\xb3" // U+e973 -#define ICON_KI_BUTTON_B "\xee\xa5\xb4" // U+e974 -#define ICON_KI_MUSIC_ON "\xee\xa5\xb5" // U+e975 -#define ICON_KI_MUSIC_OFF "\xee\xa5\xb6" // U+e976 -#define ICON_KI_SOUND_ON "\xee\xa5\xb7" // U+e977 -#define ICON_KI_SOUND_OFF "\xee\xa5\xb8" // U+e978 -#define ICON_KI_SOUND_OFF_ALT "\xee\xa5\xb9" // U+e979 -#define ICON_KI_ROBOT "\xee\xa5\xba" // U+e97a -#define ICON_KI_COMPUTER "\xee\xa5\xbb" // U+e97b -#define ICON_KI_TABLET "\xee\xa5\xbc" // U+e97c -#define ICON_KI_SMARTPHONE "\xee\xa5\xbd" // U+e97d -#define ICON_KI_DEVICE "\xee\xa5\xbe" // U+e97e -#define ICON_KI_DEVICE_TILT_LEFT "\xee\xa5\xbf" // U+e97f -#define ICON_KI_DEVICE_TILT_RIGHT "\xee\xa6\x80" // U+e980 -#define ICON_KI_GAMEPAD "\xee\xa6\x81" // U+e981 -#define ICON_KI_GAMEPAD_ALT "\xee\xa6\x82" // U+e982 -#define ICON_KI_GAMEPAD_TILT_LEFT "\xee\xa6\x83" // U+e983 -#define ICON_KI_GAMEPAD_TILT_RIGHT "\xee\xa6\x84" // U+e984 -#define ICON_KI_PLAYER_ONE "\xee\xa6\x85" // U+e985 -#define ICON_KI_PLAYER_TWO "\xee\xa6\x86" // U+e986 -#define ICON_KI_PLAYER_THREE "\xee\xa6\x87" // U+e987 -#define ICON_KI_PLAYER_FOUR "\xee\xa6\x88" // U+e988 -#define ICON_KI_JOYSTICK "\xee\xa6\x89" // U+e989 -#define ICON_KI_JOYSTICK_ALT "\xee\xa6\x8a" // U+e98a -#define ICON_KI_JOYSTICK_LEFT "\xee\xa6\x8b" // U+e98b -#define ICON_KI_JOYSTICK_RIGHT "\xee\xa6\x8c" // U+e98c -#define ICON_KI_MOUSE_ALT "\xee\xa6\x8d" // U+e98d -#define ICON_KI_MOUSE "\xee\xa6\x8e" // U+e98e -#define ICON_KI_MOUSE_LEFT_BUTTON "\xee\xa6\x8f" // U+e98f -#define ICON_KI_MOUSE_RIGHT_BUTTON "\xee\xa6\x90" // U+e990 -#define ICON_KI_BUTTON_ONE "\xee\xa6\x91" // U+e991 -#define ICON_KI_BUTTON_TWO "\xee\xa6\x92" // U+e992 -#define ICON_KI_BUTTON_THREE "\xee\xa6\x93" // U+e993 -#define ICON_KI_BUTTON_A "\xee\xa6\x94" // U+e994 -#define ICON_KI_BUTTON_X "\xee\xa6\x95" // U+e995 -#define ICON_KI_BUTON_Y "\xee\xa6\x96" // U+e996 -#define ICON_KI_BUTTON_TIMES "\xee\xa6\x97" // U+e997 -#define ICON_KI_BUTTON_SQUARE "\xee\xa6\x98" // U+e998 -#define ICON_KI_BUTTON_CIRCLE "\xee\xa6\x99" // U+e999 -#define ICON_KI_BUTTON_TRIANGLE "\xee\xa6\x9a" // U+e99a -#define ICON_KI_BUTTON_LEFT "\xee\xa6\x9b" // U+e99b -#define ICON_KI_BUTTON_L "\xee\xa6\x9c" // U+e99c -#define ICON_KI_BUTTON_L1 "\xee\xa6\x9d" // U+e99d -#define ICON_KI_BUTTON_L2 "\xee\xa6\x9e" // U+e99e -#define ICON_KI_BUTTON_LB "\xee\xa6\x9f" // U+e99f -#define ICON_KI_BUTTON_LT "\xee\xa6\xa0" // U+e9a0 -#define ICON_KI_BUTTON_RT "\xee\xa6\xa1" // U+e9a1 -#define ICON_KI_BUTTON_RB "\xee\xa6\xa2" // U+e9a2 -#define ICON_KI_BUTTON_R2 "\xee\xa6\xa3" // U+e9a3 -#define ICON_KI_BUTTON_R1 "\xee\xa6\xa4" // U+e9a4 -#define ICON_KI_BUTTON_R "\xee\xa6\xa5" // U+e9a5 -#define ICON_KI_BUTTON_RIGHT "\xee\xa6\xa6" // U+e9a6 -#define ICON_KI_BUTTON_EMPTY "\xee\xa6\xa7" // U+e9a7 -#define ICON_KI_BUTTON_START "\xee\xa6\xa8" // U+e9a8 -#define ICON_KI_BUTTON_SELECT "\xee\xa6\xa9" // U+e9a9 -#define ICON_KI_DPAD "\xee\xa6\xaa" // U+e9aa -#define ICON_KI_DPAD_ALT "\xee\xa6\xab" // U+e9ab -#define ICON_KI_DPAD_TOP "\xee\xa6\xac" // U+e9ac -#define ICON_KI_DPAD_RIGHT "\xee\xa6\xad" // U+e9ad -#define ICON_KI_DPAD_BOTTOM "\xee\xa6\xae" // U+e9ae -#define ICON_KI_DPAD_LEFT "\xee\xa6\xaf" // U+e9af -#define ICON_KI_KEY_LARGE "\xee\xa6\xb0" // U+e9b0 -#define ICON_KI_KEY_LARGE_3D "\xee\xa6\xb1" // U+e9b1 -#define ICON_KI_KEY_SMALL "\xee\xa6\xb2" // U+e9b2 -#define ICON_KI_KEY_SMALL_3D "\xee\xa6\xb3" // U+e9b3 -#define ICON_KI_STICK_LEFT_TOP "\xee\xa6\xb4" // U+e9b4 -#define ICON_KI_STICK_LEFT_SIDE "\xee\xa6\xb5" // U+e9b5 -#define ICON_KI_STICK_RIGHT_SIDE "\xee\xa6\xb6" // U+e9b6 -#define ICON_KI_STICK_RIGHT_TOP "\xee\xa6\xb7" // U+e9b7 -#define ICON_KI_STICK_SIDE "\xee\xa6\xb8" // U+e9b8 -#define ICON_KI_STICK_TILT_LEFT "\xee\xa6\xb9" // U+e9b9 -#define ICON_KI_STICK_TILT_RIGHT "\xee\xa6\xba" // U+e9ba -#define ICON_KI_MOVE_BL "\xee\xa6\xbb" // U+e9bb -#define ICON_KI_MOVE_BR "\xee\xa6\xbc" // U+e9bc -#define ICON_KI_MOVE_BT "\xee\xa6\xbd" // U+e9bd -#define ICON_KI_MOVE_BT_ALT "\xee\xa6\xbe" // U+e9be -#define ICON_KI_MOVE_LB "\xee\xa6\xbf" // U+e9bf -#define ICON_KI_MOVE_LR "\xee\xa7\x80" // U+e9c0 -#define ICON_KI_MOVE_LR_ALT "\xee\xa7\x81" // U+e9c1 -#define ICON_KI_MOVE_LT "\xee\xa7\x82" // U+e9c2 -#define ICON_KI_MOVE_RB "\xee\xa7\x83" // U+e9c3 -#define ICON_KI_MOVE_RL "\xee\xa7\x84" // U+e9c4 -#define ICON_KI_MOVE_RL_ALT "\xee\xa7\x85" // U+e9c5 -#define ICON_KI_MOVE_RT "\xee\xa7\x86" // U+e9c6 -#define ICON_KI_MOVE_TB "\xee\xa7\x87" // U+e9c7 -#define ICON_KI_MOVE_TB_ALT "\xee\xa7\x88" // U+e9c8 -#define ICON_KI_MOVE_TL "\xee\xa7\x89" // U+e9c9 -#define ICON_KI_MOVE_TR "\xee\xa7\x8a" // U+e9ca -#define ICON_KI_STICK_MOVE_BL "\xee\xa7\x8b" // U+e9cb -#define ICON_KI_STICK_MOVE_BR "\xee\xa7\x8c" // U+e9cc -#define ICON_KI_STICK_MOVE_BT "\xee\xa7\x8d" // U+e9cd -#define ICON_KI_STICK_MOVE_BT_ALT "\xee\xa7\x8e" // U+e9ce -#define ICON_KI_STICK_MOVE_LB "\xee\xa7\x8f" // U+e9cf -#define ICON_KI_STICK_MOVE_LR "\xee\xa7\x90" // U+e9d0 -#define ICON_KI_STICK_MOVE_LR_ALT "\xee\xa7\x91" // U+e9d1 -#define ICON_KI_STICK_MOVE_LT "\xee\xa7\x92" // U+e9d2 -#define ICON_KI_STICK_MOVE_RB "\xee\xa7\x93" // U+e9d3 -#define ICON_KI_STICK_MOVE_RL "\xee\xa7\x94" // U+e9d4 -#define ICON_KI_STICK_MOVE_RL_ALT "\xee\xa7\x95" // U+e9d5 -#define ICON_KI_STICK_MOVE_RT "\xee\xa7\x96" // U+e9d6 -#define ICON_KI_STICK_MOVE_TB "\xee\xa7\x97" // U+e9d7 -#define ICON_KI_STICK_MOVE_TB_ALT "\xee\xa7\x98" // U+e9d8 -#define ICON_KI_STICK_MOVE_TL "\xee\xa7\x99" // U+e9d9 -#define ICON_KI_STICK_MOVE_TR "\xee\xa7\x9a" // U+e9da -#define ICON_KI_GITHUB "\xee\xa7\x9b" // U+e9db -#define ICON_KI_GITHUB_ALT "\xee\xa7\x9c" // U+e9dc -#define ICON_KI_TWITTER "\xee\xa7\x9d" // U+e9dd -#define ICON_KI_FACEBOOK "\xee\xa7\x9e" // U+e9de -#define ICON_KI_GOOGLE_PLUS "\xee\xa7\x9f" // U+e9df -#define ICON_KI_YOUTUBE "\xee\xa7\xa2" // U+e9e2 -#define ICON_KI_WE_HEART "\xee\xa7\xa3" // U+e9e3 -#define ICON_KI_WOLFCMS "\xee\xa7\xa0" // U+e9e0 -#define ICON_KI_WOLFCMS_ALT "\xee\xa7\xa1" // U+e9e1 -#define ICON_KI_BIN "\xee\xa7\xa4" //U+e9e4 diff --git a/include/imgui/Str.h b/include/imgui/Str.h deleted file mode 100644 index 83f8943..0000000 --- a/include/imgui/Str.h +++ /dev/null @@ -1,660 +0,0 @@ -// Str v0.33 -// Simple C++ string type with an optional local buffer, by Omar Cornut -// https://github.com/ocornut/str - -// LICENSE -// This software is in the public domain. Where that dedication is not -// recognized, you are granted a perpetual, irrevocable license to copy, -// distribute, and modify this file as you see fit. - -// USAGE -// Include this file in whatever places need to refer to it. -// In ONE .cpp file, write '#define STR_IMPLEMENTATION' before the #include of this file. -// This expands out the actual implementation into that C/C++ file. - - -/* -- This isn't a fully featured string class. -- It is a simple, bearable replacement to std::string that isn't heap abusive nor bloated (can actually be debugged by humans). -- String are mutable. We don't maintain size so length() is not-constant time. -- Maximum string size currently limited to 2 MB (we allocate 21 bits to hold capacity). -- Local buffer size is currently limited to 1023 bytes (we allocate 10 bits to hold local buffer size). -- In "non-owned" mode for literals/reference we don't do any tracking/counting of references. -- Overhead is 8-bytes in 32-bits, 16-bytes in 64-bits (12 + alignment). -- This code hasn't been tested very much. it is probably incomplete or broken. Made it for my own use. - -The idea is that you can provide an arbitrary sized local buffer if you expect string to fit -most of the time, and then you avoid using costly heap. - -No local buffer, always use heap, sizeof()==8~16 (depends if your pointers are 32-bits or 64-bits) - - Str s = "hey"; - -With a local buffer of 16 bytes, sizeof() == 8~16 + 16 bytes. - - Str16 s = "filename.h"; // copy into local buffer - Str16 s = "long_filename_not_very_long_but_longer_than_expected.h"; // use heap - -With a local buffer of 256 bytes, sizeof() == 8~16 + 256 bytes. - - Str256 s = "long_filename_not_very_long_but_longer_than_expected.h"; // copy into local buffer - -Common sizes are defined at the bottom of Str.h, you may define your own. - -Functions: - - Str256 s; - s.set("hello sailor"); // set (copy) - s.setf("%s/%s.tmp", folder, filename); // set (w/format) - s.append("hello"); // append. cost a length() calculation! - s.appendf("hello %d", 42); // append (w/format). cost a length() calculation! - s.set_ref("Hey!"); // set (literal/reference, just copy pointer, no tracking) - -Constructor helper for format string: add a trailing 'f' to the type. Underlying type is the same. - - Str256f filename("%s/%s.tmp", folder, filename); // construct (w/format) - fopen(Str256f("%s/%s.tmp, folder, filename).c_str(), "rb"); // construct (w/format), use as function param, destruct - -Constructor helper for reference/literal: - - StrRef ref("literal"); // copy pointer, no allocation, no string copy - StrRef ref2(GetDebugName()); // copy pointer. no tracking of anything whatsoever, know what you are doing! - -All StrXXX types derives from Str and instance hold the local buffer capacity. So you can pass e.g. Str256* to a function taking base type Str* and it will be functional. - - void MyFunc(Str& s) { s = "Hello"; } // will use local buffer if available in Str instance - -(Using a template e.g. Str we could remove the LocalBufSize storage but it would make passing typed Str<> to functions tricky. - Instead we don't use template so you can pass them around as the base type Str*. Also, templates are ugly.) -*/ - -/* - CHANGELOG - 0.33 - fixed capacity() return value to match standard. e.g. a Str256's capacity() now returns 255, not 256. - 0.32 - added owned() accessor. - 0.31 - fixed various warnings. - 0.30 - turned into a single header file, removed Str.cpp. - 0.29 - fixed bug when calling reserve on non-owned strings (ie. when using StrRef or set_ref), and fixed include. - 0.28 - breaking change: replaced Str32 by Str30 to avoid collision with Str32 from MacTypes.h . - 0.27 - added STR_API and basic .natvis file. - 0.26 - fixed set(cont char* src, const char* src_end) writing null terminator to the wrong position. - 0.25 - allow set(const char* NULL) or operator= NULL to clear the string. note that set() from range or other types are not allowed. - 0.24 - allow set_ref(const char* NULL) to clear the string. include fixes for linux. - 0.23 - added append(char). added append_from(int idx, XXX) functions. fixed some compilers warnings. - 0.22 - documentation improvements, comments. fixes for some compilers. - 0.21 - added StrXXXf() constructor to construct directly from a format string. -*/ - -/* -TODO -- Since we lose 4-bytes of padding on 64-bits architecture, perhaps just spread the header to 8-bytes and lift size limits? -- More functions/helpers. -*/ - -#ifndef STR_INCLUDED -#define STR_INCLUDED - -//------------------------------------------------------------------------- -// CONFIGURATION -//------------------------------------------------------------------------- - -#ifndef STR_MEMALLOC -#define STR_MEMALLOC malloc -#include -#endif -#ifndef STR_MEMFREE -#define STR_MEMFREE free -#include -#endif -#ifndef STR_ASSERT -#define STR_ASSERT assert -#include -#endif -#ifndef STR_API -#define STR_API -#endif -#include // for va_list -#include // for strlen, strcmp, memcpy, etc. - -// Configuration: #define STR_SUPPORT_STD_STRING 0 to disable setters variants using const std::string& (on by default) -#ifndef STR_SUPPORT_STD_STRING -#define STR_SUPPORT_STD_STRING 1 -#endif - -// Configuration: #define STR_DEFINE_STR32 1 to keep defining Str32/Str32f, but be warned: on macOS/iOS, MacTypes.h also defines a type named Str32. -#ifndef STR_DEFINE_STR32 -#define STR_DEFINE_STR32 0 -#endif - -#if STR_SUPPORT_STD_STRING -#include -#endif - -//------------------------------------------------------------------------- -// HEADERS -//------------------------------------------------------------------------- - -// This is the base class that you can pass around -// Footprint is 8-bytes (32-bits arch) or 16-bytes (64-bits arch) -class STR_API Str -{ - char* Data; // Point to LocalBuf() or heap allocated - int Capacity : 21; // Max 2 MB. Exclude zero terminator. - int LocalBufSize : 10; // Max 1023 bytes - unsigned int Owned : 1; // Set when we have ownership of the pointed data (most common, unless using set_ref() method or StrRef constructor) - -public: - inline char* c_str() { return Data; } - inline const char* c_str() const { return Data; } - inline bool empty() const { return Data[0] == 0; } - inline int length() const { return (int)strlen(Data); } // by design, allow user to write into the buffer at any time - inline int capacity() const { return Capacity; } - inline bool owned() const { return Owned ? true : false; } - - inline void set_ref(const char* src); - int setf(const char* fmt, ...); - int setfv(const char* fmt, va_list args); - int setf_nogrow(const char* fmt, ...); - int setfv_nogrow(const char* fmt, va_list args); - int append(char c); - int append(const char* s, const char* s_end = NULL); - int appendf(const char* fmt, ...); - int appendfv(const char* fmt, va_list args); - int append_from(int idx, char c); - int append_from(int idx, const char* s, const char* s_end = NULL); // If you know the string length or want to append from a certain point - int appendf_from(int idx, const char* fmt, ...); - int appendfv_from(int idx, const char* fmt, va_list args); - - void clear(); - void reserve(int cap); - void reserve_discard(int cap); - void shrink_to_fit(); - - inline char& operator[](size_t i) { return Data[i]; } - inline char operator[](size_t i) const { return Data[i]; } - //explicit operator const char*() const{ return Data; } - - inline Str(); - inline Str(const char* rhs); - inline void set(const char* src); - inline void set(const char* src, const char* src_end); - inline Str& operator=(const char* rhs) { set(rhs); return *this; } - inline bool operator==(const char* rhs) const { return strcmp(c_str(), rhs) == 0; } - - inline Str(const Str& rhs); - inline void set(const Str& src); - inline Str& operator=(const Str& rhs) { set(rhs); return *this; } - inline bool operator==(const Str& rhs) const { return strcmp(c_str(), rhs.c_str()) == 0; } - -#if STR_SUPPORT_STD_STRING - inline Str(const std::string& rhs); - inline void set(const std::string& src); - inline Str& operator=(const std::string& rhs) { set(rhs); return *this; } - inline bool operator==(const std::string& rhs)const { return strcmp(c_str(), rhs.c_str()) == 0; } -#endif - - // Destructor for all variants - inline ~Str() - { - if (Owned && !is_using_local_buf()) - STR_MEMFREE(Data); - } - - static char* EmptyBuffer; - -protected: - inline char* local_buf() { return (char*)this + sizeof(Str); } - inline const char* local_buf() const { return (char*)this + sizeof(Str); } - inline bool is_using_local_buf() const { return Data == local_buf() && LocalBufSize != 0; } - - // Constructor for StrXXX variants with local buffer - Str(unsigned short local_buf_size) - { - STR_ASSERT(local_buf_size < 1024); - Data = local_buf(); - Data[0] = '\0'; - Capacity = local_buf_size ? local_buf_size - 1 : 0; - LocalBufSize = local_buf_size; - Owned = 1; - } -}; - -void Str::set(const char* src) -{ - // We allow set(NULL) or via = operator to clear the string. - if (src == NULL) - { - clear(); - return; - } - int buf_len = (int)strlen(src); - if (Capacity < buf_len) - reserve_discard(buf_len); - memcpy(Data, src, (size_t)(buf_len + 1)); - Owned = 1; -} - -void Str::set(const char* src, const char* src_end) -{ - STR_ASSERT(src != NULL && src_end >= src); - int buf_len = (int)(src_end - src); - if ((int)Capacity < buf_len) - reserve_discard(buf_len); - memcpy(Data, src, (size_t)buf_len); - Data[buf_len] = 0; - Owned = 1; -} - -void Str::set(const Str& src) -{ - int buf_len = (int)strlen(src.c_str()); - if ((int)Capacity < buf_len) - reserve_discard(buf_len); - memcpy(Data, src.c_str(), (size_t)(buf_len + 1)); - Owned = 1; -} - -#if STR_SUPPORT_STD_STRING -void Str::set(const std::string& src) -{ - int buf_len = (int)src.length(); - if ((int)Capacity < buf_len) - reserve_discard(buf_len); - memcpy(Data, src.c_str(), (size_t)(buf_len + 1)); - Owned = 1; -} -#endif - -inline void Str::set_ref(const char* src) -{ - if (Owned && !is_using_local_buf()) - STR_MEMFREE(Data); - Data = src ? (char*)src : EmptyBuffer; - Capacity = 0; - Owned = 0; -} - -Str::Str() -{ - Data = EmptyBuffer; // Shared READ-ONLY initial buffer for 0 capacity - Capacity = 0; - LocalBufSize = 0; - Owned = 0; -} - -Str::Str(const Str& rhs) : Str() -{ - set(rhs); -} - -Str::Str(const char* rhs) : Str() -{ - set(rhs); -} - -#if STR_SUPPORT_STD_STRING -Str::Str(const std::string& rhs) : Str() -{ - set(rhs); -} -#endif - -// Literal/reference string -class StrRef : public Str -{ -public: - StrRef(const char* s) : Str() { set_ref(s); } -}; - -// Types embedding a local buffer -// NB: we need to override the constructor and = operator for both Str& and TYPENAME (without the later compiler will call a default copy operator) -#if STR_SUPPORT_STD_STRING - -#define STR_DEFINETYPE(TYPENAME, LOCALBUFSIZE) \ -class TYPENAME : public Str \ -{ \ - char local_buf[LOCALBUFSIZE]; \ -public: \ - TYPENAME() : Str(LOCALBUFSIZE) {} \ - TYPENAME(const Str& rhs) : Str(LOCALBUFSIZE) { set(rhs); } \ - TYPENAME(const char* rhs) : Str(LOCALBUFSIZE) { set(rhs); } \ - TYPENAME(const TYPENAME& rhs) : Str(LOCALBUFSIZE) { set(rhs); } \ - TYPENAME(const std::string& rhs) : Str(LOCALBUFSIZE) { set(rhs); } \ - TYPENAME& operator=(const char* rhs) { set(rhs); return *this; } \ - TYPENAME& operator=(const Str& rhs) { set(rhs); return *this; } \ - TYPENAME& operator=(const TYPENAME& rhs) { set(rhs); return *this; } \ - TYPENAME& operator=(const std::string& rhs) { set(rhs); return *this; } \ -}; - -#else - -#define STR_DEFINETYPE(TYPENAME, LOCALBUFSIZE) \ -class TYPENAME : public Str \ -{ \ - char local_buf[LOCALBUFSIZE]; \ -public: \ - TYPENAME() : Str(LOCALBUFSIZE) {} \ - TYPENAME(const Str& rhs) : Str(LOCALBUFSIZE) { set(rhs); } \ - TYPENAME(const char* rhs) : Str(LOCALBUFSIZE) { set(rhs); } \ - TYPENAME(const TYPENAME& rhs) : Str(LOCALBUFSIZE) { set(rhs); } \ - TYPENAME& operator=(const char* rhs) { set(rhs); return *this; } \ - TYPENAME& operator=(const Str& rhs) { set(rhs); return *this; } \ - TYPENAME& operator=(const TYPENAME& rhs) { set(rhs); return *this; } \ -}; - -#endif - -// Disable PVS-Studio warning V730: Not all members of a class are initialized inside the constructor (local_buf is not initialized and that is fine) -// -V:STR_DEFINETYPE:730 - -// Helper to define StrXXXf constructors -#define STR_DEFINETYPE_F(TYPENAME, TYPENAME_F) \ -class TYPENAME_F : public TYPENAME \ -{ \ -public: \ - TYPENAME_F(const char* fmt, ...) : TYPENAME() { va_list args; va_start(args, fmt); setfv(fmt, args); va_end(args); } \ -}; - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunused-private-field" // warning : private field 'local_buf' is not used -#endif - -// Declaring types for common sizes here -STR_DEFINETYPE(Str16, 16) -STR_DEFINETYPE(Str30, 30) -STR_DEFINETYPE(Str64, 64) -STR_DEFINETYPE(Str128, 128) -STR_DEFINETYPE(Str256, 256) -STR_DEFINETYPE(Str512, 512) - -// Declaring helper constructors to pass in format strings in one statement -STR_DEFINETYPE_F(Str16, Str16f) -STR_DEFINETYPE_F(Str30, Str30f) -STR_DEFINETYPE_F(Str64, Str64f) -STR_DEFINETYPE_F(Str128, Str128f) -STR_DEFINETYPE_F(Str256, Str256f) -STR_DEFINETYPE_F(Str512, Str512f) - -#if STR_DEFINE_STR32 -STR_DEFINETYPE(Str32, 32) -STR_DEFINETYPE_F(Str32, Str32f) -#endif - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -#endif // #ifndef STR_INCLUDED - -//------------------------------------------------------------------------- -// IMPLEMENTATION -//------------------------------------------------------------------------- - -#ifdef STR_IMPLEMENTATION - -#include // for vsnprintf - -// On some platform vsnprintf() takes va_list by reference and modifies it. -// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it. -#ifndef va_copy -#define va_copy(dest, src) (dest = src) -#endif - -// Static empty buffer we can point to for empty strings -// Pointing to a literal increases the like-hood of getting a crash if someone attempts to write in the empty string buffer. -char* Str::EmptyBuffer = (char*)"\0NULL"; - -// Clear -void Str::clear() -{ - if (Owned && !is_using_local_buf()) - STR_MEMFREE(Data); - if (LocalBufSize) - { - Data = local_buf(); - Data[0] = '\0'; - Capacity = LocalBufSize - 1; - Owned = 1; - } - else - { - Data = EmptyBuffer; - Capacity = 0; - Owned = 0; - } -} - -// Reserve memory, preserving the current of the buffer -// Capacity doesn't include the zero terminator, so reserve(5) is enough to store "hello". -void Str::reserve(int new_capacity) -{ - if (new_capacity <= Capacity) - return; - - char* new_data; - if (new_capacity <= LocalBufSize - 1) - { - // Disowned -> LocalBuf - new_data = local_buf(); - new_capacity = LocalBufSize - 1; - } - else - { - // Disowned or LocalBuf -> Heap - new_data = (char*)STR_MEMALLOC((size_t)(new_capacity + 1) * sizeof(char)); - } - - // string in Data might be longer than new_capacity if it wasn't owned, don't copy too much -#ifdef _MSC_VER - strncpy_s(new_data, (size_t)new_capacity + 1, Data, (size_t)new_capacity); -#else - strncpy(new_data, Data, (size_t)new_capacity); -#endif - new_data[new_capacity] = 0; - - if (Owned && !is_using_local_buf()) - STR_MEMFREE(Data); - - Data = new_data; - Capacity = new_capacity; - Owned = 1; -} - -// Reserve memory, discarding the current of the buffer (if we expect to be fully rewritten) -void Str::reserve_discard(int new_capacity) -{ - if (new_capacity <= Capacity) - return; - - if (Owned && !is_using_local_buf()) - STR_MEMFREE(Data); - - if (new_capacity <= LocalBufSize - 1) - { - // Disowned -> LocalBuf - Data = local_buf(); - Capacity = LocalBufSize - 1; - } - else - { - // Disowned or LocalBuf -> Heap - Data = (char*)STR_MEMALLOC((size_t)(new_capacity + 1) * sizeof(char)); - Capacity = new_capacity; - } - Owned = 1; -} - -void Str::shrink_to_fit() -{ - if (!Owned || is_using_local_buf()) - return; - int new_capacity = length(); - if (Capacity <= new_capacity) - return; - - char* new_data = (char*)STR_MEMALLOC((size_t)(new_capacity + 1) * sizeof(char)); - memcpy(new_data, Data, (size_t)(new_capacity + 1)); - STR_MEMFREE(Data); - Data = new_data; - Capacity = new_capacity; -} - -// FIXME: merge setfv() and appendfv()? -int Str::setfv(const char* fmt, va_list args) -{ - // Needed for portability on platforms where va_list are passed by reference and modified by functions - va_list args2; - va_copy(args2, args); - - // MSVC returns -1 on overflow when writing, which forces us to do two passes - // FIXME-OPT: Find a way around that. -#ifdef _MSC_VER - int len = vsnprintf(NULL, 0, fmt, args); - STR_ASSERT(len >= 0); - - if (Capacity < len) - reserve_discard(len); - len = vsnprintf(Data, (size_t)len + 1, fmt, args2); -#else - // First try - int len = vsnprintf(Owned ? Data : NULL, Owned ? (size_t)(Capacity + 1): 0, fmt, args); - STR_ASSERT(len >= 0); - - if (Capacity < len) - { - reserve_discard(len); - len = vsnprintf(Data, (size_t)len + 1, fmt, args2); - } -#endif - - STR_ASSERT(Owned); - return len; -} - -int Str::setf(const char* fmt, ...) -{ - va_list args; - va_start(args, fmt); - int len = setfv(fmt, args); - va_end(args); - return len; -} - -int Str::setfv_nogrow(const char* fmt, va_list args) -{ - STR_ASSERT(Owned); - - if (Capacity == 0) - return 0; - - int w = vsnprintf(Data, (size_t)(Capacity + 1), fmt, args); - Data[Capacity] = 0; - Owned = 1; - return (w == -1) ? Capacity : w; -} - -int Str::setf_nogrow(const char* fmt, ...) -{ - va_list args; - va_start(args, fmt); - int len = setfv_nogrow(fmt, args); - va_end(args); - return len; -} - -int Str::append_from(int idx, char c) -{ - int add_len = 1; - if (Capacity < idx + add_len) - reserve(idx + add_len); - Data[idx] = c; - Data[idx + add_len] = 0; - STR_ASSERT(Owned); - return add_len; -} - -int Str::append_from(int idx, const char* s, const char* s_end) -{ - if (!s_end) - s_end = s + strlen(s); - int add_len = (int)(s_end - s); - if (Capacity < idx + add_len) - reserve(idx + add_len); - memcpy(Data + idx, (const void*)s, (size_t)add_len); - Data[idx + add_len] = 0; // Our source data isn't necessarily zero terminated - STR_ASSERT(Owned); - return add_len; -} - -// FIXME: merge setfv() and appendfv()? -int Str::appendfv_from(int idx, const char* fmt, va_list args) -{ - // Needed for portability on platforms where va_list are passed by reference and modified by functions - va_list args2; - va_copy(args2, args); - - // MSVC returns -1 on overflow when writing, which forces us to do two passes - // FIXME-OPT: Find a way around that. -#ifdef _MSC_VER - int add_len = vsnprintf(NULL, 0, fmt, args); - STR_ASSERT(add_len >= 0); - - if (Capacity < idx + add_len) - reserve(idx + add_len); - add_len = vsnprintf(Data + idx, add_len + 1, fmt, args2); -#else - // First try - int add_len = vsnprintf(Owned ? Data + idx : NULL, Owned ? (size_t)(Capacity + 1 - idx) : 0, fmt, args); - STR_ASSERT(add_len >= 0); - - if (Capacity < idx + add_len) - { - reserve(idx + add_len); - add_len = vsnprintf(Data + idx, (size_t)add_len + 1, fmt, args2); - } -#endif - - STR_ASSERT(Owned); - return add_len; -} - -int Str::appendf_from(int idx, const char* fmt, ...) -{ - va_list args; - va_start(args, fmt); - int len = appendfv_from(idx, fmt, args); - va_end(args); - return len; -} - -int Str::append(char c) -{ - int cur_len = length(); - return append_from(cur_len, c); -} - -int Str::append(const char* s, const char* s_end) -{ - int cur_len = length(); - return append_from(cur_len, s, s_end); -} - -int Str::appendfv(const char* fmt, va_list args) -{ - int cur_len = length(); - return appendfv_from(cur_len, fmt, args); -} - -int Str::appendf(const char* fmt, ...) -{ - va_list args; - va_start(args, fmt); - int len = appendfv(fmt, args); - va_end(args); - return len; -} - -#endif // #define STR_IMPLEMENTATION - -//------------------------------------------------------------------------- diff --git a/include/imgui/imconfig.h b/include/imgui/imconfig.h deleted file mode 100644 index 4dab1b6..0000000 --- a/include/imgui/imconfig.h +++ /dev/null @@ -1,145 +0,0 @@ -//----------------------------------------------------------------------------- -// DEAR IMGUI COMPILE-TIME OPTIONS -// Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure. -// You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions. -//----------------------------------------------------------------------------- -// A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it) -// B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own file without touching this template. -//----------------------------------------------------------------------------- -// You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp -// files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures. -// Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts. -// Call IMGUI_CHECKVERSION() from your .cpp file to verify that the data structures your files are using are matching the ones imgui.cpp is using. -//----------------------------------------------------------------------------- - -#pragma once - -//---- Define assertion handler. Defaults to calling assert(). -// If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement. -//#define IM_ASSERT(_EXPR) MyAssert(_EXPR) -//#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts - -//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows -// Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility. -// - Windows DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() -// for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details. -//#define IMGUI_API __declspec(dllexport) // MSVC Windows: DLL export -//#define IMGUI_API __declspec(dllimport) // MSVC Windows: DLL import -//#define IMGUI_API __attribute__((visibility("default"))) // GCC/Clang: override visibility when set is hidden - -//---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to clean your code of obsolete function/names. -//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS - -//---- Disable all of Dear ImGui or don't implement standard windows/tools. -// It is very strongly recommended to NOT disable the demo windows and debug tool during development. They are extremely useful in day to day work. Please read comments in imgui_demo.cpp. -//#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty. -//#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty. -//#define IMGUI_DISABLE_DEBUG_TOOLS // Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowIDStackToolWindow() will be empty. - -//---- Don't implement some functions to reduce linkage requirements. -//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a) -//#define IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW) -//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't implement default IME handler (won't require imm32.lib/.a) -//#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, IME). -//#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default). -//#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS // Don't implement default platform_io.Platform_OpenInShellFn() handler (Win32: ShellExecute(), require shell32.lib/.a, Mac/Linux: use system("")). -//#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf) -//#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself. -//#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies) -//#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function. -//#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). -//#define IMGUI_DISABLE_DEFAULT_FONT // Disable default embedded font (ProggyClean.ttf), remove ~9.5 KB from output binary. AddFontDefault() will assert. -//#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available - -//---- Enable Test Engine / Automation features. -//#define IMGUI_ENABLE_TEST_ENGINE // Enable imgui_test_engine hooks. Generally set automatically by include "imgui_te_config.h", see Test Engine for details. - -//---- Include imgui_user.h at the end of imgui.h as a convenience -// May be convenient for some users to only explicitly include vanilla imgui.h and have extra stuff included. -//#define IMGUI_INCLUDE_IMGUI_USER_H -//#define IMGUI_USER_H_FILENAME "my_folder/my_imgui_user.h" - -//---- Pack vertex colors as BGRA8 instead of RGBA8 (to avoid converting from one to another). Need dedicated backend support. -//#define IMGUI_USE_BGRA_PACKED_COLOR - -//---- Use legacy CRC32-adler tables (used before 1.91.6), in order to preserve old .ini data that you cannot afford to invalidate. -//#define IMGUI_USE_LEGACY_CRC32_ADLER - -//---- Use 32-bit for ImWchar (default is 16-bit) to support Unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...) -//#define IMGUI_USE_WCHAR32 - -//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version -// By default the embedded implementations are declared static and not available outside of Dear ImGui sources files. -//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" -//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" -//#define IMGUI_STB_SPRINTF_FILENAME "my_folder/stb_sprintf.h" // only used if IMGUI_USE_STB_SPRINTF is defined. -//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION -//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION -//#define IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION // only disabled if IMGUI_USE_STB_SPRINTF is defined. - -//---- Use stb_sprintf.h for a faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined) -// Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by stb_sprintf.h. -//#define IMGUI_USE_STB_SPRINTF - -//---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui) -// Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided). -// On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'. -//#define IMGUI_ENABLE_FREETYPE - -//---- Use FreeType + plutosvg or lunasvg to render OpenType SVG fonts (SVGinOT) -// Only works in combination with IMGUI_ENABLE_FREETYPE. -// - plutosvg is currently easier to install, as e.g. it is part of vcpkg. It will support more fonts and may load them faster. See misc/freetype/README for instructions. -// - Both require headers to be available in the include path + program to be linked with the library code (not provided). -// - (note: lunasvg implementation is based on Freetype's rsvg-port.c which is licensed under CeCILL-C Free Software License Agreement) -//#define IMGUI_ENABLE_FREETYPE_PLUTOSVG -//#define IMGUI_ENABLE_FREETYPE_LUNASVG - -//---- Use stb_truetype to build and rasterize the font atlas (default) -// The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend. -//#define IMGUI_ENABLE_STB_TRUETYPE - -//---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4. -// This will be inlined as part of ImVec2 and ImVec4 class declarations. -/* -#define IM_VEC2_CLASS_EXTRA \ - constexpr ImVec2(const MyVec2& f) : x(f.x), y(f.y) {} \ - operator MyVec2() const { return MyVec2(x,y); } - -#define IM_VEC4_CLASS_EXTRA \ - constexpr ImVec4(const MyVec4& f) : x(f.x), y(f.y), z(f.z), w(f.w) {} \ - operator MyVec4() const { return MyVec4(x,y,z,w); } -*/ -//---- ...Or use Dear ImGui's own very basic math operators. -//#define IMGUI_DEFINE_MATH_OPERATORS - -//---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices. -// Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices). -// Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer. -// Read about ImGuiBackendFlags_RendererHasVtxOffset for details. -//#define ImDrawIdx unsigned int - -//---- Override ImDrawCallback signature (will need to modify renderer backends accordingly) -//struct ImDrawList; -//struct ImDrawCmd; -//typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data); -//#define ImDrawCallback MyImDrawCallback - -//---- Debug Tools: Macro to break in Debugger (we provide a default implementation of this in the codebase) -// (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.) -//#define IM_DEBUG_BREAK IM_ASSERT(0) -//#define IM_DEBUG_BREAK __debugbreak() - -//---- Debug Tools: Enable highlight ID conflicts _before_ hovering items. When io.ConfigDebugHighlightIdConflicts is set. -// (THIS WILL SLOW DOWN DEAR IMGUI. Only use occasionally and disable after use) -//#define IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS - -//---- Debug Tools: Enable slower asserts -//#define IMGUI_DEBUG_PARANOID - -//---- Tip: You can add extra functions within the ImGui:: namespace from anywhere (e.g. your own sources/header files) -/* -namespace ImGui -{ - void MyFunction(const char* name, MyMatrix44* mtx); -} -*/ diff --git a/include/imgui/imgui.h b/include/imgui/imgui.h deleted file mode 100644 index a2b2a1f..0000000 --- a/include/imgui/imgui.h +++ /dev/null @@ -1,4121 +0,0 @@ -// dear imgui, v1.92.1 -// (headers) - -// Help: -// - See links below. -// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. -// - Read top of imgui.cpp for more details, links and comments. -// - Add '#define IMGUI_DEFINE_MATH_OPERATORS' before including this file (or in imconfig.h) to access courtesy maths operators for ImVec2 and ImVec4. - -// Resources: -// - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md) -// - Homepage ................... https://github.com/ocornut/imgui -// - Releases & changelog ....... https://github.com/ocornut/imgui/releases -// - Gallery .................... https://github.com/ocornut/imgui/issues?q=label%3Agallery (please post your screenshots/video there!) -// - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there) -// - Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code) -// - Third-party Extensions https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more) -// - Bindings/Backends https://github.com/ocornut/imgui/wiki/Bindings (language bindings, backends for various tech/engines) -// - Glossary https://github.com/ocornut/imgui/wiki/Glossary -// - Debug Tools https://github.com/ocornut/imgui/wiki/Debug-Tools -// - Software using Dear ImGui https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui -// - Issues & support ........... https://github.com/ocornut/imgui/issues -// - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps) - -// For first-time users having issues compiling/linking/running/loading fonts: -// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above. -// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there. - -// Library Version -// (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.92.1" -#define IMGUI_VERSION_NUM 19210 -#define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 -#define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 - -/* - -Index of this file: -// [SECTION] Header mess -// [SECTION] Forward declarations and basic types -// [SECTION] Texture identifiers (ImTextureID, ImTextureRef) -// [SECTION] Dear ImGui end-user API functions -// [SECTION] Flags & Enumerations -// [SECTION] Tables API flags and structures (ImGuiTableFlags, ImGuiTableColumnFlags, ImGuiTableRowFlags, ImGuiTableBgTarget, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) -// [SECTION] Helpers: Debug log, Memory allocations macros, ImVector<> -// [SECTION] ImGuiStyle -// [SECTION] ImGuiIO -// [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) -// [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) -// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectIO, ImGuiSelectionRequest, ImGuiSelectionBasicStorage, ImGuiSelectionExternalStorage) -// [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) -// [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) -// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFontBaked, ImFont) -// [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport) -// [SECTION] ImGuiPlatformIO + other Platform Dependent Interfaces (ImGuiPlatformImeData) -// [SECTION] Obsolete functions and types - -*/ - -#pragma once - -// Configuration file with compile-time options -// (edit imconfig.h or '#define IMGUI_USER_CONFIG "myfilename.h" from your build system) -#ifdef IMGUI_USER_CONFIG -#include IMGUI_USER_CONFIG -#endif -#include "imconfig.h" - -#ifndef IMGUI_DISABLE - -//----------------------------------------------------------------------------- -// [SECTION] Header mess -//----------------------------------------------------------------------------- - -// Includes -#include // FLT_MIN, FLT_MAX -#include // va_list, va_start, va_end -#include // ptrdiff_t, NULL -#include // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp - -// Define attributes of all API symbols declarations (e.g. for DLL under Windows) -// IMGUI_API is used for core imgui functions, IMGUI_IMPL_API is used for the default backends files (imgui_impl_xxx.h) -// Using dear imgui via a shared library is not recommended: we don't guarantee backward nor forward ABI compatibility + this is a call-heavy library and function call overhead adds up. -#ifndef IMGUI_API -#define IMGUI_API -#endif -#ifndef IMGUI_IMPL_API -#define IMGUI_IMPL_API IMGUI_API -#endif - -// Helper Macros -#ifndef IM_ASSERT -#include -#define IM_ASSERT(_EXPR) assert(_EXPR) // You can override the default assert handler by editing imconfig.h -#endif -#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR) / sizeof(*(_ARR)))) // Size of a static C-style array. Don't use on pointers! -#define IM_UNUSED(_VAR) ((void)(_VAR)) // Used to silence "unused variable warnings". Often useful as asserts may be stripped out from final builds. - -// Check that version and structures layouts are matching between compiled imgui code and caller. Read comments above DebugCheckVersionAndDataLayout() for details. -#define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) - -// Helper Macros - IM_FMTARGS, IM_FMTLIST: Apply printf-style warnings to our formatting functions. -// (MSVC provides an equivalent mechanism via SAL Annotations but it would require the macros in a different -// location. e.g. #include + void myprintf(_Printf_format_string_ const char* format, ...)) -#if !defined(IMGUI_USE_STB_SPRINTF) && defined(__MINGW32__) && !defined(__clang__) -#define IM_FMTARGS(FMT) __attribute__((format(gnu_printf, FMT, FMT+1))) -#define IM_FMTLIST(FMT) __attribute__((format(gnu_printf, FMT, 0))) -#elif !defined(IMGUI_USE_STB_SPRINTF) && (defined(__clang__) || defined(__GNUC__)) -#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) -#define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0))) -#else -#define IM_FMTARGS(FMT) -#define IM_FMTLIST(FMT) -#endif - -// Disable some of MSVC most aggressive Debug runtime checks in function header/footer (used in some simple/low-level functions) -#if defined(_MSC_VER) && !defined(__clang__) && !defined(__INTEL_COMPILER) && !defined(IMGUI_DEBUG_PARANOID) -#define IM_MSVC_RUNTIME_CHECKS_OFF __pragma(runtime_checks("",off)) __pragma(check_stack(off)) __pragma(strict_gs_check(push,off)) -#define IM_MSVC_RUNTIME_CHECKS_RESTORE __pragma(runtime_checks("",restore)) __pragma(check_stack()) __pragma(strict_gs_check(pop)) -#else -#define IM_MSVC_RUNTIME_CHECKS_OFF -#define IM_MSVC_RUNTIME_CHECKS_RESTORE -#endif - -// Warnings -#ifdef _MSC_VER -#pragma warning (push) -#pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6). -#endif -#if defined(__clang__) -#pragma clang diagnostic push -#if __has_warning("-Wunknown-warning-option") -#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' -#endif -#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' -#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast -#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe -#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant -#pragma clang diagnostic ignored "-Wreserved-identifier" // warning: identifier '_Xxx' is reserved because it starts with '_' followed by a capital letter -#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access -#pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type -#elif defined(__GNUC__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind -#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe -#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead -#endif - -//----------------------------------------------------------------------------- -// [SECTION] Forward declarations and basic types -//----------------------------------------------------------------------------- - -// Scalar data types -typedef unsigned int ImGuiID;// A unique ID used by widgets (typically the result of hashing a stack of string) -typedef signed char ImS8; // 8-bit signed integer -typedef unsigned char ImU8; // 8-bit unsigned integer -typedef signed short ImS16; // 16-bit signed integer -typedef unsigned short ImU16; // 16-bit unsigned integer -typedef signed int ImS32; // 32-bit signed integer == int -typedef unsigned int ImU32; // 32-bit unsigned integer (often used to store packed colors) -typedef signed long long ImS64; // 64-bit signed integer -typedef unsigned long long ImU64; // 64-bit unsigned integer - -// Forward declarations: ImDrawList, ImFontAtlas layer -struct ImDrawChannel; // Temporary storage to output draw commands out of order, used by ImDrawListSplitter and ImDrawList::ChannelsSplit() -struct ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call, unless it is a callback) -struct ImDrawData; // All draw command lists required to render the frame + pos/size coordinates to use for the projection matrix. -struct ImDrawList; // A single draw command list (generally one per window, conceptually you may see this as a dynamic "mesh" builder) -struct ImDrawListSharedData; // Data shared among multiple draw lists (typically owned by parent ImGui context, but you may create one yourself) -struct ImDrawListSplitter; // Helper to split a draw list into different layers which can be drawn into out of order, then flattened back. -struct ImDrawVert; // A single vertex (pos + uv + col = 20 bytes by default. Override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) -struct ImFont; // Runtime data for a single font within a parent ImFontAtlas -struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader -struct ImFontAtlasBuilder; // Opaque storage for building a ImFontAtlas -struct ImFontAtlasRect; // Output of ImFontAtlas::GetCustomRect() when using custom rectangles. -struct ImFontBaked; // Baked data for a ImFont at a given size. -struct ImFontConfig; // Configuration data when adding a font or merging fonts -struct ImFontGlyph; // A single font glyph (code point + coordinates within in ImFontAtlas + offset) -struct ImFontGlyphRangesBuilder; // Helper to build glyph ranges from text/string data -struct ImFontLoader; // Opaque interface to a font loading backend (stb_truetype, FreeType etc.). -struct ImTextureData; // Specs and pixel storage for a texture used by Dear ImGui. -struct ImTextureRect; // Coordinates of a rectangle within a texture. -struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 (*OBSOLETE* please avoid using) - -// Forward declarations: ImGui layer -struct ImGuiContext; // Dear ImGui context (opaque structure, unless including imgui_internal.h) -struct ImGuiIO; // Main configuration and I/O between your application and ImGui (also see: ImGuiPlatformIO) -struct ImGuiInputTextCallbackData; // Shared state of InputText() when using custom ImGuiInputTextCallback (rare/advanced use) -struct ImGuiKeyData; // Storage for ImGuiIO and IsKeyDown(), IsKeyPressed() etc functions. -struct ImGuiListClipper; // Helper to manually clip large list of items -struct ImGuiMultiSelectIO; // Structure to interact with a BeginMultiSelect()/EndMultiSelect() block -struct ImGuiOnceUponAFrame; // Helper for running a block of code not more than once a frame -struct ImGuiPayload; // User data payload for drag and drop operations -struct ImGuiPlatformIO; // Interface between platform/renderer backends and ImGui (e.g. Clipboard, IME hooks). Extends ImGuiIO. In docking branch, this gets extended to support multi-viewports. -struct ImGuiPlatformImeData; // Platform IME data for io.PlatformSetImeDataFn() function. -struct ImGuiSelectionBasicStorage; // Optional helper to store multi-selection state + apply multi-selection requests. -struct ImGuiSelectionExternalStorage;//Optional helper to apply multi-selection requests to existing randomly accessible storage. -struct ImGuiSelectionRequest; // A selection request (stored in ImGuiMultiSelectIO) -struct ImGuiSizeCallbackData; // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use) -struct ImGuiStorage; // Helper for key->value storage (container sorted by key) -struct ImGuiStoragePair; // Helper for key->value storage (pair) -struct ImGuiStyle; // Runtime data for styling/colors -struct ImGuiTableSortSpecs; // Sorting specifications for a table (often handling sort specs for a single column, occasionally more) -struct ImGuiTableColumnSortSpecs; // Sorting specification for one column of a table -struct ImGuiTextBuffer; // Helper to hold and append into a text buffer (~string builder) -struct ImGuiTextFilter; // Helper to parse and apply text filters (e.g. "aaaaa[,bbbbb][,ccccc]") -struct ImGuiViewport; // A Platform Window (always only one in 'master' branch), in the future may represent Platform Monitor - -// Enumerations -// - We don't use strongly typed enums much because they add constraints (can't extend in private code, can't store typed in bit fields, extra casting on iteration) -// - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists! -// - In Visual Studio: CTRL+comma ("Edit.GoToAll") can follow symbols inside comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. -// - In Visual Studio w/ Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. -// - In VS Code, CLion, etc.: CTRL+click can follow symbols inside comments. -enum ImGuiDir : int; // -> enum ImGuiDir // Enum: A cardinal direction (Left, Right, Up, Down) -enum ImGuiKey : int; // -> enum ImGuiKey // Enum: A key identifier (ImGuiKey_XXX or ImGuiMod_XXX value) -enum ImGuiMouseSource : int; // -> enum ImGuiMouseSource // Enum; A mouse input source identifier (Mouse, TouchScreen, Pen) -enum ImGuiSortDirection : ImU8; // -> enum ImGuiSortDirection // Enum: A sorting direction (ascending or descending) -typedef int ImGuiCol; // -> enum ImGuiCol_ // Enum: A color identifier for styling -typedef int ImGuiCond; // -> enum ImGuiCond_ // Enum: A condition for many Set*() functions -typedef int ImGuiDataType; // -> enum ImGuiDataType_ // Enum: A primary data type -typedef int ImGuiMouseButton; // -> enum ImGuiMouseButton_ // Enum: A mouse button identifier (0=left, 1=right, 2=middle) -typedef int ImGuiMouseCursor; // -> enum ImGuiMouseCursor_ // Enum: A mouse cursor shape -typedef int ImGuiStyleVar; // -> enum ImGuiStyleVar_ // Enum: A variable identifier for styling -typedef int ImGuiTableBgTarget; // -> enum ImGuiTableBgTarget_ // Enum: A color target for TableSetBgColor() - -// Flags (declared as int to allow using as flags without overhead, and to not pollute the top of this file) -// - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists! -// - In Visual Studio: CTRL+comma ("Edit.GoToAll") can follow symbols inside comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. -// - In Visual Studio w/ Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. -// - In VS Code, CLion, etc.: CTRL+click can follow symbols inside comments. -typedef int ImDrawFlags; // -> enum ImDrawFlags_ // Flags: for ImDrawList functions -typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList instance -typedef int ImFontFlags; // -> enum ImFontFlags_ // Flags: for ImFont -typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas -typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags -typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for InvisibleButton() -typedef int ImGuiChildFlags; // -> enum ImGuiChildFlags_ // Flags: for BeginChild() -typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc. -typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags -typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo() -typedef int ImGuiDragDropFlags; // -> enum ImGuiDragDropFlags_ // Flags: for BeginDragDropSource(), AcceptDragDropPayload() -typedef int ImGuiFocusedFlags; // -> enum ImGuiFocusedFlags_ // Flags: for IsWindowFocused() -typedef int ImGuiHoveredFlags; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc. -typedef int ImGuiInputFlags; // -> enum ImGuiInputFlags_ // Flags: for Shortcut(), SetNextItemShortcut() -typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: for InputText(), InputTextMultiline() -typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag(), shared by all items -typedef int ImGuiKeyChord; // -> ImGuiKey | ImGuiMod_XXX // Flags: for IsKeyChordPressed(), Shortcut() etc. an ImGuiKey optionally OR-ed with one or more ImGuiMod_XXX values. -typedef int ImGuiPopupFlags; // -> enum ImGuiPopupFlags_ // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() -typedef int ImGuiMultiSelectFlags; // -> enum ImGuiMultiSelectFlags_// Flags: for BeginMultiSelect() -typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable() -typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. -typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar() -typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem() -typedef int ImGuiTableFlags; // -> enum ImGuiTableFlags_ // Flags: For BeginTable() -typedef int ImGuiTableColumnFlags; // -> enum ImGuiTableColumnFlags_// Flags: For TableSetupColumn() -typedef int ImGuiTableRowFlags; // -> enum ImGuiTableRowFlags_ // Flags: For TableNextRow() -typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader() -typedef int ImGuiViewportFlags; // -> enum ImGuiViewportFlags_ // Flags: for ImGuiViewport -typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin(), BeginChild() - -// Character types -// (we generally use UTF-8 encoded string in the API. This is storage specifically for a decoded character used for keyboard input and display) -typedef unsigned int ImWchar32; // A single decoded U32 character/code point. We encode them as multi bytes UTF-8 when used in strings. -typedef unsigned short ImWchar16; // A single decoded U16 character/code point. We encode them as multi bytes UTF-8 when used in strings. -#ifdef IMGUI_USE_WCHAR32 // ImWchar [configurable type: override in imconfig.h with '#define IMGUI_USE_WCHAR32' to support Unicode planes 1-16] -typedef ImWchar32 ImWchar; -#else -typedef ImWchar16 ImWchar; -#endif - -// Multi-Selection item index or identifier when using BeginMultiSelect() -// - Used by SetNextItemSelectionUserData() + and inside ImGuiMultiSelectIO structure. -// - Most users are likely to use this store an item INDEX but this may be used to store a POINTER/ID as well. Read comments near ImGuiMultiSelectIO for details. -typedef ImS64 ImGuiSelectionUserData; - -// Callback and functions types -typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData* data); // Callback function for ImGui::InputText() -typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data); // Callback function for ImGui::SetNextWindowSizeConstraints() -typedef void* (*ImGuiMemAllocFunc)(size_t sz, void* user_data); // Function signature for ImGui::SetAllocatorFunctions() -typedef void (*ImGuiMemFreeFunc)(void* ptr, void* user_data); // Function signature for ImGui::SetAllocatorFunctions() - -// ImVec2: 2D vector used to store positions, sizes etc. [Compile-time configurable type] -// - This is a frequently used type in the API. Consider using IM_VEC2_CLASS_EXTRA to create implicit cast from/to our preferred type. -// - Add '#define IMGUI_DEFINE_MATH_OPERATORS' before including this file (or in imconfig.h) to access courtesy maths operators for ImVec2 and ImVec4. -IM_MSVC_RUNTIME_CHECKS_OFF -struct ImVec2 -{ - float x, y; - constexpr ImVec2() : x(0.0f), y(0.0f) { } - constexpr ImVec2(float _x, float _y) : x(_x), y(_y) { } - float& operator[] (size_t idx) { IM_ASSERT(idx == 0 || idx == 1); return ((float*)(void*)(char*)this)[idx]; } // We very rarely use this [] operator, so the assert overhead is fine. - float operator[] (size_t idx) const { IM_ASSERT(idx == 0 || idx == 1); return ((const float*)(const void*)(const char*)this)[idx]; } -#ifdef IM_VEC2_CLASS_EXTRA - IM_VEC2_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec2. -#endif -}; - -// ImVec4: 4D vector used to store clipping rectangles, colors etc. [Compile-time configurable type] -struct ImVec4 -{ - float x, y, z, w; - constexpr ImVec4() : x(0.0f), y(0.0f), z(0.0f), w(0.0f) { } - constexpr ImVec4(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w) { } -#ifdef IM_VEC4_CLASS_EXTRA - IM_VEC4_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec4. -#endif -}; -IM_MSVC_RUNTIME_CHECKS_RESTORE - -//----------------------------------------------------------------------------- -// [SECTION] Texture identifiers (ImTextureID, ImTextureRef) -//----------------------------------------------------------------------------- - -// ImTextureID = backend specific, low-level identifier for a texture uploaded in GPU/graphics system. -// [Compile-time configurable type] -// - When a Rendered Backend creates a texture, it store its native identifier into a ImTextureID value. -// (e.g. Used by DX11 backend to a `ID3D11ShaderResourceView*`; Used by OpenGL backends to store `GLuint`; -// Used by SDLGPU backend to store a `SDL_GPUTextureSamplerBinding*`, etc.). -// - User may submit their own textures to e.g. ImGui::Image() function by passing the same type. -// - During the rendering loop, the Renderer Backend retrieve the ImTextureID, which stored inside a -// ImTextureRef, which is stored inside a ImDrawCmd. -// - Compile-time type configuration: -// - To use something other than a 64-bit value: add '#define ImTextureID MyTextureType*' in your imconfig.h file. -// - This can be whatever to you want it to be! read the FAQ entry about textures for details. -// - You may decide to store a higher-level structure containing texture, sampler, shader etc. with various -// constructors if you like. You will need to implement ==/!= operators. -// History: -// - In v1.91.4 (2024/10/08): the default type for ImTextureID was changed from 'void*' to 'ImU64'. This allowed backends requirig 64-bit worth of data to build on 32-bit architectures. Use intermediary intptr_t cast and read FAQ if you have casting warnings. -// - In v1.92.0 (2025/06/11): added ImTextureRef which carry either a ImTextureID either a pointer to internal texture atlas. All user facing functions taking ImTextureID changed to ImTextureRef -#ifndef ImTextureID -typedef ImU64 ImTextureID; // Default: store up to 64-bits (any pointer or integer). A majority of backends are ok with that. -#endif - -// Define this if you need 0 to be a valid ImTextureID for your backend. -#ifndef ImTextureID_Invalid -#define ImTextureID_Invalid ((ImTextureID)0) -#endif - -// ImTextureRef = higher-level identifier for a texture. -// The identifier is valid even before the texture has been uploaded to the GPU/graphics system. -// This is what gets passed to functions such as `ImGui::Image()`, `ImDrawList::AddImage()`. -// This is what gets stored in draw commands (`ImDrawCmd`) to identify a texture during rendering. -// - When a texture is created by user code (e.g. custom images), we directly stores the low-level ImTextureID. -// - When a texture is created by the backend, we stores a ImTextureData* which becomes an indirection -// to extract the ImTextureID value during rendering, after texture upload has happened. -// - There is no constructor to create a ImTextureID from a ImTextureData* as we don't expect this -// to be useful to the end-user, and it would be erroneously called by many legacy code. -// - If you want to bind the current atlas when using custom rectangle, you can use io.Fonts->TexRef. -// - Binding generators for languages such as C (which don't have constructors), should provide a helper, e.g. -// inline ImTextureRef ImTextureRefFromID(ImTextureID tex_id) { ImTextureRef tex_ref = { ._TexData = NULL, .TexID = tex_id }; return tex_ref; } -// In 1.92 we changed most drawing functions using ImTextureID to use ImTextureRef. -// We intentionally do not provide an implicit ImTextureRef -> ImTextureID cast operator because it is technically lossy to convert ImTextureRef to ImTextureID before rendering. -IM_MSVC_RUNTIME_CHECKS_OFF -struct ImTextureRef -{ - ImTextureRef() { _TexData = NULL; _TexID = ImTextureID_Invalid; } - ImTextureRef(ImTextureID tex_id) { _TexData = NULL; _TexID = tex_id; } -#if !defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) && !defined(ImTextureID) - ImTextureRef(void* tex_id) { _TexData = NULL; _TexID = (ImTextureID)(size_t)tex_id; } // For legacy backends casting to ImTextureID -#endif - - inline ImTextureID GetTexID() const; // == (_TexData ? _TexData->TexID : _TexID) // Implemented below in the file. - - // Members (either are set, never both!) - ImTextureData* _TexData; // A texture, generally owned by a ImFontAtlas. Will convert to ImTextureID during render loop, after texture has been uploaded. - ImTextureID _TexID; // _OR_ Low-level backend texture identifier, if already uploaded or created by user/app. Generally provided to e.g. ImGui::Image() calls. -}; -IM_MSVC_RUNTIME_CHECKS_RESTORE - -//----------------------------------------------------------------------------- -// [SECTION] Dear ImGui end-user API functions -// (Note that ImGui:: being a namespace, you can add extra ImGui:: functions in your own separate file. Please don't modify imgui source files!) -//----------------------------------------------------------------------------- - -namespace ImGui -{ - // Context creation and access - // - Each context create its own ImFontAtlas by default. You may instance one yourself and pass it to CreateContext() to share a font atlas between contexts. - // - DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() - // for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for details. - IMGUI_API ImGuiContext* CreateContext(ImFontAtlas* shared_font_atlas = NULL); - IMGUI_API void DestroyContext(ImGuiContext* ctx = NULL); // NULL = destroy current context - IMGUI_API ImGuiContext* GetCurrentContext(); - IMGUI_API void SetCurrentContext(ImGuiContext* ctx); - - // Main - IMGUI_API ImGuiIO& GetIO(); // access the ImGuiIO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags) - IMGUI_API ImGuiPlatformIO& GetPlatformIO(); // access the ImGuiPlatformIO structure (mostly hooks/functions to connect to platform/renderer and OS Clipboard, IME etc.) - IMGUI_API ImGuiStyle& GetStyle(); // access the Style structure (colors, sizes). Always use PushStyleColor(), PushStyleVar() to modify style mid-frame! - IMGUI_API void NewFrame(); // start a new Dear ImGui frame, you can submit any command from this point until Render()/EndFrame(). - IMGUI_API void EndFrame(); // ends the Dear ImGui frame. automatically called by Render(). If you don't need to render data (skipping rendering) you may call EndFrame() without Render()... but you'll have wasted CPU already! If you don't need to render, better to not create any windows and not call NewFrame() at all! - IMGUI_API void Render(); // ends the Dear ImGui frame, finalize the draw data. You can then get call GetDrawData(). - IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). Call ImGui_ImplXXXX_RenderDrawData() function in your Renderer Backend to render. - - // Demo, Debug, Information - IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create Demo window. demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application! - IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create Metrics/Debugger window. display Dear ImGui internals: windows, draw commands, various internal state, etc. - IMGUI_API void ShowDebugLogWindow(bool* p_open = NULL); // create Debug Log window. display a simplified log of important dear imgui events. - IMGUI_API void ShowIDStackToolWindow(bool* p_open = NULL); // create Stack Tool window. hover items with mouse to query information about the source of their unique ID. - IMGUI_API void ShowAboutWindow(bool* p_open = NULL); // create About window. display Dear ImGui version, credits and build/system information. - IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style) - IMGUI_API bool ShowStyleSelector(const char* label); // add style selector block (not a window), essentially a combo listing the default styles. - IMGUI_API void ShowFontSelector(const char* label); // add font selector block (not a window), essentially a combo listing the loaded fonts. - IMGUI_API void ShowUserGuide(); // add basic help/info block (not a window): how to manipulate ImGui as an end-user (mouse/keyboard controls). - IMGUI_API const char* GetVersion(); // get the compiled version string e.g. "1.80 WIP" (essentially the value for IMGUI_VERSION from the compiled version of imgui.cpp) - - // Styles - IMGUI_API void StyleColorsDark(ImGuiStyle* dst = NULL); // new, recommended style (default) - IMGUI_API void StyleColorsLight(ImGuiStyle* dst = NULL); // best used with borders and a custom, thicker font - IMGUI_API void StyleColorsClassic(ImGuiStyle* dst = NULL); // classic imgui style - - // Windows - // - Begin() = push window to the stack and start appending to it. End() = pop window from the stack. - // - Passing 'bool* p_open != NULL' shows a window-closing widget in the upper-right corner of the window, - // which clicking will set the boolean to false when clicked. - // - You may append multiple times to the same window during the same frame by calling Begin()/End() pairs multiple times. - // Some information such as 'flags' or 'p_open' will only be considered by the first call to Begin(). - // - Begin() return false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting - // anything to the window. Always call a matching End() for each Begin() call, regardless of its return value! - // [Important: due to legacy reason, Begin/End and BeginChild/EndChild are inconsistent with all other functions - // such as BeginMenu/EndMenu, BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding - // BeginXXX function returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.] - // - Note that the bottom of window stack always contains a window called "Debug". - IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); - IMGUI_API void End(); - - // Child Windows - // - Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child. - // - Before 1.90 (November 2023), the "ImGuiChildFlags child_flags = 0" parameter was "bool border = false". - // This API is backward compatible with old code, as we guarantee that ImGuiChildFlags_Borders == true. - // Consider updating your old code: - // BeginChild("Name", size, false) -> Begin("Name", size, 0); or Begin("Name", size, ImGuiChildFlags_None); - // BeginChild("Name", size, true) -> Begin("Name", size, ImGuiChildFlags_Borders); - // - Manual sizing (each axis can use a different setting e.g. ImVec2(0.0f, 400.0f)): - // == 0.0f: use remaining parent window size for this axis. - // > 0.0f: use specified size for this axis. - // < 0.0f: right/bottom-align to specified distance from available content boundaries. - // - Specifying ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY makes the sizing automatic based on child contents. - // Combining both ImGuiChildFlags_AutoResizeX _and_ ImGuiChildFlags_AutoResizeY defeats purpose of a scrolling region and is NOT recommended. - // - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting - // anything to the window. Always call a matching EndChild() for each BeginChild() call, regardless of its return value. - // [Important: due to legacy reason, Begin/End and BeginChild/EndChild are inconsistent with all other functions - // such as BeginMenu/EndMenu, BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding - // BeginXXX function returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.] - IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0, 0), ImGuiChildFlags child_flags = 0, ImGuiWindowFlags window_flags = 0); - IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0, 0), ImGuiChildFlags child_flags = 0, ImGuiWindowFlags window_flags = 0); - IMGUI_API void EndChild(); - - // Windows Utilities - // - 'current window' = the window we are appending into while inside a Begin()/End() block. 'next window' = next window we will Begin() into. - IMGUI_API bool IsWindowAppearing(); - IMGUI_API bool IsWindowCollapsed(); - IMGUI_API bool IsWindowFocused(ImGuiFocusedFlags flags=0); // is current window focused? or its root/child, depending on flags. see flags for options. - IMGUI_API bool IsWindowHovered(ImGuiHoveredFlags flags=0); // is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options. IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app, you should not use this function! Use the 'io.WantCaptureMouse' boolean for that! Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details. - IMGUI_API ImDrawList* GetWindowDrawList(); // get draw list associated to the current window, to append your own drawing primitives - IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (IT IS UNLIKELY YOU EVER NEED TO USE THIS. Consider always using GetCursorScreenPos() and GetContentRegionAvail() instead) - IMGUI_API ImVec2 GetWindowSize(); // get current window size (IT IS UNLIKELY YOU EVER NEED TO USE THIS. Consider always using GetCursorScreenPos() and GetContentRegionAvail() instead) - IMGUI_API float GetWindowWidth(); // get current window width (IT IS UNLIKELY YOU EVER NEED TO USE THIS). Shortcut for GetWindowSize().x. - IMGUI_API float GetWindowHeight(); // get current window height (IT IS UNLIKELY YOU EVER NEED TO USE THIS). Shortcut for GetWindowSize().y. - - // Window manipulation - // - Prefer using SetNextXXX functions (before Begin) rather that SetXXX functions (after Begin). - IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiCond cond = 0, const ImVec2& pivot = ImVec2(0, 0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc. - IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin() - IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use 0.0f or FLT_MAX if you don't want limits. Use -1 for both min and max of same axis to preserve current size (which itself is a constraint). Use callback to apply non-trivial programmatic constraints. - IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ scrollable client area, which enforce the range of scrollbars). Not including window decorations (title bar, menu bar, etc.) nor WindowPadding. set an axis to 0.0f to leave it automatic. call before Begin() - IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // set next window collapsed state. call before Begin() - IMGUI_API void SetNextWindowFocus(); // set next window to be focused / top-most. call before Begin() - IMGUI_API void SetNextWindowScroll(const ImVec2& scroll); // set next window scrolling value (use < 0.0f to not affect a given axis). - IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily override the Alpha component of ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground. - IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects. - IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0, 0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects. - IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). - IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / top-most. prefer using SetNextWindowFocus(). - IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position. - IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis. - IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state - IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / top-most. use NULL to remove focus. - - // Windows Scrolling - // - Any change of Scroll will be applied at the beginning of next frame in the first call to Begin(). - // - You may instead use SetNextWindowScroll() prior to calling Begin() to avoid this delay, as an alternative to using SetScrollX()/SetScrollY(). - IMGUI_API float GetScrollX(); // get scrolling amount [0 .. GetScrollMaxX()] - IMGUI_API float GetScrollY(); // get scrolling amount [0 .. GetScrollMaxY()] - IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0 .. GetScrollMaxX()] - IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0 .. GetScrollMaxY()] - IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.x - WindowSize.x - DecorationsSize.x - IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.y - WindowSize.y - DecorationsSize.y - IMGUI_API void SetScrollHereX(float center_x_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_x_ratio=0.0: left, 0.5: center, 1.0: right. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead. - IMGUI_API void SetScrollHereY(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead. - IMGUI_API void SetScrollFromPosX(float local_x, float center_x_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. - IMGUI_API void SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. - - // Parameters stacks (font) - // - PushFont(font, 0.0f) // Change font and keep current size - // - PushFont(NULL, 20.0f) // Keep font and change current size - // - PushFont(font, 20.0f) // Change font and set size to 20.0f - // - PushFont(font, style.FontSizeBase * 2.0f) // Change font and set size to be twice bigger than current size. - // - PushFont(font, font->LegacySize) // Change font and set size to size passed to AddFontXXX() function. Same as pre-1.92 behavior. - // *IMPORTANT* before 1.92, fonts had a single size. They can now be dynamically be adjusted. - // - In 1.92 we have REMOVED the single parameter version of PushFont() because it seems like the easiest way to provide an error-proof transition. - // - PushFont(font) before 1.92 = PushFont(font, font->LegacySize) after 1.92 // Use default font size as passed to AddFontXXX() function. - // *IMPORTANT* global scale factors are applied over the provided size. - // - Global scale factors are: 'style.FontScaleMain', 'style.FontScaleDpi' and maybe more. - // - If you want to apply a factor to the _current_ font size: - // - CORRECT: PushFont(NULL, style.FontSizeBase) // use current unscaled size == does nothing - // - CORRECT: PushFont(NULL, style.FontSizeBase * 2.0f) // use current unscaled size x2 == make text twice bigger - // - INCORRECT: PushFont(NULL, GetFontSize()) // INCORRECT! using size after global factors already applied == GLOBAL SCALING FACTORS WILL APPLY TWICE! - // - INCORRECT: PushFont(NULL, GetFontSize() * 2.0f) // INCORRECT! using size after global factors already applied == GLOBAL SCALING FACTORS WILL APPLY TWICE! - IMGUI_API void PushFont(ImFont* font, float font_size_base_unscaled); // Use NULL as a shortcut to keep current font. Use 0.0f to keep current size. - IMGUI_API void PopFont(); - IMGUI_API ImFont* GetFont(); // get current font - IMGUI_API float GetFontSize(); // get current scaled font size (= height in pixels). AFTER global scale factors applied. *IMPORTANT* DO NOT PASS THIS VALUE TO PushFont()! Use ImGui::GetStyle().FontSizeBase to get value before global scale factors. - IMGUI_API ImFontBaked* GetFontBaked(); // get current font bound at current size // == GetFont()->GetFontBaked(GetFontSize()) - - // Parameters stacks (shared) - IMGUI_API void PushStyleColor(ImGuiCol idx, ImU32 col); // modify a style color. always use this if you modify the style after NewFrame(). - IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col); - IMGUI_API void PopStyleColor(int count = 1); - IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); // modify a style float variable. always use this if you modify the style after NewFrame()! - IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); // modify a style ImVec2 variable. " - IMGUI_API void PushStyleVarX(ImGuiStyleVar idx, float val_x); // modify X component of a style ImVec2 variable. " - IMGUI_API void PushStyleVarY(ImGuiStyleVar idx, float val_y); // modify Y component of a style ImVec2 variable. " - IMGUI_API void PopStyleVar(int count = 1); - IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled); // modify specified shared item flag, e.g. PushItemFlag(ImGuiItemFlags_NoTabStop, true) - IMGUI_API void PopItemFlag(); - - // Parameters stacks (current window) - IMGUI_API void PushItemWidth(float item_width); // push width of items for common large "item+label" widgets. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side). - IMGUI_API void PopItemWidth(); - IMGUI_API void SetNextItemWidth(float item_width); // set width of the _next_ common large "item+label" widget. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side) - IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position. NOT necessarily the width of last item unlike most 'Item' functions. - IMGUI_API void PushTextWrapPos(float wrap_local_pos_x = 0.0f); // push word-wrapping position for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space - IMGUI_API void PopTextWrapPos(); - - // Style read access - // - Use the ShowStyleEditor() function to interactively see/edit the colors. - IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a white pixel, useful to draw custom shapes via the ImDrawList API - IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier, packed as a 32-bit value suitable for ImDrawList - IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList - IMGUI_API ImU32 GetColorU32(ImU32 col, float alpha_mul = 1.0f); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList - IMGUI_API const ImVec4& GetStyleColorVec4(ImGuiCol idx); // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwise use GetColorU32() to get style color with style alpha baked in. - - // Layout cursor positioning - // - By "cursor" we mean the current output position. - // - The typical widget behavior is to output themselves at the current cursor position, then move the cursor one line down. - // - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceding widget. - // - YOU CAN DO 99% OF WHAT YOU NEED WITH ONLY GetCursorScreenPos() and GetContentRegionAvail(). - // - Attention! We currently have inconsistencies between window-local and absolute positions we will aim to fix with future API: - // - Absolute coordinate: GetCursorScreenPos(), SetCursorScreenPos(), all ImDrawList:: functions. -> this is the preferred way forward. - // - Window-local coordinates: SameLine(offset), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), PushTextWrapPos() - // - Window-local coordinates: GetContentRegionMax(), GetWindowContentRegionMin(), GetWindowContentRegionMax() --> all obsoleted. YOU DON'T NEED THEM. - // - GetCursorScreenPos() = GetCursorPos() + GetWindowPos(). GetWindowPos() is almost only ever useful to convert from window-local to absolute coordinates. Try not to use it. - IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position, absolute coordinates. THIS IS YOUR BEST FRIEND (prefer using this rather than GetCursorPos(), also more useful to work with ImDrawList API). - IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position, absolute coordinates. THIS IS YOUR BEST FRIEND. - IMGUI_API ImVec2 GetContentRegionAvail(); // available space from current position. THIS IS YOUR BEST FRIEND. - IMGUI_API ImVec2 GetCursorPos(); // [window-local] cursor position in window-local coordinates. This is not your best friend. - IMGUI_API float GetCursorPosX(); // [window-local] " - IMGUI_API float GetCursorPosY(); // [window-local] " - IMGUI_API void SetCursorPos(const ImVec2& local_pos); // [window-local] " - IMGUI_API void SetCursorPosX(float local_x); // [window-local] " - IMGUI_API void SetCursorPosY(float local_y); // [window-local] " - IMGUI_API ImVec2 GetCursorStartPos(); // [window-local] initial cursor position, in window-local coordinates. Call GetCursorScreenPos() after Begin() to get the absolute coordinates version. - - // Other layout functions - IMGUI_API void Separator(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator. - IMGUI_API void SameLine(float offset_from_start_x=0.0f, float spacing=-1.0f); // call between widgets or groups to layout them horizontally. X position given in window coordinates. - IMGUI_API void NewLine(); // undo a SameLine() or force a new line when in a horizontal-layout context. - IMGUI_API void Spacing(); // add vertical spacing. - IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size. unlike InvisibleButton(), Dummy() won't take the mouse click or be navigable into. - IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by indent_w, or style.IndentSpacing if indent_w <= 0 - IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by indent_w, or style.IndentSpacing if indent_w <= 0 - IMGUI_API void BeginGroup(); // lock horizontal starting position - IMGUI_API void EndGroup(); // unlock horizontal starting position + capture the whole group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) - IMGUI_API void AlignTextToFramePadding(); // vertically align upcoming text baseline to FramePadding.y so that it will align properly to regularly framed items (call if you have text on a line before a framed item) - IMGUI_API float GetTextLineHeight(); // ~ FontSize - IMGUI_API float GetTextLineHeightWithSpacing(); // ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text) - IMGUI_API float GetFrameHeight(); // ~ FontSize + style.FramePadding.y * 2 - IMGUI_API float GetFrameHeightWithSpacing(); // ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of framed widgets) - - // ID stack/scopes - // Read the FAQ (docs/FAQ.md or http://dearimgui.com/faq) for more details about how ID are handled in dear imgui. - // - Those questions are answered and impacted by understanding of the ID stack system: - // - "Q: Why is my widget not reacting when I click on it?" - // - "Q: How can I have widgets with an empty label?" - // - "Q: How can I have multiple widgets with the same label?" - // - Short version: ID are hashes of the entire ID stack. If you are creating widgets in a loop you most likely - // want to push a unique identifier (e.g. object pointer, loop index) to uniquely differentiate them. - // - You can also use the "Label##foobar" syntax within widget label to distinguish them from each others. - // - In this header file we use the "label"/"name" terminology to denote a string that will be displayed + used as an ID, - // whereas "str_id" denote a string that is only used as an ID and not normally displayed. - IMGUI_API void PushID(const char* str_id); // push string into the ID stack (will hash string). - IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end); // push string into the ID stack (will hash string). - IMGUI_API void PushID(const void* ptr_id); // push pointer into the ID stack (will hash pointer). - IMGUI_API void PushID(int int_id); // push integer into the ID stack (will hash integer). - IMGUI_API void PopID(); // pop from the ID stack. - IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage yourself - IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end); - IMGUI_API ImGuiID GetID(const void* ptr_id); - IMGUI_API ImGuiID GetID(int int_id); - - // Widgets: Text - IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // raw text without formatting. Roughly equivalent to Text("%s", text) but: A) doesn't require null terminated string if 'text_end' is specified, B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text. - IMGUI_API void Text(const char* fmt, ...) IM_FMTARGS(1); // formatted text - IMGUI_API void TextV(const char* fmt, va_list args) IM_FMTLIST(1); - IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_FMTARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor(); - IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args) IM_FMTLIST(2); - IMGUI_API void TextDisabled(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor(); - IMGUI_API void TextDisabledV(const char* fmt, va_list args) IM_FMTLIST(1); - IMGUI_API void TextWrapped(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize(). - IMGUI_API void TextWrappedV(const char* fmt, va_list args) IM_FMTLIST(1); - IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_FMTARGS(2); // display text+label aligned the same way as value+label widgets - IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args) IM_FMTLIST(2); - IMGUI_API void BulletText(const char* fmt, ...) IM_FMTARGS(1); // shortcut for Bullet()+Text() - IMGUI_API void BulletTextV(const char* fmt, va_list args) IM_FMTLIST(1); - IMGUI_API void SeparatorText(const char* label); // currently: formatted text with a horizontal line - - // Widgets: Main - // - Most widgets return true when the value has been changed or when pressed/selected - // - You may also use one of the many IsItemXXX functions (e.g. IsItemActive, IsItemHovered, etc.) to query widget state. - IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0, 0)); // button - IMGUI_API bool SmallButton(const char* label); // button with (FramePadding.y == 0) to easily embed within text - IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size, ImGuiButtonFlags flags = 0); // flexible button behavior without the visuals, frequently useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.) - IMGUI_API bool ArrowButton(const char* str_id, ImGuiDir dir); // square button with an arrow shape - IMGUI_API bool Checkbox(const char* label, bool* v); - IMGUI_API bool CheckboxFlags(const char* label, int* flags, int flags_value); - IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value); - IMGUI_API bool RadioButton(const char* label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; } - IMGUI_API bool RadioButton(const char* label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer - IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-FLT_MIN, 0), const char* overlay = NULL); - IMGUI_API void Bullet(); // draw a small circle + keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses - IMGUI_API bool TextLink(const char* label); // hyperlink text button, return true when clicked - IMGUI_API bool TextLinkOpenURL(const char* label, const char* url = NULL); // hyperlink text button, automatically open file/url when clicked - - // Widgets: Images - // - Read about ImTextureID/ImTextureRef here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples - // - 'uv0' and 'uv1' are texture coordinates. Read about them from the same link above. - // - Image() pads adds style.ImageBorderSize on each side, ImageButton() adds style.FramePadding on each side. - // - ImageButton() draws a background based on regular Button() color + optionally an inner background if specified. - // - An obsolete version of Image(), before 1.91.9 (March 2025), had a 'tint_col' parameter which is now supported by the ImageWithBg() function. - IMGUI_API void Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1)); - IMGUI_API void ImageWithBg(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); - IMGUI_API bool ImageButton(const char* str_id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); - - // Widgets: Combo Box (Dropdown) - // - The BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items. - // - The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose. This is analogous to how ListBox are created. - IMGUI_API bool BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags = 0); - IMGUI_API void EndCombo(); // only call EndCombo() if BeginCombo() returns true! - IMGUI_API bool Combo(const char* label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items = -1); - IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items = -1); // Separate items with \0 within a string, end item-list with \0\0. e.g. "One\0Two\0Three\0" - IMGUI_API bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count, int popup_max_height_in_items = -1); - - // Widgets: Drag Sliders - // - CTRL+Click on any drag box to turn them into an input box. Manually input values aren't clamped by default and can go off-bounds. Use ImGuiSliderFlags_AlwaysClamp to always clamp. - // - For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every function, note that a 'float v[X]' function argument is the same as 'float* v', - // the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x - // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. - // - Format string may also be set to NULL or use the default format ("%f" or "%d"). - // - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For keyboard/gamepad navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision). - // - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits if ImGuiSliderFlags_AlwaysClamp is not used. - // - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum. - // - We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. - // - Legacy: Pre-1.78 there are DragXXX() function signatures that take a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. - // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 - IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound - IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); - IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); - IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); - IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiSliderFlags flags = 0); - IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound - IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); - IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); - IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); - IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiSliderFlags flags = 0); - IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed = 1.0f, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0); - IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed = 1.0f, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0); - - // Widgets: Regular Sliders - // - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped by default and can go off-bounds. Use ImGuiSliderFlags_AlwaysClamp to always clamp. - // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. - // - Format string may also be set to NULL or use the default format ("%f" or "%d"). - // - Legacy: Pre-1.78 there are SliderXXX() function signatures that take a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. - // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 - IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. - IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg", ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); - IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); - IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); - IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); - - // Widgets: Input with Keyboard - // - If you want to use InputText() with std::string or any custom dynamic string type, see misc/cpp/imgui_stdlib.h and comments in imgui_demo.cpp. - // - Most of the ImGuiInputTextFlags flags are only useful for InputText() and not for InputFloatX, InputIntX, InputDouble etc. - IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); - IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); - IMGUI_API bool InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); - IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, const char* format = "%.3f", ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputFloat2(const char* label, float v[2], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputFloat3(const char* label, float v[3], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputFloat4(const char* label, float v[4], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputDouble(const char* label, double* v, double step = 0.0, double step_fast = 0.0, const char* format = "%.6f", ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0); - - // Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little color square that can be left-clicked to open a picker, and right-clicked to open an option menu.) - // - Note that in C++ a 'float v[X]' function argument is the _same_ as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. - // - You can pass the address of a first float element out of a contiguous structure, e.g. &myvector.x - IMGUI_API bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); - IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0); - IMGUI_API bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); - IMGUI_API bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL); - IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // display a color square/button, hover for details, return true when pressed. - IMGUI_API void SetColorEditOptions(ImGuiColorEditFlags flags); // initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls. - - // Widgets: Trees - // - TreeNode functions return true when the node is open, in which case you need to also call TreePop() when you are finished displaying the tree node contents. - IMGUI_API bool TreeNode(const char* label); - IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_FMTARGS(2); // helper variation to easily decorelate the id from the displayed string. Read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet(). - IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_FMTARGS(2); // " - IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args) IM_FMTLIST(2); - IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2); - IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0); - IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); - IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); - IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); - IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); - IMGUI_API void TreePush(const char* str_id); // ~ Indent()+PushID(). Already called by TreeNode() when returning true, but you can call TreePush/TreePop yourself if desired. - IMGUI_API void TreePush(const void* ptr_id); // " - IMGUI_API void TreePop(); // ~ Unindent()+PopID() - IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode - IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop(). - IMGUI_API bool CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags = 0); // when 'p_visible != NULL': if '*p_visible==true' display an additional small close button on upper right of the header which will set the bool to false when clicked, if '*p_visible==false' don't display the header. - IMGUI_API void SetNextItemOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state. - IMGUI_API void SetNextItemStorageID(ImGuiID storage_id); // set id to use for open/close storage (default to same as item id). - - // Widgets: Selectables - // - A selectable highlights when hovered, and can display another color when selected. - // - Neighbors selectable extend their highlight bounds in order to leave no gap between them. This is so a series of selected Selectable appear contiguous. - IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height - IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool* p_selected" point to the selection state (read-write), as a convenient helper. - - // Multi-selection system for Selectable(), Checkbox(), TreeNode() functions [BETA] - // - This enables standard multi-selection/range-selection idioms (CTRL+Mouse/Keyboard, SHIFT+Mouse/Keyboard, etc.) in a way that also allow a clipper to be used. - // - ImGuiSelectionUserData is often used to store your item index within the current view (but may store something else). - // - Read comments near ImGuiMultiSelectIO for instructions/details and see 'Demo->Widgets->Selection State & Multi-Select' for demo. - // - TreeNode() is technically supported but... using this correctly is more complicated. You need some sort of linear/random access to your tree, - // which is suited to advanced trees setups already implementing filters and clipper. We will work simplifying the current demo. - // - 'selection_size' and 'items_count' parameters are optional and used by a few features. If they are costly for you to compute, you may avoid them. - IMGUI_API ImGuiMultiSelectIO* BeginMultiSelect(ImGuiMultiSelectFlags flags, int selection_size = -1, int items_count = -1); - IMGUI_API ImGuiMultiSelectIO* EndMultiSelect(); - IMGUI_API void SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data); - IMGUI_API bool IsItemToggledSelection(); // Was the last item selection state toggled? Useful if you need the per-item information _before_ reaching EndMultiSelect(). We only returns toggle _event_ in order to handle clipping correctly. - - // Widgets: List Boxes - // - This is essentially a thin wrapper to using BeginChild/EndChild with the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label. - // - If you don't need a label you can probably simply use BeginChild() with the ImGuiChildFlags_FrameStyle flag for the same result. - // - You can submit contents and manage your selection state however you want it, by creating e.g. Selectable() or any other items. - // - The simplified/old ListBox() api are helpers over BeginListBox()/EndListBox() which are kept available for convenience purpose. This is analogous to how Combos are created. - // - Choose frame width: size.x > 0.0f: custom / size.x < 0.0f or -FLT_MIN: right-align / size.x = 0.0f (default): use current ItemWidth - // - Choose frame height: size.y > 0.0f: custom / size.y < 0.0f or -FLT_MIN: bottom-align / size.y = 0.0f (default): arbitrary default height which can fit ~7 items - IMGUI_API bool BeginListBox(const char* label, const ImVec2& size = ImVec2(0, 0)); // open a framed scrolling region - IMGUI_API void EndListBox(); // only call EndListBox() if BeginListBox() returned true! - IMGUI_API bool ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items = -1); - IMGUI_API bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count, int height_in_items = -1); - - // Widgets: Data Plotting - // - Consider using ImPlot (https://github.com/epezent/implot) which is much better! - IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float)); - IMGUI_API void PlotLines(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0)); - IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float)); - IMGUI_API void PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0)); - - // Widgets: Value() Helpers. - // - Those are merely shortcut to calling Text() with a format string. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace) - IMGUI_API void Value(const char* prefix, bool b); - IMGUI_API void Value(const char* prefix, int v); - IMGUI_API void Value(const char* prefix, unsigned int v); - IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL); - - // Widgets: Menus - // - Use BeginMenuBar() on a window ImGuiWindowFlags_MenuBar to append to its menu bar. - // - Use BeginMainMenuBar() to create a menu bar at the top of the screen and append to it. - // - Use BeginMenu() to create a menu. You can call BeginMenu() multiple time with the same identifier to append more items to it. - // - Not that MenuItem() keyboardshortcuts are displayed as a convenience but _not processed_ by Dear ImGui at the moment. - IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set on parent window). - IMGUI_API void EndMenuBar(); // only call EndMenuBar() if BeginMenuBar() returns true! - IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar. - IMGUI_API void EndMainMenuBar(); // only call EndMainMenuBar() if BeginMainMenuBar() returns true! - IMGUI_API bool BeginMenu(const char* label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true! - IMGUI_API void EndMenu(); // only call EndMenu() if BeginMenu() returns true! - IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. - IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL - - // Tooltips - // - Tooltips are windows following the mouse. They do not take focus away. - // - A tooltip window can contain items of any types. - // - SetTooltip() is more or less a shortcut for the 'if (BeginTooltip()) { Text(...); EndTooltip(); }' idiom (with a subtlety that it discard any previously submitted tooltip) - IMGUI_API bool BeginTooltip(); // begin/append a tooltip window. - IMGUI_API void EndTooltip(); // only call EndTooltip() if BeginTooltip()/BeginItemTooltip() returns true! - IMGUI_API void SetTooltip(const char* fmt, ...) IM_FMTARGS(1); // set a text-only tooltip. Often used after a ImGui::IsItemHovered() check. Override any previous call to SetTooltip(). - IMGUI_API void SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1); - - // Tooltips: helpers for showing a tooltip when hovering an item - // - BeginItemTooltip() is a shortcut for the 'if (IsItemHovered(ImGuiHoveredFlags_ForTooltip) && BeginTooltip())' idiom. - // - SetItemTooltip() is a shortcut for the 'if (IsItemHovered(ImGuiHoveredFlags_ForTooltip)) { SetTooltip(...); }' idiom. - // - Where 'ImGuiHoveredFlags_ForTooltip' itself is a shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' depending on active input type. For mouse it defaults to 'ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort'. - IMGUI_API bool BeginItemTooltip(); // begin/append a tooltip window if preceding item was hovered. - IMGUI_API void SetItemTooltip(const char* fmt, ...) IM_FMTARGS(1); // set a text-only tooltip if preceding item was hovered. override any previous call to SetTooltip(). - IMGUI_API void SetItemTooltipV(const char* fmt, va_list args) IM_FMTLIST(1); - - // Popups, Modals - // - They block normal mouse hovering detection (and therefore most mouse interactions) behind them. - // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE. - // - Their visibility state (~bool) is held internally instead of being held by the programmer as we are used to with regular Begin*() calls. - // - The 3 properties above are related: we need to retain popup visibility state in the library because popups may be closed as any time. - // - You can bypass the hovering restriction by using ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered(). - // - IMPORTANT: Popup identifiers are relative to the current ID stack, so OpenPopup and BeginPopup generally needs to be at the same level of the stack. - // This is sometimes leading to confusing mistakes. May rework this in the future. - // - BeginPopup(): query popup state, if open start appending into the window. Call EndPopup() afterwards if returned true. ImGuiWindowFlags are forwarded to the window. - // - BeginPopupModal(): block every interaction behind the window, cannot be closed by user, add a dimming background, has a title bar. - IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. - IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // return true if the modal is open, and you can start outputting to it. - IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true! - - // Popups: open/close functions - // - OpenPopup(): set popup state to open. ImGuiPopupFlags are available for opening options. - // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE. - // - CloseCurrentPopup(): use inside the BeginPopup()/EndPopup() scope to close manually. - // - CloseCurrentPopup() is called by default by Selectable()/MenuItem() when activated (FIXME: need some options). - // - Use ImGuiPopupFlags_NoOpenOverExistingPopup to avoid opening a popup if there's already one at the same level. This is equivalent to e.g. testing for !IsAnyPopupOpen() prior to OpenPopup(). - // - Use IsWindowAppearing() after BeginPopup() to tell if a window just opened. - // - IMPORTANT: Notice that for OpenPopupOnItemClick() we exceptionally default flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter - IMGUI_API void OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags = 0); // call to mark popup as open (don't call every frame!). - IMGUI_API void OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags = 0); // id overload to facilitate calling from nested stacks - IMGUI_API void OpenPopupOnItemClick(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // helper to open popup when clicked on last item. Default to ImGuiPopupFlags_MouseButtonRight == 1. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) - IMGUI_API void CloseCurrentPopup(); // manually close the popup we have begin-ed into. - - // Popups: open+begin combined functions helpers - // - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking. - // - They are convenient to easily create context menus, hence the name. - // - IMPORTANT: Notice that BeginPopupContextXXX takes ImGuiPopupFlags just like OpenPopup() and unlike BeginPopup(). For full consistency, we may add ImGuiWindowFlags to the BeginPopupContextXXX functions in the future. - // - IMPORTANT: Notice that we exceptionally default their flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter, so if you add other flags remember to re-add the ImGuiPopupFlags_MouseButtonRight. - IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked on last item. Use str_id==NULL to associate the popup to previous item. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! - IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1);// open+begin popup when clicked on current window. - IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked in void (where there are no windows). - - // Popups: query functions - // - IsPopupOpen(): return true if the popup is open at the current BeginPopup() level of the popup stack. - // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId: return true if any popup is open at the current BeginPopup() level of the popup stack. - // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId + ImGuiPopupFlags_AnyPopupLevel: return true if any popup is open. - IMGUI_API bool IsPopupOpen(const char* str_id, ImGuiPopupFlags flags = 0); // return true if the popup is open. - - // Tables - // - Full-featured replacement for old Columns API. - // - See Demo->Tables for demo code. See top of imgui_tables.cpp for general commentary. - // - See ImGuiTableFlags_ and ImGuiTableColumnFlags_ enums for a description of available flags. - // The typical call flow is: - // - 1. Call BeginTable(), early out if returning false. - // - 2. Optionally call TableSetupColumn() to submit column name/flags/defaults. - // - 3. Optionally call TableSetupScrollFreeze() to request scroll freezing of columns/rows. - // - 4. Optionally call TableHeadersRow() to submit a header row. Names are pulled from TableSetupColumn() data. - // - 5. Populate contents: - // - In most situations you can use TableNextRow() + TableSetColumnIndex(N) to start appending into a column. - // - If you are using tables as a sort of grid, where every column is holding the same type of contents, - // you may prefer using TableNextColumn() instead of TableNextRow() + TableSetColumnIndex(). - // TableNextColumn() will automatically wrap-around into the next row if needed. - // - IMPORTANT: Comparatively to the old Columns() API, we need to call TableNextColumn() for the first column! - // - Summary of possible call flow: - // - TableNextRow() -> TableSetColumnIndex(0) -> Text("Hello 0") -> TableSetColumnIndex(1) -> Text("Hello 1") // OK - // - TableNextRow() -> TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK - // - TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK: TableNextColumn() automatically gets to next row! - // - TableNextRow() -> Text("Hello 0") // Not OK! Missing TableSetColumnIndex() or TableNextColumn()! Text will not appear! - // - 5. Call EndTable() - IMGUI_API bool BeginTable(const char* str_id, int columns, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0.0f, 0.0f), float inner_width = 0.0f); - IMGUI_API void EndTable(); // only call EndTable() if BeginTable() returns true! - IMGUI_API void TableNextRow(ImGuiTableRowFlags row_flags = 0, float min_row_height = 0.0f); // append into the first cell of a new row. - IMGUI_API bool TableNextColumn(); // append into the next column (or first column of next row if currently in last column). Return true when column is visible. - IMGUI_API bool TableSetColumnIndex(int column_n); // append into the specified column. Return true when column is visible. - - // Tables: Headers & Columns declaration - // - Use TableSetupColumn() to specify label, resizing policy, default width/weight, id, various other flags etc. - // - Use TableHeadersRow() to create a header row and automatically submit a TableHeader() for each column. - // Headers are required to perform: reordering, sorting, and opening the context menu. - // The context menu can also be made available in columns body using ImGuiTableFlags_ContextMenuInBody. - // - You may manually submit headers using TableNextRow() + TableHeader() calls, but this is only useful in - // some advanced use cases (e.g. adding custom widgets in header row). - // - Use TableSetupScrollFreeze() to lock columns/rows so they stay visible when scrolled. - IMGUI_API void TableSetupColumn(const char* label, ImGuiTableColumnFlags flags = 0, float init_width_or_weight = 0.0f, ImGuiID user_id = 0); - IMGUI_API void TableSetupScrollFreeze(int cols, int rows); // lock columns/rows so they stay visible when scrolled. - IMGUI_API void TableHeader(const char* label); // submit one header cell manually (rarely used) - IMGUI_API void TableHeadersRow(); // submit a row with headers cells based on data provided to TableSetupColumn() + submit context menu - IMGUI_API void TableAngledHeadersRow(); // submit a row with angled headers for every column with the ImGuiTableColumnFlags_AngledHeader flag. MUST BE FIRST ROW. - - // Tables: Sorting & Miscellaneous functions - // - Sorting: call TableGetSortSpecs() to retrieve latest sort specs for the table. NULL when not sorting. - // When 'sort_specs->SpecsDirty == true' you should sort your data. It will be true when sorting specs have - // changed since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, - // else you may wastefully sort your data every frame! - // - Functions args 'int column_n' treat the default value of -1 as the same as passing the current column index. - IMGUI_API ImGuiTableSortSpecs* TableGetSortSpecs(); // get latest sort specs for the table (NULL if not sorting). Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable(). - IMGUI_API int TableGetColumnCount(); // return number of columns (value passed to BeginTable) - IMGUI_API int TableGetColumnIndex(); // return current column index. - IMGUI_API int TableGetRowIndex(); // return current row index. - IMGUI_API const char* TableGetColumnName(int column_n = -1); // return "" if column didn't have a name declared by TableSetupColumn(). Pass -1 to use current column. - IMGUI_API ImGuiTableColumnFlags TableGetColumnFlags(int column_n = -1); // return column flags so you can query their Enabled/Visible/Sorted/Hovered status flags. Pass -1 to use current column. - IMGUI_API void TableSetColumnEnabled(int column_n, bool v);// change user accessible enabled/disabled state of a column. Set to false to hide the column. User can use the context menu to change this themselves (right-click in headers, or right-click in columns body with ImGuiTableFlags_ContextMenuInBody) - IMGUI_API int TableGetHoveredColumn(); // return hovered column. return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered. Can also use (TableGetColumnFlags() & ImGuiTableColumnFlags_IsHovered) instead. - IMGUI_API void TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n = -1); // change the color of a cell, row, or column. See ImGuiTableBgTarget_ flags for details. - - // Legacy Columns API (prefer using Tables!) - // - You can also use SameLine(pos_x) to mimic simplified columns. - IMGUI_API void Columns(int count = 1, const char* id = NULL, bool borders = true); - IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished - IMGUI_API int GetColumnIndex(); // get current column index - IMGUI_API float GetColumnWidth(int column_index = -1); // get column width (in pixels). pass -1 to use current column - IMGUI_API void SetColumnWidth(int column_index, float width); // set column width (in pixels). pass -1 to use current column - IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f - IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column - IMGUI_API int GetColumnsCount(); - - // Tab Bars, Tabs - // - Note: Tabs are automatically created by the docking system (when in 'docking' branch). Use this to create tab bars/tabs yourself. - IMGUI_API bool BeginTabBar(const char* str_id, ImGuiTabBarFlags flags = 0); // create and append into a TabBar - IMGUI_API void EndTabBar(); // only call EndTabBar() if BeginTabBar() returns true! - IMGUI_API bool BeginTabItem(const char* label, bool* p_open = NULL, ImGuiTabItemFlags flags = 0); // create a Tab. Returns true if the Tab is selected. - IMGUI_API void EndTabItem(); // only call EndTabItem() if BeginTabItem() returns true! - IMGUI_API bool TabItemButton(const char* label, ImGuiTabItemFlags flags = 0); // create a Tab behaving like a button. return true when clicked. cannot be selected in the tab bar. - IMGUI_API void SetTabItemClosed(const char* tab_or_docked_window_label); // notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name. - - // Logging/Capture - // - All text output from the interface can be captured into tty/file/clipboard. By default, tree nodes are automatically opened during logging. - IMGUI_API void LogToTTY(int auto_open_depth = -1); // start logging to tty (stdout) - IMGUI_API void LogToFile(int auto_open_depth = -1, const char* filename = NULL); // start logging to file - IMGUI_API void LogToClipboard(int auto_open_depth = -1); // start logging to OS clipboard - IMGUI_API void LogFinish(); // stop logging (close file, etc.) - IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard - IMGUI_API void LogText(const char* fmt, ...) IM_FMTARGS(1); // pass text data straight to log (without being displayed) - IMGUI_API void LogTextV(const char* fmt, va_list args) IM_FMTLIST(1); - - // Drag and Drop - // - On source items, call BeginDragDropSource(), if it returns true also call SetDragDropPayload() + EndDragDropSource(). - // - On target candidates, call BeginDragDropTarget(), if it returns true also call AcceptDragDropPayload() + EndDragDropTarget(). - // - If you stop calling BeginDragDropSource() the payload is preserved however it won't have a preview tooltip (we currently display a fallback "..." tooltip, see #1725) - // - An item can be both drag source and drop target. - IMGUI_API bool BeginDragDropSource(ImGuiDragDropFlags flags = 0); // call after submitting an item which may be dragged. when this return true, you can call SetDragDropPayload() + EndDragDropSource() - IMGUI_API bool SetDragDropPayload(const char* type, const void* data, size_t sz, ImGuiCond cond = 0); // type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui. Return true when payload has been accepted. - IMGUI_API void EndDragDropSource(); // only call EndDragDropSource() if BeginDragDropSource() returns true! - IMGUI_API bool BeginDragDropTarget(); // call after submitting an item that may receive a payload. If this returns true, you can call AcceptDragDropPayload() + EndDragDropTarget() - IMGUI_API const ImGuiPayload* AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags = 0); // accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released. - IMGUI_API void EndDragDropTarget(); // only call EndDragDropTarget() if BeginDragDropTarget() returns true! - IMGUI_API const ImGuiPayload* GetDragDropPayload(); // peek directly into the current payload from anywhere. returns NULL when drag and drop is finished or inactive. use ImGuiPayload::IsDataType() to test for the payload type. - - // Disabling [BETA API] - // - Disable all user interactions and dim items visuals (applying style.DisabledAlpha over current colors) - // - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled) - // - Tooltips windows by exception are opted out of disabling. - // - BeginDisabled(false)/EndDisabled() essentially does nothing but is provided to facilitate use of boolean expressions (as a micro-optimization: if you have tens of thousands of BeginDisabled(false)/EndDisabled() pairs, you might want to reformulate your code to avoid making those calls) - IMGUI_API void BeginDisabled(bool disabled = true); - IMGUI_API void EndDisabled(); - - // Clipping - // - Mouse hovering is affected by ImGui::PushClipRect() calls, unlike direct calls to ImDrawList::PushClipRect() which are render only. - IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect); - IMGUI_API void PopClipRect(); - - // Focus, Activation - IMGUI_API void SetItemDefaultFocus(); // make last item the default focused item of a newly appearing window. - IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use -1 to access previous widget. - - // Keyboard/Gamepad Navigation - IMGUI_API void SetNavCursorVisible(bool visible); // alter visibility of keyboard/gamepad cursor. by default: show when using an arrow key, hide when clicking with mouse. - - // Overlapping mode - IMGUI_API void SetNextItemAllowOverlap(); // allow next item to be overlapped by a subsequent item. Useful with invisible buttons, selectable, treenode covering an area where subsequent items may need to be added. Note that both Selectable() and TreeNode() have dedicated flags doing this. - - // Item/Widgets Utilities and Query Functions - // - Most of the functions are referring to the previous Item that has been submitted. - // - See Demo Window under "Widgets->Querying Status" for an interactive visualization of most of those functions. - IMGUI_API bool IsItemHovered(ImGuiHoveredFlags flags = 0); // is the last item hovered? (and usable, aka not blocked by a popup, etc.). See ImGuiHoveredFlags for more options. - IMGUI_API bool IsItemActive(); // is the last item active? (e.g. button being held, text field being edited. This will continuously return true while holding mouse button on an item. Items that don't interact will always return false) - IMGUI_API bool IsItemFocused(); // is the last item focused for keyboard/gamepad navigation? - IMGUI_API bool IsItemClicked(ImGuiMouseButton mouse_button = 0); // is the last item hovered and mouse clicked on? (**) == IsMouseClicked(mouse_button) && IsItemHovered()Important. (**) this is NOT equivalent to the behavior of e.g. Button(). Read comments in function definition. - IMGUI_API bool IsItemVisible(); // is the last item visible? (items may be out of sight because of clipping/scrolling) - IMGUI_API bool IsItemEdited(); // did the last item modify its underlying value this frame? or was pressed? This is generally the same as the "bool" return value of many widgets. - IMGUI_API bool IsItemActivated(); // was the last item just made active (item was previously inactive). - IMGUI_API bool IsItemDeactivated(); // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that require continuous editing. - IMGUI_API bool IsItemDeactivatedAfterEdit(); // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that require continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item). - IMGUI_API bool IsItemToggledOpen(); // was the last item open state toggled? set by TreeNode(). - IMGUI_API bool IsAnyItemHovered(); // is any item hovered? - IMGUI_API bool IsAnyItemActive(); // is any item active? - IMGUI_API bool IsAnyItemFocused(); // is any item focused? - IMGUI_API ImGuiID GetItemID(); // get ID of last item (~~ often same ImGui::GetID(label) beforehand) - IMGUI_API ImVec2 GetItemRectMin(); // get upper-left bounding rectangle of the last item (screen space) - IMGUI_API ImVec2 GetItemRectMax(); // get lower-right bounding rectangle of the last item (screen space) - IMGUI_API ImVec2 GetItemRectSize(); // get size of last item - - // Viewports - // - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows. - // - In 'docking' branch with multi-viewport enabled, we extend this concept to have multiple active viewports. - // - In the future we will extend this concept further to also represent Platform Monitor and support a "no main platform window" operation mode. - IMGUI_API ImGuiViewport* GetMainViewport(); // return primary/default viewport. This can never be NULL. - - // Background/Foreground Draw Lists - IMGUI_API ImDrawList* GetBackgroundDrawList(); // this draw list will be the first rendered one. Useful to quickly draw shapes/text behind dear imgui contents. - IMGUI_API ImDrawList* GetForegroundDrawList(); // this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents. - - // Miscellaneous Utilities - IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle (of given size, starting from cursor position) is visible / not clipped. - IMGUI_API bool IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max); // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side. - IMGUI_API double GetTime(); // get global imgui time. incremented by io.DeltaTime every frame. - IMGUI_API int GetFrameCount(); // get global imgui frame count. incremented by 1 every frame. - IMGUI_API ImDrawListSharedData* GetDrawListSharedData(); // you may use this when creating your own ImDrawList instances. - IMGUI_API const char* GetStyleColorName(ImGuiCol idx); // get a string corresponding to the enum value (for display, saving, etc.). - IMGUI_API void SetStateStorage(ImGuiStorage* storage); // replace current window storage with our own (if you want to manipulate it yourself, typically clear subsection of it) - IMGUI_API ImGuiStorage* GetStateStorage(); - - // Text Utilities - IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f); - - // Color Utilities - IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in); - IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in); - IMGUI_API void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v); - IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b); - - // Inputs Utilities: Keyboard/Mouse/Gamepad - // - the ImGuiKey enum contains all possible keyboard, mouse and gamepad inputs (e.g. ImGuiKey_A, ImGuiKey_MouseLeft, ImGuiKey_GamepadDpadUp...). - // - (legacy: before v1.87, we used ImGuiKey to carry native/user indices as defined by each backends. This was obsoleted in 1.87 (2022-02) and completely removed in 1.91.5 (2024-11). See https://github.com/ocornut/imgui/issues/4921) - // - (legacy: any use of ImGuiKey will assert when key < 512 to detect passing legacy native/user indices) - IMGUI_API bool IsKeyDown(ImGuiKey key); // is key being held. - IMGUI_API bool IsKeyPressed(ImGuiKey key, bool repeat = true); // was key pressed (went from !Down to Down)? if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate - IMGUI_API bool IsKeyReleased(ImGuiKey key); // was key released (went from Down to !Down)? - IMGUI_API bool IsKeyChordPressed(ImGuiKeyChord key_chord); // was key chord (mods + key) pressed, e.g. you can pass 'ImGuiMod_Ctrl | ImGuiKey_S' as a key-chord. This doesn't do any routing or focus check, please consider using Shortcut() function instead. - IMGUI_API int GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float rate); // uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate - IMGUI_API const char* GetKeyName(ImGuiKey key); // [DEBUG] returns English name of the key. Those names are provided for debugging purpose and are not meant to be saved persistently nor compared. - IMGUI_API void SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard); // Override io.WantCaptureKeyboard flag next frame (said flag is left for your application to handle, typically when true it instructs your app to ignore inputs). e.g. force capture keyboard when your widget is being hovered. This is equivalent to setting "io.WantCaptureKeyboard = want_capture_keyboard"; after the next NewFrame() call. - - // Inputs Utilities: Shortcut Testing & Routing [BETA] - // - ImGuiKeyChord = a ImGuiKey + optional ImGuiMod_Alt/ImGuiMod_Ctrl/ImGuiMod_Shift/ImGuiMod_Super. - // ImGuiKey_C // Accepted by functions taking ImGuiKey or ImGuiKeyChord arguments) - // ImGuiMod_Ctrl | ImGuiKey_C // Accepted by functions taking ImGuiKeyChord arguments) - // only ImGuiMod_XXX values are legal to combine with an ImGuiKey. You CANNOT combine two ImGuiKey values. - // - The general idea is that several callers may register interest in a shortcut, and only one owner gets it. - // Parent -> call Shortcut(Ctrl+S) // When Parent is focused, Parent gets the shortcut. - // Child1 -> call Shortcut(Ctrl+S) // When Child1 is focused, Child1 gets the shortcut (Child1 overrides Parent shortcuts) - // Child2 -> no call // When Child2 is focused, Parent gets the shortcut. - // The whole system is order independent, so if Child1 makes its calls before Parent, results will be identical. - // This is an important property as it facilitate working with foreign code or larger codebase. - // - To understand the difference: - // - IsKeyChordPressed() compares mods and call IsKeyPressed() -> function has no side-effect. - // - Shortcut() submits a route, routes are resolved, if it currently can be routed it calls IsKeyChordPressed() -> function has (desirable) side-effects as it can prevents another call from getting the route. - // - Visualize registered routes in 'Metrics/Debugger->Inputs'. - IMGUI_API bool Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0); - IMGUI_API void SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0); - - // Inputs Utilities: Key/Input Ownership [BETA] - // - One common use case would be to allow your items to disable standard inputs behaviors such - // as Tab or Alt key handling, Mouse Wheel scrolling, etc. - // e.g. Button(...); SetItemKeyOwner(ImGuiKey_MouseWheelY); to make hovering/activating a button disable wheel for scrolling. - // - Reminder ImGuiKey enum include access to mouse buttons and gamepad, so key ownership can apply to them. - // - Many related features are still in imgui_internal.h. For instance, most IsKeyXXX()/IsMouseXXX() functions have an owner-id-aware version. - IMGUI_API void SetItemKeyOwner(ImGuiKey key); // Set key owner to last item ID if it is hovered or active. Equivalent to 'if (IsItemHovered() || IsItemActive()) { SetKeyOwner(key, GetItemID());'. - - // Inputs Utilities: Mouse - // - To refer to a mouse button, you may use named enums in your code e.g. ImGuiMouseButton_Left, ImGuiMouseButton_Right. - // - You can also use regular integer: it is forever guaranteed that 0=Left, 1=Right, 2=Middle. - // - Dragging operations are only reported after mouse has moved a certain distance away from the initial clicking position (see 'lock_threshold' and 'io.MouseDraggingThreshold') - IMGUI_API bool IsMouseDown(ImGuiMouseButton button); // is mouse button held? - IMGUI_API bool IsMouseClicked(ImGuiMouseButton button, bool repeat = false); // did mouse button clicked? (went from !Down to Down). Same as GetMouseClickedCount() == 1. - IMGUI_API bool IsMouseReleased(ImGuiMouseButton button); // did mouse button released? (went from Down to !Down) - IMGUI_API bool IsMouseDoubleClicked(ImGuiMouseButton button); // did mouse button double-clicked? Same as GetMouseClickedCount() == 2. (note that a double-click will also report IsMouseClicked() == true) - IMGUI_API bool IsMouseReleasedWithDelay(ImGuiMouseButton button, float delay); // delayed mouse release (use very sparingly!). Generally used with 'delay >= io.MouseDoubleClickTime' + combined with a 'io.MouseClickedLastCount==1' test. This is a very rarely used UI idiom, but some apps use this: e.g. MS Explorer single click on an icon to rename. - IMGUI_API int GetMouseClickedCount(ImGuiMouseButton button); // return the number of successive mouse-clicks at the time where a click happen (otherwise 0). - IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true);// is mouse hovering given bounding rect (in screen space). clipped by current clipping settings, but disregarding of other consideration of focus/window ordering/popup-block. - IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); // by convention we use (-FLT_MAX,-FLT_MAX) to denote that there is no mouse available - IMGUI_API bool IsAnyMouseDown(); // [WILL OBSOLETE] is any mouse button held? This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid. - IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls - IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve mouse position at the time of opening popup we have BeginPopup() into (helper to avoid user backing that value themselves) - IMGUI_API bool IsMouseDragging(ImGuiMouseButton button, float lock_threshold = -1.0f); // is mouse dragging? (uses io.MouseDraggingThreshold if lock_threshold < 0.0f) - IMGUI_API ImVec2 GetMouseDragDelta(ImGuiMouseButton button = 0, float lock_threshold = -1.0f); // return the delta from the initial clicking position while the mouse button is pressed or was just released. This is locked and return 0.0f until the mouse moves past a distance threshold at least once (uses io.MouseDraggingThreshold if lock_threshold < 0.0f) - IMGUI_API void ResetMouseDragDelta(ImGuiMouseButton button = 0); // - IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired mouse cursor shape. Important: reset in ImGui::NewFrame(), this is updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you - IMGUI_API void SetMouseCursor(ImGuiMouseCursor cursor_type); // set desired mouse cursor shape - IMGUI_API void SetNextFrameWantCaptureMouse(bool want_capture_mouse); // Override io.WantCaptureMouse flag next frame (said flag is left for your application to handle, typical when true it instructs your app to ignore inputs). This is equivalent to setting "io.WantCaptureMouse = want_capture_mouse;" after the next NewFrame() call. - - // Clipboard Utilities - // - Also see the LogToClipboard() function to capture GUI into clipboard, or easily output text data to the clipboard. - IMGUI_API const char* GetClipboardText(); - IMGUI_API void SetClipboardText(const char* text); - - // Settings/.Ini Utilities - // - The disk functions are automatically called if io.IniFilename != NULL (default is "imgui.ini"). - // - Set io.IniFilename to NULL to load/save manually. Read io.WantSaveIniSettings description about handling .ini saving manually. - // - Important: default value "imgui.ini" is relative to current working dir! Most apps will want to lock this to an absolute path (e.g. same path as executables). - IMGUI_API void LoadIniSettingsFromDisk(const char* ini_filename); // call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename). - IMGUI_API void LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size=0); // call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source. - IMGUI_API void SaveIniSettingsToDisk(const char* ini_filename); // this is automatically called (if io.IniFilename is not empty) a few seconds after any modification that should be reflected in the .ini file (and also by DestroyContext). - IMGUI_API const char* SaveIniSettingsToMemory(size_t* out_ini_size = NULL); // return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings. - - // Debug Utilities - // - Your main debugging friend is the ShowMetricsWindow() function, which is also accessible from Demo->Tools->Metrics Debugger - IMGUI_API void DebugTextEncoding(const char* text); - IMGUI_API void DebugFlashStyleColor(ImGuiCol idx); - IMGUI_API void DebugStartItemPicker(); - IMGUI_API bool DebugCheckVersionAndDataLayout(const char* version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert, size_t sz_drawidx); // This is called by IMGUI_CHECKVERSION() macro. -#ifndef IMGUI_DISABLE_DEBUG_TOOLS - IMGUI_API void DebugLog(const char* fmt, ...) IM_FMTARGS(1); // Call via IMGUI_DEBUG_LOG() for maximum stripping in caller code! - IMGUI_API void DebugLogV(const char* fmt, va_list args) IM_FMTLIST(1); -#endif - - // Memory Allocators - // - Those functions are not reliant on the current context. - // - DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() - // for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details. - IMGUI_API void SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data = NULL); - IMGUI_API void GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data); - IMGUI_API void* MemAlloc(size_t size); - IMGUI_API void MemFree(void* ptr); - -} // namespace ImGui - -//----------------------------------------------------------------------------- -// [SECTION] Flags & Enumerations -//----------------------------------------------------------------------------- - -// Flags for ImGui::Begin() -// (Those are per-window flags. There are shared flags in ImGuiIO: io.ConfigWindowsResizeFromEdges and io.ConfigWindowsMoveFromTitleBarOnly) -enum ImGuiWindowFlags_ -{ - ImGuiWindowFlags_None = 0, - ImGuiWindowFlags_NoTitleBar = 1 << 0, // Disable title-bar - ImGuiWindowFlags_NoResize = 1 << 1, // Disable user resizing with the lower-right grip - ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window - ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programmatically) - ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set. - ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it. Also referred to as Window Menu Button (e.g. within a docking node). - ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame - ImGuiWindowFlags_NoBackground = 1 << 7, // Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f). - ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file - ImGuiWindowFlags_NoMouseInputs = 1 << 9, // Disable catching mouse, hovering test with pass through. - ImGuiWindowFlags_MenuBar = 1 << 10, // Has a menu-bar - ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. - ImGuiWindowFlags_NoFocusOnAppearing = 1 << 12, // Disable taking focus when transitioning from hidden to visible state - ImGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13, // Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus) - ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y) - ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x) - ImGuiWindowFlags_NoNavInputs = 1 << 16, // No keyboard/gamepad navigation within the window - ImGuiWindowFlags_NoNavFocus = 1 << 17, // No focusing toward this window with keyboard/gamepad navigation (e.g. skipped by CTRL+TAB) - ImGuiWindowFlags_UnsavedDocument = 1 << 18, // Display a dot next to the title. When used in a tab/docking context, tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. - ImGuiWindowFlags_NoNav = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, - ImGuiWindowFlags_NoDecoration = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse, - ImGuiWindowFlags_NoInputs = ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, - - // [Internal] - ImGuiWindowFlags_ChildWindow = 1 << 24, // Don't use! For internal use by BeginChild() - ImGuiWindowFlags_Tooltip = 1 << 25, // Don't use! For internal use by BeginTooltip() - ImGuiWindowFlags_Popup = 1 << 26, // Don't use! For internal use by BeginPopup() - ImGuiWindowFlags_Modal = 1 << 27, // Don't use! For internal use by BeginPopupModal() - ImGuiWindowFlags_ChildMenu = 1 << 28, // Don't use! For internal use by BeginMenu() - - // Obsolete names -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiWindowFlags_NavFlattened = 1 << 29, // Obsoleted in 1.90.9: Use ImGuiChildFlags_NavFlattened in BeginChild() call. - ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 30, // Obsoleted in 1.90.0: Use ImGuiChildFlags_AlwaysUseWindowPadding in BeginChild() call. -#endif -}; - -// Flags for ImGui::BeginChild() -// (Legacy: bit 0 must always correspond to ImGuiChildFlags_Borders to be backward compatible with old API using 'bool border = false'. -// About using AutoResizeX/AutoResizeY flags: -// - May be combined with SetNextWindowSizeConstraints() to set a min/max size for each axis (see "Demo->Child->Auto-resize with Constraints"). -// - Size measurement for a given axis is only performed when the child window is within visible boundaries, or is just appearing. -// - This allows BeginChild() to return false when not within boundaries (e.g. when scrolling), which is more optimal. BUT it won't update its auto-size while clipped. -// While not perfect, it is a better default behavior as the always-on performance gain is more valuable than the occasional "resizing after becoming visible again" glitch. -// - You may also use ImGuiChildFlags_AlwaysAutoResize to force an update even when child window is not in view. -// HOWEVER PLEASE UNDERSTAND THAT DOING SO WILL PREVENT BeginChild() FROM EVER RETURNING FALSE, disabling benefits of coarse clipping. -enum ImGuiChildFlags_ -{ - ImGuiChildFlags_None = 0, - ImGuiChildFlags_Borders = 1 << 0, // Show an outer border and enable WindowPadding. (IMPORTANT: this is always == 1 == true for legacy reason) - ImGuiChildFlags_AlwaysUseWindowPadding = 1 << 1, // Pad with style.WindowPadding even if no border are drawn (no padding by default for non-bordered child windows because it makes more sense) - ImGuiChildFlags_ResizeX = 1 << 2, // Allow resize from right border (layout direction). Enable .ini saving (unless ImGuiWindowFlags_NoSavedSettings passed to window flags) - ImGuiChildFlags_ResizeY = 1 << 3, // Allow resize from bottom border (layout direction). " - ImGuiChildFlags_AutoResizeX = 1 << 4, // Enable auto-resizing width. Read "IMPORTANT: Size measurement" details above. - ImGuiChildFlags_AutoResizeY = 1 << 5, // Enable auto-resizing height. Read "IMPORTANT: Size measurement" details above. - ImGuiChildFlags_AlwaysAutoResize = 1 << 6, // Combined with AutoResizeX/AutoResizeY. Always measure size even when child is hidden, always return true, always disable clipping optimization! NOT RECOMMENDED. - ImGuiChildFlags_FrameStyle = 1 << 7, // Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding. - ImGuiChildFlags_NavFlattened = 1 << 8, // [BETA] Share focus scope, allow keyboard/gamepad navigation to cross over parent border to this child or between sibling child windows. - - // Obsolete names -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiChildFlags_Border = ImGuiChildFlags_Borders, // Renamed in 1.91.1 (August 2024) for consistency. -#endif -}; - -// Flags for ImGui::PushItemFlag() -// (Those are shared by all items) -enum ImGuiItemFlags_ -{ - ImGuiItemFlags_None = 0, // (Default) - ImGuiItemFlags_NoTabStop = 1 << 0, // false // Disable keyboard tabbing. This is a "lighter" version of ImGuiItemFlags_NoNav. - ImGuiItemFlags_NoNav = 1 << 1, // false // Disable any form of focusing (keyboard/gamepad directional navigation and SetKeyboardFocusHere() calls). - ImGuiItemFlags_NoNavDefaultFocus = 1 << 2, // false // Disable item being a candidate for default focus (e.g. used by title bar items). - ImGuiItemFlags_ButtonRepeat = 1 << 3, // false // Any button-like behavior will have repeat mode enabled (based on io.KeyRepeatDelay and io.KeyRepeatRate values). Note that you can also call IsItemActive() after any button to tell if it is being held. - ImGuiItemFlags_AutoClosePopups = 1 << 4, // true // MenuItem()/Selectable() automatically close their parent popup window. - ImGuiItemFlags_AllowDuplicateId = 1 << 5, // false // Allow submitting an item with the same identifier as an item already submitted this frame without triggering a warning tooltip if io.ConfigDebugHighlightIdConflicts is set. -}; - -// Flags for ImGui::InputText() -// (Those are per-item flags. There are shared flags in ImGuiIO: io.ConfigInputTextCursorBlink and io.ConfigInputTextEnterKeepActive) -enum ImGuiInputTextFlags_ -{ - // Basic filters (also see ImGuiInputTextFlags_CallbackCharFilter) - ImGuiInputTextFlags_None = 0, - ImGuiInputTextFlags_CharsDecimal = 1 << 0, // Allow 0123456789.+-*/ - ImGuiInputTextFlags_CharsHexadecimal = 1 << 1, // Allow 0123456789ABCDEFabcdef - ImGuiInputTextFlags_CharsScientific = 1 << 2, // Allow 0123456789.+-*/eE (Scientific notation input) - ImGuiInputTextFlags_CharsUppercase = 1 << 3, // Turn a..z into A..Z - ImGuiInputTextFlags_CharsNoBlank = 1 << 4, // Filter out spaces, tabs - - // Inputs - ImGuiInputTextFlags_AllowTabInput = 1 << 5, // Pressing TAB input a '\t' character into the text field - ImGuiInputTextFlags_EnterReturnsTrue = 1 << 6, // Return 'true' when Enter is pressed (as opposed to every time the value was modified). Consider using IsItemDeactivatedAfterEdit() instead! - ImGuiInputTextFlags_EscapeClearsAll = 1 << 7, // Escape key clears content if not empty, and deactivate otherwise (contrast to default behavior of Escape to revert) - ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 8, // In multi-line mode, validate with Enter, add new line with Ctrl+Enter (default is opposite: validate with Ctrl+Enter, add line with Enter). - - // Other options - ImGuiInputTextFlags_ReadOnly = 1 << 9, // Read-only mode - ImGuiInputTextFlags_Password = 1 << 10, // Password mode, display all characters as '*', disable copy - ImGuiInputTextFlags_AlwaysOverwrite = 1 << 11, // Overwrite mode - ImGuiInputTextFlags_AutoSelectAll = 1 << 12, // Select entire text when first taking mouse focus - ImGuiInputTextFlags_ParseEmptyRefVal = 1 << 13, // InputFloat(), InputInt(), InputScalar() etc. only: parse empty string as zero value. - ImGuiInputTextFlags_DisplayEmptyRefVal = 1 << 14, // InputFloat(), InputInt(), InputScalar() etc. only: when value is zero, do not display it. Generally used with ImGuiInputTextFlags_ParseEmptyRefVal. - ImGuiInputTextFlags_NoHorizontalScroll = 1 << 15, // Disable following the cursor horizontally - ImGuiInputTextFlags_NoUndoRedo = 1 << 16, // Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID(). - - // Elide display / Alignment - ImGuiInputTextFlags_ElideLeft = 1 << 17, // When text doesn't fit, elide left side to ensure right side stays visible. Useful for path/filenames. Single-line only! - - // Callback features - ImGuiInputTextFlags_CallbackCompletion = 1 << 18, // Callback on pressing TAB (for completion handling) - ImGuiInputTextFlags_CallbackHistory = 1 << 19, // Callback on pressing Up/Down arrows (for history handling) - ImGuiInputTextFlags_CallbackAlways = 1 << 20, // Callback on each iteration. User code may query cursor position, modify text buffer. - ImGuiInputTextFlags_CallbackCharFilter = 1 << 21, // Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. - ImGuiInputTextFlags_CallbackResize = 1 << 22, // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this) - ImGuiInputTextFlags_CallbackEdit = 1 << 23, // Callback on any edit. Note that InputText() already returns true on edit + you can always use IsItemEdited(). The callback is useful to manipulate the underlying buffer while focus is active. - - // Obsolete names - //ImGuiInputTextFlags_AlwaysInsertMode = ImGuiInputTextFlags_AlwaysOverwrite // [renamed in 1.82] name was not matching behavior -}; - -// Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*() -enum ImGuiTreeNodeFlags_ -{ - ImGuiTreeNodeFlags_None = 0, - ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected - ImGuiTreeNodeFlags_Framed = 1 << 1, // Draw frame with background (e.g. for CollapsingHeader) - ImGuiTreeNodeFlags_AllowOverlap = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one - ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack - ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) - ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, // Default node to be open - ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, // Open on double-click instead of simple click (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. - ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Open when clicking on the arrow part (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. - ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes). - ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow. IMPORTANT: node can still be marked open/close if you don't set the _Leaf flag! - ImGuiTreeNodeFlags_FramePadding = 1 << 10, // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding() before the node. - ImGuiTreeNodeFlags_SpanAvailWidth = 1 << 11, // Extend hit box to the right-most edge, even if not framed. This is not the default in order to allow adding other items on the same line without using AllowOverlap mode. - ImGuiTreeNodeFlags_SpanFullWidth = 1 << 12, // Extend hit box to the left-most and right-most edges (cover the indent area). - ImGuiTreeNodeFlags_SpanLabelWidth = 1 << 13, // Narrow hit box + narrow hovering highlight, will only cover the label text. - ImGuiTreeNodeFlags_SpanAllColumns = 1 << 14, // Frame will span all columns of its container table (label will still fit in current column) - ImGuiTreeNodeFlags_LabelSpanAllColumns = 1 << 15, // Label will span all columns of its container table - //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 16, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible - ImGuiTreeNodeFlags_NavLeftJumpsToParent = 1 << 17, // Nav: left arrow moves back to parent. This is processed in TreePop() when there's an unfullfilled Left nav request remaining. - ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog, - - // [EXPERIMENTAL] Draw lines connecting TreeNode hierarchy. Discuss in GitHub issue #2920. - // Default value is pulled from style.TreeLinesFlags. May be overridden in TreeNode calls. - ImGuiTreeNodeFlags_DrawLinesNone = 1 << 18, // No lines drawn - ImGuiTreeNodeFlags_DrawLinesFull = 1 << 19, // Horizontal lines to child nodes. Vertical line drawn down to TreePop() position: cover full contents. Faster (for large trees). - ImGuiTreeNodeFlags_DrawLinesToNodes = 1 << 20, // Horizontal lines to child nodes. Vertical line drawn down to bottom-most child node. Slower (for large trees). - -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiTreeNodeFlags_NavLeftJumpsBackHere = ImGuiTreeNodeFlags_NavLeftJumpsToParent, // Renamed in 1.92.0 - ImGuiTreeNodeFlags_SpanTextWidth = ImGuiTreeNodeFlags_SpanLabelWidth, // Renamed in 1.90.7 - ImGuiTreeNodeFlags_AllowItemOverlap = ImGuiTreeNodeFlags_AllowOverlap, // Renamed in 1.89.7 -#endif -}; - -// Flags for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() functions. -// - To be backward compatible with older API which took an 'int mouse_button = 1' argument instead of 'ImGuiPopupFlags flags', -// we need to treat small flags values as a mouse button index, so we encode the mouse button in the first few bits of the flags. -// It is therefore guaranteed to be legal to pass a mouse button index in ImGuiPopupFlags. -// - For the same reason, we exceptionally default the ImGuiPopupFlags argument of BeginPopupContextXXX functions to 1 instead of 0. -// IMPORTANT: because the default parameter is 1 (==ImGuiPopupFlags_MouseButtonRight), if you rely on the default parameter -// and want to use another flag, you need to pass in the ImGuiPopupFlags_MouseButtonRight flag explicitly. -// - Multiple buttons currently cannot be combined/or-ed in those functions (we could allow it later). -enum ImGuiPopupFlags_ -{ - ImGuiPopupFlags_None = 0, - ImGuiPopupFlags_MouseButtonLeft = 0, // For BeginPopupContext*(): open on Left Mouse release. Guaranteed to always be == 0 (same as ImGuiMouseButton_Left) - ImGuiPopupFlags_MouseButtonRight = 1, // For BeginPopupContext*(): open on Right Mouse release. Guaranteed to always be == 1 (same as ImGuiMouseButton_Right) - ImGuiPopupFlags_MouseButtonMiddle = 2, // For BeginPopupContext*(): open on Middle Mouse release. Guaranteed to always be == 2 (same as ImGuiMouseButton_Middle) - ImGuiPopupFlags_MouseButtonMask_ = 0x1F, - ImGuiPopupFlags_MouseButtonDefault_ = 1, - ImGuiPopupFlags_NoReopen = 1 << 5, // For OpenPopup*(), BeginPopupContext*(): don't reopen same popup if already open (won't reposition, won't reinitialize navigation) - //ImGuiPopupFlags_NoReopenAlwaysNavInit = 1 << 6, // For OpenPopup*(), BeginPopupContext*(): focus and initialize navigation even when not reopening. - ImGuiPopupFlags_NoOpenOverExistingPopup = 1 << 7, // For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack - ImGuiPopupFlags_NoOpenOverItems = 1 << 8, // For BeginPopupContextWindow(): don't return true when hovering items, only when hovering empty space - ImGuiPopupFlags_AnyPopupId = 1 << 10, // For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup. - ImGuiPopupFlags_AnyPopupLevel = 1 << 11, // For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level) - ImGuiPopupFlags_AnyPopup = ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel, -}; - -// Flags for ImGui::Selectable() -enum ImGuiSelectableFlags_ -{ - ImGuiSelectableFlags_None = 0, - ImGuiSelectableFlags_NoAutoClosePopups = 1 << 0, // Clicking this doesn't close parent popup window (overrides ImGuiItemFlags_AutoClosePopups) - ImGuiSelectableFlags_SpanAllColumns = 1 << 1, // Frame will span all columns of its container table (text will still fit in current column) - ImGuiSelectableFlags_AllowDoubleClick = 1 << 2, // Generate press events on double clicks too - ImGuiSelectableFlags_Disabled = 1 << 3, // Cannot be selected, display grayed out text - ImGuiSelectableFlags_AllowOverlap = 1 << 4, // (WIP) Hit testing to allow subsequent widgets to overlap this one - ImGuiSelectableFlags_Highlight = 1 << 5, // Make the item be displayed as if it is hovered - -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiSelectableFlags_DontClosePopups = ImGuiSelectableFlags_NoAutoClosePopups, // Renamed in 1.91.0 - ImGuiSelectableFlags_AllowItemOverlap = ImGuiSelectableFlags_AllowOverlap, // Renamed in 1.89.7 -#endif -}; - -// Flags for ImGui::BeginCombo() -enum ImGuiComboFlags_ -{ - ImGuiComboFlags_None = 0, - ImGuiComboFlags_PopupAlignLeft = 1 << 0, // Align the popup toward the left by default - ImGuiComboFlags_HeightSmall = 1 << 1, // Max ~4 items visible. Tip: If you want your combo popup to be a specific size you can use SetNextWindowSizeConstraints() prior to calling BeginCombo() - ImGuiComboFlags_HeightRegular = 1 << 2, // Max ~8 items visible (default) - ImGuiComboFlags_HeightLarge = 1 << 3, // Max ~20 items visible - ImGuiComboFlags_HeightLargest = 1 << 4, // As many fitting items as possible - ImGuiComboFlags_NoArrowButton = 1 << 5, // Display on the preview box without the square arrow button - ImGuiComboFlags_NoPreview = 1 << 6, // Display only a square arrow button - ImGuiComboFlags_WidthFitPreview = 1 << 7, // Width dynamically calculated from preview contents - ImGuiComboFlags_HeightMask_ = ImGuiComboFlags_HeightSmall | ImGuiComboFlags_HeightRegular | ImGuiComboFlags_HeightLarge | ImGuiComboFlags_HeightLargest, -}; - -// Flags for ImGui::BeginTabBar() -enum ImGuiTabBarFlags_ -{ - ImGuiTabBarFlags_None = 0, - ImGuiTabBarFlags_Reorderable = 1 << 0, // Allow manually dragging tabs to re-order them + New tabs are appended at the end of list - ImGuiTabBarFlags_AutoSelectNewTabs = 1 << 1, // Automatically select new tabs when they appear - ImGuiTabBarFlags_TabListPopupButton = 1 << 2, // Disable buttons to open the tab list popup - ImGuiTabBarFlags_NoCloseWithMiddleMouseButton = 1 << 3, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You may handle this behavior manually on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. - ImGuiTabBarFlags_NoTabListScrollingButtons = 1 << 4, // Disable scrolling buttons (apply when fitting policy is ImGuiTabBarFlags_FittingPolicyScroll) - ImGuiTabBarFlags_NoTooltip = 1 << 5, // Disable tooltips when hovering a tab - ImGuiTabBarFlags_DrawSelectedOverline = 1 << 6, // Draw selected overline markers over selected tab - ImGuiTabBarFlags_FittingPolicyResizeDown = 1 << 7, // Resize tabs when they don't fit - ImGuiTabBarFlags_FittingPolicyScroll = 1 << 8, // Add scroll buttons when tabs don't fit - ImGuiTabBarFlags_FittingPolicyMask_ = ImGuiTabBarFlags_FittingPolicyResizeDown | ImGuiTabBarFlags_FittingPolicyScroll, - ImGuiTabBarFlags_FittingPolicyDefault_ = ImGuiTabBarFlags_FittingPolicyResizeDown, -}; - -// Flags for ImGui::BeginTabItem() -enum ImGuiTabItemFlags_ -{ - ImGuiTabItemFlags_None = 0, - ImGuiTabItemFlags_UnsavedDocument = 1 << 0, // Display a dot next to the title + set ImGuiTabItemFlags_NoAssumedClosure. - ImGuiTabItemFlags_SetSelected = 1 << 1, // Trigger flag to programmatically make the tab selected when calling BeginTabItem() - ImGuiTabItemFlags_NoCloseWithMiddleMouseButton = 1 << 2, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You may handle this behavior manually on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. - ImGuiTabItemFlags_NoPushId = 1 << 3, // Don't call PushID()/PopID() on BeginTabItem()/EndTabItem() - ImGuiTabItemFlags_NoTooltip = 1 << 4, // Disable tooltip for the given tab - ImGuiTabItemFlags_NoReorder = 1 << 5, // Disable reordering this tab or having another tab cross over this tab - ImGuiTabItemFlags_Leading = 1 << 6, // Enforce the tab position to the left of the tab bar (after the tab list popup button) - ImGuiTabItemFlags_Trailing = 1 << 7, // Enforce the tab position to the right of the tab bar (before the scrolling buttons) - ImGuiTabItemFlags_NoAssumedClosure = 1 << 8, // Tab is selected when trying to close + closure is not immediately assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. -}; - -// Flags for ImGui::IsWindowFocused() -enum ImGuiFocusedFlags_ -{ - ImGuiFocusedFlags_None = 0, - ImGuiFocusedFlags_ChildWindows = 1 << 0, // Return true if any children of the window is focused - ImGuiFocusedFlags_RootWindow = 1 << 1, // Test from root window (top most parent of the current hierarchy) - ImGuiFocusedFlags_AnyWindow = 1 << 2, // Return true if any window is focused. Important: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use 'io.WantCaptureMouse' instead! Please read the FAQ! - ImGuiFocusedFlags_NoPopupHierarchy = 1 << 3, // Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) - //ImGuiFocusedFlags_DockHierarchy = 1 << 4, // Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) - ImGuiFocusedFlags_RootAndChildWindows = ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows, -}; - -// Flags for ImGui::IsItemHovered(), ImGui::IsWindowHovered() -// Note: if you are trying to check whether your mouse should be dispatched to Dear ImGui or to your app, you should use 'io.WantCaptureMouse' instead! Please read the FAQ! -// Note: windows with the ImGuiWindowFlags_NoInputs flag are ignored by IsWindowHovered() calls. -enum ImGuiHoveredFlags_ -{ - ImGuiHoveredFlags_None = 0, // Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them. - ImGuiHoveredFlags_ChildWindows = 1 << 0, // IsWindowHovered() only: Return true if any children of the window is hovered - ImGuiHoveredFlags_RootWindow = 1 << 1, // IsWindowHovered() only: Test from root window (top most parent of the current hierarchy) - ImGuiHoveredFlags_AnyWindow = 1 << 2, // IsWindowHovered() only: Return true if any window is hovered - ImGuiHoveredFlags_NoPopupHierarchy = 1 << 3, // IsWindowHovered() only: Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) - //ImGuiHoveredFlags_DockHierarchy = 1 << 4, // IsWindowHovered() only: Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) - ImGuiHoveredFlags_AllowWhenBlockedByPopup = 1 << 5, // Return true even if a popup window is normally blocking access to this item/window - //ImGuiHoveredFlags_AllowWhenBlockedByModal = 1 << 6, // Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet. - ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = 1 << 7, // Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns. - ImGuiHoveredFlags_AllowWhenOverlappedByItem = 1 << 8, // IsItemHovered() only: Return true even if the item uses AllowOverlap mode and is overlapped by another hoverable item. - ImGuiHoveredFlags_AllowWhenOverlappedByWindow = 1 << 9, // IsItemHovered() only: Return true even if the position is obstructed or overlapped by another window. - ImGuiHoveredFlags_AllowWhenDisabled = 1 << 10, // IsItemHovered() only: Return true even if the item is disabled - ImGuiHoveredFlags_NoNavOverride = 1 << 11, // IsItemHovered() only: Disable using keyboard/gamepad navigation state when active, always query mouse - ImGuiHoveredFlags_AllowWhenOverlapped = ImGuiHoveredFlags_AllowWhenOverlappedByItem | ImGuiHoveredFlags_AllowWhenOverlappedByWindow, - ImGuiHoveredFlags_RectOnly = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped, - ImGuiHoveredFlags_RootAndChildWindows = ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows, - - // Tooltips mode - // - typically used in IsItemHovered() + SetTooltip() sequence. - // - this is a shortcut to pull flags from 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' where you can reconfigure desired behavior. - // e.g. 'TooltipHoveredFlagsForMouse' defaults to 'ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort'. - // - for frequently actioned or hovered items providing a tooltip, you want may to use ImGuiHoveredFlags_ForTooltip (stationary + delay) so the tooltip doesn't show too often. - // - for items which main purpose is to be hovered, or items with low affordance, or in less consistent apps, prefer no delay or shorter delay. - ImGuiHoveredFlags_ForTooltip = 1 << 12, // Shortcut for standard flags when using IsItemHovered() + SetTooltip() sequence. - - // (Advanced) Mouse Hovering delays. - // - generally you can use ImGuiHoveredFlags_ForTooltip to use application-standardized flags. - // - use those if you need specific overrides. - ImGuiHoveredFlags_Stationary = 1 << 13, // Require mouse to be stationary for style.HoverStationaryDelay (~0.15 sec) _at least one time_. After this, can move on same item/window. Using the stationary test tends to reduces the need for a long delay. - ImGuiHoveredFlags_DelayNone = 1 << 14, // IsItemHovered() only: Return true immediately (default). As this is the default you generally ignore this. - ImGuiHoveredFlags_DelayShort = 1 << 15, // IsItemHovered() only: Return true after style.HoverDelayShort elapsed (~0.15 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item). - ImGuiHoveredFlags_DelayNormal = 1 << 16, // IsItemHovered() only: Return true after style.HoverDelayNormal elapsed (~0.40 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item). - ImGuiHoveredFlags_NoSharedDelay = 1 << 17, // IsItemHovered() only: Disable shared delay system where moving from one item to the next keeps the previous timer for a short time (standard for tooltips with long delays) -}; - -// Flags for ImGui::BeginDragDropSource(), ImGui::AcceptDragDropPayload() -enum ImGuiDragDropFlags_ -{ - ImGuiDragDropFlags_None = 0, - // BeginDragDropSource() flags - ImGuiDragDropFlags_SourceNoPreviewTooltip = 1 << 0, // Disable preview tooltip. By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disables this behavior. - ImGuiDragDropFlags_SourceNoDisableHover = 1 << 1, // By default, when dragging we clear data so that IsItemHovered() will return false, to avoid subsequent user code submitting tooltips. This flag disables this behavior so you can still call IsItemHovered() on the source item. - ImGuiDragDropFlags_SourceNoHoldToOpenOthers = 1 << 2, // Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item. - ImGuiDragDropFlags_SourceAllowNullID = 1 << 3, // Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit. - ImGuiDragDropFlags_SourceExtern = 1 << 4, // External source (from outside of dear imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously. - ImGuiDragDropFlags_PayloadAutoExpire = 1 << 5, // Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged) - ImGuiDragDropFlags_PayloadNoCrossContext = 1 << 6, // Hint to specify that the payload may not be copied outside current dear imgui context. - ImGuiDragDropFlags_PayloadNoCrossProcess = 1 << 7, // Hint to specify that the payload may not be copied outside current process. - // AcceptDragDropPayload() flags - ImGuiDragDropFlags_AcceptBeforeDelivery = 1 << 10, // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered. - ImGuiDragDropFlags_AcceptNoDrawDefaultRect = 1 << 11, // Do not draw the default highlight rectangle when hovering over target. - ImGuiDragDropFlags_AcceptNoPreviewTooltip = 1 << 12, // Request hiding the BeginDragDropSource tooltip from the BeginDragDropTarget site. - ImGuiDragDropFlags_AcceptPeekOnly = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect, // For peeking ahead and inspecting the payload before delivery. - -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiDragDropFlags_SourceAutoExpirePayload = ImGuiDragDropFlags_PayloadAutoExpire, // Renamed in 1.90.9 -#endif -}; - -// Standard Drag and Drop payload types. You can define you own payload types using short strings. Types starting with '_' are defined by Dear ImGui. -#define IMGUI_PAYLOAD_TYPE_COLOR_3F "_COL3F" // float[3]: Standard type for colors, without alpha. User code may use this type. -#define IMGUI_PAYLOAD_TYPE_COLOR_4F "_COL4F" // float[4]: Standard type for colors. User code may use this type. - -// A primary data type -enum ImGuiDataType_ -{ - ImGuiDataType_S8, // signed char / char (with sensible compilers) - ImGuiDataType_U8, // unsigned char - ImGuiDataType_S16, // short - ImGuiDataType_U16, // unsigned short - ImGuiDataType_S32, // int - ImGuiDataType_U32, // unsigned int - ImGuiDataType_S64, // long long / __int64 - ImGuiDataType_U64, // unsigned long long / unsigned __int64 - ImGuiDataType_Float, // float - ImGuiDataType_Double, // double - ImGuiDataType_Bool, // bool (provided for user convenience, not supported by scalar widgets) - ImGuiDataType_String, // char* (provided for user convenience, not supported by scalar widgets) - ImGuiDataType_COUNT -}; - -// A cardinal direction -enum ImGuiDir : int -{ - ImGuiDir_None = -1, - ImGuiDir_Left = 0, - ImGuiDir_Right = 1, - ImGuiDir_Up = 2, - ImGuiDir_Down = 3, - ImGuiDir_COUNT -}; - -// A sorting direction -enum ImGuiSortDirection : ImU8 -{ - ImGuiSortDirection_None = 0, - ImGuiSortDirection_Ascending = 1, // Ascending = 0->9, A->Z etc. - ImGuiSortDirection_Descending = 2 // Descending = 9->0, Z->A etc. -}; - -// A key identifier (ImGuiKey_XXX or ImGuiMod_XXX value): can represent Keyboard, Mouse and Gamepad values. -// All our named keys are >= 512. Keys value 0 to 511 are left unused and were legacy native/opaque key values (< 1.87). -// Support for legacy keys was completely removed in 1.91.5. -// Read details about the 1.87+ transition : https://github.com/ocornut/imgui/issues/4921 -// Note that "Keys" related to physical keys and are not the same concept as input "Characters", the later are submitted via io.AddInputCharacter(). -// The keyboard key enum values are named after the keys on a standard US keyboard, and on other keyboard types the keys reported may not match the keycaps. -enum ImGuiKey : int -{ - // Keyboard - ImGuiKey_None = 0, - ImGuiKey_NamedKey_BEGIN = 512, // First valid key value (other than 0) - - ImGuiKey_Tab = 512, // == ImGuiKey_NamedKey_BEGIN - ImGuiKey_LeftArrow, - ImGuiKey_RightArrow, - ImGuiKey_UpArrow, - ImGuiKey_DownArrow, - ImGuiKey_PageUp, - ImGuiKey_PageDown, - ImGuiKey_Home, - ImGuiKey_End, - ImGuiKey_Insert, - ImGuiKey_Delete, - ImGuiKey_Backspace, - ImGuiKey_Space, - ImGuiKey_Enter, - ImGuiKey_Escape, - ImGuiKey_LeftCtrl, ImGuiKey_LeftShift, ImGuiKey_LeftAlt, ImGuiKey_LeftSuper, // Also see ImGuiMod_Ctrl, ImGuiMod_Shift, ImGuiMod_Alt, ImGuiMod_Super below! - ImGuiKey_RightCtrl, ImGuiKey_RightShift, ImGuiKey_RightAlt, ImGuiKey_RightSuper, - ImGuiKey_Menu, - ImGuiKey_0, ImGuiKey_1, ImGuiKey_2, ImGuiKey_3, ImGuiKey_4, ImGuiKey_5, ImGuiKey_6, ImGuiKey_7, ImGuiKey_8, ImGuiKey_9, - ImGuiKey_A, ImGuiKey_B, ImGuiKey_C, ImGuiKey_D, ImGuiKey_E, ImGuiKey_F, ImGuiKey_G, ImGuiKey_H, ImGuiKey_I, ImGuiKey_J, - ImGuiKey_K, ImGuiKey_L, ImGuiKey_M, ImGuiKey_N, ImGuiKey_O, ImGuiKey_P, ImGuiKey_Q, ImGuiKey_R, ImGuiKey_S, ImGuiKey_T, - ImGuiKey_U, ImGuiKey_V, ImGuiKey_W, ImGuiKey_X, ImGuiKey_Y, ImGuiKey_Z, - ImGuiKey_F1, ImGuiKey_F2, ImGuiKey_F3, ImGuiKey_F4, ImGuiKey_F5, ImGuiKey_F6, - ImGuiKey_F7, ImGuiKey_F8, ImGuiKey_F9, ImGuiKey_F10, ImGuiKey_F11, ImGuiKey_F12, - ImGuiKey_F13, ImGuiKey_F14, ImGuiKey_F15, ImGuiKey_F16, ImGuiKey_F17, ImGuiKey_F18, - ImGuiKey_F19, ImGuiKey_F20, ImGuiKey_F21, ImGuiKey_F22, ImGuiKey_F23, ImGuiKey_F24, - ImGuiKey_Apostrophe, // ' - ImGuiKey_Comma, // , - ImGuiKey_Minus, // - - ImGuiKey_Period, // . - ImGuiKey_Slash, // / - ImGuiKey_Semicolon, // ; - ImGuiKey_Equal, // = - ImGuiKey_LeftBracket, // [ - ImGuiKey_Backslash, // \ (this text inhibit multiline comment caused by backslash) - ImGuiKey_RightBracket, // ] - ImGuiKey_GraveAccent, // ` - ImGuiKey_CapsLock, - ImGuiKey_ScrollLock, - ImGuiKey_NumLock, - ImGuiKey_PrintScreen, - ImGuiKey_Pause, - ImGuiKey_Keypad0, ImGuiKey_Keypad1, ImGuiKey_Keypad2, ImGuiKey_Keypad3, ImGuiKey_Keypad4, - ImGuiKey_Keypad5, ImGuiKey_Keypad6, ImGuiKey_Keypad7, ImGuiKey_Keypad8, ImGuiKey_Keypad9, - ImGuiKey_KeypadDecimal, - ImGuiKey_KeypadDivide, - ImGuiKey_KeypadMultiply, - ImGuiKey_KeypadSubtract, - ImGuiKey_KeypadAdd, - ImGuiKey_KeypadEnter, - ImGuiKey_KeypadEqual, - ImGuiKey_AppBack, // Available on some keyboard/mouses. Often referred as "Browser Back" - ImGuiKey_AppForward, - ImGuiKey_Oem102, // Non-US backslash. - - // Gamepad - // (analog values are 0.0f to 1.0f) - // (download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets) - // // XBOX | SWITCH | PLAYSTA. | -> ACTION - ImGuiKey_GamepadStart, // Menu | + | Options | - ImGuiKey_GamepadBack, // View | - | Share | - ImGuiKey_GamepadFaceLeft, // X | Y | Square | Tap: Toggle Menu. Hold: Windowing mode (Focus/Move/Resize windows) - ImGuiKey_GamepadFaceRight, // B | A | Circle | Cancel / Close / Exit - ImGuiKey_GamepadFaceUp, // Y | X | Triangle | Text Input / On-screen Keyboard - ImGuiKey_GamepadFaceDown, // A | B | Cross | Activate / Open / Toggle / Tweak - ImGuiKey_GamepadDpadLeft, // D-pad Left | " | " | Move / Tweak / Resize Window (in Windowing mode) - ImGuiKey_GamepadDpadRight, // D-pad Right | " | " | Move / Tweak / Resize Window (in Windowing mode) - ImGuiKey_GamepadDpadUp, // D-pad Up | " | " | Move / Tweak / Resize Window (in Windowing mode) - ImGuiKey_GamepadDpadDown, // D-pad Down | " | " | Move / Tweak / Resize Window (in Windowing mode) - ImGuiKey_GamepadL1, // L Bumper | L | L1 | Tweak Slower / Focus Previous (in Windowing mode) - ImGuiKey_GamepadR1, // R Bumper | R | R1 | Tweak Faster / Focus Next (in Windowing mode) - ImGuiKey_GamepadL2, // L Trigger | ZL | L2 | [Analog] - ImGuiKey_GamepadR2, // R Trigger | ZR | R2 | [Analog] - ImGuiKey_GamepadL3, // L Stick | L3 | L3 | - ImGuiKey_GamepadR3, // R Stick | R3 | R3 | - ImGuiKey_GamepadLStickLeft, // | | | [Analog] Move Window (in Windowing mode) - ImGuiKey_GamepadLStickRight, // | | | [Analog] Move Window (in Windowing mode) - ImGuiKey_GamepadLStickUp, // | | | [Analog] Move Window (in Windowing mode) - ImGuiKey_GamepadLStickDown, // | | | [Analog] Move Window (in Windowing mode) - ImGuiKey_GamepadRStickLeft, // | | | [Analog] - ImGuiKey_GamepadRStickRight, // | | | [Analog] - ImGuiKey_GamepadRStickUp, // | | | [Analog] - ImGuiKey_GamepadRStickDown, // | | | [Analog] - - // Aliases: Mouse Buttons (auto-submitted from AddMouseButtonEvent() calls) - // - This is mirroring the data also written to io.MouseDown[], io.MouseWheel, in a format allowing them to be accessed via standard key API. - ImGuiKey_MouseLeft, ImGuiKey_MouseRight, ImGuiKey_MouseMiddle, ImGuiKey_MouseX1, ImGuiKey_MouseX2, ImGuiKey_MouseWheelX, ImGuiKey_MouseWheelY, - - // [Internal] Reserved for mod storage - ImGuiKey_ReservedForModCtrl, ImGuiKey_ReservedForModShift, ImGuiKey_ReservedForModAlt, ImGuiKey_ReservedForModSuper, - - // [Internal] If you need to iterate all keys (for e.g. an input mapper) you may use ImGuiKey_NamedKey_BEGIN..ImGuiKey_NamedKey_END. - ImGuiKey_NamedKey_END, - ImGuiKey_NamedKey_COUNT = ImGuiKey_NamedKey_END - ImGuiKey_NamedKey_BEGIN, - - // Keyboard Modifiers (explicitly submitted by backend via AddKeyEvent() calls) - // - Any functions taking a ImGuiKeyChord parameter can binary-or those with regular keys, e.g. Shortcut(ImGuiMod_Ctrl | ImGuiKey_S). - // - Those are written back into io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper for convenience, - // but may be accessed via standard key API such as IsKeyPressed(), IsKeyReleased(), querying duration etc. - // - Code polling every key (e.g. an interface to detect a key press for input mapping) might want to ignore those - // and prefer using the real keys (e.g. ImGuiKey_LeftCtrl, ImGuiKey_RightCtrl instead of ImGuiMod_Ctrl). - // - In theory the value of keyboard modifiers should be roughly equivalent to a logical or of the equivalent left/right keys. - // In practice: it's complicated; mods are often provided from different sources. Keyboard layout, IME, sticky keys and - // backends tend to interfere and break that equivalence. The safer decision is to relay that ambiguity down to the end-user... - // - On macOS, we swap Cmd(Super) and Ctrl keys at the time of the io.AddKeyEvent() call. - ImGuiMod_None = 0, - ImGuiMod_Ctrl = 1 << 12, // Ctrl (non-macOS), Cmd (macOS) - ImGuiMod_Shift = 1 << 13, // Shift - ImGuiMod_Alt = 1 << 14, // Option/Menu - ImGuiMod_Super = 1 << 15, // Windows/Super (non-macOS), Ctrl (macOS) - ImGuiMod_Mask_ = 0xF000, // 4-bits - -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiKey_COUNT = ImGuiKey_NamedKey_END, // Obsoleted in 1.91.5 because it was extremely misleading (since named keys don't start at 0 anymore) - ImGuiMod_Shortcut = ImGuiMod_Ctrl, // Removed in 1.90.7, you can now simply use ImGuiMod_Ctrl - ImGuiKey_ModCtrl = ImGuiMod_Ctrl, ImGuiKey_ModShift = ImGuiMod_Shift, ImGuiKey_ModAlt = ImGuiMod_Alt, ImGuiKey_ModSuper = ImGuiMod_Super, // Renamed in 1.89 - //ImGuiKey_KeyPadEnter = ImGuiKey_KeypadEnter, // Renamed in 1.87 -#endif -}; - -// Flags for Shortcut(), SetNextItemShortcut(), -// (and for upcoming extended versions of IsKeyPressed(), IsMouseClicked(), Shortcut(), SetKeyOwner(), SetItemKeyOwner() that are still in imgui_internal.h) -// Don't mistake with ImGuiInputTextFlags! (which is for ImGui::InputText() function) -enum ImGuiInputFlags_ -{ - ImGuiInputFlags_None = 0, - ImGuiInputFlags_Repeat = 1 << 0, // Enable repeat. Return true on successive repeats. Default for legacy IsKeyPressed(). NOT Default for legacy IsMouseClicked(). MUST BE == 1. - - // Flags for Shortcut(), SetNextItemShortcut() - // - Routing policies: RouteGlobal+OverActive >> RouteActive or RouteFocused (if owner is active item) >> RouteGlobal+OverFocused >> RouteFocused (if in focused window stack) >> RouteGlobal. - // - Default policy is RouteFocused. Can select only 1 policy among all available. - ImGuiInputFlags_RouteActive = 1 << 10, // Route to active item only. - ImGuiInputFlags_RouteFocused = 1 << 11, // Route to windows in the focus stack (DEFAULT). Deep-most focused window takes inputs. Active item takes inputs over deep-most focused window. - ImGuiInputFlags_RouteGlobal = 1 << 12, // Global route (unless a focused window or active item registered the route). - ImGuiInputFlags_RouteAlways = 1 << 13, // Do not register route, poll keys directly. - // - Routing options - ImGuiInputFlags_RouteOverFocused = 1 << 14, // Option: global route: higher priority than focused route (unless active item in focused route). - ImGuiInputFlags_RouteOverActive = 1 << 15, // Option: global route: higher priority than active item. Unlikely you need to use that: will interfere with every active items, e.g. CTRL+A registered by InputText will be overridden by this. May not be fully honored as user/internal code is likely to always assume they can access keys when active. - ImGuiInputFlags_RouteUnlessBgFocused = 1 << 16, // Option: global route: will not be applied if underlying background/void is focused (== no Dear ImGui windows are focused). Useful for overlay applications. - ImGuiInputFlags_RouteFromRootWindow = 1 << 17, // Option: route evaluated from the point of view of root window rather than current window. - - // Flags for SetNextItemShortcut() - ImGuiInputFlags_Tooltip = 1 << 18, // Automatically display a tooltip when hovering item [BETA] Unsure of right api (opt-in/opt-out) -}; - -// Configuration flags stored in io.ConfigFlags. Set by user/application. -enum ImGuiConfigFlags_ -{ - ImGuiConfigFlags_None = 0, - ImGuiConfigFlags_NavEnableKeyboard = 1 << 0, // Master keyboard navigation enable flag. Enable full Tabbing + directional arrows + space/enter to activate. - ImGuiConfigFlags_NavEnableGamepad = 1 << 1, // Master gamepad navigation enable flag. Backend also needs to set ImGuiBackendFlags_HasGamepad. - ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct dear imgui to disable mouse inputs and interactions. - ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct backend to not alter mouse cursor shape and visibility. Use if the backend cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead. - ImGuiConfigFlags_NoKeyboard = 1 << 6, // Instruct dear imgui to disable keyboard inputs and interactions. This is done by ignoring keyboard events and clearing existing states. - - // User storage (to allow your backend/engine to communicate to code that may be shared between multiple projects. Those flags are NOT used by core Dear ImGui) - ImGuiConfigFlags_IsSRGB = 1 << 20, // Application is SRGB-aware. - ImGuiConfigFlags_IsTouchScreen = 1 << 21, // Application is using a touch screen instead of a mouse. - -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiConfigFlags_NavEnableSetMousePos = 1 << 2, // [moved/renamed in 1.91.4] -> use bool io.ConfigNavMoveSetMousePos - ImGuiConfigFlags_NavNoCaptureKeyboard = 1 << 3, // [moved/renamed in 1.91.4] -> use bool io.ConfigNavCaptureKeyboard -#endif -}; - -// Backend capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom backend. -enum ImGuiBackendFlags_ -{ - ImGuiBackendFlags_None = 0, - ImGuiBackendFlags_HasGamepad = 1 << 0, // Backend Platform supports gamepad and currently has one connected. - ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Backend Platform supports honoring GetMouseCursor() value to change the OS cursor shape. - ImGuiBackendFlags_HasSetMousePos = 1 << 2, // Backend Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if io.ConfigNavMoveSetMousePos is set). - ImGuiBackendFlags_RendererHasVtxOffset = 1 << 3, // Backend Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bit indices. - ImGuiBackendFlags_RendererHasTextures = 1 << 4, // Backend Renderer supports ImTextureData requests to create/update/destroy textures. This enables incremental texture updates and texture reloads. See https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md for instructions on how to upgrade your custom backend. -}; - -// Enumeration for PushStyleColor() / PopStyleColor() -enum ImGuiCol_ -{ - ImGuiCol_Text, - ImGuiCol_TextDisabled, - ImGuiCol_WindowBg, // Background of normal windows - ImGuiCol_ChildBg, // Background of child windows - ImGuiCol_PopupBg, // Background of popups, menus, tooltips windows - ImGuiCol_Border, - ImGuiCol_BorderShadow, - ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input - ImGuiCol_FrameBgHovered, - ImGuiCol_FrameBgActive, - ImGuiCol_TitleBg, // Title bar - ImGuiCol_TitleBgActive, // Title bar when focused - ImGuiCol_TitleBgCollapsed, // Title bar when collapsed - ImGuiCol_MenuBarBg, - ImGuiCol_ScrollbarBg, - ImGuiCol_ScrollbarGrab, - ImGuiCol_ScrollbarGrabHovered, - ImGuiCol_ScrollbarGrabActive, - ImGuiCol_CheckMark, // Checkbox tick and RadioButton circle - ImGuiCol_SliderGrab, - ImGuiCol_SliderGrabActive, - ImGuiCol_Button, - ImGuiCol_ButtonHovered, - ImGuiCol_ButtonActive, - ImGuiCol_Header, // Header* colors are used for CollapsingHeader, TreeNode, Selectable, MenuItem - ImGuiCol_HeaderHovered, - ImGuiCol_HeaderActive, - ImGuiCol_Separator, - ImGuiCol_SeparatorHovered, - ImGuiCol_SeparatorActive, - ImGuiCol_ResizeGrip, // Resize grip in lower-right and lower-left corners of windows. - ImGuiCol_ResizeGripHovered, - ImGuiCol_ResizeGripActive, - ImGuiCol_InputTextCursor, // InputText cursor/caret - ImGuiCol_TabHovered, // Tab background, when hovered - ImGuiCol_Tab, // Tab background, when tab-bar is focused & tab is unselected - ImGuiCol_TabSelected, // Tab background, when tab-bar is focused & tab is selected - ImGuiCol_TabSelectedOverline, // Tab horizontal overline, when tab-bar is focused & tab is selected - ImGuiCol_TabDimmed, // Tab background, when tab-bar is unfocused & tab is unselected - ImGuiCol_TabDimmedSelected, // Tab background, when tab-bar is unfocused & tab is selected - ImGuiCol_TabDimmedSelectedOverline,//..horizontal overline, when tab-bar is unfocused & tab is selected - ImGuiCol_PlotLines, - ImGuiCol_PlotLinesHovered, - ImGuiCol_PlotHistogram, - ImGuiCol_PlotHistogramHovered, - ImGuiCol_TableHeaderBg, // Table header background - ImGuiCol_TableBorderStrong, // Table outer and header borders (prefer using Alpha=1.0 here) - ImGuiCol_TableBorderLight, // Table inner borders (prefer using Alpha=1.0 here) - ImGuiCol_TableRowBg, // Table row background (even rows) - ImGuiCol_TableRowBgAlt, // Table row background (odd rows) - ImGuiCol_TextLink, // Hyperlink color - ImGuiCol_TextSelectedBg, // Selected text inside an InputText - ImGuiCol_TreeLines, // Tree node hierarchy outlines when using ImGuiTreeNodeFlags_DrawLines - ImGuiCol_DragDropTarget, // Rectangle highlighting a drop target - ImGuiCol_NavCursor, // Color of keyboard/gamepad navigation cursor/rectangle, when visible - ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB - ImGuiCol_NavWindowingDimBg, // Darken/colorize entire screen behind the CTRL+TAB window list, when active - ImGuiCol_ModalWindowDimBg, // Darken/colorize entire screen behind a modal window, when one is active - ImGuiCol_COUNT, - -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiCol_TabActive = ImGuiCol_TabSelected, // [renamed in 1.90.9] - ImGuiCol_TabUnfocused = ImGuiCol_TabDimmed, // [renamed in 1.90.9] - ImGuiCol_TabUnfocusedActive = ImGuiCol_TabDimmedSelected, // [renamed in 1.90.9] - ImGuiCol_NavHighlight = ImGuiCol_NavCursor, // [renamed in 1.91.4] -#endif -}; - -// Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure. -// - The enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code. -// During initialization or between frames, feel free to just poke into ImGuiStyle directly. -// - Tip: Use your programming IDE navigation facilities on the names in the _second column_ below to find the actual members and their description. -// - In Visual Studio: CTRL+comma ("Edit.GoToAll") can follow symbols inside comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. -// - In Visual Studio w/ Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. -// - In VS Code, CLion, etc.: CTRL+click can follow symbols inside comments. -// - When changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type. -enum ImGuiStyleVar_ -{ - // Enum name -------------------------- // Member in ImGuiStyle structure (see ImGuiStyle for descriptions) - ImGuiStyleVar_Alpha, // float Alpha - ImGuiStyleVar_DisabledAlpha, // float DisabledAlpha - ImGuiStyleVar_WindowPadding, // ImVec2 WindowPadding - ImGuiStyleVar_WindowRounding, // float WindowRounding - ImGuiStyleVar_WindowBorderSize, // float WindowBorderSize - ImGuiStyleVar_WindowMinSize, // ImVec2 WindowMinSize - ImGuiStyleVar_WindowTitleAlign, // ImVec2 WindowTitleAlign - ImGuiStyleVar_ChildRounding, // float ChildRounding - ImGuiStyleVar_ChildBorderSize, // float ChildBorderSize - ImGuiStyleVar_PopupRounding, // float PopupRounding - ImGuiStyleVar_PopupBorderSize, // float PopupBorderSize - ImGuiStyleVar_FramePadding, // ImVec2 FramePadding - ImGuiStyleVar_FrameRounding, // float FrameRounding - ImGuiStyleVar_FrameBorderSize, // float FrameBorderSize - ImGuiStyleVar_ItemSpacing, // ImVec2 ItemSpacing - ImGuiStyleVar_ItemInnerSpacing, // ImVec2 ItemInnerSpacing - ImGuiStyleVar_IndentSpacing, // float IndentSpacing - ImGuiStyleVar_CellPadding, // ImVec2 CellPadding - ImGuiStyleVar_ScrollbarSize, // float ScrollbarSize - ImGuiStyleVar_ScrollbarRounding, // float ScrollbarRounding - ImGuiStyleVar_GrabMinSize, // float GrabMinSize - ImGuiStyleVar_GrabRounding, // float GrabRounding - ImGuiStyleVar_ImageBorderSize, // float ImageBorderSize - ImGuiStyleVar_TabRounding, // float TabRounding - ImGuiStyleVar_TabBorderSize, // float TabBorderSize - ImGuiStyleVar_TabBarBorderSize, // float TabBarBorderSize - ImGuiStyleVar_TabBarOverlineSize, // float TabBarOverlineSize - ImGuiStyleVar_TableAngledHeadersAngle, // float TableAngledHeadersAngle - ImGuiStyleVar_TableAngledHeadersTextAlign,// ImVec2 TableAngledHeadersTextAlign - ImGuiStyleVar_TreeLinesSize, // float TreeLinesSize - ImGuiStyleVar_TreeLinesRounding, // float TreeLinesRounding - ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign - ImGuiStyleVar_SelectableTextAlign, // ImVec2 SelectableTextAlign - ImGuiStyleVar_SeparatorTextBorderSize, // float SeparatorTextBorderSize - ImGuiStyleVar_SeparatorTextAlign, // ImVec2 SeparatorTextAlign - ImGuiStyleVar_SeparatorTextPadding, // ImVec2 SeparatorTextPadding - ImGuiStyleVar_COUNT -}; - -// Flags for InvisibleButton() [extended in imgui_internal.h] -enum ImGuiButtonFlags_ -{ - ImGuiButtonFlags_None = 0, - ImGuiButtonFlags_MouseButtonLeft = 1 << 0, // React on left mouse button (default) - ImGuiButtonFlags_MouseButtonRight = 1 << 1, // React on right mouse button - ImGuiButtonFlags_MouseButtonMiddle = 1 << 2, // React on center mouse button - ImGuiButtonFlags_MouseButtonMask_ = ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight | ImGuiButtonFlags_MouseButtonMiddle, // [Internal] - ImGuiButtonFlags_EnableNav = 1 << 3, // InvisibleButton(): do not disable navigation/tabbing. Otherwise disabled by default. -}; - -// Flags for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton() -enum ImGuiColorEditFlags_ -{ - ImGuiColorEditFlags_None = 0, - ImGuiColorEditFlags_NoAlpha = 1 << 1, // // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (will only read 3 components from the input pointer). - ImGuiColorEditFlags_NoPicker = 1 << 2, // // ColorEdit: disable picker when clicking on color square. - ImGuiColorEditFlags_NoOptions = 1 << 3, // // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview. - ImGuiColorEditFlags_NoSmallPreview = 1 << 4, // // ColorEdit, ColorPicker: disable color square preview next to the inputs. (e.g. to show only the inputs) - ImGuiColorEditFlags_NoInputs = 1 << 5, // // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview color square). - ImGuiColorEditFlags_NoTooltip = 1 << 6, // // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview. - ImGuiColorEditFlags_NoLabel = 1 << 7, // // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker). - ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead. - ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source. - ImGuiColorEditFlags_NoBorder = 1 << 10, // // ColorButton: disable border (which is enforced by default) - - // Alpha preview - // - Prior to 1.91.8 (2025/01/21): alpha was made opaque in the preview by default using old name ImGuiColorEditFlags_AlphaPreview. - // - We now display the preview as transparent by default. You can use ImGuiColorEditFlags_AlphaOpaque to use old behavior. - // - The new flags may be combined better and allow finer controls. - ImGuiColorEditFlags_AlphaOpaque = 1 << 11, // // ColorEdit, ColorPicker, ColorButton: disable alpha in the preview,. Contrary to _NoAlpha it may still be edited when calling ColorEdit4()/ColorPicker4(). For ColorButton() this does the same as _NoAlpha. - ImGuiColorEditFlags_AlphaNoBg = 1 << 12, // // ColorEdit, ColorPicker, ColorButton: disable rendering a checkerboard background behind transparent color. - ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 13, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half transparent preview. - - // User Options (right-click on widget to change some of them). - ImGuiColorEditFlags_AlphaBar = 1 << 16, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. - ImGuiColorEditFlags_HDR = 1 << 19, // // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use ImGuiColorEditFlags_Float flag as well). - ImGuiColorEditFlags_DisplayRGB = 1 << 20, // [Display] // ColorEdit: override _display_ type among RGB/HSV/Hex. ColorPicker: select any combination using one or more of RGB/HSV/Hex. - ImGuiColorEditFlags_DisplayHSV = 1 << 21, // [Display] // " - ImGuiColorEditFlags_DisplayHex = 1 << 22, // [Display] // " - ImGuiColorEditFlags_Uint8 = 1 << 23, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255. - ImGuiColorEditFlags_Float = 1 << 24, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers. - ImGuiColorEditFlags_PickerHueBar = 1 << 25, // [Picker] // ColorPicker: bar for Hue, rectangle for Sat/Value. - ImGuiColorEditFlags_PickerHueWheel = 1 << 26, // [Picker] // ColorPicker: wheel for Hue, triangle for Sat/Value. - ImGuiColorEditFlags_InputRGB = 1 << 27, // [Input] // ColorEdit, ColorPicker: input and output data in RGB format. - ImGuiColorEditFlags_InputHSV = 1 << 28, // [Input] // ColorEdit, ColorPicker: input and output data in HSV format. - - // Defaults Options. You can set application defaults using SetColorEditOptions(). The intent is that you probably don't want to - // override them in most of your calls. Let the user choose via the option menu and/or call SetColorEditOptions() once during startup. - ImGuiColorEditFlags_DefaultOptions_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_PickerHueBar, - - // [Internal] Masks - ImGuiColorEditFlags_AlphaMask_ = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaOpaque | ImGuiColorEditFlags_AlphaNoBg | ImGuiColorEditFlags_AlphaPreviewHalf, - ImGuiColorEditFlags_DisplayMask_ = ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_DisplayHex, - ImGuiColorEditFlags_DataTypeMask_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_Float, - ImGuiColorEditFlags_PickerMask_ = ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_PickerHueBar, - ImGuiColorEditFlags_InputMask_ = ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_InputHSV, - - // Obsolete names -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiColorEditFlags_AlphaPreview = 0, // [Removed in 1.91.8] This is the default now. Will display a checkerboard unless ImGuiColorEditFlags_AlphaNoBg is set. -#endif - //ImGuiColorEditFlags_RGB = ImGuiColorEditFlags_DisplayRGB, ImGuiColorEditFlags_HSV = ImGuiColorEditFlags_DisplayHSV, ImGuiColorEditFlags_HEX = ImGuiColorEditFlags_DisplayHex // [renamed in 1.69] -}; - -// Flags for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. -// We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. -// (Those are per-item flags. There is shared behavior flag too: ImGuiIO: io.ConfigDragClickToInputText) -enum ImGuiSliderFlags_ -{ - ImGuiSliderFlags_None = 0, - ImGuiSliderFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits. - ImGuiSliderFlags_NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits). - ImGuiSliderFlags_NoInput = 1 << 7, // Disable CTRL+Click or Enter key allowing to input text directly into the widget. - ImGuiSliderFlags_WrapAround = 1 << 8, // Enable wrapping around from max to min and from min to max. Only supported by DragXXX() functions for now. - ImGuiSliderFlags_ClampOnInput = 1 << 9, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. - ImGuiSliderFlags_ClampZeroRange = 1 << 10, // Clamp even if min==max==0.0f. Otherwise due to legacy reason DragXXX functions don't clamp with those values. When your clamping limits are dynamic you almost always want to use it. - ImGuiSliderFlags_NoSpeedTweaks = 1 << 11, // Disable keyboard modifiers altering tweak speed. Useful if you want to alter tweak speed yourself based on your own logic. - ImGuiSliderFlags_AlwaysClamp = ImGuiSliderFlags_ClampOnInput | ImGuiSliderFlags_ClampZeroRange, - ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. -}; - -// Identify a mouse button. -// Those values are guaranteed to be stable and we frequently use 0/1 directly. Named enums provided for convenience. -enum ImGuiMouseButton_ -{ - ImGuiMouseButton_Left = 0, - ImGuiMouseButton_Right = 1, - ImGuiMouseButton_Middle = 2, - ImGuiMouseButton_COUNT = 5 -}; - -// Enumeration for GetMouseCursor() -// User code may request backend to display given cursor by calling SetMouseCursor(), which is why we have some cursors that are marked unused here -enum ImGuiMouseCursor_ -{ - ImGuiMouseCursor_None = -1, - ImGuiMouseCursor_Arrow = 0, - ImGuiMouseCursor_TextInput, // When hovering over InputText, etc. - ImGuiMouseCursor_ResizeAll, // (Unused by Dear ImGui functions) - ImGuiMouseCursor_ResizeNS, // When hovering over a horizontal border - ImGuiMouseCursor_ResizeEW, // When hovering over a vertical border or a column - ImGuiMouseCursor_ResizeNESW, // When hovering over the bottom-left corner of a window - ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window - ImGuiMouseCursor_Hand, // (Unused by Dear ImGui functions. Use for e.g. hyperlinks) - ImGuiMouseCursor_Wait, // When waiting for something to process/load. - ImGuiMouseCursor_Progress, // When waiting for something to process/load, but application is still interactive. - ImGuiMouseCursor_NotAllowed, // When hovering something with disallowed interaction. Usually a crossed circle. - ImGuiMouseCursor_COUNT -}; - -// Enumeration for AddMouseSourceEvent() actual source of Mouse Input data. -// Historically we use "Mouse" terminology everywhere to indicate pointer data, e.g. MousePos, IsMousePressed(), io.AddMousePosEvent() -// But that "Mouse" data can come from different source which occasionally may be useful for application to know about. -// You can submit a change of pointer type using io.AddMouseSourceEvent(). -enum ImGuiMouseSource : int -{ - ImGuiMouseSource_Mouse = 0, // Input is coming from an actual mouse. - ImGuiMouseSource_TouchScreen, // Input is coming from a touch screen (no hovering prior to initial press, less precise initial press aiming, dual-axis wheeling possible). - ImGuiMouseSource_Pen, // Input is coming from a pressure/magnetic pen (often used in conjunction with high-sampling rates). - ImGuiMouseSource_COUNT -}; - -// Enumeration for ImGui::SetNextWindow***(), SetWindow***(), SetNextItem***() functions -// Represent a condition. -// Important: Treat as a regular enum! Do NOT combine multiple values using binary operators! All the functions above treat 0 as a shortcut to ImGuiCond_Always. -enum ImGuiCond_ -{ - ImGuiCond_None = 0, // No condition (always set the variable), same as _Always - ImGuiCond_Always = 1 << 0, // No condition (always set the variable), same as _None - ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call will succeed) - ImGuiCond_FirstUseEver = 1 << 2, // Set the variable if the object/window has no persistently saved data (no entry in .ini file) - ImGuiCond_Appearing = 1 << 3, // Set the variable if the object/window is appearing after being hidden/inactive (or the first time) -}; - -//----------------------------------------------------------------------------- -// [SECTION] Tables API flags and structures (ImGuiTableFlags, ImGuiTableColumnFlags, ImGuiTableRowFlags, ImGuiTableBgTarget, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) -//----------------------------------------------------------------------------- - -// Flags for ImGui::BeginTable() -// - Important! Sizing policies have complex and subtle side effects, much more so than you would expect. -// Read comments/demos carefully + experiment with live demos to get acquainted with them. -// - The DEFAULT sizing policies are: -// - Default to ImGuiTableFlags_SizingFixedFit if ScrollX is on, or if host window has ImGuiWindowFlags_AlwaysAutoResize. -// - Default to ImGuiTableFlags_SizingStretchSame if ScrollX is off. -// - When ScrollX is off: -// - Table defaults to ImGuiTableFlags_SizingStretchSame -> all Columns defaults to ImGuiTableColumnFlags_WidthStretch with same weight. -// - Columns sizing policy allowed: Stretch (default), Fixed/Auto. -// - Fixed Columns (if any) will generally obtain their requested width (unless the table cannot fit them all). -// - Stretch Columns will share the remaining width according to their respective weight. -// - Mixed Fixed/Stretch columns is possible but has various side-effects on resizing behaviors. -// The typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns. -// (this is because the visible order of columns have subtle but necessary effects on how they react to manual resizing). -// - When ScrollX is on: -// - Table defaults to ImGuiTableFlags_SizingFixedFit -> all Columns defaults to ImGuiTableColumnFlags_WidthFixed -// - Columns sizing policy allowed: Fixed/Auto mostly. -// - Fixed Columns can be enlarged as needed. Table will show a horizontal scrollbar if needed. -// - When using auto-resizing (non-resizable) fixed columns, querying the content width to use item right-alignment e.g. SetNextItemWidth(-FLT_MIN) doesn't make sense, would create a feedback loop. -// - Using Stretch columns OFTEN DOES NOT MAKE SENSE if ScrollX is on, UNLESS you have specified a value for 'inner_width' in BeginTable(). -// If you specify a value for 'inner_width' then effectively the scrolling space is known and Stretch or mixed Fixed/Stretch columns become meaningful again. -// - Read on documentation at the top of imgui_tables.cpp for details. -enum ImGuiTableFlags_ -{ - // Features - ImGuiTableFlags_None = 0, - ImGuiTableFlags_Resizable = 1 << 0, // Enable resizing columns. - ImGuiTableFlags_Reorderable = 1 << 1, // Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers) - ImGuiTableFlags_Hideable = 1 << 2, // Enable hiding/disabling columns in context menu. - ImGuiTableFlags_Sortable = 1 << 3, // Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate. - ImGuiTableFlags_NoSavedSettings = 1 << 4, // Disable persisting columns order, width and sort settings in the .ini file. - ImGuiTableFlags_ContextMenuInBody = 1 << 5, // Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow(). - // Decorations - ImGuiTableFlags_RowBg = 1 << 6, // Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually) - ImGuiTableFlags_BordersInnerH = 1 << 7, // Draw horizontal borders between rows. - ImGuiTableFlags_BordersOuterH = 1 << 8, // Draw horizontal borders at the top and bottom. - ImGuiTableFlags_BordersInnerV = 1 << 9, // Draw vertical borders between columns. - ImGuiTableFlags_BordersOuterV = 1 << 10, // Draw vertical borders on the left and right sides. - ImGuiTableFlags_BordersH = ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_BordersOuterH, // Draw horizontal borders. - ImGuiTableFlags_BordersV = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersOuterV, // Draw vertical borders. - ImGuiTableFlags_BordersInner = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersInnerH, // Draw inner borders. - ImGuiTableFlags_BordersOuter = ImGuiTableFlags_BordersOuterV | ImGuiTableFlags_BordersOuterH, // Draw outer borders. - ImGuiTableFlags_Borders = ImGuiTableFlags_BordersInner | ImGuiTableFlags_BordersOuter, // Draw all borders. - ImGuiTableFlags_NoBordersInBody = 1 << 11, // [ALPHA] Disable vertical borders in columns Body (borders will always appear in Headers). -> May move to style - ImGuiTableFlags_NoBordersInBodyUntilResize = 1 << 12, // [ALPHA] Disable vertical borders in columns Body until hovered for resize (borders will always appear in Headers). -> May move to style - // Sizing Policy (read above for defaults) - ImGuiTableFlags_SizingFixedFit = 1 << 13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching contents width. - ImGuiTableFlags_SizingFixedSame = 2 << 13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching the maximum contents width of all columns. Implicitly enable ImGuiTableFlags_NoKeepColumnsVisible. - ImGuiTableFlags_SizingStretchProp = 3 << 13, // Columns default to _WidthStretch with default weights proportional to each columns contents widths. - ImGuiTableFlags_SizingStretchSame = 4 << 13, // Columns default to _WidthStretch with default weights all equal, unless overridden by TableSetupColumn(). - // Sizing Extra Options - ImGuiTableFlags_NoHostExtendX = 1 << 16, // Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. - ImGuiTableFlags_NoHostExtendY = 1 << 17, // Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible. - ImGuiTableFlags_NoKeepColumnsVisible = 1 << 18, // Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable. - ImGuiTableFlags_PreciseWidths = 1 << 19, // Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth. - // Clipping - ImGuiTableFlags_NoClip = 1 << 20, // Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with TableSetupScrollFreeze(). - // Padding - ImGuiTableFlags_PadOuterX = 1 << 21, // Default if BordersOuterV is on. Enable outermost padding. Generally desirable if you have headers. - ImGuiTableFlags_NoPadOuterX = 1 << 22, // Default if BordersOuterV is off. Disable outermost padding. - ImGuiTableFlags_NoPadInnerX = 1 << 23, // Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off). - // Scrolling - ImGuiTableFlags_ScrollX = 1 << 24, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this creates a child window, ScrollY is currently generally recommended when using ScrollX. - ImGuiTableFlags_ScrollY = 1 << 25, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. - // Sorting - ImGuiTableFlags_SortMulti = 1 << 26, // Hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1). - ImGuiTableFlags_SortTristate = 1 << 27, // Allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0). - // Miscellaneous - ImGuiTableFlags_HighlightHoveredColumn = 1 << 28, // Highlight column headers when hovered (may evolve into a fuller highlight) - - // [Internal] Combinations and masks - ImGuiTableFlags_SizingMask_ = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_SizingFixedSame | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_SizingStretchSame, -}; - -// Flags for ImGui::TableSetupColumn() -enum ImGuiTableColumnFlags_ -{ - // Input configuration flags - ImGuiTableColumnFlags_None = 0, - ImGuiTableColumnFlags_Disabled = 1 << 0, // Overriding/master disable flag: hide column, won't show in context menu (unlike calling TableSetColumnEnabled() which manipulates the user accessible state) - ImGuiTableColumnFlags_DefaultHide = 1 << 1, // Default as a hidden/disabled column. - ImGuiTableColumnFlags_DefaultSort = 1 << 2, // Default as a sorting column. - ImGuiTableColumnFlags_WidthStretch = 1 << 3, // Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp). - ImGuiTableColumnFlags_WidthFixed = 1 << 4, // Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable). - ImGuiTableColumnFlags_NoResize = 1 << 5, // Disable manual resizing. - ImGuiTableColumnFlags_NoReorder = 1 << 6, // Disable manual reordering this column, this will also prevent other columns from crossing over this column. - ImGuiTableColumnFlags_NoHide = 1 << 7, // Disable ability to hide/disable this column. - ImGuiTableColumnFlags_NoClip = 1 << 8, // Disable clipping for this column (all NoClip columns will render in a same draw command). - ImGuiTableColumnFlags_NoSort = 1 << 9, // Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table). - ImGuiTableColumnFlags_NoSortAscending = 1 << 10, // Disable ability to sort in the ascending direction. - ImGuiTableColumnFlags_NoSortDescending = 1 << 11, // Disable ability to sort in the descending direction. - ImGuiTableColumnFlags_NoHeaderLabel = 1 << 12, // TableHeadersRow() will submit an empty label for this column. Convenient for some small columns. Name will still appear in context menu or in angled headers. You may append into this cell by calling TableSetColumnIndex() right after the TableHeadersRow() call. - ImGuiTableColumnFlags_NoHeaderWidth = 1 << 13, // Disable header text width contribution to automatic column width. - ImGuiTableColumnFlags_PreferSortAscending = 1 << 14, // Make the initial sort direction Ascending when first sorting on this column (default). - ImGuiTableColumnFlags_PreferSortDescending = 1 << 15, // Make the initial sort direction Descending when first sorting on this column. - ImGuiTableColumnFlags_IndentEnable = 1 << 16, // Use current Indent value when entering cell (default for column 0). - ImGuiTableColumnFlags_IndentDisable = 1 << 17, // Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored. - ImGuiTableColumnFlags_AngledHeader = 1 << 18, // TableHeadersRow() will submit an angled header row for this column. Note this will add an extra row. - - // Output status flags, read-only via TableGetColumnFlags() - ImGuiTableColumnFlags_IsEnabled = 1 << 24, // Status: is enabled == not hidden by user/api (referred to as "Hide" in _DefaultHide and _NoHide) flags. - ImGuiTableColumnFlags_IsVisible = 1 << 25, // Status: is visible == is enabled AND not clipped by scrolling. - ImGuiTableColumnFlags_IsSorted = 1 << 26, // Status: is currently part of the sort specs - ImGuiTableColumnFlags_IsHovered = 1 << 27, // Status: is hovered by mouse - - // [Internal] Combinations and masks - ImGuiTableColumnFlags_WidthMask_ = ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_WidthFixed, - ImGuiTableColumnFlags_IndentMask_ = ImGuiTableColumnFlags_IndentEnable | ImGuiTableColumnFlags_IndentDisable, - ImGuiTableColumnFlags_StatusMask_ = ImGuiTableColumnFlags_IsEnabled | ImGuiTableColumnFlags_IsVisible | ImGuiTableColumnFlags_IsSorted | ImGuiTableColumnFlags_IsHovered, - ImGuiTableColumnFlags_NoDirectResize_ = 1 << 30, // [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge) -}; - -// Flags for ImGui::TableNextRow() -enum ImGuiTableRowFlags_ -{ - ImGuiTableRowFlags_None = 0, - ImGuiTableRowFlags_Headers = 1 << 0, // Identify header row (set default background color + width of its contents accounted differently for auto column width) -}; - -// Enum for ImGui::TableSetBgColor() -// Background colors are rendering in 3 layers: -// - Layer 0: draw with RowBg0 color if set, otherwise draw with ColumnBg0 if set. -// - Layer 1: draw with RowBg1 color if set, otherwise draw with ColumnBg1 if set. -// - Layer 2: draw with CellBg color if set. -// The purpose of the two row/columns layers is to let you decide if a background color change should override or blend with the existing color. -// When using ImGuiTableFlags_RowBg on the table, each row has the RowBg0 color automatically set for odd/even rows. -// If you set the color of RowBg0 target, your color will override the existing RowBg0 color. -// If you set the color of RowBg1 or ColumnBg1 target, your color will blend over the RowBg0 color. -enum ImGuiTableBgTarget_ -{ - ImGuiTableBgTarget_None = 0, - ImGuiTableBgTarget_RowBg0 = 1, // Set row background color 0 (generally used for background, automatically set when ImGuiTableFlags_RowBg is used) - ImGuiTableBgTarget_RowBg1 = 2, // Set row background color 1 (generally used for selection marking) - ImGuiTableBgTarget_CellBg = 3, // Set cell background color (top-most color) -}; - -// Sorting specifications for a table (often handling sort specs for a single column, occasionally more) -// Obtained by calling TableGetSortSpecs(). -// When 'SpecsDirty == true' you can sort your data. It will be true with sorting specs have changed since last call, or the first time. -// Make sure to set 'SpecsDirty = false' after sorting, else you may wastefully sort your data every frame! -struct ImGuiTableSortSpecs -{ - const ImGuiTableColumnSortSpecs* Specs; // Pointer to sort spec array. - int SpecsCount; // Sort spec count. Most often 1. May be > 1 when ImGuiTableFlags_SortMulti is enabled. May be == 0 when ImGuiTableFlags_SortTristate is enabled. - bool SpecsDirty; // Set to true when specs have changed since last time! Use this to sort again, then clear the flag. - - ImGuiTableSortSpecs() { memset(this, 0, sizeof(*this)); } -}; - -// Sorting specification for one column of a table (sizeof == 12 bytes) -struct ImGuiTableColumnSortSpecs -{ - ImGuiID ColumnUserID; // User id of the column (if specified by a TableSetupColumn() call) - ImS16 ColumnIndex; // Index of the column - ImS16 SortOrder; // Index within parent ImGuiTableSortSpecs (always stored in order starting from 0, tables sorted on a single criteria will always have a 0 here) - ImGuiSortDirection SortDirection; // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending - - ImGuiTableColumnSortSpecs() { memset(this, 0, sizeof(*this)); } -}; - -//----------------------------------------------------------------------------- -// [SECTION] Helpers: Debug log, memory allocations macros, ImVector<> -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -// Debug Logging into ShowDebugLogWindow(), tty and more. -//----------------------------------------------------------------------------- - -#ifndef IMGUI_DISABLE_DEBUG_TOOLS -#define IMGUI_DEBUG_LOG(...) ImGui::DebugLog(__VA_ARGS__) -#else -#define IMGUI_DEBUG_LOG(...) ((void)0) -#endif - -//----------------------------------------------------------------------------- -// IM_MALLOC(), IM_FREE(), IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE() -// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax. -// Defining a custom placement new() with a custom parameter allows us to bypass including which on some platforms complains when user has disabled exceptions. -//----------------------------------------------------------------------------- - -struct ImNewWrapper {}; -inline void* operator new(size_t, ImNewWrapper, void* ptr) { return ptr; } -inline void operator delete(void*, ImNewWrapper, void*) {} // This is only required so we can use the symmetrical new() -#define IM_ALLOC(_SIZE) ImGui::MemAlloc(_SIZE) -#define IM_FREE(_PTR) ImGui::MemFree(_PTR) -#define IM_PLACEMENT_NEW(_PTR) new(ImNewWrapper(), _PTR) -#define IM_NEW(_TYPE) new(ImNewWrapper(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE -template void IM_DELETE(T* p) { if (p) { p->~T(); ImGui::MemFree(p); } } - -//----------------------------------------------------------------------------- -// ImVector<> -// Lightweight std::vector<>-like class to avoid dragging dependencies (also, some implementations of STL with debug enabled are absurdly slow, we bypass it so our code runs fast in debug). -//----------------------------------------------------------------------------- -// - You generally do NOT need to care or use this ever. But we need to make it available in imgui.h because some of our public structures are relying on it. -// - We use std-like naming convention here, which is a little unusual for this codebase. -// - Important: clear() frees memory, resize(0) keep the allocated buffer. We use resize(0) a lot to intentionally recycle allocated buffers across frames and amortize our costs. -// - Important: our implementation does NOT call C++ constructors/destructors, we treat everything as raw data! This is intentional but be extra mindful of that, -// Do NOT use this class as a std::vector replacement in your own code! Many of the structures used by dear imgui can be safely initialized by a zero-memset. -//----------------------------------------------------------------------------- - -IM_MSVC_RUNTIME_CHECKS_OFF -template -struct ImVector -{ - int Size; - int Capacity; - T* Data; - - // Provide standard typedefs but we don't use them ourselves. - typedef T value_type; - typedef value_type* iterator; - typedef const value_type* const_iterator; - - // Constructors, destructor - inline ImVector() { Size = Capacity = 0; Data = NULL; } - inline ImVector(const ImVector& src) { Size = Capacity = 0; Data = NULL; operator=(src); } - inline ImVector& operator=(const ImVector& src) { clear(); resize(src.Size); if (src.Data) memcpy(Data, src.Data, (size_t)Size * sizeof(T)); return *this; } - inline ~ImVector() { if (Data) IM_FREE(Data); } // Important: does not destruct anything - - inline void clear() { if (Data) { Size = Capacity = 0; IM_FREE(Data); Data = NULL; } } // Important: does not destruct anything - inline void clear_delete() { for (int n = 0; n < Size; n++) IM_DELETE(Data[n]); clear(); } // Important: never called automatically! always explicit. - inline void clear_destruct() { for (int n = 0; n < Size; n++) Data[n].~T(); clear(); } // Important: never called automatically! always explicit. - - inline bool empty() const { return Size == 0; } - inline int size() const { return Size; } - inline int size_in_bytes() const { return Size * (int)sizeof(T); } - inline int max_size() const { return 0x7FFFFFFF / (int)sizeof(T); } - inline int capacity() const { return Capacity; } - inline T& operator[](int i) { IM_ASSERT(i >= 0 && i < Size); return Data[i]; } - inline const T& operator[](int i) const { IM_ASSERT(i >= 0 && i < Size); return Data[i]; } - - inline T* begin() { return Data; } - inline const T* begin() const { return Data; } - inline T* end() { return Data + Size; } - inline const T* end() const { return Data + Size; } - inline T& front() { IM_ASSERT(Size > 0); return Data[0]; } - inline const T& front() const { IM_ASSERT(Size > 0); return Data[0]; } - inline T& back() { IM_ASSERT(Size > 0); return Data[Size - 1]; } - inline const T& back() const { IM_ASSERT(Size > 0); return Data[Size - 1]; } - inline void swap(ImVector& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; T* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; } - - inline int _grow_capacity(int sz) const { int new_capacity = Capacity ? (Capacity + Capacity / 2) : 8; return new_capacity > sz ? new_capacity : sz; } - inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; } - inline void resize(int new_size, const T& v) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) memcpy(&Data[n], &v, sizeof(v)); Size = new_size; } - inline void shrink(int new_size) { IM_ASSERT(new_size <= Size); Size = new_size; } // Resize a vector to a smaller size, guaranteed not to cause a reallocation - inline void reserve(int new_capacity) { if (new_capacity <= Capacity) return; T* new_data = (T*)IM_ALLOC((size_t)new_capacity * sizeof(T)); if (Data) { memcpy(new_data, Data, (size_t)Size * sizeof(T)); IM_FREE(Data); } Data = new_data; Capacity = new_capacity; } - inline void reserve_discard(int new_capacity) { if (new_capacity <= Capacity) return; if (Data) IM_FREE(Data); Data = (T*)IM_ALLOC((size_t)new_capacity * sizeof(T)); Capacity = new_capacity; } - - // NB: It is illegal to call push_back/push_front/insert with a reference pointing inside the ImVector data itself! e.g. v.push_back(v[10]) is forbidden. - inline void push_back(const T& v) { if (Size == Capacity) reserve(_grow_capacity(Size + 1)); memcpy(&Data[Size], &v, sizeof(v)); Size++; } - inline void pop_back() { IM_ASSERT(Size > 0); Size--; } - inline void push_front(const T& v) { if (Size == 0) push_back(v); else insert(Data, v); } - inline T* erase(const T* it) { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(T)); Size--; return Data + off; } - inline T* erase(const T* it, const T* it_last){ IM_ASSERT(it >= Data && it < Data + Size && it_last >= it && it_last <= Data + Size); const ptrdiff_t count = it_last - it; const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + count, ((size_t)Size - (size_t)off - (size_t)count) * sizeof(T)); Size -= (int)count; return Data + off; } - inline T* erase_unsorted(const T* it) { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; if (it < Data + Size - 1) memcpy(Data + off, Data + Size - 1, sizeof(T)); Size--; return Data + off; } - inline T* insert(const T* it, const T& v) { IM_ASSERT(it >= Data && it <= Data + Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(_grow_capacity(Size + 1)); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(T)); memcpy(&Data[off], &v, sizeof(v)); Size++; return Data + off; } - inline bool contains(const T& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data++ == v) return true; return false; } - inline T* find(const T& v) { T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; } - inline const T* find(const T& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; } - inline int find_index(const T& v) const { const T* data_end = Data + Size; const T* it = find(v); if (it == data_end) return -1; const ptrdiff_t off = it - Data; return (int)off; } - inline bool find_erase(const T& v) { const T* it = find(v); if (it < Data + Size) { erase(it); return true; } return false; } - inline bool find_erase_unsorted(const T& v) { const T* it = find(v); if (it < Data + Size) { erase_unsorted(it); return true; } return false; } - inline int index_from_ptr(const T* it) const { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; return (int)off; } -}; -IM_MSVC_RUNTIME_CHECKS_RESTORE - -//----------------------------------------------------------------------------- -// [SECTION] ImGuiStyle -//----------------------------------------------------------------------------- -// You may modify the ImGui::GetStyle() main instance during initialization and before NewFrame(). -// During the frame, use ImGui::PushStyleVar(ImGuiStyleVar_XXXX)/PopStyleVar() to alter the main style values, -// and ImGui::PushStyleColor(ImGuiCol_XXX)/PopStyleColor() for colors. -//----------------------------------------------------------------------------- - -struct ImGuiStyle -{ - // Font scaling - // - recap: ImGui::GetFontSize() == FontSizeBase * (FontScaleMain * FontScaleDpi * other_scaling_factors) - float FontSizeBase; // Current base font size before external global factors are applied. Use PushFont(NULL, size) to modify. Use ImGui::GetFontSize() to obtain scaled value. - float FontScaleMain; // Main global scale factor. May be set by application once, or exposed to end-user. - float FontScaleDpi; // Additional global scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI. - - float Alpha; // Global alpha applies to everything in Dear ImGui. - float DisabledAlpha; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. - ImVec2 WindowPadding; // Padding within a window. - float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended. - float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). - float WindowBorderHoverPadding; // Hit-testing extent outside/inside resizing border. Also extend determination of hovered window. Generally meaningfully larger than WindowBorderSize to make it easy to reach borders. - ImVec2 WindowMinSize; // Minimum window size. This is a global setting. If you want to constrain individual windows, use SetNextWindowSizeConstraints(). - ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered. - ImGuiDir WindowMenuButtonPosition; // Side of the collapsing/docking button in the title bar (None/Left/Right). Defaults to ImGuiDir_Left. - float ChildRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows. - float ChildBorderSize; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). - float PopupRounding; // Radius of popup window corners rounding. (Note that tooltip windows use WindowRounding) - float PopupBorderSize; // Thickness of border around popup/tooltip windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). - ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets). - float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets). - float FrameBorderSize; // Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). - ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines. - ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label). - ImVec2 CellPadding; // Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows. - ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! - float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). - float ColumnsMinSpacing; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). - float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar. - float ScrollbarRounding; // Radius of grab corners for scrollbar. - float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar. - float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. - float LogSliderDeadzone; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. - float ImageBorderSize; // Thickness of border around Image() calls. - float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. - float TabBorderSize; // Thickness of border around tabs. - float TabCloseButtonMinWidthSelected; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. - float TabCloseButtonMinWidthUnselected; // -1: always visible. 0.0f: visible when hovered. >0.0f: visible when hovered if minimum width. FLT_MAX: never show close button when unselected. - float TabBarBorderSize; // Thickness of tab-bar separator, which takes on the tab active color to denote focus. - float TabBarOverlineSize; // Thickness of tab-bar overline, which highlights the selected tab-bar. - float TableAngledHeadersAngle; // Angle of angled headers (supported values range from -50.0f degrees to +50.0f degrees). - ImVec2 TableAngledHeadersTextAlign;// Alignment of angled headers within the cell - ImGuiTreeNodeFlags TreeLinesFlags; // Default way to draw lines connecting TreeNode hierarchy. ImGuiTreeNodeFlags_DrawLinesNone or ImGuiTreeNodeFlags_DrawLinesFull or ImGuiTreeNodeFlags_DrawLinesToNodes. - float TreeLinesSize; // Thickness of outlines when using ImGuiTreeNodeFlags_DrawLines. - float TreeLinesRounding; // Radius of lines connecting child nodes to the vertical line. - ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. - ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered). - ImVec2 SelectableTextAlign; // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. - float SeparatorTextBorderSize; // Thickness of border in SeparatorText() - ImVec2 SeparatorTextAlign; // Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center). - ImVec2 SeparatorTextPadding; // Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y. - ImVec2 DisplayWindowPadding; // Apply to regular windows: amount which we enforce to keep visible when moving near edges of your screen. - ImVec2 DisplaySafeAreaPadding; // Apply to every windows, menus, popups, tooltips: amount where we avoid displaying contents. Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured). - float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). We apply per-monitor DPI scaling over this scale. May be removed later. - bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). - bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). Latched at the beginning of the frame (copied to ImDrawList). - bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). - float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. - float CircleTessellationMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. - - // Colors - ImVec4 Colors[ImGuiCol_COUNT]; - - // Behaviors - // (It is possible to modify those fields mid-frame if specific behavior need it, unlike e.g. configuration fields in ImGuiIO) - float HoverStationaryDelay; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary. - float HoverDelayShort; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay. - float HoverDelayNormal; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). " - ImGuiHoveredFlags HoverFlagsForTooltipMouse;// Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse. - ImGuiHoveredFlags HoverFlagsForTooltipNav; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad. - - // [Internal] - float _MainScale; // FIXME-WIP: Reference scale, as applied by ScaleAllSizes(). - float _NextFrameFontSizeBase; // FIXME: Temporary hack until we finish remaining work. - - // Functions - IMGUI_API ImGuiStyle(); - IMGUI_API void ScaleAllSizes(float scale_factor); // Scale all spacing/padding/thickness values. Do not scale fonts. - - // Obsolete names -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - // TabMinWidthForCloseButton = TabCloseButtonMinWidthUnselected // Renamed in 1.91.9. -#endif -}; - -//----------------------------------------------------------------------------- -// [SECTION] ImGuiIO -//----------------------------------------------------------------------------- -// Communicate most settings and inputs/outputs to Dear ImGui using this structure. -// Access via ImGui::GetIO(). Read 'Programmer guide' section in .cpp file for general usage. -// It is generally expected that: -// - initialization: backends and user code writes to ImGuiIO. -// - main loop: backends writes to ImGuiIO, user code and imgui code reads from ImGuiIO. -//----------------------------------------------------------------------------- -// Also see ImGui::GetPlatformIO() and ImGuiPlatformIO struct for OS/platform related functions: clipboard, IME etc. -//----------------------------------------------------------------------------- - -// [Internal] Storage used by IsKeyDown(), IsKeyPressed() etc functions. -// If prior to 1.87 you used io.KeysDownDuration[] (which was marked as internal), you should use GetKeyData(key)->DownDuration and *NOT* io.KeysData[key]->DownDuration. -struct ImGuiKeyData -{ - bool Down; // True for if key is down - float DownDuration; // Duration the key has been down (<0.0f: not pressed, 0.0f: just pressed, >0.0f: time held) - float DownDurationPrev; // Last frame duration the key has been down - float AnalogValue; // 0.0f..1.0f for gamepad values -}; - -struct ImGuiIO -{ - //------------------------------------------------------------------ - // Configuration // Default value - //------------------------------------------------------------------ - - ImGuiConfigFlags ConfigFlags; // = 0 // See ImGuiConfigFlags_ enum. Set by user/application. Keyboard/Gamepad navigation options, etc. - ImGuiBackendFlags BackendFlags; // = 0 // See ImGuiBackendFlags_ enum. Set by backend (imgui_impl_xxx files or custom backend) to communicate features supported by the backend. - ImVec2 DisplaySize; // // Main display size, in pixels (== GetMainViewport()->Size). May change every frame. - ImVec2 DisplayFramebufferScale; // = (1, 1) // Main display density. For retina display where window coordinates are different from framebuffer coordinates. This will affect font density + will end up in ImDrawData::FramebufferScale. - float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. May change every frame. - float IniSavingRate; // = 5.0f // Minimum time between saving positions/sizes to .ini file, in seconds. - const char* IniFilename; // = "imgui.ini" // Path to .ini file (important: default "imgui.ini" is relative to current working dir!). Set NULL to disable automatic .ini loading/saving or if you want to manually call LoadIniSettingsXXX() / SaveIniSettingsXXX() functions. - const char* LogFilename; // = "imgui_log.txt"// Path to .log file (default parameter to ImGui::LogToFile when no file is specified). - void* UserData; // = NULL // Store your own data. - - // Font system - ImFontAtlas*Fonts; // // Font atlas: load, rasterize and pack one or more fonts into a single texture. - ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. - bool FontAllowUserScaling; // = false // [OBSOLETE] Allow user scaling text of individual window with CTRL+Wheel. - - // Keyboard/Gamepad Navigation options - bool ConfigNavSwapGamepadButtons; // = false // Swap Activate<>Cancel (A<>B) buttons, matching typical "Nintendo/Japanese style" gamepad layout. - bool ConfigNavMoveSetMousePos; // = false // Directional/tabbing navigation teleports the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is difficult. Will update io.MousePos and set io.WantSetMousePos=true. - bool ConfigNavCaptureKeyboard; // = true // Sets io.WantCaptureKeyboard when io.NavActive is set. - bool ConfigNavEscapeClearFocusItem; // = true // Pressing Escape can clear focused item + navigation id/highlight. Set to false if you want to always keep highlight on. - bool ConfigNavEscapeClearFocusWindow;// = false // Pressing Escape can clear focused window as well (super set of io.ConfigNavEscapeClearFocusItem). - bool ConfigNavCursorVisibleAuto; // = true // Using directional navigation key makes the cursor visible. Mouse click hides the cursor. - bool ConfigNavCursorVisibleAlways; // = false // Navigation cursor is always visible. - - // Miscellaneous options - // (you can visualize and interact with all options in 'Demo->Configuration') - bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations. - bool ConfigMacOSXBehaviors; // = defined(__APPLE__) // Swap Cmd<>Ctrl keys + OS X style text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl. - bool ConfigInputTrickleEventQueue; // = true // Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates. - bool ConfigInputTextCursorBlink; // = true // Enable blinking cursor (optional as some users consider it to be distracting). - bool ConfigInputTextEnterKeepActive; // = false // [BETA] Pressing Enter will keep item active and select contents (single-line only). - bool ConfigDragClickToInputText; // = false // [BETA] Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving). Not desirable on devices without a keyboard. - bool ConfigWindowsResizeFromEdges; // = true // Enable resizing of windows from their edges and from the lower-left corner. This requires ImGuiBackendFlags_HasMouseCursors for better mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag) - bool ConfigWindowsMoveFromTitleBarOnly; // = false // Enable allowing to move windows only when clicking on their title bar. Does not apply to windows without a title bar. - bool ConfigWindowsCopyContentsWithCtrlC; // = false // [EXPERIMENTAL] CTRL+C copy the contents of focused window into the clipboard. Experimental because: (1) has known issues with nested Begin/End pairs (2) text output quality varies (3) text output is in submission order rather than spatial order. - bool ConfigScrollbarScrollByPage; // = true // Enable scrolling page by page when clicking outside the scrollbar grab. When disabled, always scroll to clicked location. When enabled, Shift+Click scrolls to clicked location. - float ConfigMemoryCompactTimer; // = 60.0f // Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable. - - // Inputs Behaviors - // (other variables, ones which are expected to be tweaked within UI code, are exposed in ImGuiStyle) - float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds. - float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels. - float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging. - float KeyRepeatDelay; // = 0.275f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.). - float KeyRepeatRate; // = 0.050f // When holding a key/button, rate at which it repeats, in seconds. - - //------------------------------------------------------------------ - // Debug options - //------------------------------------------------------------------ - - // Options to configure Error Handling and how we handle recoverable errors [EXPERIMENTAL] - // - Error recovery is provided as a way to facilitate: - // - Recovery after a programming error (native code or scripting language - the later tends to facilitate iterating on code while running). - // - Recovery after running an exception handler or any error processing which may skip code after an error has been detected. - // - Error recovery is not perfect nor guaranteed! It is a feature to ease development. - // You not are not supposed to rely on it in the course of a normal application run. - // - Functions that support error recovery are using IM_ASSERT_USER_ERROR() instead of IM_ASSERT(). - // - By design, we do NOT allow error recovery to be 100% silent. One of the three options needs to be checked! - // - Always ensure that on programmers seats you have at minimum Asserts or Tooltips enabled when making direct imgui API calls! - // Otherwise it would severely hinder your ability to catch and correct mistakes! - // Read https://github.com/ocornut/imgui/wiki/Error-Handling for details. - // - Programmer seats: keep asserts (default), or disable asserts and keep error tooltips (new and nice!) - // - Non-programmer seats: maybe disable asserts, but make sure errors are resurfaced (tooltips, visible log entries, use callback etc.) - // - Recovery after error/exception: record stack sizes with ErrorRecoveryStoreState(), disable assert, set log callback (to e.g. trigger high-level breakpoint), recover with ErrorRecoveryTryToRecoverState(), restore settings. - bool ConfigErrorRecovery; // = true // Enable error recovery support. Some errors won't be detected and lead to direct crashes if recovery is disabled. - bool ConfigErrorRecoveryEnableAssert; // = true // Enable asserts on recoverable error. By default call IM_ASSERT() when returning from a failing IM_ASSERT_USER_ERROR() - bool ConfigErrorRecoveryEnableDebugLog; // = true // Enable debug log output on recoverable errors. - bool ConfigErrorRecoveryEnableTooltip; // = true // Enable tooltip on recoverable errors. The tooltip include a way to enable asserts if they were disabled. - - // Option to enable various debug tools showing buttons that will call the IM_DEBUG_BREAK() macro. - // - The Item Picker tool will be available regardless of this being enabled, in order to maximize its discoverability. - // - Requires a debugger being attached, otherwise IM_DEBUG_BREAK() options will appear to crash your application. - // e.g. io.ConfigDebugIsDebuggerPresent = ::IsDebuggerPresent() on Win32, or refer to ImOsIsDebuggerPresent() imgui_test_engine/imgui_te_utils.cpp for a Unix compatible version). - bool ConfigDebugIsDebuggerPresent; // = false // Enable various tools calling IM_DEBUG_BREAK(). - - // Tools to detect code submitting items with conflicting/duplicate IDs - // - Code should use PushID()/PopID() in loops, or append "##xx" to same-label identifiers. - // - Empty label e.g. Button("") == same ID as parent widget/node. Use Button("##xx") instead! - // - See FAQ https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#q-about-the-id-stack-system - bool ConfigDebugHighlightIdConflicts;// = true // Highlight and show an error message popup when multiple items have conflicting identifiers. - bool ConfigDebugHighlightIdConflictsShowItemPicker;//=true // Show "Item Picker" button in aforementioned popup. - - // Tools to test correct Begin/End and BeginChild/EndChild behaviors. - // - Presently Begin()/End() and BeginChild()/EndChild() needs to ALWAYS be called in tandem, regardless of return value of BeginXXX() - // - This is inconsistent with other BeginXXX functions and create confusion for many users. - // - We expect to update the API eventually. In the meanwhile we provide tools to facilitate checking user-code behavior. - bool ConfigDebugBeginReturnValueOnce;// = false // First-time calls to Begin()/BeginChild() will return false. NEEDS TO BE SET AT APPLICATION BOOT TIME if you don't want to miss windows. - bool ConfigDebugBeginReturnValueLoop;// = false // Some calls to Begin()/BeginChild() will return false. Will cycle through window depths then repeat. Suggested use: add "io.ConfigDebugBeginReturnValue = io.KeyShift" in your main loop then occasionally press SHIFT. Windows should be flickering while running. - - // Option to deactivate io.AddFocusEvent(false) handling. - // - May facilitate interactions with a debugger when focus loss leads to clearing inputs data. - // - Backends may have other side-effects on focus loss, so this will reduce side-effects but not necessary remove all of them. - bool ConfigDebugIgnoreFocusLoss; // = false // Ignore io.AddFocusEvent(false), consequently not calling io.ClearInputKeys()/io.ClearInputMouse() in input processing. - - // Option to audit .ini data - bool ConfigDebugIniSettings; // = false // Save .ini data with extra comments (particularly helpful for Docking, but makes saving slower) - - //------------------------------------------------------------------ - // Platform Identifiers - // (the imgui_impl_xxxx backend files are setting those up for you) - //------------------------------------------------------------------ - - // Nowadays those would be stored in ImGuiPlatformIO but we are leaving them here for legacy reasons. - // Optional: Platform/Renderer backend name (informational only! will be displayed in About Window) + User data for backend/wrappers to store their own stuff. - const char* BackendPlatformName; // = NULL - const char* BackendRendererName; // = NULL - void* BackendPlatformUserData; // = NULL // User data for platform backend - void* BackendRendererUserData; // = NULL // User data for renderer backend - void* BackendLanguageUserData; // = NULL // User data for non C++ programming language backend - - //------------------------------------------------------------------ - // Input - Call before calling NewFrame() - //------------------------------------------------------------------ - - // Input Functions - IMGUI_API void AddKeyEvent(ImGuiKey key, bool down); // Queue a new key down/up event. Key should be "translated" (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character) - IMGUI_API void AddKeyAnalogEvent(ImGuiKey key, bool down, float v); // Queue a new key down/up event for analog values (e.g. ImGuiKey_Gamepad_ values). Dead-zones should be handled by the backend. - IMGUI_API void AddMousePosEvent(float x, float y); // Queue a mouse position update. Use -FLT_MAX,-FLT_MAX to signify no mouse (e.g. app not focused and not hovered) - IMGUI_API void AddMouseButtonEvent(int button, bool down); // Queue a mouse button change - IMGUI_API void AddMouseWheelEvent(float wheel_x, float wheel_y); // Queue a mouse wheel update. wheel_y<0: scroll down, wheel_y>0: scroll up, wheel_x<0: scroll right, wheel_x>0: scroll left. - IMGUI_API void AddMouseSourceEvent(ImGuiMouseSource source); // Queue a mouse source change (Mouse/TouchScreen/Pen) - IMGUI_API void AddFocusEvent(bool focused); // Queue a gain/loss of focus for the application (generally based on OS/platform focus of your window) - IMGUI_API void AddInputCharacter(unsigned int c); // Queue a new character input - IMGUI_API void AddInputCharacterUTF16(ImWchar16 c); // Queue a new character input from a UTF-16 character, it can be a surrogate - IMGUI_API void AddInputCharactersUTF8(const char* str); // Queue a new characters input from a UTF-8 string - - IMGUI_API void SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index = -1); // [Optional] Specify index for legacy <1.87 IsKeyXXX() functions with native indices + specify native keycode, scancode. - IMGUI_API void SetAppAcceptingEvents(bool accepting_events); // Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen. - IMGUI_API void ClearEventsQueue(); // Clear all incoming events. - IMGUI_API void ClearInputKeys(); // Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons. - IMGUI_API void ClearInputMouse(); // Clear current mouse state. -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - IMGUI_API void ClearInputCharacters(); // [Obsoleted in 1.89.8] Clear the current frame text input buffer. Now included within ClearInputKeys(). -#endif - - //------------------------------------------------------------------ - // Output - Updated by NewFrame() or EndFrame()/Render() - // (when reading from the io.WantCaptureMouse, io.WantCaptureKeyboard flags to dispatch your inputs, it is - // generally easier and more correct to use their state BEFORE calling NewFrame(). See FAQ for details!) - //------------------------------------------------------------------ - - bool WantCaptureMouse; // Set when Dear ImGui will use mouse inputs, in this case do not dispatch them to your main game/application (either way, always pass on mouse inputs to imgui). (e.g. unclicked mouse is hovering over an imgui window, widget is active, mouse was clicked over an imgui window, etc.). - bool WantCaptureKeyboard; // Set when Dear ImGui will use keyboard inputs, in this case do not dispatch them to your main game/application (either way, always pass keyboard inputs to imgui). (e.g. InputText active, or an imgui window is focused and navigation is enabled, etc.). - bool WantTextInput; // Mobile/console: when set, you may display an on-screen keyboard. This is set by Dear ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active). - bool WantSetMousePos; // MousePos has been altered, backend should reposition mouse on next frame. Rarely used! Set only when io.ConfigNavMoveSetMousePos is enabled. - bool WantSaveIniSettings; // When manual .ini load/save is active (io.IniFilename == NULL), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving! - bool NavActive; // Keyboard/Gamepad navigation is currently allowed (will handle ImGuiKey_NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags_NoNavInputs flag. - bool NavVisible; // Keyboard/Gamepad navigation highlight is visible and allowed (will handle ImGuiKey_NavXXX events). - float Framerate; // Estimate of application framerate (rolling average over 60 frames, based on io.DeltaTime), in frame per second. Solely for convenience. Slow applications may not want to use a moving average or may want to reset underlying buffers occasionally. - int MetricsRenderVertices; // Vertices output during last call to Render() - int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3 - int MetricsRenderWindows; // Number of visible windows - int MetricsActiveWindows; // Number of active windows - ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are invalid (-FLT_MAX,-FLT_MAX), so a disappearing/reappearing mouse won't have a huge delta. - - //------------------------------------------------------------------ - // [Internal] Dear ImGui will maintain those fields. Forward compatibility not guaranteed! - //------------------------------------------------------------------ - - ImGuiContext* Ctx; // Parent UI context (needs to be set explicitly by parent). - - // Main Input State - // (this block used to be written by backend, since 1.87 it is best to NOT write to those directly, call the AddXXX functions above instead) - // (reading from those variables is fair game, as they are extremely unlikely to be moving anywhere) - ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX, -FLT_MAX) if mouse is unavailable (on another screen, etc.) - bool MouseDown[5]; // Mouse buttons: 0=left, 1=right, 2=middle + extras (ImGuiMouseButton_COUNT == 5). Dear ImGui mostly uses left and right buttons. Other buttons allow us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. - float MouseWheel; // Mouse wheel Vertical: 1 unit scrolls about 5 lines text. >0 scrolls Up, <0 scrolls Down. Hold SHIFT to turn vertical scroll into horizontal scroll. - float MouseWheelH; // Mouse wheel Horizontal. >0 scrolls Left, <0 scrolls Right. Most users don't have a mouse with a horizontal wheel, may not be filled by all backends. - ImGuiMouseSource MouseSource; // Mouse actual input peripheral (Mouse/TouchScreen/Pen). - bool KeyCtrl; // Keyboard modifier down: Control - bool KeyShift; // Keyboard modifier down: Shift - bool KeyAlt; // Keyboard modifier down: Alt - bool KeySuper; // Keyboard modifier down: Cmd/Super/Windows - - // Other state maintained from data above + IO function calls - ImGuiKeyChord KeyMods; // Key mods flags (any of ImGuiMod_Ctrl/ImGuiMod_Shift/ImGuiMod_Alt/ImGuiMod_Super flags, same as io.KeyCtrl/KeyShift/KeyAlt/KeySuper but merged into flags. Read-only, updated by NewFrame() - ImGuiKeyData KeysData[ImGuiKey_NamedKey_COUNT];// Key state for all known keys. MUST use 'key - ImGuiKey_NamedKey_BEGIN' as index. Use IsKeyXXX() functions to access this. - bool WantCaptureMouseUnlessPopupClose; // Alternative to WantCaptureMouse: (WantCaptureMouse == true && WantCaptureMouseUnlessPopupClose == false) when a click over void is expected to close a popup. - ImVec2 MousePosPrev; // Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid) - ImVec2 MouseClickedPos[5]; // Position at time of clicking - double MouseClickedTime[5]; // Time of last click (used to figure out double-click) - bool MouseClicked[5]; // Mouse button went from !Down to Down (same as MouseClickedCount[x] != 0) - bool MouseDoubleClicked[5]; // Has mouse button been double-clicked? (same as MouseClickedCount[x] == 2) - ImU16 MouseClickedCount[5]; // == 0 (not clicked), == 1 (same as MouseClicked[]), == 2 (double-clicked), == 3 (triple-clicked) etc. when going from !Down to Down - ImU16 MouseClickedLastCount[5]; // Count successive number of clicks. Stays valid after mouse release. Reset after another click is done. - bool MouseReleased[5]; // Mouse button went from Down to !Down - double MouseReleasedTime[5]; // Time of last released (rarely used! but useful to handle delayed single-click when trying to disambiguate them from double-click). - bool MouseDownOwned[5]; // Track if button was clicked inside a dear imgui window or over void blocked by a popup. We don't request mouse capture from the application if click started outside ImGui bounds. - bool MouseDownOwnedUnlessPopupClose[5]; // Track if button was clicked inside a dear imgui window. - bool MouseWheelRequestAxisSwap; // On a non-Mac system, holding SHIFT requests WheelY to perform the equivalent of a WheelX event. On a Mac system this is already enforced by the system. - bool MouseCtrlLeftAsRightClick; // (OSX) Set to true when the current click was a Ctrl+click that spawned a simulated right click - float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked) - float MouseDownDurationPrev[5]; // Previous time the mouse button has been down - float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the clicking point (used for moving thresholds) - float PenPressure; // Touch/Pen pressure (0.0f to 1.0f, should be >0.0f only when MouseDown[0] == true). Helper storage currently unused by Dear ImGui. - bool AppFocusLost; // Only modify via AddFocusEvent() - bool AppAcceptingEvents; // Only modify via SetAppAcceptingEvents() - ImWchar16 InputQueueSurrogate; // For AddInputCharacterUTF16() - ImVector InputQueueCharacters; // Queue of _characters_ input (obtained by platform backend). Fill using AddInputCharacter() helper. - - // Legacy: before 1.87, we required backend to fill io.KeyMap[] (imgui->native map) during initialization and io.KeysDown[] (native indices) every frame. - // This is still temporarily supported as a legacy feature. However the new preferred scheme is for backend to call io.AddKeyEvent(). - // Old (<1.87): ImGui::IsKeyPressed(ImGui::GetIO().KeyMap[ImGuiKey_Space]) --> New (1.87+) ImGui::IsKeyPressed(ImGuiKey_Space) - // Old (<1.87): ImGui::IsKeyPressed(MYPLATFORM_KEY_SPACE) --> New (1.87+) ImGui::IsKeyPressed(ImGuiKey_Space) - // Read https://github.com/ocornut/imgui/issues/4921 for details. - //int KeyMap[ImGuiKey_COUNT]; // [LEGACY] Input: map of indices into the KeysDown[512] entries array which represent your "native" keyboard state. The first 512 are now unused and should be kept zero. Legacy backend will write into KeyMap[] using ImGuiKey_ indices which are always >512. - //bool KeysDown[ImGuiKey_COUNT]; // [LEGACY] Input: Keyboard keys that are pressed (ideally left in the "native" order your engine has access to keyboard keys, so you can use your own defines/enums for keys). This used to be [512] sized. It is now ImGuiKey_COUNT to allow legacy io.KeysDown[GetKeyIndex(...)] to work without an overflow. - //float NavInputs[ImGuiNavInput_COUNT]; // [LEGACY] Since 1.88, NavInputs[] was removed. Backends from 1.60 to 1.86 won't build. Feed gamepad inputs via io.AddKeyEvent() and ImGuiKey_GamepadXXX enums. - //void* ImeWindowHandle; // [Obsoleted in 1.87] Set ImGuiViewport::PlatformHandleRaw instead. Set this to your HWND to get automatic IME cursor positioning. - -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - float FontGlobalScale; // Moved io.FontGlobalScale to style.FontScaleMain in 1.92 (June 2025) - - // Legacy: before 1.91.1, clipboard functions were stored in ImGuiIO instead of ImGuiPlatformIO. - // As this is will affect all users of custom engines/backends, we are providing proper legacy redirection (will obsolete). - const char* (*GetClipboardTextFn)(void* user_data); - void (*SetClipboardTextFn)(void* user_data, const char* text); - void* ClipboardUserData; -#endif - - IMGUI_API ImGuiIO(); -}; - -//----------------------------------------------------------------------------- -// [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) -//----------------------------------------------------------------------------- - -// Shared state of InputText(), passed as an argument to your callback when a ImGuiInputTextFlags_Callback* flag is used. -// The callback function should return 0 by default. -// Callbacks (follow a flag name and see comments in ImGuiInputTextFlags_ declarations for more details) -// - ImGuiInputTextFlags_CallbackEdit: Callback on buffer edit. Note that InputText() already returns true on edit + you can always use IsItemEdited(). The callback is useful to manipulate the underlying buffer while focus is active. -// - ImGuiInputTextFlags_CallbackAlways: Callback on each iteration -// - ImGuiInputTextFlags_CallbackCompletion: Callback on pressing TAB -// - ImGuiInputTextFlags_CallbackHistory: Callback on pressing Up/Down arrows -// - ImGuiInputTextFlags_CallbackCharFilter: Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. -// - ImGuiInputTextFlags_CallbackResize: Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. -struct ImGuiInputTextCallbackData -{ - ImGuiContext* Ctx; // Parent UI context - ImGuiInputTextFlags EventFlag; // One ImGuiInputTextFlags_Callback* // Read-only - ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only - void* UserData; // What user passed to InputText() // Read-only - - // Arguments for the different callback events - // - During Resize callback, Buf will be same as your input buffer. - // - However, during Completion/History/Always callback, Buf always points to our own internal data (it is not the same as your buffer)! Changes to it will be reflected into your own buffer shortly after the callback. - // - To modify the text buffer in a callback, prefer using the InsertChars() / DeleteChars() function. InsertChars() will take care of calling the resize callback if necessary. - // - If you know your edits are not going to resize the underlying buffer allocation, you may modify the contents of 'Buf[]' directly. You need to update 'BufTextLen' accordingly (0 <= BufTextLen < BufSize) and set 'BufDirty'' to true so InputText can update its internal state. - ImWchar EventChar; // Character input // Read-write // [CharFilter] Replace character with another one, or set to zero to drop. return 1 is equivalent to setting EventChar=0; - ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only // [Completion,History] - char* Buf; // Text buffer // Read-write // [Resize] Can replace pointer / [Completion,History,Always] Only write to pointed data, don't replace the actual pointer! - int BufTextLen; // Text length (in bytes) // Read-write // [Resize,Completion,History,Always] Exclude zero-terminator storage. In C land: == strlen(some_text), in C++ land: string.length() - int BufSize; // Buffer size (in bytes) = capacity+1 // Read-only // [Resize,Completion,History,Always] Include zero-terminator storage. In C land == ARRAYSIZE(my_char_array), in C++ land: string.capacity()+1 - bool BufDirty; // Set if you modify Buf/BufTextLen! // Write // [Completion,History,Always] - int CursorPos; // // Read-write // [Completion,History,Always] - int SelectionStart; // // Read-write // [Completion,History,Always] == to SelectionEnd when no selection) - int SelectionEnd; // // Read-write // [Completion,History,Always] - - // Helper functions for text manipulation. - // Use those function to benefit from the CallbackResize behaviors. Calling those function reset the selection. - IMGUI_API ImGuiInputTextCallbackData(); - IMGUI_API void DeleteChars(int pos, int bytes_count); - IMGUI_API void InsertChars(int pos, const char* text, const char* text_end = NULL); - void SelectAll() { SelectionStart = 0; SelectionEnd = BufTextLen; } - void ClearSelection() { SelectionStart = SelectionEnd = BufTextLen; } - bool HasSelection() const { return SelectionStart != SelectionEnd; } -}; - -// Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin(). -// NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough. -struct ImGuiSizeCallbackData -{ - void* UserData; // Read-only. What user passed to SetNextWindowSizeConstraints(). Generally store an integer or float in here (need reinterpret_cast<>). - ImVec2 Pos; // Read-only. Window position, for reference. - ImVec2 CurrentSize; // Read-only. Current window size. - ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing. -}; - -// Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload() -struct ImGuiPayload -{ - // Members - void* Data; // Data (copied and owned by dear imgui) - int DataSize; // Data size - - // [Internal] - ImGuiID SourceId; // Source item id - ImGuiID SourceParentId; // Source parent id (if available) - int DataFrameCount; // Data timestamp - char DataType[32 + 1]; // Data type tag (short user-supplied string, 32 characters max) - bool Preview; // Set when AcceptDragDropPayload() was called and mouse has been hovering the target item (nb: handle overlapping drag targets) - bool Delivery; // Set when AcceptDragDropPayload() was called and mouse button is released over the target item. - - ImGuiPayload() { Clear(); } - void Clear() { SourceId = SourceParentId = 0; Data = NULL; DataSize = 0; memset(DataType, 0, sizeof(DataType)); DataFrameCount = -1; Preview = Delivery = false; } - bool IsDataType(const char* type) const { return DataFrameCount != -1 && strcmp(type, DataType) == 0; } - bool IsPreview() const { return Preview; } - bool IsDelivery() const { return Delivery; } -}; - -//----------------------------------------------------------------------------- -// [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) -//----------------------------------------------------------------------------- - -// Helper: Unicode defines -#define IM_UNICODE_CODEPOINT_INVALID 0xFFFD // Invalid Unicode code point (standard value). -#ifdef IMGUI_USE_WCHAR32 -#define IM_UNICODE_CODEPOINT_MAX 0x10FFFF // Maximum Unicode code point supported by this build. -#else -#define IM_UNICODE_CODEPOINT_MAX 0xFFFF // Maximum Unicode code point supported by this build. -#endif - -// Helper: Execute a block of code at maximum once a frame. Convenient if you want to quickly create a UI within deep-nested code that runs multiple times every frame. -// Usage: static ImGuiOnceUponAFrame oaf; if (oaf) ImGui::Text("This will be called only once per frame"); -struct ImGuiOnceUponAFrame -{ - ImGuiOnceUponAFrame() { RefFrame = -1; } - mutable int RefFrame; - operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } -}; - -// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" -struct ImGuiTextFilter -{ - IMGUI_API ImGuiTextFilter(const char* default_filter = ""); - IMGUI_API bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build - IMGUI_API bool PassFilter(const char* text, const char* text_end = NULL) const; - IMGUI_API void Build(); - void Clear() { InputBuf[0] = 0; Build(); } - bool IsActive() const { return !Filters.empty(); } - - // [Internal] - struct ImGuiTextRange - { - const char* b; - const char* e; - - ImGuiTextRange() { b = e = NULL; } - ImGuiTextRange(const char* _b, const char* _e) { b = _b; e = _e; } - bool empty() const { return b == e; } - IMGUI_API void split(char separator, ImVector* out) const; - }; - char InputBuf[256]; - ImVectorFilters; - int CountGrep; -}; - -// Helper: Growable text buffer for logging/accumulating text -// (this could be called 'ImGuiTextBuilder' / 'ImGuiStringBuilder') -struct ImGuiTextBuffer -{ - ImVector Buf; - IMGUI_API static char EmptyString[1]; - - ImGuiTextBuffer() { } - inline char operator[](int i) const { IM_ASSERT(Buf.Data != NULL); return Buf.Data[i]; } - const char* begin() const { return Buf.Data ? &Buf.front() : EmptyString; } - const char* end() const { return Buf.Data ? &Buf.back() : EmptyString; } // Buf is zero-terminated, so end() will point on the zero-terminator - int size() const { return Buf.Size ? Buf.Size - 1 : 0; } - bool empty() const { return Buf.Size <= 1; } - void clear() { Buf.clear(); } - void resize(int size) { if (Buf.Size > size) Buf.Data[size] = 0; Buf.resize(size ? size + 1 : 0, 0); } // Similar to resize(0) on ImVector: empty string but don't free buffer. - void reserve(int capacity) { Buf.reserve(capacity); } - const char* c_str() const { return Buf.Data ? Buf.Data : EmptyString; } - IMGUI_API void append(const char* str, const char* str_end = NULL); - IMGUI_API void appendf(const char* fmt, ...) IM_FMTARGS(2); - IMGUI_API void appendfv(const char* fmt, va_list args) IM_FMTLIST(2); -}; - -// [Internal] Key+Value for ImGuiStorage -struct ImGuiStoragePair -{ - ImGuiID key; - union { int val_i; float val_f; void* val_p; }; - ImGuiStoragePair(ImGuiID _key, int _val) { key = _key; val_i = _val; } - ImGuiStoragePair(ImGuiID _key, float _val) { key = _key; val_f = _val; } - ImGuiStoragePair(ImGuiID _key, void* _val) { key = _key; val_p = _val; } -}; - -// Helper: Key->Value storage -// Typically you don't have to worry about this since a storage is held within each Window. -// We use it to e.g. store collapse state for a tree (Int 0/1) -// This is optimized for efficient lookup (dichotomy into a contiguous buffer) and rare insertion (typically tied to user interactions aka max once a frame) -// You can use it as custom user storage for temporary values. Declare your own storage if, for example: -// - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state). -// - You want to store custom debug data easily without adding or editing structures in your code (probably not efficient, but convenient) -// Types are NOT stored, so it is up to you to make sure your Key don't collide with different types. -struct ImGuiStorage -{ - // [Internal] - ImVector Data; - - // - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N) - // - Set***() functions find pair, insertion on demand if missing. - // - Sorted insertion is costly, paid once. A typical frame shouldn't need to insert any new pair. - void Clear() { Data.clear(); } - IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const; - IMGUI_API void SetInt(ImGuiID key, int val); - IMGUI_API bool GetBool(ImGuiID key, bool default_val = false) const; - IMGUI_API void SetBool(ImGuiID key, bool val); - IMGUI_API float GetFloat(ImGuiID key, float default_val = 0.0f) const; - IMGUI_API void SetFloat(ImGuiID key, float val); - IMGUI_API void* GetVoidPtr(ImGuiID key) const; // default_val is NULL - IMGUI_API void SetVoidPtr(ImGuiID key, void* val); - - // - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set. - // - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. - // - A typical use case where this is convenient for quick hacking (e.g. add storage during a live Edit&Continue session if you can't modify existing struct) - // float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar; - IMGUI_API int* GetIntRef(ImGuiID key, int default_val = 0); - IMGUI_API bool* GetBoolRef(ImGuiID key, bool default_val = false); - IMGUI_API float* GetFloatRef(ImGuiID key, float default_val = 0.0f); - IMGUI_API void** GetVoidPtrRef(ImGuiID key, void* default_val = NULL); - - // Advanced: for quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once. - IMGUI_API void BuildSortByKey(); - // Obsolete: use on your own storage if you know only integer are being stored (open/close all tree nodes) - IMGUI_API void SetAllInt(int val); - -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - //typedef ::ImGuiStoragePair ImGuiStoragePair; // 1.90.8: moved type outside struct -#endif -}; - -// Helper: Manually clip large list of items. -// If you have lots evenly spaced items and you have random access to the list, you can perform coarse -// clipping based on visibility to only submit items that are in view. -// The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we have skipped. -// (Dear ImGui already clip items based on their bounds but: it needs to first layout the item to do so, and generally -// fetching/submitting your own data incurs additional cost. Coarse clipping using ImGuiListClipper allows you to easily -// scale using lists with tens of thousands of items without a problem) -// Usage: -// ImGuiListClipper clipper; -// clipper.Begin(1000); // We have 1000 elements, evenly spaced. -// while (clipper.Step()) -// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) -// ImGui::Text("line number %d", i); -// Generally what happens is: -// - Clipper lets you process the first element (DisplayStart = 0, DisplayEnd = 1) regardless of it being visible or not. -// - User code submit that one element. -// - Clipper can measure the height of the first element -// - Clipper calculate the actual range of elements to display based on the current clipping rectangle, position the cursor before the first visible element. -// - User code submit visible elements. -// - The clipper also handles various subtleties related to keyboard/gamepad navigation, wrapping etc. -struct ImGuiListClipper -{ - ImGuiContext* Ctx; // Parent UI context - int DisplayStart; // First item to display, updated by each call to Step() - int DisplayEnd; // End of items to display (exclusive) - int ItemsCount; // [Internal] Number of items - float ItemsHeight; // [Internal] Height of item after a first step and item submission can calculate it - double StartPosY; // [Internal] Cursor position at the time of Begin() or after table frozen rows are all processed - double StartSeekOffsetY; // [Internal] Account for frozen rows in a table and initial loss of precision in very large windows. - void* TempData; // [Internal] Internal data - - // items_count: Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step, and you can call SeekCursorForItem() manually if you need) - // items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetFrameHeightWithSpacing(). - IMGUI_API ImGuiListClipper(); - IMGUI_API ~ImGuiListClipper(); - IMGUI_API void Begin(int items_count, float items_height = -1.0f); - IMGUI_API void End(); // Automatically called on the last call of Step() that returns false. - IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items. - - // Call IncludeItemByIndex() or IncludeItemsByIndex() *BEFORE* first call to Step() if you need a range of items to not be clipped, regardless of their visibility. - // (Due to alignment / padding of certain items it is possible that an extra item may be included on either end of the display range). - inline void IncludeItemByIndex(int item_index) { IncludeItemsByIndex(item_index, item_index + 1); } - IMGUI_API void IncludeItemsByIndex(int item_begin, int item_end); // item_end is exclusive e.g. use (42, 42+1) to make item 42 never clipped. - - // Seek cursor toward given item. This is automatically called while stepping. - // - The only reason to call this is: you can use ImGuiListClipper::Begin(INT_MAX) if you don't know item count ahead of time. - // - In this case, after all steps are done, you'll want to call SeekCursorForItem(item_count). - IMGUI_API void SeekCursorForItem(int item_index); - -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - inline void IncludeRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.9] - //inline void ForceDisplayRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.6] - //inline ImGuiListClipper(int items_count, float items_height = -1.0f) { memset(this, 0, sizeof(*this)); ItemsCount = -1; Begin(items_count, items_height); } // [removed in 1.79] -#endif -}; - -// Helpers: ImVec2/ImVec4 operators -// - It is important that we are keeping those disabled by default so they don't leak in user space. -// - This is in order to allow user enabling implicit cast operators between ImVec2/ImVec4 and their own types (using IM_VEC2_CLASS_EXTRA in imconfig.h) -// - Add '#define IMGUI_DEFINE_MATH_OPERATORS' before including this file (or in imconfig.h) to access courtesy maths operators for ImVec2 and ImVec4. -// - We intentionally provide ImVec2*float but not float*ImVec2: this is rare enough and we want to reduce the surface for possible user mistake. -#ifdef IMGUI_DEFINE_MATH_OPERATORS -#define IMGUI_DEFINE_MATH_OPERATORS_IMPLEMENTED -IM_MSVC_RUNTIME_CHECKS_OFF -// ImVec2 operators -inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x * rhs, lhs.y * rhs); } -inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x / rhs, lhs.y / rhs); } -inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); } -inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); } -inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } -inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x / rhs.x, lhs.y / rhs.y); } -inline ImVec2 operator-(const ImVec2& lhs) { return ImVec2(-lhs.x, -lhs.y); } -inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } -inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } -inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } -inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } -inline ImVec2& operator*=(ImVec2& lhs, const ImVec2& rhs) { lhs.x *= rhs.x; lhs.y *= rhs.y; return lhs; } -inline ImVec2& operator/=(ImVec2& lhs, const ImVec2& rhs) { lhs.x /= rhs.x; lhs.y /= rhs.y; return lhs; } -inline bool operator==(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } -inline bool operator!=(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y; } -// ImVec4 operators -inline ImVec4 operator*(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs); } -inline ImVec4 operator/(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs); } -inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w); } -inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w); } -inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w); } -inline ImVec4 operator/(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w); } -inline ImVec4 operator-(const ImVec4& lhs) { return ImVec4(-lhs.x, -lhs.y, -lhs.z, -lhs.w); } -inline bool operator==(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w; } -inline bool operator!=(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z || lhs.w != rhs.w; } -IM_MSVC_RUNTIME_CHECKS_RESTORE -#endif - -// Helpers macros to generate 32-bit encoded colors -// - User can declare their own format by #defining the 5 _SHIFT/_MASK macros in their imconfig file. -// - Any setting other than the default will need custom backend support. The only standard backend that supports anything else than the default is DirectX9. -#ifndef IM_COL32_R_SHIFT -#ifdef IMGUI_USE_BGRA_PACKED_COLOR -#define IM_COL32_R_SHIFT 16 -#define IM_COL32_G_SHIFT 8 -#define IM_COL32_B_SHIFT 0 -#define IM_COL32_A_SHIFT 24 -#define IM_COL32_A_MASK 0xFF000000 -#else -#define IM_COL32_R_SHIFT 0 -#define IM_COL32_G_SHIFT 8 -#define IM_COL32_B_SHIFT 16 -#define IM_COL32_A_SHIFT 24 -#define IM_COL32_A_MASK 0xFF000000 -#endif -#endif -#define IM_COL32(R,G,B,A) (((ImU32)(A)<> IM_COL32_R_SHIFT) & 0xFF) * (1.0f / 255.0f), (float)((rgba >> IM_COL32_G_SHIFT) & 0xFF) * (1.0f / 255.0f), (float)((rgba >> IM_COL32_B_SHIFT) & 0xFF) * (1.0f / 255.0f), (float)((rgba >> IM_COL32_A_SHIFT) & 0xFF) * (1.0f / 255.0f)) {} - inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); } - inline operator ImVec4() const { return Value; } - - // FIXME-OBSOLETE: May need to obsolete/cleanup those helpers. - inline void SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; } - static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r, g, b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r, g, b, a); } -}; - -//----------------------------------------------------------------------------- -// [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiSelectionRequestType, ImGuiSelectionRequest, ImGuiMultiSelectIO, ImGuiSelectionBasicStorage) -//----------------------------------------------------------------------------- - -// Multi-selection system -// Documentation at: https://github.com/ocornut/imgui/wiki/Multi-Select -// - Refer to 'Demo->Widgets->Selection State & Multi-Select' for demos using this. -// - This system implements standard multi-selection idioms (CTRL+Mouse/Keyboard, SHIFT+Mouse/Keyboard, etc) -// with support for clipper (skipping non-visible items), box-select and many other details. -// - Selectable(), Checkbox() are supported but custom widgets may use it as well. -// - TreeNode() is technically supported but... using this correctly is more complicated: you need some sort of linear/random access to your tree, -// which is suited to advanced trees setups also implementing filters and clipper. We will work toward simplifying and demoing it. -// - In the spirit of Dear ImGui design, your code owns actual selection data. -// This is designed to allow all kinds of selection storage you may use in your application e.g. set/map/hash. -// About ImGuiSelectionBasicStorage: -// - This is an optional helper to store a selection state and apply selection requests. -// - It is used by our demos and provided as a convenience to quickly implement multi-selection. -// Usage: -// - Identify submitted items with SetNextItemSelectionUserData(), most likely using an index into your current data-set. -// - Store and maintain actual selection data using persistent object identifiers. -// - Usage flow: -// BEGIN - (1) Call BeginMultiSelect() and retrieve the ImGuiMultiSelectIO* result. -// - (2) Honor request list (SetAll/SetRange requests) by updating your selection data. Same code as Step 6. -// - (3) [If using clipper] You need to make sure RangeSrcItem is always submitted. Calculate its index and pass to clipper.IncludeItemByIndex(). If storing indices in ImGuiSelectionUserData, a simple clipper.IncludeItemByIndex(ms_io->RangeSrcItem) call will work. -// LOOP - (4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. -// END - (5) Call EndMultiSelect() and retrieve the ImGuiMultiSelectIO* result. -// - (6) Honor request list (SetAll/SetRange requests) by updating your selection data. Same code as Step 2. -// If you submit all items (no clipper), Step 2 and 3 are optional and will be handled by each item themselves. It is fine to always honor those steps. -// About ImGuiSelectionUserData: -// - This can store an application-defined identifier (e.g. index or pointer) submitted via SetNextItemSelectionUserData(). -// - In return we store them into RangeSrcItem/RangeFirstItem/RangeLastItem and other fields in ImGuiMultiSelectIO. -// - Most applications will store an object INDEX, hence the chosen name and type. Storing an index is natural, because -// SetRange requests will give you two end-points and you will need to iterate/interpolate between them to update your selection. -// - However it is perfectly possible to store a POINTER or another IDENTIFIER inside ImGuiSelectionUserData. -// Our system never assume that you identify items by indices, it never attempts to interpolate between two values. -// - If you enable ImGuiMultiSelectFlags_NoRangeSelect then it is guaranteed that you will never have to interpolate -// between two ImGuiSelectionUserData, which may be a convenient way to use part of the feature with less code work. -// - As most users will want to store an index, for convenience and to reduce confusion we use ImS64 instead of void*, -// being syntactically easier to downcast. Feel free to reinterpret_cast and store a pointer inside. - -// Flags for BeginMultiSelect() -enum ImGuiMultiSelectFlags_ -{ - ImGuiMultiSelectFlags_None = 0, - ImGuiMultiSelectFlags_SingleSelect = 1 << 0, // Disable selecting more than one item. This is available to allow single-selection code to share same code/logic if desired. It essentially disables the main purpose of BeginMultiSelect() tho! - ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, // Disable CTRL+A shortcut to select all. - ImGuiMultiSelectFlags_NoRangeSelect = 1 << 2, // Disable Shift+selection mouse/keyboard support (useful for unordered 2D selection). With BoxSelect is also ensure contiguous SetRange requests are not combined into one. This allows not handling interpolation in SetRange requests. - ImGuiMultiSelectFlags_NoAutoSelect = 1 << 3, // Disable selecting items when navigating (useful for e.g. supporting range-select in a list of checkboxes). - ImGuiMultiSelectFlags_NoAutoClear = 1 << 4, // Disable clearing selection when navigating or selecting another one (generally used with ImGuiMultiSelectFlags_NoAutoSelect. useful for e.g. supporting range-select in a list of checkboxes). - ImGuiMultiSelectFlags_NoAutoClearOnReselect = 1 << 5, // Disable clearing selection when clicking/selecting an already selected item. - ImGuiMultiSelectFlags_BoxSelect1d = 1 << 6, // Enable box-selection with same width and same x pos items (e.g. full row Selectable()). Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. - ImGuiMultiSelectFlags_BoxSelect2d = 1 << 7, // Enable box-selection with varying width or varying x pos items support (e.g. different width labels, or 2D layout/grid). This is slower: alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. - ImGuiMultiSelectFlags_BoxSelectNoScroll = 1 << 8, // Disable scrolling when box-selecting near edges of scope. - ImGuiMultiSelectFlags_ClearOnEscape = 1 << 9, // Clear selection when pressing Escape while scope is focused. - ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 10, // Clear selection when clicking on empty location within scope. - ImGuiMultiSelectFlags_ScopeWindow = 1 << 11, // Scope for _BoxSelect and _ClearOnClickVoid is whole window (Default). Use if BeginMultiSelect() covers a whole window or used a single time in same window. - ImGuiMultiSelectFlags_ScopeRect = 1 << 12, // Scope for _BoxSelect and _ClearOnClickVoid is rectangle encompassing BeginMultiSelect()/EndMultiSelect(). Use if BeginMultiSelect() is called multiple times in same window. - ImGuiMultiSelectFlags_SelectOnClick = 1 << 13, // Apply selection on mouse down when clicking on unselected item. (Default) - ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 14, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. - //ImGuiMultiSelectFlags_RangeSelect2d = 1 << 15, // Shift+Selection uses 2d geometry instead of linear sequence, so possible to use Shift+up/down to select vertically in grid. Analogous to what BoxSelect does. - ImGuiMultiSelectFlags_NavWrapX = 1 << 16, // [Temporary] Enable navigation wrapping on X axis. Provided as a convenience because we don't have a design for the general Nav API for this yet. When the more general feature be public we may obsolete this flag in favor of new one. -}; - -// Main IO structure returned by BeginMultiSelect()/EndMultiSelect(). -// This mainly contains a list of selection requests. -// - Use 'Demo->Tools->Debug Log->Selection' to see requests as they happen. -// - Some fields are only useful if your list is dynamic and allows deletion (getting post-deletion focus/state right is shown in the demo) -// - Below: who reads/writes each fields? 'r'=read, 'w'=write, 'ms'=multi-select code, 'app'=application/user code. -struct ImGuiMultiSelectIO -{ - //------------------------------------------// BeginMultiSelect / EndMultiSelect - ImVector Requests; // ms:w, app:r / ms:w app:r // Requests to apply to your selection data. - ImGuiSelectionUserData RangeSrcItem; // ms:w app:r / // (If using clipper) Begin: Source item (often the first selected item) must never be clipped: use clipper.IncludeItemByIndex() to ensure it is submitted. - ImGuiSelectionUserData NavIdItem; // ms:w, app:r / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). - bool NavIdSelected; // ms:w, app:r / app:r // (If using deletion) Last known selection state for NavId (if part of submitted items). - bool RangeSrcReset; // app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). - int ItemsCount; // ms:w, app:r / app:r // 'int items_count' parameter to BeginMultiSelect() is copied here for convenience, allowing simpler calls to your ApplyRequests handler. Not used internally. -}; - -// Selection request type -enum ImGuiSelectionRequestType -{ - ImGuiSelectionRequestType_None = 0, - ImGuiSelectionRequestType_SetAll, // Request app to clear selection (if Selected==false) or select all items (if Selected==true). We cannot set RangeFirstItem/RangeLastItem as its contents is entirely up to user (not necessarily an index) - ImGuiSelectionRequestType_SetRange, // Request app to select/unselect [RangeFirstItem..RangeLastItem] items (inclusive) based on value of Selected. Only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. -}; - -// Selection request item -struct ImGuiSelectionRequest -{ - //------------------------------------------// BeginMultiSelect / EndMultiSelect - ImGuiSelectionRequestType Type; // ms:w, app:r / ms:w, app:r // Request type. You'll most often receive 1 Clear + 1 SetRange with a single-item range. - bool Selected; // ms:w, app:r / ms:w, app:r // Parameter for SetAll/SetRange requests (true = select, false = unselect) - ImS8 RangeDirection; // / ms:w app:r // Parameter for SetRange request: +1 when RangeFirstItem comes before RangeLastItem, -1 otherwise. Useful if you want to preserve selection order on a backward Shift+Click. - ImGuiSelectionUserData RangeFirstItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom). - ImGuiSelectionUserData RangeLastItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top). Inclusive! -}; - -// Optional helper to store multi-selection state + apply multi-selection requests. -// - Used by our demos and provided as a convenience to easily implement basic multi-selection. -// - Iterate selection with 'void* it = NULL; ImGuiID id; while (selection.GetNextSelectedItem(&it, &id)) { ... }' -// Or you can check 'if (Contains(id)) { ... }' for each possible object if their number is not too high to iterate. -// - USING THIS IS NOT MANDATORY. This is only a helper and not a required API. -// To store a multi-selection, in your application you could: -// - Use this helper as a convenience. We use our simple key->value ImGuiStorage as a std::set replacement. -// - Use your own external storage: e.g. std::set, std::vector, interval trees, intrusively stored selection etc. -// In ImGuiSelectionBasicStorage we: -// - always use indices in the multi-selection API (passed to SetNextItemSelectionUserData(), retrieved in ImGuiMultiSelectIO) -// - use the AdapterIndexToStorageId() indirection layer to abstract how persistent selection data is derived from an index. -// - use decently optimized logic to allow queries and insertion of very large selection sets. -// - do not preserve selection order. -// Many combinations are possible depending on how you prefer to store your items and how you prefer to store your selection. -// Large applications are likely to eventually want to get rid of this indirection layer and do their own thing. -// See https://github.com/ocornut/imgui/wiki/Multi-Select for details and pseudo-code using this helper. -struct ImGuiSelectionBasicStorage -{ - // Members - int Size; // // Number of selected items, maintained by this helper. - bool PreserveOrder; // = false // GetNextSelectedItem() will return ordered selection (currently implemented by two additional sorts of selection. Could be improved) - void* UserData; // = NULL // User data for use by adapter function // e.g. selection.UserData = (void*)my_items; - ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->UserData)[idx]->ID; }; - int _SelectionOrder;// [Internal] Increasing counter to store selection order - ImGuiStorage _Storage; // [Internal] Selection set. Think of this as similar to e.g. std::set. Prefer not accessing directly: iterate with GetNextSelectedItem(). - - // Methods - IMGUI_API ImGuiSelectionBasicStorage(); - IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io); // Apply selection requests coming from BeginMultiSelect() and EndMultiSelect() functions. It uses 'items_count' passed to BeginMultiSelect() - IMGUI_API bool Contains(ImGuiID id) const; // Query if an item id is in selection. - IMGUI_API void Clear(); // Clear selection - IMGUI_API void Swap(ImGuiSelectionBasicStorage& r); // Swap two selections - IMGUI_API void SetItemSelected(ImGuiID id, bool selected); // Add/remove an item from selection (generally done by ApplyRequests() function) - IMGUI_API bool GetNextSelectedItem(void** opaque_it, ImGuiID* out_id); // Iterate selection with 'void* it = NULL; ImGuiID id; while (selection.GetNextSelectedItem(&it, &id)) { ... }' - inline ImGuiID GetStorageIdFromIndex(int idx) { return AdapterIndexToStorageId(this, idx); } // Convert index to item id based on provided adapter. -}; - -// Optional helper to apply multi-selection requests to existing randomly accessible storage. -// Convenient if you want to quickly wire multi-select API on e.g. an array of bool or items storing their own selection state. -struct ImGuiSelectionExternalStorage -{ - // Members - void* UserData; // User data for use by adapter function // e.g. selection.UserData = (void*)my_items; - void (*AdapterSetItemSelected)(ImGuiSelectionExternalStorage* self, int idx, bool selected); // e.g. AdapterSetItemSelected = [](ImGuiSelectionExternalStorage* self, int idx, bool selected) { ((MyItems**)self->UserData)[idx]->Selected = selected; } - - // Methods - IMGUI_API ImGuiSelectionExternalStorage(); - IMGUI_API void ApplyRequests(ImGuiMultiSelectIO* ms_io); // Apply selection requests by using AdapterSetItemSelected() calls -}; - -//----------------------------------------------------------------------------- -// [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData) -// Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. -//----------------------------------------------------------------------------- - -// The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking. -#ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX -#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32) -#endif - -// ImDrawIdx: vertex index. [Compile-time configurable type] -// - To use 16-bit indices + allow large meshes: backend need to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset (recommended). -// - To use 32-bit indices: override with '#define ImDrawIdx unsigned int' in your imconfig.h file. -#ifndef ImDrawIdx -typedef unsigned short ImDrawIdx; // Default: 16-bit (for maximum compatibility with renderer backends) -#endif - -// ImDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h] -// NB: You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering, -// you can poke into the draw list for that! Draw callback may be useful for example to: -// A) Change your GPU render state, -// B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc. -// The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }' -// If you want to override the signature of ImDrawCallback, you can simply use e.g. '#define ImDrawCallback MyDrawCallback' (in imconfig.h) + update rendering backend accordingly. -#ifndef ImDrawCallback -typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); -#endif - -// Special Draw callback value to request renderer backend to reset the graphics/render state. -// The renderer backend needs to handle this special value, otherwise it will crash trying to call a function at this address. -// This is useful, for example, if you submitted callbacks which you know have altered the render state and you want it to be restored. -// Render state is not reset by default because they are many perfectly useful way of altering render state (e.g. changing shader/blending settings before an Image call). -#define ImDrawCallback_ResetRenderState (ImDrawCallback)(-8) - -// Typically, 1 command = 1 GPU draw call (unless command is a callback) -// - VtxOffset: When 'io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset' is enabled, -// this fields allow us to render meshes larger than 64K vertices while keeping 16-bit indices. -// Backends made for <1.71. will typically ignore the VtxOffset fields. -// - The ClipRect/TexRef/VtxOffset fields must be contiguous as we memcmp() them together (this is asserted for). -struct ImDrawCmd -{ - ImVec4 ClipRect; // 4*4 // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates - ImTextureRef TexRef; // 16 // Reference to a font/texture atlas (where backend called ImTextureData::SetTexID()) or to a user-provided texture ID (via e.g. ImGui::Image() calls). Both will lead to a ImTextureID value. - unsigned int VtxOffset; // 4 // Start offset in vertex buffer. ImGuiBackendFlags_RendererHasVtxOffset: always 0, otherwise may be >0 to support meshes larger than 64K vertices with 16-bit indices. - unsigned int IdxOffset; // 4 // Start offset in index buffer. - unsigned int ElemCount; // 4 // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[]. - ImDrawCallback UserCallback; // 4-8 // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. - void* UserCallbackData; // 4-8 // Callback user data (when UserCallback != NULL). If called AddCallback() with size == 0, this is a copy of the AddCallback() argument. If called AddCallback() with size > 0, this is pointing to a buffer where data is stored. - int UserCallbackDataSize; // 4 // Size of callback user data when using storage, otherwise 0. - int UserCallbackDataOffset;// 4 // [Internal] Offset of callback user data when using storage, otherwise -1. - - ImDrawCmd() { memset(this, 0, sizeof(*this)); } // Also ensure our padding fields are zeroed - - // Since 1.83: returns ImTextureID associated with this draw call. Warning: DO NOT assume this is always same as 'TextureId' (we will change this function for an upcoming feature) - // Since 1.92: removed ImDrawCmd::TextureId field, the getter function must be used! - inline ImTextureID GetTexID() const; // == (TexRef._TexData ? TexRef._TexData->TexID : TexRef._TexID -}; - -// Vertex layout -#ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT -struct ImDrawVert -{ - ImVec2 pos; - ImVec2 uv; - ImU32 col; -}; -#else -// You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h -// The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine. -// The type has to be described within the macro (you can either declare the struct or use a typedef). This is because ImVec2/ImU32 are likely not declared at the time you'd want to set your type up. -// NOTE: IMGUI DOESN'T CLEAR THE STRUCTURE AND DOESN'T CALL A CONSTRUCTOR SO ANY CUSTOM FIELD WILL BE UNINITIALIZED. IF YOU ADD EXTRA FIELDS (SUCH AS A 'Z' COORDINATES) YOU WILL NEED TO CLEAR THEM DURING RENDER OR TO IGNORE THEM. -IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; -#endif - -// [Internal] For use by ImDrawList -struct ImDrawCmdHeader -{ - ImVec4 ClipRect; - ImTextureRef TexRef; - unsigned int VtxOffset; -}; - -// [Internal] For use by ImDrawListSplitter -struct ImDrawChannel -{ - ImVector _CmdBuffer; - ImVector _IdxBuffer; -}; - -// Split/Merge functions are used to split the draw list into different layers which can be drawn into out of order. -// This is used by the Columns/Tables API, so items of each column can be batched together in a same draw call. -struct ImDrawListSplitter -{ - int _Current; // Current channel number (0) - int _Count; // Number of active channels (1+) - ImVector _Channels; // Draw channels (not resized down so _Count might be < Channels.Size) - - inline ImDrawListSplitter() { memset(this, 0, sizeof(*this)); } - inline ~ImDrawListSplitter() { ClearFreeMemory(); } - inline void Clear() { _Current = 0; _Count = 1; } // Do not clear Channels[] so our allocations are reused next frame - IMGUI_API void ClearFreeMemory(); - IMGUI_API void Split(ImDrawList* draw_list, int count); - IMGUI_API void Merge(ImDrawList* draw_list); - IMGUI_API void SetCurrentChannel(ImDrawList* draw_list, int channel_idx); -}; - -// Flags for ImDrawList functions -// (Legacy: bit 0 must always correspond to ImDrawFlags_Closed to be backward compatible with old API using a bool. Bits 1..3 must be unused) -enum ImDrawFlags_ -{ - ImDrawFlags_None = 0, - ImDrawFlags_Closed = 1 << 0, // PathStroke(), AddPolyline(): specify that shape should be closed (Important: this is always == 1 for legacy reason) - ImDrawFlags_RoundCornersTopLeft = 1 << 4, // AddRect(), AddRectFilled(), PathRect(): enable rounding top-left corner only (when rounding > 0.0f, we default to all corners). Was 0x01. - ImDrawFlags_RoundCornersTopRight = 1 << 5, // AddRect(), AddRectFilled(), PathRect(): enable rounding top-right corner only (when rounding > 0.0f, we default to all corners). Was 0x02. - ImDrawFlags_RoundCornersBottomLeft = 1 << 6, // AddRect(), AddRectFilled(), PathRect(): enable rounding bottom-left corner only (when rounding > 0.0f, we default to all corners). Was 0x04. - ImDrawFlags_RoundCornersBottomRight = 1 << 7, // AddRect(), AddRectFilled(), PathRect(): enable rounding bottom-right corner only (when rounding > 0.0f, we default to all corners). Wax 0x08. - ImDrawFlags_RoundCornersNone = 1 << 8, // AddRect(), AddRectFilled(), PathRect(): disable rounding on all corners (when rounding > 0.0f). This is NOT zero, NOT an implicit flag! - ImDrawFlags_RoundCornersTop = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight, - ImDrawFlags_RoundCornersBottom = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, - ImDrawFlags_RoundCornersLeft = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersTopLeft, - ImDrawFlags_RoundCornersRight = ImDrawFlags_RoundCornersBottomRight | ImDrawFlags_RoundCornersTopRight, - ImDrawFlags_RoundCornersAll = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight | ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, - ImDrawFlags_RoundCornersDefault_ = ImDrawFlags_RoundCornersAll, // Default to ALL corners if none of the _RoundCornersXX flags are specified. - ImDrawFlags_RoundCornersMask_ = ImDrawFlags_RoundCornersAll | ImDrawFlags_RoundCornersNone, -}; - -// Flags for ImDrawList instance. Those are set automatically by ImGui:: functions from ImGuiIO settings, and generally not manipulated directly. -// It is however possible to temporarily alter flags between calls to ImDrawList:: functions. -enum ImDrawListFlags_ -{ - ImDrawListFlags_None = 0, - ImDrawListFlags_AntiAliasedLines = 1 << 0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles) - ImDrawListFlags_AntiAliasedLinesUseTex = 1 << 1, // Enable anti-aliased lines/borders using textures when possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). - ImDrawListFlags_AntiAliasedFill = 1 << 2, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). - ImDrawListFlags_AllowVtxOffset = 1 << 3, // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. -}; - -// Draw command list -// This is the low-level list of polygons that ImGui:: functions are filling. At the end of the frame, -// all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering. -// Each dear imgui window contains its own ImDrawList. You can use ImGui::GetWindowDrawList() to -// access the current window draw list and draw custom primitives. -// You can interleave normal ImGui:: calls and adding primitives to the current draw list. -// In single viewport mode, top-left is == GetMainViewport()->Pos (generally 0,0), bottom-right is == GetMainViewport()->Pos+Size (generally io.DisplaySize). -// You are totally free to apply whatever transformation matrix you want to the data (depending on the use of the transformation you may want to apply it to ClipRect as well!) -// Important: Primitives are always added to the list and not culled (culling is done at higher-level by ImGui:: functions), if you use this API a lot consider coarse culling your drawn objects. -struct ImDrawList -{ - // This is what you have to render - ImVector CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback. - ImVector IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those - ImVector VtxBuffer; // Vertex buffer. - ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive. - - // [Internal, used while building lists] - unsigned int _VtxCurrentIdx; // [Internal] generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0. - ImDrawListSharedData* _Data; // Pointer to shared draw data (you can use ImGui::GetDrawListSharedData() to get the one from current ImGui context) - ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) - ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) - ImVector _Path; // [Internal] current path building - ImDrawCmdHeader _CmdHeader; // [Internal] template of active commands. Fields should match those of CmdBuffer.back(). - ImDrawListSplitter _Splitter; // [Internal] for channels api (note: prefer using your own persistent instance of ImDrawListSplitter!) - ImVector _ClipRectStack; // [Internal] - ImVector _TextureStack; // [Internal] - ImVector _CallbacksDataBuf; // [Internal] - float _FringeScale; // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content - const char* _OwnerName; // Pointer to owner window's name for debugging - - // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData(). - // (advanced: you may create and use your own ImDrawListSharedData so you can use ImDrawList without ImGui, but that's more involved) - IMGUI_API ImDrawList(ImDrawListSharedData* shared_data); - IMGUI_API ~ImDrawList(); - - IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) - IMGUI_API void PushClipRectFullScreen(); - IMGUI_API void PopClipRect(); - IMGUI_API void PushTexture(ImTextureRef tex_ref); - IMGUI_API void PopTexture(); - inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); } - inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); } - - // Primitives - // - Filled shapes must always use clockwise winding order. The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. - // - For rectangular primitives, "p_min" and "p_max" represent the upper-left and lower-right corners. - // - For circle primitives, use "num_segments == 0" to automatically calculate tessellation (preferred). - // In older versions (until Dear ImGui 1.77) the AddCircle functions defaulted to num_segments == 12. - // In future versions we will use textures to provide cheaper and higher-quality circles. - // Use AddNgon() and AddNgonFilled() functions if you need to guarantee a specific number of sides. - IMGUI_API void AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness = 1.0f); - IMGUI_API void AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawFlags flags = 0, float thickness = 1.0f); // a: upper-left, b: lower-right (== upper-left + size) - IMGUI_API void AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawFlags flags = 0); // a: upper-left, b: lower-right (== upper-left + size) - IMGUI_API void AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); - IMGUI_API void AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness = 1.0f); - IMGUI_API void AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col); - IMGUI_API void AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness = 1.0f); - IMGUI_API void AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col); - IMGUI_API void AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments = 0, float thickness = 1.0f); - IMGUI_API void AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments = 0); - IMGUI_API void AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness = 1.0f); - IMGUI_API void AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments); - IMGUI_API void AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot = 0.0f, int num_segments = 0, float thickness = 1.0f); - IMGUI_API void AddEllipseFilled(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot = 0.0f, int num_segments = 0); - IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); - IMGUI_API void AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL); - IMGUI_API void AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0); // Cubic Bezier (4 control points) - IMGUI_API void AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments = 0); // Quadratic Bezier (3 control points) - - // General polygon - // - Only simple polygons are supported by filling functions (no self-intersections, no holes). - // - Concave polygon fill is more expensive than convex one: it has O(N^2) complexity. Provided as a convenience for the user but not used by the main library. - IMGUI_API void AddPolyline(const ImVec2* points, int num_points, ImU32 col, ImDrawFlags flags, float thickness); - IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col); - IMGUI_API void AddConcavePolyFilled(const ImVec2* points, int num_points, ImU32 col); - - // Image primitives - // - Read FAQ to understand what ImTextureID/ImTextureRef are. - // - "p_min" and "p_max" represent the upper-left and lower-right corners of the rectangle. - // - "uv_min" and "uv_max" represent the normalized texture coordinates to use for those corners. Using (0,0)->(1,1) texture coordinates will generally display the entire texture. - IMGUI_API void AddImage(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min = ImVec2(0, 0), const ImVec2& uv_max = ImVec2(1, 1), ImU32 col = IM_COL32_WHITE); - IMGUI_API void AddImageQuad(ImTextureRef tex_ref, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1 = ImVec2(0, 0), const ImVec2& uv2 = ImVec2(1, 0), const ImVec2& uv3 = ImVec2(1, 1), const ImVec2& uv4 = ImVec2(0, 1), ImU32 col = IM_COL32_WHITE); - IMGUI_API void AddImageRounded(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags = 0); - - // Stateful path API, add points then finish with PathFillConvex() or PathStroke() - // - Important: filled shapes must always use clockwise winding order! The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. - // so e.g. 'PathArcTo(center, radius, PI * -0.5f, PI)' is ok, whereas 'PathArcTo(center, radius, PI, PI * -0.5f)' won't have correct anti-aliasing when followed by PathFillConvex(). - inline void PathClear() { _Path.Size = 0; } - inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); } - inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path.Data[_Path.Size - 1], &pos, 8) != 0) _Path.push_back(pos); } - inline void PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col); _Path.Size = 0; } - inline void PathFillConcave(ImU32 col) { AddConcavePolyFilled(_Path.Data, _Path.Size, col); _Path.Size = 0; } - inline void PathStroke(ImU32 col, ImDrawFlags flags = 0, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, flags, thickness); _Path.Size = 0; } - IMGUI_API void PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments = 0); - IMGUI_API void PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle - IMGUI_API void PathEllipticalArcTo(const ImVec2& center, const ImVec2& radius, float rot, float a_min, float a_max, int num_segments = 0); // Ellipse - IMGUI_API void PathBezierCubicCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0); // Cubic Bezier (4 control points) - IMGUI_API void PathBezierQuadraticCurveTo(const ImVec2& p2, const ImVec2& p3, int num_segments = 0); // Quadratic Bezier (3 control points) - IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, ImDrawFlags flags = 0); - - // Advanced: Draw Callbacks - // - May be used to alter render state (change sampler, blending, current shader). May be used to emit custom rendering commands (difficult to do correctly, but possible). - // - Use special ImDrawCallback_ResetRenderState callback to instruct backend to reset its render state to the default. - // - Your rendering loop must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles. All standard backends are honoring this. - // - For some backends, the callback may access selected render-states exposed by the backend in a ImGui_ImplXXXX_RenderState structure pointed to by platform_io.Renderer_RenderState. - // - IMPORTANT: please be mindful of the different level of indirection between using size==0 (copying argument) and using size>0 (copying pointed data into a buffer). - // - If userdata_size == 0: we copy/store the 'userdata' argument as-is. It will be available unmodified in ImDrawCmd::UserCallbackData during render. - // - If userdata_size > 0, we copy/store 'userdata_size' bytes pointed to by 'userdata'. We store them in a buffer stored inside the drawlist. ImDrawCmd::UserCallbackData will point inside that buffer so you have to retrieve data from there. Your callback may need to use ImDrawCmd::UserCallbackDataSize if you expect dynamically-sized data. - // - Support for userdata_size > 0 was added in v1.91.4, October 2024. So earlier code always only allowed to copy/store a simple void*. - IMGUI_API void AddCallback(ImDrawCallback callback, void* userdata, size_t userdata_size = 0); - - // Advanced: Miscellaneous - IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible - IMGUI_API ImDrawList* CloneOutput() const; // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer. - - // Advanced: Channels - // - Use to split render into layers. By switching channels to can render out-of-order (e.g. submit FG primitives before BG primitives) - // - Use to minimize draw calls (e.g. if going back-and-forth between multiple clipping rectangles, prefer to append into separate channels then merge at the end) - // - This API shouldn't have been in ImDrawList in the first place! - // Prefer using your own persistent instance of ImDrawListSplitter as you can stack them. - // Using the ImDrawList::ChannelsXXXX you cannot stack a split over another. - inline void ChannelsSplit(int count) { _Splitter.Split(this, count); } - inline void ChannelsMerge() { _Splitter.Merge(this); } - inline void ChannelsSetCurrent(int n) { _Splitter.SetCurrentChannel(this, n); } - - // Advanced: Primitives allocations - // - We render triangles (three vertices) - // - All primitives needs to be reserved via PrimReserve() beforehand. - IMGUI_API void PrimReserve(int idx_count, int vtx_count); - IMGUI_API void PrimUnreserve(int idx_count, int vtx_count); - IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles) - IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col); - IMGUI_API void PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col); - inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; } - inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; } - inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } // Write vertex with unique index - - // Obsolete names -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - inline void PushTextureID(ImTextureRef tex_ref) { PushTexture(tex_ref); } // RENAMED in 1.92.x - inline void PopTextureID() { PopTexture(); } // RENAMED in 1.92.x -#endif - //inline void AddEllipse(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0, float thickness = 1.0f) { AddEllipse(center, ImVec2(radius_x, radius_y), col, rot, num_segments, thickness); } // OBSOLETED in 1.90.5 (Mar 2024) - //inline void AddEllipseFilled(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0) { AddEllipseFilled(center, ImVec2(radius_x, radius_y), col, rot, num_segments); } // OBSOLETED in 1.90.5 (Mar 2024) - //inline void PathEllipticalArcTo(const ImVec2& center, float radius_x, float radius_y, float rot, float a_min, float a_max, int num_segments = 0) { PathEllipticalArcTo(center, ImVec2(radius_x, radius_y), rot, a_min, a_max, num_segments); } // OBSOLETED in 1.90.5 (Mar 2024) - //inline void AddBezierCurve(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0) { AddBezierCubic(p1, p2, p3, p4, col, thickness, num_segments); } // OBSOLETED in 1.80 (Jan 2021) - //inline void PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0) { PathBezierCubicCurveTo(p2, p3, p4, num_segments); } // OBSOLETED in 1.80 (Jan 2021) - - // [Internal helpers] - IMGUI_API void _SetDrawListSharedData(ImDrawListSharedData* data); - IMGUI_API void _ResetForNewFrame(); - IMGUI_API void _ClearFreeMemory(); - IMGUI_API void _PopUnusedDrawCmd(); - IMGUI_API void _TryMergeDrawCmds(); - IMGUI_API void _OnChangedClipRect(); - IMGUI_API void _OnChangedTexture(); - IMGUI_API void _OnChangedVtxOffset(); - IMGUI_API void _SetTexture(ImTextureRef tex_ref); - IMGUI_API int _CalcCircleAutoSegmentCount(float radius) const; - IMGUI_API void _PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step); - IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments); -}; - -// All draw data to render a Dear ImGui frame -// (NB: the style and the naming convention here is a little inconsistent, we currently preserve them for backward compatibility purpose, -// as this is one of the oldest structure exposed by the library! Basically, ImDrawList == CmdList) -struct ImDrawData -{ - bool Valid; // Only valid after Render() is called and before the next NewFrame() is called. - int CmdListsCount; // Number of ImDrawList* to render. (== CmdLists.Size). Exists for legacy reason. - int TotalIdxCount; // For convenience, sum of all ImDrawList's IdxBuffer.Size - int TotalVtxCount; // For convenience, sum of all ImDrawList's VtxBuffer.Size - ImVector CmdLists; // Array of ImDrawList* to render. The ImDrawLists are owned by ImGuiContext and only pointed to from here. - ImVec2 DisplayPos; // Top-left position of the viewport to render (== top-left of the orthogonal projection matrix to use) (== GetMainViewport()->Pos for the main viewport, == (0.0) in most single-viewport applications) - ImVec2 DisplaySize; // Size of the viewport to render (== GetMainViewport()->Size for the main viewport, == io.DisplaySize in most single-viewport applications) - ImVec2 FramebufferScale; // Amount of pixels for each unit of DisplaySize. Copied from viewport->FramebufferScale (== io.DisplayFramebufferScale for main viewport). Generally (1,1) on normal display, (2,2) on OSX with Retina display. - ImGuiViewport* OwnerViewport; // Viewport carrying the ImDrawData instance, might be of use to the renderer (generally not). - ImVector* Textures; // List of textures to update. Most of the times the list is shared by all ImDrawData, has only 1 texture and it doesn't need any update. This almost always points to ImGui::GetPlatformIO().Textures[]. May be overriden or set to NULL if you want to manually update textures. - - // Functions - ImDrawData() { Clear(); } - IMGUI_API void Clear(); - IMGUI_API void AddDrawList(ImDrawList* draw_list); // Helper to add an external draw list into an existing ImDrawData. - IMGUI_API void DeIndexAllBuffers(); // Helper to convert all buffers from indexed to non-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! - IMGUI_API void ScaleClipRects(const ImVec2& fb_scale); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than Dear ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. -}; - -//----------------------------------------------------------------------------- -// [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) -//----------------------------------------------------------------------------- -// In principle, the only data types that user/application code should care about are 'ImTextureRef' and 'ImTextureID'. -// They are defined above in this header file. Read their description to the difference between ImTextureRef and ImTextureID. -// FOR ALL OTHER ImTextureXXXX TYPES: ONLY CORE LIBRARY AND RENDERER BACKENDS NEED TO KNOW AND CARE ABOUT THEM. -//----------------------------------------------------------------------------- - -#undef Status // X11 headers are leaking this. - -// We intentionally support a limited amount of texture formats to limit burden on CPU-side code and extension. -// Most standard backends only support RGBA32 but we provide a single channel option for low-resource/embedded systems. -enum ImTextureFormat -{ - ImTextureFormat_RGBA32, // 4 components per pixel, each is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 - ImTextureFormat_Alpha8, // 1 component per pixel, each is unsigned 8-bit. Total size = TexWidth * TexHeight -}; - -// Status of a texture to communicate with Renderer Backend. -enum ImTextureStatus -{ - ImTextureStatus_OK, - ImTextureStatus_Destroyed, // Backend destroyed the texture. - ImTextureStatus_WantCreate, // Requesting backend to create the texture. Set status OK when done. - ImTextureStatus_WantUpdates, // Requesting backend to update specific blocks of pixels (write to texture portions which have never been used before). Set status OK when done. - ImTextureStatus_WantDestroy, // Requesting backend to destroy the texture. Set status to Destroyed when done. -}; - -// Coordinates of a rectangle within a texture. -// When a texture is in ImTextureStatus_WantUpdates state, we provide a list of individual rectangles to copy to the graphics system. -// You may use ImTextureData::Updates[] for the list, or ImTextureData::UpdateBox for a single bounding box. -struct ImTextureRect -{ - unsigned short x, y; // Upper-left coordinates of rectangle to update - unsigned short w, h; // Size of rectangle to update (in pixels) -}; - -// Specs and pixel storage for a texture used by Dear ImGui. -// This is only useful for (1) core library and (2) backends. End-user/applications do not need to care about this. -// Renderer Backends will create a GPU-side version of this. -// Why does we store two identifiers: TexID and BackendUserData? -// - ImTextureID TexID = lower-level identifier stored in ImDrawCmd. ImDrawCmd can refer to textures not created by the backend, and for which there's no ImTextureData. -// - void* BackendUserData = higher-level opaque storage for backend own book-keeping. Some backends may have enough with TexID and not need both. - // In columns below: who reads/writes each fields? 'r'=read, 'w'=write, 'core'=main library, 'backend'=renderer backend -struct ImTextureData -{ - //------------------------------------------ core / backend --------------------------------------- - int UniqueID; // w - // Sequential index to facilitate identifying a texture when debugging/printing. Unique per atlas. - ImTextureStatus Status; // rw rw // ImTextureStatus_OK/_WantCreate/_WantUpdates/_WantDestroy. Always use SetStatus() to modify! - void* BackendUserData; // - rw // Convenience storage for backend. Some backends may have enough with TexID. - ImTextureID TexID; // r w // Backend-specific texture identifier. Always use SetTexID() to modify! The identifier will stored in ImDrawCmd::GetTexID() and passed to backend's RenderDrawData function. - ImTextureFormat Format; // w r // ImTextureFormat_RGBA32 (default) or ImTextureFormat_Alpha8 - int Width; // w r // Texture width - int Height; // w r // Texture height - int BytesPerPixel; // w r // 4 or 1 - unsigned char* Pixels; // w r // Pointer to buffer holding 'Width*Height' pixels and 'Width*Height*BytesPerPixels' bytes. - ImTextureRect UsedRect; // w r // Bounding box encompassing all past and queued Updates[]. - ImTextureRect UpdateRect; // w r // Bounding box encompassing all queued Updates[]. - ImVector Updates; // w r // Array of individual updates. - int UnusedFrames; // w r // In order to facilitate handling Status==WantDestroy in some backend: this is a count successive frames where the texture was not used. Always >0 when Status==WantDestroy. - unsigned short RefCount; // w r // Number of contexts using this texture. Used during backend shutdown. - bool UseColors; // w r // Tell whether our texture data is known to use colors (rather than just white + alpha). - bool WantDestroyNextFrame; // rw - // [Internal] Queued to set ImTextureStatus_WantDestroy next frame. May still be used in the current frame. - - // Functions - ImTextureData() { memset(this, 0, sizeof(*this)); TexID = ImTextureID_Invalid; } - ~ImTextureData() { DestroyPixels(); } - IMGUI_API void Create(ImTextureFormat format, int w, int h); - IMGUI_API void DestroyPixels(); - void* GetPixels() { IM_ASSERT(Pixels != NULL); return Pixels; } - void* GetPixelsAt(int x, int y) { IM_ASSERT(Pixels != NULL); return Pixels + (x + y * Width) * BytesPerPixel; } - int GetSizeInBytes() const { return Width * Height * BytesPerPixel; } - int GetPitch() const { return Width * BytesPerPixel; } - ImTextureRef GetTexRef() { ImTextureRef tex_ref; tex_ref._TexData = this; tex_ref._TexID = ImTextureID_Invalid; return tex_ref; } - ImTextureID GetTexID() const { return TexID; } - - // Called by Renderer backend - void SetTexID(ImTextureID tex_id) { TexID = tex_id; } // Call after creating or destroying the texture. Never modify TexID directly! - void SetStatus(ImTextureStatus status) { Status = status; } // Call after honoring a request. Never modify Status directly! -}; - -//----------------------------------------------------------------------------- -// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFontGlyphRangesBuilder, ImFont) -//----------------------------------------------------------------------------- - -// A font input/source (we may rename this to ImFontSource in the future) -struct ImFontConfig -{ - // Data Source - char Name[40]; // // Name (strictly to ease debugging, hence limited size buffer) - void* FontData; // // TTF/OTF data - int FontDataSize; // // TTF/OTF data size - bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself). - - // Options - bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. - bool PixelSnapH; // false // Align every glyph AdvanceX to pixel boundaries. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. - bool PixelSnapV; // true // Align Scaled GlyphOffset.y to pixel boundaries. - ImS8 OversampleH; // 0 (2) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1 or 2 depending on size. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. - ImS8 OversampleV; // 0 (1) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1. This is not really useful as we don't use sub-pixel positions on the Y axis. - ImWchar EllipsisChar; // 0 // Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. - float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). - const ImWchar* GlyphRanges; // NULL // *LEGACY* THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). - const ImWchar* GlyphExcludeRanges; // NULL // Pointer to a small user-provided list of Unicode ranges (2 value per range, values are inclusive, zero-terminated list). This is very close to GlyphRanges[] but designed to exclude ranges from a font source, when merging fonts with overlapping glyphs. Use "Input Glyphs Overlap Detection Tool" to find about your overlapping ranges. - //ImVec2 GlyphExtraSpacing; // 0, 0 // (REMOVED AT IT SEEMS LARGELY OBSOLETE. PLEASE REPORT IF YOU WERE USING THIS). Extra spacing (in pixels) between glyphs when rendered: essentially add to glyph->AdvanceX. Only X axis is supported for now. - ImVec2 GlyphOffset; // 0, 0 // Offset (in pixels) all glyphs from this font input. Absolute value for default size, other sizes will scale this value. - float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font. Absolute value for default size, other sizes will scale this value. - float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs - float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. // FIXME-NEWATLAS: Intentionally unscaled - ImU32 FontNo; // 0 // Index of font within TTF/OTF file - unsigned int FontLoaderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. - //unsigned int FontBuilderFlags; // -- // [Renamed in 1.92] Ue FontLoaderFlags. - float RasterizerMultiply; // 1.0f // Linearly brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. This is a silly thing we may remove in the future. - float RasterizerDensity; // 1.0f // [LEGACY: this only makes sense when ImGuiBackendFlags_RendererHasTextures is not supported] DPI scale multiplier for rasterization. Not altering other font metrics: makes it easy to swap between e.g. a 100% and a 400% fonts for a zooming display, or handle Retina screen. IMPORTANT: If you change this it is expected that you increase/decrease font scale roughly to the inverse of this, otherwise quality may look lowered. - - // [Internal] - ImFontFlags Flags; // Font flags (don't use just yet, will be exposed in upcoming 1.92.X updates) - ImFont* DstFont; // Target font (as we merging fonts, multiple ImFontConfig may target the same font) - const ImFontLoader* FontLoader; // Custom font backend for this source (default source is the one stored in ImFontAtlas) - void* FontLoaderData; // Font loader opaque storage (per font config) - - IMGUI_API ImFontConfig(); -}; - -// Hold rendering data for one glyph. -// (Note: some language parsers may fail to convert the bitfield members, in this case maybe drop store a single u32 or we can rework this) -struct ImFontGlyph -{ - unsigned int Colored : 1; // Flag to indicate glyph is colored and should generally ignore tinting (make it usable with no shift on little-endian as this is used in loops) - unsigned int Visible : 1; // Flag to indicate glyph has no visible pixels (e.g. space). Allow early out when rendering. - unsigned int SourceIdx : 4; // Index of source in parent font - unsigned int Codepoint : 26; // 0x0000..0x10FFFF - float AdvanceX; // Horizontal distance to advance cursor/layout position. - float X0, Y0, X1, Y1; // Glyph corners. Offsets from current cursor/layout position. - float U0, V0, U1, V1; // Texture coordinates for the current value of ImFontAtlas->TexRef. Cached equivalent of calling GetCustomRect() with PackId. - int PackId; // [Internal] ImFontAtlasRectId value (FIXME: Cold data, could be moved elsewhere?) - - ImFontGlyph() { memset(this, 0, sizeof(*this)); PackId = -1; } -}; - -// Helper to build glyph ranges from text/string data. Feed your application strings/characters to it then call BuildRanges(). -// This is essentially a tightly packed of vector of 64k booleans = 8KB storage. -struct ImFontGlyphRangesBuilder -{ - ImVector UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used) - - ImFontGlyphRangesBuilder() { Clear(); } - inline void Clear() { int size_in_bytes = (IM_UNICODE_CODEPOINT_MAX + 1) / 8; UsedChars.resize(size_in_bytes / (int)sizeof(ImU32)); memset(UsedChars.Data, 0, (size_t)size_in_bytes); } - inline bool GetBit(size_t n) const { int off = (int)(n >> 5); ImU32 mask = 1u << (n & 31); return (UsedChars[off] & mask) != 0; } // Get bit n in the array - inline void SetBit(size_t n) { int off = (int)(n >> 5); ImU32 mask = 1u << (n & 31); UsedChars[off] |= mask; } // Set bit n in the array - inline void AddChar(ImWchar c) { SetBit(c); } // Add character - IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added) - IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault()) to force add all of ASCII/Latin+Ext - IMGUI_API void BuildRanges(ImVector* out_ranges); // Output new ranges -}; - -// An opaque identifier to a rectangle in the atlas. -1 when invalid. -// The rectangle may move and UV may be invalidated, use GetCustomRect() to retrieve it. -typedef int ImFontAtlasRectId; -#define ImFontAtlasRectId_Invalid -1 - -// Output of ImFontAtlas::GetCustomRect() when using custom rectangles. -// Those values may not be cached/stored as they are only valid for the current value of atlas->TexRef -// (this is in theory derived from ImTextureRect but we use separate structures for reasons) -struct ImFontAtlasRect -{ - unsigned short x, y; // Position (in current texture) - unsigned short w, h; // Size - ImVec2 uv0, uv1; // UV coordinates (in current texture) - - ImFontAtlasRect() { memset(this, 0, sizeof(*this)); } -}; - -// Flags for ImFontAtlas build -enum ImFontAtlasFlags_ -{ - ImFontAtlasFlags_None = 0, - ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two - ImFontAtlasFlags_NoMouseCursors = 1 << 1, // Don't build software mouse cursors into the atlas (save a little texture memory) - ImFontAtlasFlags_NoBakedLines = 1 << 2, // Don't build thick line textures into the atlas (save a little texture memory, allow support for point/nearest filtering). The AntiAliasedLinesUseTex features uses them, otherwise they will be rendered using polygons (more expensive for CPU/GPU). -}; - -// Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: -// - One or more fonts. -// - Custom graphics data needed to render the shapes needed by Dear ImGui. -// - Mouse cursor shapes for software cursor rendering (unless setting 'Flags |= ImFontAtlasFlags_NoMouseCursors' in the font atlas). -// - If you don't call any AddFont*** functions, the default font embedded in the code will be loaded for you. -// It is the rendering backend responsibility to upload texture into your graphics API: -// - ImGui_ImplXXXX_RenderDrawData() functions generally iterate platform_io->Textures[] to create/update/destroy each ImTextureData instance. -// - Backend then set ImTextureData's TexID and BackendUserData. -// - Texture id are passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID/ImTextureRef for more details. -// Legacy path: -// - Call Build() + GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data. -// - Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture in a format natural to your graphics API. -// Common pitfalls: -// - If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the -// atlas is build (when calling GetTexData*** or Build()). We only copy the pointer, not the data. -// - Important: By default, AddFontFromMemoryTTF() takes ownership of the data. Even though we are not writing to it, we will free the pointer on destruction. -// You can set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed, -// - Even though many functions are suffixed with "TTF", OTF data is supported just as well. -// - This is an old API and it is currently awkward for those and various other reasons! We will address them in the future! -struct ImFontAtlas -{ - IMGUI_API ImFontAtlas(); - IMGUI_API ~ImFontAtlas(); - IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg); - IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL); - IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); - IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_data_size, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after destruction of the atlas. Set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed. - IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_data_size, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp. - IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter. - IMGUI_API void RemoveFont(ImFont* font); - - IMGUI_API void Clear(); // Clear everything (input fonts, output glyphs/textures) - IMGUI_API void CompactCache(); // Compact cached glyphs and texture. - IMGUI_API void SetFontLoader(const ImFontLoader* font_loader); // Change font loader at runtime. - - // As we are transitioning toward a new font system, we expect to obsolete those soon: - IMGUI_API void ClearInputData(); // [OBSOLETE] Clear input data (all ImFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used to build the texture and fonts. - IMGUI_API void ClearFonts(); // [OBSOLETE] Clear input+output font data (same as ClearInputData() + glyphs storage, UV coordinates). - IMGUI_API void ClearTexData(); // [OBSOLETE] Clear CPU-side copy of the texture data. Saves RAM once the texture has been copied to graphics memory. - -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - // Legacy path for build atlas + retrieving pixel data. - // - User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). - // - The pitch is always = Width * BytesPerPixels (1 or 4) - // - Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into - // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste. - // - From 1.92 with backends supporting ImGuiBackendFlags_RendererHasTextures: - // - Calling Build(), GetTexDataAsAlpha8(), GetTexDataAsRGBA32() is not needed. - // - In backend: replace calls to ImFontAtlas::SetTexID() with calls to ImTextureData::SetTexID() after honoring texture creation. - IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions. - IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel - IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel - void SetTexID(ImTextureID id) { IM_ASSERT(TexRef._TexID == ImTextureID_Invalid); TexRef._TexData->TexID = id; } // Called by legacy backends. May be called before texture creation. - void SetTexID(ImTextureRef id) { IM_ASSERT(TexRef._TexID == ImTextureID_Invalid && id._TexData == NULL); TexRef._TexData->TexID = id._TexID; } // Called by legacy backends. - bool IsBuilt() const { return Fonts.Size > 0 && TexIsBuilt; } // Bit ambiguous: used to detect when user didn't build texture but effectively we should check TexID != 0 except that would be backend dependent.. -#endif - - //------------------------------------------- - // Glyph Ranges - //------------------------------------------- - - // Since 1.92: specifying glyph ranges is only useful/necessary if your backend doesn't support ImGuiBackendFlags_RendererHasTextures! - IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list) - // NB: Make sure that your string are UTF-8 and NOT in your local code page. - // Read https://github.com/ocornut/imgui/blob/master/docs/FONTS.md/#about-utf-8-encoding for details. - // NB: Consider using ImFontGlyphRangesBuilder to build glyph ranges from textual data. - IMGUI_API const ImWchar* GetGlyphRangesGreek(); // Default + Greek and Coptic - IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters - IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 2999 Ideographs - IMGUI_API const ImWchar* GetGlyphRangesChineseFull(); // Default + Half-Width + Japanese Hiragana/Katakana + full set of about 21000 CJK Unified Ideographs - IMGUI_API const ImWchar* GetGlyphRangesChineseSimplifiedCommon();// Default + Half-Width + Japanese Hiragana/Katakana + set of 2500 CJK Unified Ideographs for common simplified Chinese - IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters - IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters - IMGUI_API const ImWchar* GetGlyphRangesVietnamese(); // Default + Vietnamese characters -#endif - - //------------------------------------------- - // [ALPHA] Custom Rectangles/Glyphs API - //------------------------------------------- - - // Register and retrieve custom rectangles - // - You can request arbitrary rectangles to be packed into the atlas, for your own purpose. - // - Since 1.92.X, packing is done immediately in the function call (previously packing was done during the Build call) - // - You can render your pixels into the texture right after calling the AddCustomRect() functions. - // - VERY IMPORTANT: - // - Texture may be created/resized at any time when calling ImGui or ImFontAtlas functions. - // - IT WILL INVALIDATE RECTANGLE DATA SUCH AS UV COORDINATES. Always use latest values from GetCustomRect(). - // - UV coordinates are associated to the current texture identifier aka 'atlas->TexRef'. Both TexRef and UV coordinates are typically changed at the same time. - // - If you render colored output into your custom rectangles: set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of preferred texture format. - // - Read docs/FONTS.md for more details about using colorful icons. - // - Note: this API may be reworked further in order to facilitate supporting e.g. multi-monitor, varying DPI settings. - // - (Pre-1.92 names) ------------> (1.92 names) - // - GetCustomRectByIndex() --> Use GetCustomRect() - // - CalcCustomRectUV() --> Use GetCustomRect() and read uv0, uv1 fields. - // - AddCustomRectRegular() --> Renamed to AddCustomRect() - // - AddCustomRectFontGlyph() --> Prefer using custom ImFontLoader inside ImFontConfig - // - ImFontAtlasCustomRect --> Renamed to ImFontAtlasRect - IMGUI_API ImFontAtlasRectId AddCustomRect(int width, int height, ImFontAtlasRect* out_r = NULL);// Register a rectangle. Return -1 (ImFontAtlasRectId_Invalid) on error. - IMGUI_API void RemoveCustomRect(ImFontAtlasRectId id); // Unregister a rectangle. Existing pixels will stay in texture until resized / garbage collected. - IMGUI_API bool GetCustomRect(ImFontAtlasRectId id, ImFontAtlasRect* out_r) const; // Get rectangle coordinates for current texture. Valid immediately, never store this (read above)! - - //------------------------------------------- - // Members - //------------------------------------------- - - // Input - ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_) - ImTextureFormat TexDesiredFormat; // Desired texture format (default to ImTextureFormat_RGBA32 but may be changed to ImTextureFormat_Alpha8). - int TexGlyphPadding; // FIXME: Should be called "TexPackPadding". Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false). - int TexMinWidth; // Minimum desired texture width. Must be a power of two. Default to 512. - int TexMinHeight; // Minimum desired texture height. Must be a power of two. Default to 128. - int TexMaxWidth; // Maximum desired texture width. Must be a power of two. Default to 8192. - int TexMaxHeight; // Maximum desired texture height. Must be a power of two. Default to 8192. - void* UserData; // Store your own atlas related user-data (if e.g. you have multiple font atlas). - - // Output - // - Because textures are dynamically created/resized, the current texture identifier may changed at *ANY TIME* during the frame. - // - This should not affect you as you can always use the latest value. But note that any precomputed UV coordinates are only valid for the current TexRef. -#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImTextureRef TexRef; // Latest texture identifier == TexData->GetTexRef(). -#else - union { ImTextureRef TexRef; ImTextureRef TexID; }; // Latest texture identifier == TexData->GetTexRef(). // RENAMED TexID to TexRef in 1.92.x -#endif - ImTextureData* TexData; // Latest texture. - - // [Internal] - ImVector TexList; // Texture list (most often TexList.Size == 1). TexData is always == TexList.back(). DO NOT USE DIRECTLY, USE GetDrawData().Textures[]/GetPlatformIO().Textures[] instead! - bool Locked; // Marked as locked during ImGui::NewFrame()..EndFrame() scope if TexUpdates are not supported. Any attempt to modify the atlas will assert. - bool RendererHasTextures;// Copy of (BackendFlags & ImGuiBackendFlags_RendererHasTextures) from supporting context. - bool TexIsBuilt; // Set when texture was built matching current font input. Mostly useful for legacy IsBuilt() call. - bool TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format or conversion process. - ImVec2 TexUvScale; // = (1.0f/TexData->TexWidth, 1.0f/TexData->TexHeight). May change as new texture gets created. - ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel. May change as new texture gets created. - ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. - ImVector Sources; // Source/configuration data - ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines - int TexNextUniqueID; // Next value to be stored in TexData->UniqueID - int FontNextUniqueID; // Next value to be stored in ImFont->FontID - ImVector DrawListSharedDatas; // List of users for this atlas. Typically one per Dear ImGui context. - ImFontAtlasBuilder* Builder; // Opaque interface to our data that doesn't need to be public and may be discarded when rebuilding. - const ImFontLoader* FontLoader; // Font loader opaque interface (default to use FreeType when IMGUI_ENABLE_FREETYPE is defined, otherwise default to use stb_truetype). Use SetFontLoader() to change this at runtime. - const char* FontLoaderName; // Font loader name (for display e.g. in About box) == FontLoader->Name - void* FontLoaderData; // Font backend opaque storage - unsigned int FontLoaderFlags; // Shared flags (for all fonts) for font loader. THIS IS BUILD IMPLEMENTATION DEPENDENT (e.g. Per-font override is also available in ImFontConfig). - int RefCount; // Number of contexts using this atlas - ImGuiContext* OwnerContext; // Context which own the atlas will be in charge of updating and destroying it. - - // [Obsolete] -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - // Legacy: You can request your rectangles to be mapped as font glyph (given a font + Unicode point), so you can render e.g. custom colorful icons and use them as regular glyphs. --> Prefer using a custom ImFontLoader. - ImFontAtlasRect TempRect; // For old GetCustomRectByIndex() API - inline ImFontAtlasRectId AddCustomRectRegular(int w, int h) { return AddCustomRect(w, h); } // RENAMED in 1.92.X - inline const ImFontAtlasRect* GetCustomRectByIndex(ImFontAtlasRectId id) { return GetCustomRect(id, &TempRect) ? &TempRect : NULL; } // OBSOLETED in 1.92.X - inline void CalcCustomRectUV(const ImFontAtlasRect* r, ImVec2* out_uv_min, ImVec2* out_uv_max) const { *out_uv_min = r->uv0; *out_uv_max = r->uv1; } // OBSOLETED in 1.92.X - IMGUI_API ImFontAtlasRectId AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // OBSOLETED in 1.92.X: Use custom ImFontLoader in ImFontConfig - IMGUI_API ImFontAtlasRectId AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // ADDED AND OBSOLETED in 1.92.X -#endif - //unsigned int FontBuilderFlags; // OBSOLETED in 1.92.X: Renamed to FontLoaderFlags. - //int TexDesiredWidth; // OBSOLETED in 1.92.X: Force texture width before calling Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height) - //typedef ImFontAtlasRect ImFontAtlasCustomRect; // OBSOLETED in 1.92.X - //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ - //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ -}; - -// Font runtime data for a given size -// Important: pointers to ImFontBaked are only valid for the current frame. -struct ImFontBaked -{ - // [Internal] Members: Hot ~20/24 bytes (for CalcTextSize) - ImVector IndexAdvanceX; // 12-16 // out // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this info, and are often bottleneck in large UI). - float FallbackAdvanceX; // 4 // out // FindGlyph(FallbackChar)->AdvanceX - float Size; // 4 // in // Height of characters/line, set during loading (doesn't change after loading) - float RasterizerDensity; // 4 // in // Density this is baked at - - // [Internal] Members: Hot ~28/36 bytes (for RenderText loop) - ImVector IndexLookup; // 12-16 // out // Sparse. Index glyphs by Unicode code-point. - ImVector Glyphs; // 12-16 // out // All glyphs. - int FallbackGlyphIndex; // 4 // out // Index of FontFallbackChar - - // [Internal] Members: Cold - float Ascent, Descent; // 4+4 // out // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) - unsigned int MetricsTotalSurface:26;// 3 // out // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) - unsigned int WantDestroy:1; // 0 // // Queued for destroy - unsigned int LockLoadingFallback:1; // 0 // // - int LastUsedFrame; // 4 // // Record of that time this was bounds - ImGuiID BakedId; // 4 // - ImFont* ContainerFont; // 4-8 // in // Parent font - void* FontLoaderDatas; // 4-8 // // Font loader opaque storage (per baked font * sources): single contiguous buffer allocated by imgui, passed to loader. - - // Functions - IMGUI_API ImFontBaked(); - IMGUI_API void ClearOutputData(); - IMGUI_API ImFontGlyph* FindGlyph(ImWchar c); // Return U+FFFD glyph if requested glyph doesn't exists. - IMGUI_API ImFontGlyph* FindGlyphNoFallback(ImWchar c); // Return NULL if glyph doesn't exist - IMGUI_API float GetCharAdvance(ImWchar c); - IMGUI_API bool IsGlyphLoaded(ImWchar c); -}; - -// Font flags -// (in future versions as we redesign font loading API, this will become more important and better documented. for now please consider this as internal/advanced use) -enum ImFontFlags_ -{ - ImFontFlags_None = 0, - ImFontFlags_NoLoadError = 1 << 1, // Disable throwing an error/assert when calling AddFontXXX() with missing file/data. Calling code is expected to check AddFontXXX() return value. - ImFontFlags_NoLoadGlyphs = 1 << 2, // [Internal] Disable loading new glyphs. - ImFontFlags_LockBakedSizes = 1 << 3, // [Internal] Disable loading new baked sizes, disable garbage collecting current ones. e.g. if you want to lock a font to a single size. Important: if you use this to preload given sizes, consider the possibility of multiple font density used on Retina display. -}; - -// Font runtime data and rendering -// - ImFontAtlas automatically loads a default embedded font for you if you didn't load one manually. -// - Since 1.92.X a font may be rendered as any size! Therefore a font doesn't have one specific size. -// - Use 'font->GetFontBaked(size)' to retrieve the ImFontBaked* corresponding to a given size. -// - If you used g.Font + g.FontSize (which is frequent from the ImGui layer), you can use g.FontBaked as a shortcut, as g.FontBaked == g.Font->GetFontBaked(g.FontSize). -struct ImFont -{ - // [Internal] Members: Hot ~12-20 bytes - ImFontBaked* LastBaked; // 4-8 // Cache last bound baked. NEVER USE DIRECTLY. Use GetFontBaked(). - ImFontAtlas* ContainerAtlas; // 4-8 // What we have been loaded into. - ImFontFlags Flags; // 4 // Font flags. - float CurrentRasterizerDensity; // Current rasterizer density. This is a varying state of the font. - - // [Internal] Members: Cold ~24-52 bytes - // Conceptually Sources[] is the list of font sources merged to create this font. - ImGuiID FontId; // Unique identifier for the font - float LegacySize; // 4 // in // Font size passed to AddFont(). Use for old code calling PushFont() expecting to use that size. (use ImGui::GetFontBaked() to get font baked at current bound size). - ImVector Sources; // 16 // in // List of sources. Pointers within ContainerAtlas->Sources[] - ImWchar EllipsisChar; // 2-4 // out // Character used for ellipsis rendering ('...'). - ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') - ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 16 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. - bool EllipsisAutoBake; // 1 // // Mark when the "..." glyph needs to be generated. - ImGuiStorage RemapPairs; // 16 // // Remapping pairs when using AddRemapChar(), otherwise empty. -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - float Scale; // 4 // in // Legacy base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() -#endif - - // Methods - IMGUI_API ImFont(); - IMGUI_API ~ImFont(); - IMGUI_API bool IsGlyphInFont(ImWchar c); - bool IsLoaded() const { return ContainerAtlas != NULL; } - const char* GetDebugName() const { return Sources.Size ? Sources[0]->Name : ""; } // Fill ImFontConfig::Name. - - // [Internal] Don't use! - // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. - // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable. - IMGUI_API ImFontBaked* GetFontBaked(float font_size, float density = -1.0f); // Get or create baked data for given size - IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL); // utf8 - IMGUI_API const char* CalcWordWrapPosition(float size, const char* text, const char* text_end, float wrap_width); - IMGUI_API void RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c, const ImVec4* cpu_fine_clip = NULL); - IMGUI_API void RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false); -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - inline const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) { return CalcWordWrapPosition(LegacySize * scale, text, text_end, wrap_width); } -#endif - - // [Internal] Don't use! - IMGUI_API void ClearOutputData(); - IMGUI_API void AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint); // Makes 'from_codepoint' character points to 'to_codepoint' glyph. - IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last); -}; - -// This is provided for consistency (but we don't actually use this) -inline ImTextureID ImTextureRef::GetTexID() const -{ - IM_ASSERT(!(_TexData != NULL && _TexID != ImTextureID_Invalid)); - return _TexData ? _TexData->TexID : _TexID; -} - -// Using an indirection to avoid patching ImDrawCmd after a SetTexID() call (but this could be an alternative solution too) -inline ImTextureID ImDrawCmd::GetTexID() const -{ - // If you are getting this assert: A renderer backend with support for ImGuiBackendFlags_RendererHasTextures (1.92) - // must iterate and handle ImTextureData requests stored in ImDrawData::Textures[]. - ImTextureID tex_id = TexRef._TexData ? TexRef._TexData->TexID : TexRef._TexID; // == TexRef.GetTexID() above. - if (TexRef._TexData != NULL) - IM_ASSERT(tex_id != ImTextureID_Invalid && "ImDrawCmd is referring to ImTextureData that wasn't uploaded to graphics system. Backend must call ImTextureData::SetTexID() after handling ImTextureStatus_WantCreate request!"); - return tex_id; -} - -//----------------------------------------------------------------------------- -// [SECTION] Viewports -//----------------------------------------------------------------------------- - -// Flags stored in ImGuiViewport::Flags, giving indications to the platform backends. -enum ImGuiViewportFlags_ -{ - ImGuiViewportFlags_None = 0, - ImGuiViewportFlags_IsPlatformWindow = 1 << 0, // Represent a Platform Window - ImGuiViewportFlags_IsPlatformMonitor = 1 << 1, // Represent a Platform Monitor (unused yet) - ImGuiViewportFlags_OwnedByApp = 1 << 2, // Platform Window: Is created/managed by the application (rather than a dear imgui backend) -}; - -// - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows. -// - In 'docking' branch with multi-viewport enabled, we extend this concept to have multiple active viewports. -// - In the future we will extend this concept further to also represent Platform Monitor and support a "no main platform window" operation mode. -// - About Main Area vs Work Area: -// - Main Area = entire viewport. -// - Work Area = entire viewport minus sections used by main menu bars (for platform windows), or by task bar (for platform monitor). -// - Windows are generally trying to stay within the Work Area of their host viewport. -struct ImGuiViewport -{ - ImGuiID ID; // Unique identifier for the viewport - ImGuiViewportFlags Flags; // See ImGuiViewportFlags_ - ImVec2 Pos; // Main Area: Position of the viewport (Dear ImGui coordinates are the same as OS desktop/native coordinates) - ImVec2 Size; // Main Area: Size of the viewport. - ImVec2 FramebufferScale; // Density of the viewport for Retina display (always 1,1 on Windows, may be 2,2 etc on macOS/iOS). This will affect font rasterizer density. - ImVec2 WorkPos; // Work Area: Position of the viewport minus task bars, menus bars, status bars (>= Pos) - ImVec2 WorkSize; // Work Area: Size of the viewport minus task bars, menu bars, status bars (<= Size) - - // Platform/Backend Dependent Data - void* PlatformHandle; // void* to hold higher-level, platform window handle (e.g. HWND, GLFWWindow*, SDL_Window*) - void* PlatformHandleRaw; // void* to hold lower-level, platform-native window handle (under Win32 this is expected to be a HWND, unused for other platforms) - - ImGuiViewport() { memset(this, 0, sizeof(*this)); } - - // Helpers - ImVec2 GetCenter() const { return ImVec2(Pos.x + Size.x * 0.5f, Pos.y + Size.y * 0.5f); } - ImVec2 GetWorkCenter() const { return ImVec2(WorkPos.x + WorkSize.x * 0.5f, WorkPos.y + WorkSize.y * 0.5f); } -}; - -//----------------------------------------------------------------------------- -// [SECTION] Platform Dependent Interfaces -//----------------------------------------------------------------------------- - -// Access via ImGui::GetPlatformIO() -struct ImGuiPlatformIO -{ - IMGUI_API ImGuiPlatformIO(); - - //------------------------------------------------------------------ - // Input - Interface with OS and Platform backend (most common stuff) - //------------------------------------------------------------------ - - // Optional: Access OS clipboard - // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) - const char* (*Platform_GetClipboardTextFn)(ImGuiContext* ctx); - void (*Platform_SetClipboardTextFn)(ImGuiContext* ctx, const char* text); - void* Platform_ClipboardUserData; - - // Optional: Open link/folder/file in OS Shell - // (default to use ShellExecuteW() on Windows, system() on Linux/Mac) - bool (*Platform_OpenInShellFn)(ImGuiContext* ctx, const char* path); - void* Platform_OpenInShellUserData; - - // Optional: Notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME on Windows) - // (default to use native imm32 api on Windows) - void (*Platform_SetImeDataFn)(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); - void* Platform_ImeUserData; - //void (*SetPlatformImeDataFn)(ImGuiViewport* viewport, ImGuiPlatformImeData* data); // [Renamed to platform_io.PlatformSetImeDataFn in 1.91.1] - - // Optional: Platform locale - // [Experimental] Configure decimal point e.g. '.' or ',' useful for some languages (e.g. German), generally pulled from *localeconv()->decimal_point - ImWchar Platform_LocaleDecimalPoint; // '.' - - //------------------------------------------------------------------ - // Input - Interface with Renderer Backend - //------------------------------------------------------------------ - - // Optional: Maximum texture size supported by renderer (used to adjust how we size textures). 0 if not known. - int Renderer_TextureMaxWidth; - int Renderer_TextureMaxHeight; - - // Written by some backends during ImGui_ImplXXXX_RenderDrawData() call to point backend_specific ImGui_ImplXXXX_RenderState* structure. - void* Renderer_RenderState; - - //------------------------------------------------------------------ - // Output - //------------------------------------------------------------------ - - // Textures list (the list is updated by calling ImGui::EndFrame or ImGui::Render) - // The ImGui_ImplXXXX_RenderDrawData() function of each backend generally access this via ImDrawData::Textures which points to this. The array is available here mostly because backends will want to destroy textures on shutdown. - ImVector Textures; // List of textures used by Dear ImGui (most often 1) + contents of external texture list is automatically appended into this. -}; - -// (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function. Handler is called during EndFrame(). -struct ImGuiPlatformImeData -{ - bool WantVisible; // A widget wants the IME to be visible. - bool WantTextInput; // A widget wants text input, not necessarily IME to be visible. This is automatically set to the upcoming value of io.WantTextInput. - ImVec2 InputPos; // Position of input cursor (for IME). - float InputLineHeight; // Line height (for IME). - ImGuiID ViewportId; // ID of platform window/viewport. - - ImGuiPlatformImeData() { memset(this, 0, sizeof(*this)); } -}; - -//----------------------------------------------------------------------------- -// [SECTION] Obsolete functions and types -// (Will be removed! Read 'API BREAKING CHANGES' section in imgui.cpp for details) -// Please keep your copy of dear imgui up to date! Occasionally set '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in imconfig.h to stay ahead. -//----------------------------------------------------------------------------- - -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -namespace ImGui -{ - // OBSOLETED in 1.92.0 (from June 2025) - static inline void PushFont(ImFont* font) { PushFont(font, font ? font->LegacySize : 0.0f); } - IMGUI_API void SetWindowFontScale(float scale); // Set font scale factor for current window. Prefer using PushFont(NULL, style.FontSizeBase * factor) or use style.FontScaleMain to scale all windows. - // OBSOLETED in 1.91.9 (from February 2025) - IMGUI_API void Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col); // <-- 'border_col' was removed in favor of ImGuiCol_ImageBorder. If you use 'tint_col', use ImageWithBg() instead. - // OBSOLETED in 1.91.0 (from July 2024) - static inline void PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } - static inline void PopButtonRepeat() { PopItemFlag(); } - static inline void PushTabStop(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } - static inline void PopTabStop() { PopItemFlag(); } - IMGUI_API ImVec2 GetContentRegionMax(); // Content boundaries max (e.g. window boundaries including scrolling, or current column boundaries). You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! - IMGUI_API ImVec2 GetWindowContentRegionMin(); // Content boundaries min for the window (roughly (0,0)-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! - IMGUI_API ImVec2 GetWindowContentRegionMax(); // Content boundaries max for the window (roughly (0,0)+Size-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! - // OBSOLETED in 1.90.0 (from September 2023) - static inline bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags window_flags = 0) { return BeginChild(id, size, ImGuiChildFlags_FrameStyle, window_flags); } - static inline void EndChildFrame() { EndChild(); } - //static inline bool BeginChild(const char* str_id, const ImVec2& size_arg, bool borders, ImGuiWindowFlags window_flags){ return BeginChild(str_id, size_arg, borders ? ImGuiChildFlags_Borders : ImGuiChildFlags_None, window_flags); } // Unnecessary as true == ImGuiChildFlags_Borders - //static inline bool BeginChild(ImGuiID id, const ImVec2& size_arg, bool borders, ImGuiWindowFlags window_flags) { return BeginChild(id, size_arg, borders ? ImGuiChildFlags_Borders : ImGuiChildFlags_None, window_flags); } // Unnecessary as true == ImGuiChildFlags_Borders - static inline void ShowStackToolWindow(bool* p_open = NULL) { ShowIDStackToolWindow(p_open); } - IMGUI_API bool Combo(const char* label, int* current_item, bool (*old_callback)(void* user_data, int idx, const char** out_text), void* user_data, int items_count, int popup_max_height_in_items = -1); - IMGUI_API bool ListBox(const char* label, int* current_item, bool (*old_callback)(void* user_data, int idx, const char** out_text), void* user_data, int items_count, int height_in_items = -1); - // OBSOLETED in 1.89.7 (from June 2023) - IMGUI_API void SetItemAllowOverlap(); // Use SetNextItemAllowOverlap() before item. - - // Some of the older obsolete names along with their replacement (commented out so they are not reported in IDE) - //-- OBSOLETED in 1.89.4 (from March 2023) - //static inline void PushAllowKeyboardFocus(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } - //static inline void PopAllowKeyboardFocus() { PopItemFlag(); } - //-- OBSOLETED in 1.89 (from August 2022) - //IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); // --> Use new ImageButton() signature (explicit item id, regular FramePadding). Refer to code in 1.91 if you want to grab a copy of this version. - //-- OBSOLETED in 1.88 (from May 2022) - //static inline void CaptureKeyboardFromApp(bool want_capture_keyboard = true) { SetNextFrameWantCaptureKeyboard(want_capture_keyboard); } // Renamed as name was misleading + removed default value. - //static inline void CaptureMouseFromApp(bool want_capture_mouse = true) { SetNextFrameWantCaptureMouse(want_capture_mouse); } // Renamed as name was misleading + removed default value. - //-- OBSOLETED in 1.87 (from February 2022, more formally obsoleted April 2024) - //IMGUI_API ImGuiKey GetKeyIndex(ImGuiKey key); { IM_ASSERT(key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END); const ImGuiKeyData* key_data = GetKeyData(key); return (ImGuiKey)(key_data - g.IO.KeysData); } // Map ImGuiKey_* values into legacy native key index. == io.KeyMap[key]. When using a 1.87+ backend using io.AddKeyEvent(), calling GetKeyIndex() with ANY ImGuiKey_XXXX values will return the same value! - //static inline ImGuiKey GetKeyIndex(ImGuiKey key) { IM_ASSERT(key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END); return key; } - //-- OBSOLETED in 1.86 (from November 2021) - //IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // Code removed, see 1.90 for last version of the code. Calculate range of visible items for large list of evenly sized items. Prefer using ImGuiListClipper. - //-- OBSOLETED in 1.85 (from August 2021) - //static inline float GetWindowContentRegionWidth() { return GetWindowContentRegionMax().x - GetWindowContentRegionMin().x; } - //-- OBSOLETED in 1.81 (from February 2021) - //static inline bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0, 0)) { return BeginListBox(label, size); } - //static inline bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1) { float height = GetTextLineHeightWithSpacing() * ((height_in_items < 0 ? ImMin(items_count, 7) : height_in_items) + 0.25f) + GetStyle().FramePadding.y * 2.0f; return BeginListBox(label, ImVec2(0.0f, height)); } // Helper to calculate size from items_count and height_in_items - //static inline void ListBoxFooter() { EndListBox(); } - //-- OBSOLETED in 1.79 (from August 2020) - //static inline void OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mb = 1) { OpenPopupOnItemClick(str_id, mb); } // Bool return value removed. Use IsWindowAppearing() in BeginPopup() instead. Renamed in 1.77, renamed back in 1.79. Sorry! - //-- OBSOLETED in 1.78 (from June 2020): Old drag/sliders functions that took a 'float power > 1.0f' argument instead of ImGuiSliderFlags_Logarithmic. See github.com/ocornut/imgui/issues/3361 for details. - //IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power = 1.0f) // OBSOLETED in 1.78 (from June 2020) - //IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power = 1.0f); // OBSOLETED in 1.78 (from June 2020) - //IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power = 1.0f); // OBSOLETED in 1.78 (from June 2020) - //IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format, float power = 1.0f); // OBSOLETED in 1.78 (from June 2020) - //static inline bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) - //static inline bool DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) - //static inline bool DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) - //static inline bool DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) - //static inline bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) - //static inline bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) - //static inline bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) - //static inline bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) - //-- OBSOLETED in 1.77 and before - //static inline bool BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mb, bool over_items) { return BeginPopupContextWindow(str_id, mb | (over_items ? 0 : ImGuiPopupFlags_NoOpenOverItems)); } // OBSOLETED in 1.77 (from June 2020) - //static inline void TreeAdvanceToLabelPos() { SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()); } // OBSOLETED in 1.72 (from July 2019) - //static inline void SetNextTreeNodeOpen(bool open, ImGuiCond cond = 0) { SetNextItemOpen(open, cond); } // OBSOLETED in 1.71 (from June 2019) - //static inline float GetContentRegionAvailWidth() { return GetContentRegionAvail().x; } // OBSOLETED in 1.70 (from May 2019) - //static inline ImDrawList* GetOverlayDrawList() { return GetForegroundDrawList(); } // OBSOLETED in 1.69 (from Mar 2019) - //static inline void SetScrollHere(float ratio = 0.5f) { SetScrollHereY(ratio); } // OBSOLETED in 1.66 (from Nov 2018) - //static inline bool IsItemDeactivatedAfterChange() { return IsItemDeactivatedAfterEdit(); } // OBSOLETED in 1.63 (from Aug 2018) - //-- OBSOLETED in 1.60 and before - //static inline bool IsAnyWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_AnyWindow); } // OBSOLETED in 1.60 (from Apr 2018) - //static inline bool IsAnyWindowHovered() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } // OBSOLETED in 1.60 (between Dec 2017 and Apr 2018) - //static inline void ShowTestWindow() { return ShowDemoWindow(); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) - //static inline bool IsRootWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootWindow); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) - //static inline bool IsRootWindowOrAnyChildFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) - //static inline void SetNextWindowContentWidth(float w) { SetNextWindowContentSize(ImVec2(w, 0.0f)); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) - //static inline float GetItemsLineHeightWithSpacing() { return GetFrameHeightWithSpacing(); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) - //IMGUI_API bool Begin(char* name, bool* p_open, ImVec2 size_first_use, float bg_alpha = -1.0f, ImGuiWindowFlags flags=0); // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017): Equivalent of using SetNextWindowSize(size, ImGuiCond_FirstUseEver) and SetNextWindowBgAlpha(). - //static inline bool IsRootWindowOrAnyChildHovered() { return IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows); } // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017) - //static inline void AlignFirstTextHeightToWidgets() { AlignTextToFramePadding(); } // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017) - //static inline void SetNextWindowPosCenter(ImGuiCond c=0) { SetNextWindowPos(GetMainViewport()->GetCenter(), c, ImVec2(0.5f,0.5f)); } // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017) - //static inline bool IsItemHoveredRect() { return IsItemHovered(ImGuiHoveredFlags_RectOnly); } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017) - //static inline bool IsPosHoveringAnyWindow(const ImVec2&) { IM_ASSERT(0); return false; } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017): This was misleading and partly broken. You probably want to use the io.WantCaptureMouse flag instead. - //static inline bool IsMouseHoveringAnyWindow() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017) - //static inline bool IsMouseHoveringWindow() { return IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017) - //-- OBSOLETED in 1.50 and before - //static inline bool CollapsingHeader(char* label, const char* str_id, bool framed = true, bool default_open = false) { return CollapsingHeader(label, (default_open ? (1 << 5) : 0)); } // OBSOLETED in 1.49 - //static inline ImFont*GetWindowFont() { return GetFont(); } // OBSOLETED in 1.48 - //static inline float GetWindowFontSize() { return GetFontSize(); } // OBSOLETED in 1.48 - //static inline void SetScrollPosHere() { SetScrollHere(); } // OBSOLETED in 1.42 -} - -//-- OBSOLETED in 1.92.x: ImFontAtlasCustomRect becomes ImTextureRect -// - ImFontAtlasCustomRect::X,Y --> ImTextureRect::x,y -// - ImFontAtlasCustomRect::Width,Height --> ImTextureRect::w,h -// - ImFontAtlasCustomRect::GlyphColored --> if you need to write to this, instead you can write to 'font->Glyphs.back()->Colored' after calling AddCustomRectFontGlyph() -// We could make ImTextureRect an union to use old names, but 1) this would be confusing 2) the fix is easy 3) ImFontAtlasCustomRect was always a rather esoteric api. -typedef ImFontAtlasRect ImFontAtlasCustomRect; -/*struct ImFontAtlasCustomRect -{ - unsigned short X, Y; // Output // Packed position in Atlas - unsigned short Width, Height; // Input // [Internal] Desired rectangle dimension - unsigned int GlyphID:31; // Input // [Internal] For custom font glyphs only (ID < 0x110000) - unsigned int GlyphColored:1; // Input // [Internal] For custom font glyphs only: glyph is colored, removed tinting. - float GlyphAdvanceX; // Input // [Internal] For custom font glyphs only: glyph xadvance - ImVec2 GlyphOffset; // Input // [Internal] For custom font glyphs only: glyph display offset - ImFont* Font; // Input // [Internal] For custom font glyphs only: target font - ImFontAtlasCustomRect() { X = Y = 0xFFFF; Width = Height = 0; GlyphID = 0; GlyphColored = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0, 0); Font = NULL; } - bool IsPacked() const { return X != 0xFFFF; } -};*/ - -//-- OBSOLETED in 1.82 (from Mars 2021): flags for AddRect(), AddRectFilled(), AddImageRounded(), PathRect() -//typedef ImDrawFlags ImDrawCornerFlags; -//enum ImDrawCornerFlags_ -//{ -// ImDrawCornerFlags_None = ImDrawFlags_RoundCornersNone, // Was == 0 prior to 1.82, this is now == ImDrawFlags_RoundCornersNone which is != 0 and not implicit -// ImDrawCornerFlags_TopLeft = ImDrawFlags_RoundCornersTopLeft, // Was == 0x01 (1 << 0) prior to 1.82. Order matches ImDrawFlags_NoRoundCorner* flag (we exploit this internally). -// ImDrawCornerFlags_TopRight = ImDrawFlags_RoundCornersTopRight, // Was == 0x02 (1 << 1) prior to 1.82. -// ImDrawCornerFlags_BotLeft = ImDrawFlags_RoundCornersBottomLeft, // Was == 0x04 (1 << 2) prior to 1.82. -// ImDrawCornerFlags_BotRight = ImDrawFlags_RoundCornersBottomRight, // Was == 0x08 (1 << 3) prior to 1.82. -// ImDrawCornerFlags_All = ImDrawFlags_RoundCornersAll, // Was == 0x0F prior to 1.82 -// ImDrawCornerFlags_Top = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_TopRight, -// ImDrawCornerFlags_Bot = ImDrawCornerFlags_BotLeft | ImDrawCornerFlags_BotRight, -// ImDrawCornerFlags_Left = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotLeft, -// ImDrawCornerFlags_Right = ImDrawCornerFlags_TopRight | ImDrawCornerFlags_BotRight, -//}; - -// RENAMED and MERGED both ImGuiKey_ModXXX and ImGuiModFlags_XXX into ImGuiMod_XXX (from September 2022) -// RENAMED ImGuiKeyModFlags -> ImGuiModFlags in 1.88 (from April 2022). Exceptionally commented out ahead of obscolescence schedule to reduce confusion and because they were not meant to be used in the first place. -//typedef ImGuiKeyChord ImGuiModFlags; // == int. We generally use ImGuiKeyChord to mean "a ImGuiKey or-ed with any number of ImGuiMod_XXX value", so you may store mods in there. -//enum ImGuiModFlags_ { ImGuiModFlags_None = 0, ImGuiModFlags_Ctrl = ImGuiMod_Ctrl, ImGuiModFlags_Shift = ImGuiMod_Shift, ImGuiModFlags_Alt = ImGuiMod_Alt, ImGuiModFlags_Super = ImGuiMod_Super }; -//typedef ImGuiKeyChord ImGuiKeyModFlags; // == int -//enum ImGuiKeyModFlags_ { ImGuiKeyModFlags_None = 0, ImGuiKeyModFlags_Ctrl = ImGuiMod_Ctrl, ImGuiKeyModFlags_Shift = ImGuiMod_Shift, ImGuiKeyModFlags_Alt = ImGuiMod_Alt, ImGuiKeyModFlags_Super = ImGuiMod_Super }; - -#define IM_OFFSETOF(_TYPE,_MEMBER) offsetof(_TYPE, _MEMBER) // OBSOLETED IN 1.90 (now using C++11 standard version) - -#endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - -// RENAMED IMGUI_DISABLE_METRICS_WINDOW > IMGUI_DISABLE_DEBUG_TOOLS in 1.88 (from June 2022) -#ifdef IMGUI_DISABLE_METRICS_WINDOW -#error IMGUI_DISABLE_METRICS_WINDOW was renamed to IMGUI_DISABLE_DEBUG_TOOLS, please use new name. -#endif - -//----------------------------------------------------------------------------- - -#if defined(__clang__) -#pragma clang diagnostic pop -#elif defined(__GNUC__) -#pragma GCC diagnostic pop -#endif - -#ifdef _MSC_VER -#pragma warning (pop) -#endif - -// Include imgui_user.h at the end of imgui.h -// May be convenient for some users to only explicitly include vanilla imgui.h and have extra stuff included. -#ifdef IMGUI_INCLUDE_IMGUI_USER_H -#ifdef IMGUI_USER_H_FILENAME -#include IMGUI_USER_H_FILENAME -#else -#include "imgui_user.h" -#endif -#endif - -#endif // #ifndef IMGUI_DISABLE diff --git a/include/imgui/imgui_impl_raylib.h b/include/imgui/imgui_impl_raylib.h deleted file mode 100644 index da38375..0000000 --- a/include/imgui/imgui_impl_raylib.h +++ /dev/null @@ -1,53 +0,0 @@ -/********************************************************************************************** -* -* raylibExtras * Utilities and Shared Components for Raylib -* -* rlImGui * basic ImGui integration -* -* LICENSE: ZLIB -* -* Copyright (c) 2024 Jeffery Myers -* -* Permission is hereby granted, free of charge, to any person obtaining a copy -* of this software and associated documentation files (the "Software"), to deal -* in the Software without restriction, including without limitation the rights -* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -* copies of the Software, and to permit persons to whom the Software is -* furnished to do so, subject to the following conditions: -* -* The above copyright notice and this permission notice shall be included in all -* copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -* SOFTWARE. -* -**********************************************************************************************/ - -// dear imgui: Platform Backend for Raylib -// (Info: Raylib is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc. using OpenGL) -// This is is the low level ImGui backend for raylib, a higher level API that matches the raylib API can be found in rlImGui.h - -// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. -// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. -// Learn about Dear ImGui: -// - FAQ https://dearimgui.com/faq -// - Getting Started https://dearimgui.com/getting-started -// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). -// - Introduction, links and more at the top of imgui.cpp - -#pragma once -#include "imgui.h" // IMGUI_IMPL_API -#ifndef IMGUI_DISABLE - -IMGUI_IMPL_API bool ImGui_ImplRaylib_Init(void); -IMGUI_IMPL_API void ImGui_ImplRaylib_Shutdown(void); -IMGUI_IMPL_API void ImGui_ImplRaylib_NewFrame(void); -IMGUI_IMPL_API void ImGui_ImplRaylib_RenderDrawData(ImDrawData* draw_data); -IMGUI_IMPL_API bool ImGui_ImplRaylib_ProcessEvents(void); - -#endif // #ifndef IMGUI_DISABLE diff --git a/include/imgui/imgui_internal.h b/include/imgui/imgui_internal.h deleted file mode 100644 index ccb979b..0000000 --- a/include/imgui/imgui_internal.h +++ /dev/null @@ -1,3906 +0,0 @@ -// dear imgui, v1.92.1 -// (internal structures/api) - -// You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. - -/* - -Index of this file: - -// [SECTION] Header mess -// [SECTION] Forward declarations -// [SECTION] Context pointer -// [SECTION] STB libraries includes -// [SECTION] Macros -// [SECTION] Generic helpers -// [SECTION] ImDrawList support -// [SECTION] Style support -// [SECTION] Data types support -// [SECTION] Widgets support: flags, enums, data structures -// [SECTION] Popup support -// [SECTION] Inputs support -// [SECTION] Clipper support -// [SECTION] Navigation support -// [SECTION] Typing-select support -// [SECTION] Columns support -// [SECTION] Box-select support -// [SECTION] Multi-select support -// [SECTION] Docking support -// [SECTION] Viewport support -// [SECTION] Settings support -// [SECTION] Localization support -// [SECTION] Error handling, State recovery support -// [SECTION] Metrics, Debug tools -// [SECTION] Generic context hooks -// [SECTION] ImGuiContext (main imgui context) -// [SECTION] ImGuiWindowTempData, ImGuiWindow -// [SECTION] Tab bar, Tab item support -// [SECTION] Table support -// [SECTION] ImGui internal API -// [SECTION] ImFontLoader -// [SECTION] ImFontAtlas internal API -// [SECTION] Test Engine specific hooks (imgui_test_engine) - -*/ - -#pragma once -#ifndef IMGUI_DISABLE - -//----------------------------------------------------------------------------- -// [SECTION] Header mess -//----------------------------------------------------------------------------- - -#ifndef IMGUI_VERSION -#include "imgui.h" -#endif - -#include // FILE*, sscanf -#include // NULL, malloc, free, qsort, atoi, atof -#include // sqrtf, fabsf, fmodf, powf, floorf, ceilf, cosf, sinf -#include // INT_MIN, INT_MAX - -// Enable SSE intrinsics if available -#if (defined __SSE__ || defined __x86_64__ || defined _M_X64 || (defined(_M_IX86_FP) && (_M_IX86_FP >= 1))) && !defined(IMGUI_DISABLE_SSE) -#define IMGUI_ENABLE_SSE -#include -#if (defined __AVX__ || defined __SSE4_2__) -#define IMGUI_ENABLE_SSE4_2 -#include -#endif -#endif -// Emscripten has partial SSE 4.2 support where _mm_crc32_u32 is not available. See https://emscripten.org/docs/porting/simd.html#id11 and #8213 -#if defined(IMGUI_ENABLE_SSE4_2) && !defined(IMGUI_USE_LEGACY_CRC32_ADLER) && !defined(__EMSCRIPTEN__) -#define IMGUI_ENABLE_SSE4_2_CRC -#endif - -// Visual Studio warnings -#ifdef _MSC_VER -#pragma warning (push) -#pragma warning (disable: 4251) // class 'xxx' needs to have dll-interface to be used by clients of struct 'xxx' // when IMGUI_API is set to__declspec(dllexport) -#pragma warning (disable: 26812) // The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). [MSVC Static Analyzer) -#pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6). -#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later -#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types -#endif -#endif - -// Clang/GCC warnings with -Weverything -#if defined(__clang__) -#pragma clang diagnostic push -#if __has_warning("-Wunknown-warning-option") -#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' -#endif -#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' -#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants ok, for ImFloor() -#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast -#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant -#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function -#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision -#pragma clang diagnostic ignored "-Wmissing-noreturn" // warning: function 'xxx' could be declared with attribute 'noreturn' -#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated -#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access -#pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type -#elif defined(__GNUC__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind -#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe -#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead -#pragma GCC diagnostic ignored "-Wdeprecated-enum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated -#endif - -// In 1.89.4, we moved the implementation of "courtesy maths operators" from imgui_internal.h in imgui.h -// As they are frequently requested, we do not want to encourage to many people using imgui_internal.h -#if defined(IMGUI_DEFINE_MATH_OPERATORS) && !defined(IMGUI_DEFINE_MATH_OPERATORS_IMPLEMENTED) -#error Please '#define IMGUI_DEFINE_MATH_OPERATORS' _BEFORE_ including imgui.h! -#endif - -// Legacy defines -#ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // Renamed in 1.74 -#error Use IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS -#endif -#ifdef IMGUI_DISABLE_MATH_FUNCTIONS // Renamed in 1.74 -#error Use IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS -#endif - -// Enable stb_truetype by default unless FreeType is enabled. -// You can compile with both by defining both IMGUI_ENABLE_FREETYPE and IMGUI_ENABLE_STB_TRUETYPE together. -#ifndef IMGUI_ENABLE_FREETYPE -#define IMGUI_ENABLE_STB_TRUETYPE -#endif - -//----------------------------------------------------------------------------- -// [SECTION] Forward declarations -//----------------------------------------------------------------------------- - -// Utilities -// (other types which are not forwarded declared are: ImBitArray<>, ImSpan<>, ImSpanAllocator<>, ImStableVector<>, ImPool<>, ImChunkStream<>) -struct ImBitVector; // Store 1-bit per value -struct ImRect; // An axis-aligned rectangle (2 points) -struct ImGuiTextIndex; // Maintain a line index for a text buffer. - -// ImDrawList/ImFontAtlas -struct ImDrawDataBuilder; // Helper to build a ImDrawData instance -struct ImDrawListSharedData; // Data shared between all ImDrawList instances -struct ImFontAtlasBuilder; // Internal storage for incrementally packing and building a ImFontAtlas -struct ImFontAtlasPostProcessData; // Data available to potential texture post-processing functions -struct ImFontAtlasRectEntry; // Packed rectangle lookup entry - -// ImGui -struct ImGuiBoxSelectState; // Box-selection state (currently used by multi-selection, could potentially be used by others) -struct ImGuiColorMod; // Stacked color modifier, backup of modified data so we can restore it -struct ImGuiContext; // Main Dear ImGui context -struct ImGuiContextHook; // Hook for extensions like ImGuiTestEngine -struct ImGuiDataTypeInfo; // Type information associated to a ImGuiDataType enum -struct ImGuiDeactivatedItemData; // Data for IsItemDeactivated()/IsItemDeactivatedAfterEdit() function. -struct ImGuiErrorRecoveryState; // Storage of stack sizes for error handling and recovery -struct ImGuiGroupData; // Stacked storage data for BeginGroup()/EndGroup() -struct ImGuiInputTextState; // Internal state of the currently focused/edited text input box -struct ImGuiInputTextDeactivateData;// Short term storage to backup text of a deactivating InputText() while another is stealing active id -struct ImGuiLastItemData; // Status storage for last submitted items -struct ImGuiLocEntry; // A localization entry. -struct ImGuiMenuColumns; // Simple column measurement, currently used for MenuItem() only -struct ImGuiMultiSelectState; // Multi-selection persistent state (for focused selection). -struct ImGuiMultiSelectTempData; // Multi-selection temporary state (while traversing). -struct ImGuiNavItemData; // Result of a keyboard/gamepad directional navigation move query result -struct ImGuiMetricsConfig; // Storage for ShowMetricsWindow() and DebugNodeXXX() functions -struct ImGuiNextWindowData; // Storage for SetNextWindow** functions -struct ImGuiNextItemData; // Storage for SetNextItem** functions -struct ImGuiOldColumnData; // Storage data for a single column for legacy Columns() api -struct ImGuiOldColumns; // Storage data for a columns set for legacy Columns() api -struct ImGuiPopupData; // Storage for current popup stack -struct ImGuiSettingsHandler; // Storage for one type registered in the .ini file -struct ImGuiStyleMod; // Stacked style modifier, backup of modified data so we can restore it -struct ImGuiStyleVarInfo; // Style variable information (e.g. to access style variables from an enum) -struct ImGuiTabBar; // Storage for a tab bar -struct ImGuiTabItem; // Storage for a tab item (within a tab bar) -struct ImGuiTable; // Storage for a table -struct ImGuiTableHeaderData; // Storage for TableAngledHeadersRow() -struct ImGuiTableColumn; // Storage for one column of a table -struct ImGuiTableInstanceData; // Storage for one instance of a same table -struct ImGuiTableTempData; // Temporary storage for one table (one per table in the stack), shared between tables. -struct ImGuiTableSettings; // Storage for a table .ini settings -struct ImGuiTableColumnsSettings; // Storage for a column .ini settings -struct ImGuiTreeNodeStackData; // Temporary storage for TreeNode(). -struct ImGuiTypingSelectState; // Storage for GetTypingSelectRequest() -struct ImGuiTypingSelectRequest; // Storage for GetTypingSelectRequest() (aimed to be public) -struct ImGuiWindow; // Storage for one window -struct ImGuiWindowTempData; // Temporary storage for one window (that's the data which in theory we could ditch at the end of the frame, in practice we currently keep it for each window) -struct ImGuiWindowSettings; // Storage for a window .ini settings (we keep one of those even if the actual window wasn't instanced during this session) - -// Enumerations -// Use your programming IDE "Go to definition" facility on the names of the center columns to find the actual flags/enum lists. -enum ImGuiLocKey : int; // -> enum ImGuiLocKey // Enum: a localization entry for translation. -typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical - -// Flags -typedef int ImGuiActivateFlags; // -> enum ImGuiActivateFlags_ // Flags: for navigation/focus function (will be for ActivateItem() later) -typedef int ImGuiDebugLogFlags; // -> enum ImGuiDebugLogFlags_ // Flags: for ShowDebugLogWindow(), g.DebugLogFlags -typedef int ImGuiFocusRequestFlags; // -> enum ImGuiFocusRequestFlags_ // Flags: for FocusWindow() -typedef int ImGuiItemStatusFlags; // -> enum ImGuiItemStatusFlags_ // Flags: for g.LastItemData.StatusFlags -typedef int ImGuiOldColumnFlags; // -> enum ImGuiOldColumnFlags_ // Flags: for BeginColumns() -typedef int ImGuiLogFlags; // -> enum ImGuiLogFlags_ // Flags: for LogBegin() text capturing function -typedef int ImGuiNavRenderCursorFlags; // -> enum ImGuiNavRenderCursorFlags_//Flags: for RenderNavCursor() -typedef int ImGuiNavMoveFlags; // -> enum ImGuiNavMoveFlags_ // Flags: for navigation requests -typedef int ImGuiNextItemDataFlags; // -> enum ImGuiNextItemDataFlags_ // Flags: for SetNextItemXXX() functions -typedef int ImGuiNextWindowDataFlags; // -> enum ImGuiNextWindowDataFlags_// Flags: for SetNextWindowXXX() functions -typedef int ImGuiScrollFlags; // -> enum ImGuiScrollFlags_ // Flags: for ScrollToItem() and navigation requests -typedef int ImGuiSeparatorFlags; // -> enum ImGuiSeparatorFlags_ // Flags: for SeparatorEx() -typedef int ImGuiTextFlags; // -> enum ImGuiTextFlags_ // Flags: for TextEx() -typedef int ImGuiTooltipFlags; // -> enum ImGuiTooltipFlags_ // Flags: for BeginTooltipEx() -typedef int ImGuiTypingSelectFlags; // -> enum ImGuiTypingSelectFlags_ // Flags: for GetTypingSelectRequest() -typedef int ImGuiWindowRefreshFlags; // -> enum ImGuiWindowRefreshFlags_ // Flags: for SetNextWindowRefreshPolicy() - -// Table column indexing -typedef ImS16 ImGuiTableColumnIdx; -typedef ImU16 ImGuiTableDrawChannelIdx; - -//----------------------------------------------------------------------------- -// [SECTION] Context pointer -// See implementation of this variable in imgui.cpp for comments and details. -//----------------------------------------------------------------------------- - -#ifndef GImGui -extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer -#endif - -//----------------------------------------------------------------------------- -// [SECTION] Macros -//----------------------------------------------------------------------------- - -// Debug Printing Into TTY -// (since IMGUI_VERSION_NUM >= 18729: IMGUI_DEBUG_LOG was reworked into IMGUI_DEBUG_PRINTF (and removed framecount from it). If you were using a #define IMGUI_DEBUG_LOG please rename) -#ifndef IMGUI_DEBUG_PRINTF -#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS -#define IMGUI_DEBUG_PRINTF(_FMT,...) printf(_FMT, __VA_ARGS__) -#else -#define IMGUI_DEBUG_PRINTF(_FMT,...) ((void)0) -#endif -#endif - -// Debug Logging for ShowDebugLogWindow(). This is designed for relatively rare events so please don't spam. -#define IMGUI_DEBUG_LOG_ERROR(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventError) IMGUI_DEBUG_LOG(__VA_ARGS__); else g.DebugLogSkippedErrors++; } while (0) -#define IMGUI_DEBUG_LOG_ACTIVEID(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventActiveId) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) -#define IMGUI_DEBUG_LOG_FOCUS(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventFocus) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) -#define IMGUI_DEBUG_LOG_POPUP(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventPopup) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) -#define IMGUI_DEBUG_LOG_NAV(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventNav) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) -#define IMGUI_DEBUG_LOG_SELECTION(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) -#define IMGUI_DEBUG_LOG_CLIPPER(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventClipper) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) -#define IMGUI_DEBUG_LOG_IO(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) -#define IMGUI_DEBUG_LOG_FONT(...) do { ImGuiContext* g2 = GImGui; if (g2 && g2->DebugLogFlags & ImGuiDebugLogFlags_EventFont) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) // Called from ImFontAtlas function which may operate without a context. -#define IMGUI_DEBUG_LOG_INPUTROUTING(...) do{if (g.DebugLogFlags & ImGuiDebugLogFlags_EventInputRouting)IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) - -// Static Asserts -#define IM_STATIC_ASSERT(_COND) static_assert(_COND, "") - -// "Paranoid" Debug Asserts are meant to only be enabled during specific debugging/work, otherwise would slow down the code too much. -// We currently don't have many of those so the effect is currently negligible, but onward intent to add more aggressive ones in the code. -//#define IMGUI_DEBUG_PARANOID -#ifdef IMGUI_DEBUG_PARANOID -#define IM_ASSERT_PARANOID(_EXPR) IM_ASSERT(_EXPR) -#else -#define IM_ASSERT_PARANOID(_EXPR) -#endif - -// Misc Macros -#define IM_PI 3.14159265358979323846f -#ifdef _WIN32 -#define IM_NEWLINE "\r\n" // Play it nice with Windows users (Update: since 2018-05, Notepad finally appears to support Unix-style carriage returns!) -#else -#define IM_NEWLINE "\n" -#endif -#ifndef IM_TABSIZE // Until we move this to runtime and/or add proper tab support, at least allow users to compile-time override -#define IM_TABSIZE (4) -#endif -#define IM_MEMALIGN(_OFF,_ALIGN) (((_OFF) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1)) // Memory align e.g. IM_ALIGN(0,4)=0, IM_ALIGN(1,4)=4, IM_ALIGN(4,4)=4, IM_ALIGN(5,4)=8 -#define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose -#define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255 -#define IM_TRUNC(_VAL) ((float)(int)(_VAL)) // ImTrunc() is not inlined in MSVC debug builds -#define IM_ROUND(_VAL) ((float)(int)((_VAL) + 0.5f)) // -#define IM_STRINGIFY_HELPER(_X) #_X -#define IM_STRINGIFY(_X) IM_STRINGIFY_HELPER(_X) // Preprocessor idiom to stringify e.g. an integer. -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -#define IM_FLOOR IM_TRUNC -#endif - -// Hint for branch prediction -#if (defined(__cplusplus) && (__cplusplus >= 202002L)) || (defined(_MSVC_LANG) && (_MSVC_LANG >= 202002L)) -#define IM_LIKELY [[likely]] -#define IM_UNLIKELY [[unlikely]] -#else -#define IM_LIKELY -#define IM_UNLIKELY -#endif - -// Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall -#ifdef _MSC_VER -#define IMGUI_CDECL __cdecl -#else -#define IMGUI_CDECL -#endif - -// Warnings -#if defined(_MSC_VER) && !defined(__clang__) -#define IM_MSVC_WARNING_SUPPRESS(XXXX) __pragma(warning(suppress: XXXX)) -#else -#define IM_MSVC_WARNING_SUPPRESS(XXXX) -#endif - -// Debug Tools -// Use 'Metrics/Debugger->Tools->Item Picker' to break into the call-stack of a specific item. -// This will call IM_DEBUG_BREAK() which you may redefine yourself. See https://github.com/scottt/debugbreak for more reference. -#ifndef IM_DEBUG_BREAK -#if defined (_MSC_VER) -#define IM_DEBUG_BREAK() __debugbreak() -#elif defined(__clang__) -#define IM_DEBUG_BREAK() __builtin_debugtrap() -#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) -#define IM_DEBUG_BREAK() __asm__ volatile("int3;nop") -#elif defined(__GNUC__) && defined(__thumb__) -#define IM_DEBUG_BREAK() __asm__ volatile(".inst 0xde01") -#elif defined(__GNUC__) && defined(__arm__) && !defined(__thumb__) -#define IM_DEBUG_BREAK() __asm__ volatile(".inst 0xe7f001f0") -#else -#define IM_DEBUG_BREAK() IM_ASSERT(0) // It is expected that you define IM_DEBUG_BREAK() into something that will break nicely in a debugger! -#endif -#endif // #ifndef IM_DEBUG_BREAK - -// Format specifiers, printing 64-bit hasn't been decently standardized... -// In a real application you should be using PRId64 and PRIu64 from (non-windows) and on Windows define them yourself. -#if defined(_MSC_VER) && !defined(__clang__) -#define IM_PRId64 "I64d" -#define IM_PRIu64 "I64u" -#define IM_PRIX64 "I64X" -#else -#define IM_PRId64 "lld" -#define IM_PRIu64 "llu" -#define IM_PRIX64 "llX" -#endif - -//----------------------------------------------------------------------------- -// [SECTION] Generic helpers -// Note that the ImXXX helpers functions are lower-level than ImGui functions. -// ImGui functions or the ImGui context are never called/used from other ImXXX functions. -//----------------------------------------------------------------------------- -// - Helpers: Hashing -// - Helpers: Sorting -// - Helpers: Bit manipulation -// - Helpers: String -// - Helpers: Formatting -// - Helpers: UTF-8 <> wchar conversions -// - Helpers: ImVec2/ImVec4 operators -// - Helpers: Maths -// - Helpers: Geometry -// - Helper: ImVec1 -// - Helper: ImVec2ih -// - Helper: ImRect -// - Helper: ImBitArray -// - Helper: ImBitVector -// - Helper: ImSpan<>, ImSpanAllocator<> -// - Helper: ImStableVector<> -// - Helper: ImPool<> -// - Helper: ImChunkStream<> -// - Helper: ImGuiTextIndex -// - Helper: ImGuiStorage -//----------------------------------------------------------------------------- - -// Helpers: Hashing -IMGUI_API ImGuiID ImHashData(const void* data, size_t data_size, ImGuiID seed = 0); -IMGUI_API ImGuiID ImHashStr(const char* data, size_t data_size = 0, ImGuiID seed = 0); - -// Helpers: Sorting -#ifndef ImQsort -static inline void ImQsort(void* base, size_t count, size_t size_of_element, int(IMGUI_CDECL *compare_func)(void const*, void const*)) { if (count > 1) qsort(base, count, size_of_element, compare_func); } -#endif - -// Helpers: Color Blending -IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b); - -// Helpers: Bit manipulation -static inline bool ImIsPowerOfTwo(int v) { return v != 0 && (v & (v - 1)) == 0; } -static inline bool ImIsPowerOfTwo(ImU64 v) { return v != 0 && (v & (v - 1)) == 0; } -static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } -static inline unsigned int ImCountSetBits(unsigned int v) { unsigned int count = 0; while (v > 0) { v = v & (v - 1); count++; } return count; } - -// Helpers: String -#define ImStrlen strlen -#define ImMemchr memchr -IMGUI_API int ImStricmp(const char* str1, const char* str2); // Case insensitive compare. -IMGUI_API int ImStrnicmp(const char* str1, const char* str2, size_t count); // Case insensitive compare to a certain count. -IMGUI_API void ImStrncpy(char* dst, const char* src, size_t count); // Copy to a certain count and always zero terminate (strncpy doesn't). -IMGUI_API char* ImStrdup(const char* str); // Duplicate a string. -IMGUI_API void* ImMemdup(const void* src, size_t size); // Duplicate a chunk of memory. -IMGUI_API char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* str); // Copy in provided buffer, recreate buffer if needed. -IMGUI_API const char* ImStrchrRange(const char* str_begin, const char* str_end, char c); // Find first occurrence of 'c' in string range. -IMGUI_API const char* ImStreolRange(const char* str, const char* str_end); // End end-of-line -IMGUI_API const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end); // Find a substring in a string range. -IMGUI_API void ImStrTrimBlanks(char* str); // Remove leading and trailing blanks from a buffer. -IMGUI_API const char* ImStrSkipBlank(const char* str); // Find first non-blank character. -IMGUI_API int ImStrlenW(const ImWchar* str); // Computer string length (ImWchar string) -IMGUI_API const char* ImStrbol(const char* buf_mid_line, const char* buf_begin); // Find beginning-of-line -IM_MSVC_RUNTIME_CHECKS_OFF -static inline char ImToUpper(char c) { return (c >= 'a' && c <= 'z') ? c &= ~32 : c; } -static inline bool ImCharIsBlankA(char c) { return c == ' ' || c == '\t'; } -static inline bool ImCharIsBlankW(unsigned int c) { return c == ' ' || c == '\t' || c == 0x3000; } -static inline bool ImCharIsXdigitA(char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); } -IM_MSVC_RUNTIME_CHECKS_RESTORE - -// Helpers: Formatting -IMGUI_API int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) IM_FMTARGS(3); -IMGUI_API int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) IM_FMTLIST(3); -IMGUI_API void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...) IM_FMTARGS(3); -IMGUI_API void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args) IM_FMTLIST(3); -IMGUI_API const char* ImParseFormatFindStart(const char* format); -IMGUI_API const char* ImParseFormatFindEnd(const char* format); -IMGUI_API const char* ImParseFormatTrimDecorations(const char* format, char* buf, size_t buf_size); -IMGUI_API void ImParseFormatSanitizeForPrinting(const char* fmt_in, char* fmt_out, size_t fmt_out_size); -IMGUI_API const char* ImParseFormatSanitizeForScanning(const char* fmt_in, char* fmt_out, size_t fmt_out_size); -IMGUI_API int ImParseFormatPrecision(const char* format, int default_value); - -// Helpers: UTF-8 <> wchar conversions -IMGUI_API const char* ImTextCharToUtf8(char out_buf[5], unsigned int c); // return out_buf -IMGUI_API int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count -IMGUI_API int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // read one character. return input UTF-8 bytes count -IMGUI_API int ImTextStrFromUtf8(ImWchar* out_buf, int out_buf_size, const char* in_text, const char* in_text_end, const char** in_remaining = NULL); // return input UTF-8 bytes count -IMGUI_API int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count) -IMGUI_API int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end); // return number of bytes to express one char in UTF-8 -IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string in UTF-8 -IMGUI_API const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr); // return previous UTF-8 code-point. -IMGUI_API int ImTextCountLines(const char* in_text, const char* in_text_end); // return number of lines taken by text. trailing carriage return doesn't count as an extra line. - -// Helpers: File System -#ifdef IMGUI_DISABLE_FILE_FUNCTIONS -#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS -typedef void* ImFileHandle; -static inline ImFileHandle ImFileOpen(const char*, const char*) { return NULL; } -static inline bool ImFileClose(ImFileHandle) { return false; } -static inline ImU64 ImFileGetSize(ImFileHandle) { return (ImU64)-1; } -static inline ImU64 ImFileRead(void*, ImU64, ImU64, ImFileHandle) { return 0; } -static inline ImU64 ImFileWrite(const void*, ImU64, ImU64, ImFileHandle) { return 0; } -#endif -#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS -typedef FILE* ImFileHandle; -IMGUI_API ImFileHandle ImFileOpen(const char* filename, const char* mode); -IMGUI_API bool ImFileClose(ImFileHandle file); -IMGUI_API ImU64 ImFileGetSize(ImFileHandle file); -IMGUI_API ImU64 ImFileRead(void* data, ImU64 size, ImU64 count, ImFileHandle file); -IMGUI_API ImU64 ImFileWrite(const void* data, ImU64 size, ImU64 count, ImFileHandle file); -#else -#define IMGUI_DISABLE_TTY_FUNCTIONS // Can't use stdout, fflush if we are not using default file functions -#endif -IMGUI_API void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size = NULL, int padding_bytes = 0); - -// Helpers: Maths -IM_MSVC_RUNTIME_CHECKS_OFF -// - Wrapper for standard libs functions. (Note that imgui_demo.cpp does _not_ use them to keep the code easy to copy) -#ifndef IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS -#define ImFabs(X) fabsf(X) -#define ImSqrt(X) sqrtf(X) -#define ImFmod(X, Y) fmodf((X), (Y)) -#define ImCos(X) cosf(X) -#define ImSin(X) sinf(X) -#define ImAcos(X) acosf(X) -#define ImAtan2(Y, X) atan2f((Y), (X)) -#define ImAtof(STR) atof(STR) -#define ImCeil(X) ceilf(X) -static inline float ImPow(float x, float y) { return powf(x, y); } // DragBehaviorT/SliderBehaviorT uses ImPow with either float/double and need the precision -static inline double ImPow(double x, double y) { return pow(x, y); } -static inline float ImLog(float x) { return logf(x); } // DragBehaviorT/SliderBehaviorT uses ImLog with either float/double and need the precision -static inline double ImLog(double x) { return log(x); } -static inline int ImAbs(int x) { return x < 0 ? -x : x; } -static inline float ImAbs(float x) { return fabsf(x); } -static inline double ImAbs(double x) { return fabs(x); } -static inline float ImSign(float x) { return (x < 0.0f) ? -1.0f : (x > 0.0f) ? 1.0f : 0.0f; } // Sign operator - returns -1, 0 or 1 based on sign of argument -static inline double ImSign(double x) { return (x < 0.0) ? -1.0 : (x > 0.0) ? 1.0 : 0.0; } -#ifdef IMGUI_ENABLE_SSE -static inline float ImRsqrt(float x) { return _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ss(x))); } -#else -static inline float ImRsqrt(float x) { return 1.0f / sqrtf(x); } -#endif -static inline double ImRsqrt(double x) { return 1.0 / sqrt(x); } -#endif -// - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support variety of types: signed/unsigned int/long long float/double -// (Exceptionally using templates here but we could also redefine them for those types) -template static inline T ImMin(T lhs, T rhs) { return lhs < rhs ? lhs : rhs; } -template static inline T ImMax(T lhs, T rhs) { return lhs >= rhs ? lhs : rhs; } -template static inline T ImClamp(T v, T mn, T mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } -template static inline T ImLerp(T a, T b, float t) { return (T)(a + (b - a) * t); } -template static inline void ImSwap(T& a, T& b) { T tmp = a; a = b; b = tmp; } -template static inline T ImAddClampOverflow(T a, T b, T mn, T mx) { if (b < 0 && (a < mn - b)) return mn; if (b > 0 && (a > mx - b)) return mx; return a + b; } -template static inline T ImSubClampOverflow(T a, T b, T mn, T mx) { if (b > 0 && (a < mn + b)) return mn; if (b < 0 && (a > mx + b)) return mx; return a - b; } -// - Misc maths helpers -static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x < rhs.x ? lhs.x : rhs.x, lhs.y < rhs.y ? lhs.y : rhs.y); } -static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x >= rhs.x ? lhs.x : rhs.x, lhs.y >= rhs.y ? lhs.y : rhs.y); } -static inline ImVec2 ImClamp(const ImVec2& v, const ImVec2&mn, const ImVec2&mx) { return ImVec2((v.x < mn.x) ? mn.x : (v.x > mx.x) ? mx.x : v.x, (v.y < mn.y) ? mn.y : (v.y > mx.y) ? mx.y : v.y); } -static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, float t) { return ImVec2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t); } -static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); } -static inline ImVec4 ImLerp(const ImVec4& a, const ImVec4& b, float t) { return ImVec4(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t, a.w + (b.w - a.w) * t); } -static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; } -static inline float ImLengthSqr(const ImVec2& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y); } -static inline float ImLengthSqr(const ImVec4& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y) + (lhs.z * lhs.z) + (lhs.w * lhs.w); } -static inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = (lhs.x * lhs.x) + (lhs.y * lhs.y); if (d > 0.0f) return ImRsqrt(d); return fail_value; } -static inline float ImTrunc(float f) { return (float)(int)(f); } -static inline ImVec2 ImTrunc(const ImVec2& v) { return ImVec2((float)(int)(v.x), (float)(int)(v.y)); } -static inline float ImFloor(float f) { return (float)((f >= 0 || (float)(int)f == f) ? (int)f : (int)f - 1); } // Decent replacement for floorf() -static inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2(ImFloor(v.x), ImFloor(v.y)); } -static inline float ImTrunc64(float f) { return (float)(ImS64)(f); } -static inline float ImRound64(float f) { return (float)(ImS64)(f + 0.5f); } -static inline int ImModPositive(int a, int b) { return (a + b) % b; } -static inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; } -static inline ImVec2 ImRotate(const ImVec2& v, float cos_a, float sin_a) { return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_a); } -static inline float ImLinearSweep(float current, float target, float speed) { if (current < target) return ImMin(current + speed, target); if (current > target) return ImMax(current - speed, target); return current; } -static inline float ImLinearRemapClamp(float s0, float s1, float d0, float d1, float x) { return ImSaturate((x - s0) / (s1 - s0)) * (d1 - d0) + d0; } -static inline ImVec2 ImMul(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } -static inline bool ImIsFloatAboveGuaranteedIntegerPrecision(float f) { return f <= -16777216 || f >= 16777216; } -static inline float ImExponentialMovingAverage(float avg, float sample, int n) { avg -= avg / n; avg += sample / n; return avg; } -IM_MSVC_RUNTIME_CHECKS_RESTORE - -// Helpers: Geometry -IMGUI_API ImVec2 ImBezierCubicCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, float t); -IMGUI_API ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments); // For curves with explicit number of segments -IMGUI_API ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol);// For auto-tessellated curves you can use tess_tol = style.CurveTessellationTol -IMGUI_API ImVec2 ImBezierQuadraticCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, float t); -IMGUI_API ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p); -IMGUI_API bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p); -IMGUI_API ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p); -IMGUI_API void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w); -inline float ImTriangleArea(const ImVec2& a, const ImVec2& b, const ImVec2& c) { return ImFabs((a.x * (b.y - c.y)) + (b.x * (c.y - a.y)) + (c.x * (a.y - b.y))) * 0.5f; } -inline bool ImTriangleIsClockwise(const ImVec2& a, const ImVec2& b, const ImVec2& c) { return ((b.x - a.x) * (c.y - b.y)) - ((c.x - b.x) * (b.y - a.y)) > 0.0f; } - -// Helper: ImVec1 (1D vector) -// (this odd construct is used to facilitate the transition between 1D and 2D, and the maintenance of some branches/patches) -IM_MSVC_RUNTIME_CHECKS_OFF -struct ImVec1 -{ - float x; - constexpr ImVec1() : x(0.0f) { } - constexpr ImVec1(float _x) : x(_x) { } -}; - -// Helper: ImVec2i (2D vector, integer) -struct ImVec2i -{ - int x, y; - constexpr ImVec2i() : x(0), y(0) {} - constexpr ImVec2i(int _x, int _y) : x(_x), y(_y) {} -}; - -// Helper: ImVec2ih (2D vector, half-size integer, for long-term packed storage) -struct ImVec2ih -{ - short x, y; - constexpr ImVec2ih() : x(0), y(0) {} - constexpr ImVec2ih(short _x, short _y) : x(_x), y(_y) {} - constexpr explicit ImVec2ih(const ImVec2& rhs) : x((short)rhs.x), y((short)rhs.y) {} -}; - -// Helper: ImRect (2D axis aligned bounding-box) -// NB: we can't rely on ImVec2 math operators being available here! -struct IMGUI_API ImRect -{ - ImVec2 Min; // Upper-left - ImVec2 Max; // Lower-right - - constexpr ImRect() : Min(0.0f, 0.0f), Max(0.0f, 0.0f) {} - constexpr ImRect(const ImVec2& min, const ImVec2& max) : Min(min), Max(max) {} - constexpr ImRect(const ImVec4& v) : Min(v.x, v.y), Max(v.z, v.w) {} - constexpr ImRect(float x1, float y1, float x2, float y2) : Min(x1, y1), Max(x2, y2) {} - - ImVec2 GetCenter() const { return ImVec2((Min.x + Max.x) * 0.5f, (Min.y + Max.y) * 0.5f); } - ImVec2 GetSize() const { return ImVec2(Max.x - Min.x, Max.y - Min.y); } - float GetWidth() const { return Max.x - Min.x; } - float GetHeight() const { return Max.y - Min.y; } - float GetArea() const { return (Max.x - Min.x) * (Max.y - Min.y); } - ImVec2 GetTL() const { return Min; } // Top-left - ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } // Top-right - ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } // Bottom-left - ImVec2 GetBR() const { return Max; } // Bottom-right - bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; } - bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x <= Max.x && r.Max.y <= Max.y; } - bool ContainsWithPad(const ImVec2& p, const ImVec2& pad) const { return p.x >= Min.x - pad.x && p.y >= Min.y - pad.y && p.x < Max.x + pad.x && p.y < Max.y + pad.y; } - bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; } - void Add(const ImVec2& p) { if (Min.x > p.x) Min.x = p.x; if (Min.y > p.y) Min.y = p.y; if (Max.x < p.x) Max.x = p.x; if (Max.y < p.y) Max.y = p.y; } - void Add(const ImRect& r) { if (Min.x > r.Min.x) Min.x = r.Min.x; if (Min.y > r.Min.y) Min.y = r.Min.y; if (Max.x < r.Max.x) Max.x = r.Max.x; if (Max.y < r.Max.y) Max.y = r.Max.y; } - void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; } - void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; } - void Translate(const ImVec2& d) { Min.x += d.x; Min.y += d.y; Max.x += d.x; Max.y += d.y; } - void TranslateX(float dx) { Min.x += dx; Max.x += dx; } - void TranslateY(float dy) { Min.y += dy; Max.y += dy; } - void ClipWith(const ImRect& r) { Min = ImMax(Min, r.Min); Max = ImMin(Max, r.Max); } // Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display. - void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped. - void Floor() { Min.x = IM_TRUNC(Min.x); Min.y = IM_TRUNC(Min.y); Max.x = IM_TRUNC(Max.x); Max.y = IM_TRUNC(Max.y); } - bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } - ImVec4 ToVec4() const { return ImVec4(Min.x, Min.y, Max.x, Max.y); } -}; - -// Helper: ImBitArray -#define IM_BITARRAY_TESTBIT(_ARRAY, _N) ((_ARRAY[(_N) >> 5] & ((ImU32)1 << ((_N) & 31))) != 0) // Macro version of ImBitArrayTestBit(): ensure args have side-effect or are costly! -#define IM_BITARRAY_CLEARBIT(_ARRAY, _N) ((_ARRAY[(_N) >> 5] &= ~((ImU32)1 << ((_N) & 31)))) // Macro version of ImBitArrayClearBit(): ensure args have side-effect or are costly! -inline size_t ImBitArrayGetStorageSizeInBytes(int bitcount) { return (size_t)((bitcount + 31) >> 5) << 2; } -inline void ImBitArrayClearAllBits(ImU32* arr, int bitcount){ memset(arr, 0, ImBitArrayGetStorageSizeInBytes(bitcount)); } -inline bool ImBitArrayTestBit(const ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); return (arr[n >> 5] & mask) != 0; } -inline void ImBitArrayClearBit(ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] &= ~mask; } -inline void ImBitArraySetBit(ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] |= mask; } -inline void ImBitArraySetBitRange(ImU32* arr, int n, int n2) // Works on range [n..n2) -{ - n2--; - while (n <= n2) - { - int a_mod = (n & 31); - int b_mod = (n2 > (n | 31) ? 31 : (n2 & 31)) + 1; - ImU32 mask = (ImU32)(((ImU64)1 << b_mod) - 1) & ~(ImU32)(((ImU64)1 << a_mod) - 1); - arr[n >> 5] |= mask; - n = (n + 32) & ~31; - } -} - -typedef ImU32* ImBitArrayPtr; // Name for use in structs - -// Helper: ImBitArray class (wrapper over ImBitArray functions) -// Store 1-bit per value. -template -struct ImBitArray -{ - ImU32 Storage[(BITCOUNT + 31) >> 5]; - ImBitArray() { ClearAllBits(); } - void ClearAllBits() { memset(Storage, 0, sizeof(Storage)); } - void SetAllBits() { memset(Storage, 255, sizeof(Storage)); } - bool TestBit(int n) const { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); return IM_BITARRAY_TESTBIT(Storage, n); } - void SetBit(int n) { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); ImBitArraySetBit(Storage, n); } - void ClearBit(int n) { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); ImBitArrayClearBit(Storage, n); } - void SetBitRange(int n, int n2) { n += OFFSET; n2 += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT && n2 > n && n2 <= BITCOUNT); ImBitArraySetBitRange(Storage, n, n2); } // Works on range [n..n2) - bool operator[](int n) const { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); return IM_BITARRAY_TESTBIT(Storage, n); } -}; - -// Helper: ImBitVector -// Store 1-bit per value. -struct IMGUI_API ImBitVector -{ - ImVector Storage; - void Create(int sz) { Storage.resize((sz + 31) >> 5); memset(Storage.Data, 0, (size_t)Storage.Size * sizeof(Storage.Data[0])); } - void Clear() { Storage.clear(); } - bool TestBit(int n) const { IM_ASSERT(n < (Storage.Size << 5)); return IM_BITARRAY_TESTBIT(Storage.Data, n); } - void SetBit(int n) { IM_ASSERT(n < (Storage.Size << 5)); ImBitArraySetBit(Storage.Data, n); } - void ClearBit(int n) { IM_ASSERT(n < (Storage.Size << 5)); ImBitArrayClearBit(Storage.Data, n); } -}; -IM_MSVC_RUNTIME_CHECKS_RESTORE - -// Helper: ImSpan<> -// Pointing to a span of data we don't own. -template -struct ImSpan -{ - T* Data; - T* DataEnd; - - // Constructors, destructor - inline ImSpan() { Data = DataEnd = NULL; } - inline ImSpan(T* data, int size) { Data = data; DataEnd = data + size; } - inline ImSpan(T* data, T* data_end) { Data = data; DataEnd = data_end; } - - inline void set(T* data, int size) { Data = data; DataEnd = data + size; } - inline void set(T* data, T* data_end) { Data = data; DataEnd = data_end; } - inline int size() const { return (int)(ptrdiff_t)(DataEnd - Data); } - inline int size_in_bytes() const { return (int)(ptrdiff_t)(DataEnd - Data) * (int)sizeof(T); } - inline T& operator[](int i) { T* p = Data + i; IM_ASSERT(p >= Data && p < DataEnd); return *p; } - inline const T& operator[](int i) const { const T* p = Data + i; IM_ASSERT(p >= Data && p < DataEnd); return *p; } - - inline T* begin() { return Data; } - inline const T* begin() const { return Data; } - inline T* end() { return DataEnd; } - inline const T* end() const { return DataEnd; } - - // Utilities - inline int index_from_ptr(const T* it) const { IM_ASSERT(it >= Data && it < DataEnd); const ptrdiff_t off = it - Data; return (int)off; } -}; - -// Helper: ImSpanAllocator<> -// Facilitate storing multiple chunks into a single large block (the "arena") -// - Usage: call Reserve() N times, allocate GetArenaSizeInBytes() worth, pass it to SetArenaBasePtr(), call GetSpan() N times to retrieve the aligned ranges. -template -struct ImSpanAllocator -{ - char* BasePtr; - int CurrOff; - int CurrIdx; - int Offsets[CHUNKS]; - int Sizes[CHUNKS]; - - ImSpanAllocator() { memset(this, 0, sizeof(*this)); } - inline void Reserve(int n, size_t sz, int a=4) { IM_ASSERT(n == CurrIdx && n < CHUNKS); CurrOff = IM_MEMALIGN(CurrOff, a); Offsets[n] = CurrOff; Sizes[n] = (int)sz; CurrIdx++; CurrOff += (int)sz; } - inline int GetArenaSizeInBytes() { return CurrOff; } - inline void SetArenaBasePtr(void* base_ptr) { BasePtr = (char*)base_ptr; } - inline void* GetSpanPtrBegin(int n) { IM_ASSERT(n >= 0 && n < CHUNKS && CurrIdx == CHUNKS); return (void*)(BasePtr + Offsets[n]); } - inline void* GetSpanPtrEnd(int n) { IM_ASSERT(n >= 0 && n < CHUNKS && CurrIdx == CHUNKS); return (void*)(BasePtr + Offsets[n] + Sizes[n]); } - template - inline void GetSpan(int n, ImSpan* span) { span->set((T*)GetSpanPtrBegin(n), (T*)GetSpanPtrEnd(n)); } -}; - -// Helper: ImStableVector<> -// Allocating chunks of BLOCK_SIZE items. Objects pointers are never invalidated when growing, only by clear(). -// Important: does not destruct anything! -// Implemented only the minimum set of functions we need for it. -template -struct ImStableVector -{ - int Size = 0; - int Capacity = 0; - ImVector Blocks; - - // Functions - inline ~ImStableVector() { for (T* block : Blocks) IM_FREE(block); } - - inline void clear() { Size = Capacity = 0; Blocks.clear_delete(); } - inline void resize(int new_size) { if (new_size > Capacity) reserve(new_size); Size = new_size; } - inline void reserve(int new_cap) - { - new_cap = IM_MEMALIGN(new_cap, BLOCK_SIZE); - int old_count = Capacity / BLOCK_SIZE; - int new_count = new_cap / BLOCK_SIZE; - if (new_count <= old_count) - return; - Blocks.resize(new_count); - for (int n = old_count; n < new_count; n++) - Blocks[n] = (T*)IM_ALLOC(sizeof(T) * BLOCK_SIZE); - Capacity = new_cap; - } - inline T& operator[](int i) { IM_ASSERT(i >= 0 && i < Size); return Blocks[i / BLOCK_SIZE][i % BLOCK_SIZE]; } - inline const T& operator[](int i) const { IM_ASSERT(i >= 0 && i < Size); return Blocks[i / BLOCK_SIZE][i % BLOCK_SIZE]; } - inline T* push_back(const T& v) { int i = Size; IM_ASSERT(i >= 0); if (Size == Capacity) reserve(Capacity + BLOCK_SIZE); void* ptr = &Blocks[i / BLOCK_SIZE][i % BLOCK_SIZE]; memcpy(ptr, &v, sizeof(v)); Size++; return (T*)ptr; } -}; - -// Helper: ImPool<> -// Basic keyed storage for contiguous instances, slow/amortized insertion, O(1) indexable, O(Log N) queries by ID over a dense/hot buffer, -// Honor constructor/destructor. Add/remove invalidate all pointers. Indexes have the same lifetime as the associated object. -typedef int ImPoolIdx; -template -struct ImPool -{ - ImVector Buf; // Contiguous data - ImGuiStorage Map; // ID->Index - ImPoolIdx FreeIdx; // Next free idx to use - ImPoolIdx AliveCount; // Number of active/alive items (for display purpose) - - ImPool() { FreeIdx = AliveCount = 0; } - ~ImPool() { Clear(); } - T* GetByKey(ImGuiID key) { int idx = Map.GetInt(key, -1); return (idx != -1) ? &Buf[idx] : NULL; } - T* GetByIndex(ImPoolIdx n) { return &Buf[n]; } - ImPoolIdx GetIndex(const T* p) const { IM_ASSERT(p >= Buf.Data && p < Buf.Data + Buf.Size); return (ImPoolIdx)(p - Buf.Data); } - T* GetOrAddByKey(ImGuiID key) { int* p_idx = Map.GetIntRef(key, -1); if (*p_idx != -1) return &Buf[*p_idx]; *p_idx = FreeIdx; return Add(); } - bool Contains(const T* p) const { return (p >= Buf.Data && p < Buf.Data + Buf.Size); } - void Clear() { for (int n = 0; n < Map.Data.Size; n++) { int idx = Map.Data[n].val_i; if (idx != -1) Buf[idx].~T(); } Map.Clear(); Buf.clear(); FreeIdx = AliveCount = 0; } - T* Add() { int idx = FreeIdx; if (idx == Buf.Size) { Buf.resize(Buf.Size + 1); FreeIdx++; } else { FreeIdx = *(int*)&Buf[idx]; } IM_PLACEMENT_NEW(&Buf[idx]) T(); AliveCount++; return &Buf[idx]; } - void Remove(ImGuiID key, const T* p) { Remove(key, GetIndex(p)); } - void Remove(ImGuiID key, ImPoolIdx idx) { Buf[idx].~T(); *(int*)&Buf[idx] = FreeIdx; FreeIdx = idx; Map.SetInt(key, -1); AliveCount--; } - void Reserve(int capacity) { Buf.reserve(capacity); Map.Data.reserve(capacity); } - - // To iterate a ImPool: for (int n = 0; n < pool.GetMapSize(); n++) if (T* t = pool.TryGetMapData(n)) { ... } - // Can be avoided if you know .Remove() has never been called on the pool, or AliveCount == GetMapSize() - int GetAliveCount() const { return AliveCount; } // Number of active/alive items in the pool (for display purpose) - int GetBufSize() const { return Buf.Size; } - int GetMapSize() const { return Map.Data.Size; } // It is the map we need iterate to find valid items, since we don't have "alive" storage anywhere - T* TryGetMapData(ImPoolIdx n) { int idx = Map.Data[n].val_i; if (idx == -1) return NULL; return GetByIndex(idx); } -}; - -// Helper: ImChunkStream<> -// Build and iterate a contiguous stream of variable-sized structures. -// This is used by Settings to store persistent data while reducing allocation count. -// We store the chunk size first, and align the final size on 4 bytes boundaries. -// The tedious/zealous amount of casting is to avoid -Wcast-align warnings. -template -struct ImChunkStream -{ - ImVector Buf; - - void clear() { Buf.clear(); } - bool empty() const { return Buf.Size == 0; } - int size() const { return Buf.Size; } - T* alloc_chunk(size_t sz) { size_t HDR_SZ = 4; sz = IM_MEMALIGN(HDR_SZ + sz, 4u); int off = Buf.Size; Buf.resize(off + (int)sz); ((int*)(void*)(Buf.Data + off))[0] = (int)sz; return (T*)(void*)(Buf.Data + off + (int)HDR_SZ); } - T* begin() { size_t HDR_SZ = 4; if (!Buf.Data) return NULL; return (T*)(void*)(Buf.Data + HDR_SZ); } - T* next_chunk(T* p) { size_t HDR_SZ = 4; IM_ASSERT(p >= begin() && p < end()); p = (T*)(void*)((char*)(void*)p + chunk_size(p)); if (p == (T*)(void*)((char*)end() + HDR_SZ)) return (T*)0; IM_ASSERT(p < end()); return p; } - int chunk_size(const T* p) { return ((const int*)p)[-1]; } - T* end() { return (T*)(void*)(Buf.Data + Buf.Size); } - int offset_from_ptr(const T* p) { IM_ASSERT(p >= begin() && p < end()); const ptrdiff_t off = (const char*)p - Buf.Data; return (int)off; } - T* ptr_from_offset(int off) { IM_ASSERT(off >= 4 && off < Buf.Size); return (T*)(void*)(Buf.Data + off); } - void swap(ImChunkStream& rhs) { rhs.Buf.swap(Buf); } -}; - -// Helper: ImGuiTextIndex -// Maintain a line index for a text buffer. This is a strong candidate to be moved into the public API. -struct ImGuiTextIndex -{ - ImVector LineOffsets; - int EndOffset = 0; // Because we don't own text buffer we need to maintain EndOffset (may bake in LineOffsets?) - - void clear() { LineOffsets.clear(); EndOffset = 0; } - int size() { return LineOffsets.Size; } - const char* get_line_begin(const char* base, int n) { return base + LineOffsets[n]; } - const char* get_line_end(const char* base, int n) { return base + (n + 1 < LineOffsets.Size ? (LineOffsets[n + 1] - 1) : EndOffset); } - void append(const char* base, int old_size, int new_size); -}; - -// Helper: ImGuiStorage -IMGUI_API ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key); - -//----------------------------------------------------------------------------- -// [SECTION] ImDrawList support -//----------------------------------------------------------------------------- - -// ImDrawList: Helper function to calculate a circle's segment count given its radius and a "maximum error" value. -// Estimation of number of circle segment based on error is derived using method described in https://stackoverflow.com/a/2244088/15194693 -// Number of segments (N) is calculated using equation: -// N = ceil ( pi / acos(1 - error / r) ) where r > 0, error <= r -// Our equation is significantly simpler that one in the post thanks for choosing segment that is -// perpendicular to X axis. Follow steps in the article from this starting condition and you will -// will get this result. -// -// Rendering circles with an odd number of segments, while mathematically correct will produce -// asymmetrical results on the raster grid. Therefore we're rounding N to next even number (7->8, 8->8, 9->10 etc.) -#define IM_ROUNDUP_TO_EVEN(_V) ((((_V) + 1) / 2) * 2) -#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN 4 -#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX 512 -#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(_RAD,_MAXERROR) ImClamp(IM_ROUNDUP_TO_EVEN((int)ImCeil(IM_PI / ImAcos(1 - ImMin((_MAXERROR), (_RAD)) / (_RAD)))), IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX) - -// Raw equation from IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC rewritten for 'r' and 'error'. -#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(_N,_MAXERROR) ((_MAXERROR) / (1 - ImCos(IM_PI / ImMax((float)(_N), IM_PI)))) -#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_ERROR(_N,_RAD) ((1 - ImCos(IM_PI / ImMax((float)(_N), IM_PI))) / (_RAD)) - -// ImDrawList: Lookup table size for adaptive arc drawing, cover full circle. -#ifndef IM_DRAWLIST_ARCFAST_TABLE_SIZE -#define IM_DRAWLIST_ARCFAST_TABLE_SIZE 48 // Number of samples in lookup table. -#endif -#define IM_DRAWLIST_ARCFAST_SAMPLE_MAX IM_DRAWLIST_ARCFAST_TABLE_SIZE // Sample index _PathArcToFastEx() for 360 angle. - -// Data shared between all ImDrawList instances -// Conceptually this could have been called e.g. ImDrawListSharedContext -// Typically one ImGui context would create and maintain one of this. -// You may want to create your own instance of you try to ImDrawList completely without ImGui. In that case, watch out for future changes to this structure. -struct IMGUI_API ImDrawListSharedData -{ - ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel) - const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas (== FontAtlas->TexUvLines) - ImFontAtlas* FontAtlas; // Current font atlas - ImFont* Font; // Current font (used for simplified AddText overload) - float FontSize; // Current font size (used for for simplified AddText overload) - float FontScale; // Current font scale (== FontSize / Font->FontSize) - float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() - float CircleSegmentMaxError; // Number of circle segments to use per pixel of radius for AddCircle() etc - float InitialFringeScale; // Initial scale to apply to AA fringe - ImDrawListFlags InitialFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards) - ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen() - ImVector TempBuffer; // Temporary write buffer - ImVector DrawLists; // All draw lists associated to this ImDrawListSharedData - ImGuiContext* Context; // [OPTIONAL] Link to Dear ImGui context. 99% of ImDrawList/ImFontAtlas can function without an ImGui context, but this facilitate handling one legacy edge case. - - // Lookup tables - ImVec2 ArcFastVtx[IM_DRAWLIST_ARCFAST_TABLE_SIZE]; // Sample points on the quarter of the circle. - float ArcFastRadiusCutoff; // Cutoff radius after which arc drawing will fallback to slower PathArcTo() - ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead) - - ImDrawListSharedData(); - ~ImDrawListSharedData(); - void SetCircleTessellationMaxError(float max_error); -}; - -struct ImDrawDataBuilder -{ - ImVector* Layers[2]; // Pointers to global layers for: regular, tooltip. LayersP[0] is owned by DrawData. - ImVector LayerData1; - - ImDrawDataBuilder() { memset(this, 0, sizeof(*this)); } -}; - -struct ImFontStackData -{ - ImFont* Font; - float FontSizeBeforeScaling; // ~~ style.FontSizeBase - float FontSizeAfterScaling; // ~~ g.FontSize -}; - -//----------------------------------------------------------------------------- -// [SECTION] Style support -//----------------------------------------------------------------------------- - -struct ImGuiStyleVarInfo -{ - ImU32 Count : 8; // 1+ - ImGuiDataType DataType : 8; - ImU32 Offset : 16; // Offset in parent structure - void* GetVarPtr(void* parent) const { return (void*)((unsigned char*)parent + Offset); } -}; - -// Stacked color modifier, backup of modified data so we can restore it -struct ImGuiColorMod -{ - ImGuiCol Col; - ImVec4 BackupValue; -}; - -// Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable. -struct ImGuiStyleMod -{ - ImGuiStyleVar VarIdx; - union { int BackupInt[2]; float BackupFloat[2]; }; - ImGuiStyleMod(ImGuiStyleVar idx, int v) { VarIdx = idx; BackupInt[0] = v; } - ImGuiStyleMod(ImGuiStyleVar idx, float v) { VarIdx = idx; BackupFloat[0] = v; } - ImGuiStyleMod(ImGuiStyleVar idx, ImVec2 v) { VarIdx = idx; BackupFloat[0] = v.x; BackupFloat[1] = v.y; } -}; - -//----------------------------------------------------------------------------- -// [SECTION] Data types support -//----------------------------------------------------------------------------- - -struct ImGuiDataTypeStorage -{ - ImU8 Data[8]; // Opaque storage to fit any data up to ImGuiDataType_COUNT -}; - -// Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo(). -struct ImGuiDataTypeInfo -{ - size_t Size; // Size in bytes - const char* Name; // Short descriptive name for the type, for debugging - const char* PrintFmt; // Default printf format for the type - const char* ScanFmt; // Default scanf format for the type -}; - -// Extend ImGuiDataType_ -enum ImGuiDataTypePrivate_ -{ - ImGuiDataType_Pointer = ImGuiDataType_COUNT, - ImGuiDataType_ID, -}; - -//----------------------------------------------------------------------------- -// [SECTION] Widgets support: flags, enums, data structures -//----------------------------------------------------------------------------- - -// Extend ImGuiItemFlags -// - input: PushItemFlag() manipulates g.CurrentItemFlags, g.NextItemData.ItemFlags, ItemAdd() calls may add extra flags too. -// - output: stored in g.LastItemData.ItemFlags -enum ImGuiItemFlagsPrivate_ -{ - // Controlled by user - ImGuiItemFlags_Disabled = 1 << 10, // false // Disable interactions (DOES NOT affect visuals. DO NOT mix direct use of this with BeginDisabled(). See BeginDisabled()/EndDisabled() for full disable feature, and github #211). - ImGuiItemFlags_ReadOnly = 1 << 11, // false // [ALPHA] Allow hovering interactions but underlying value is not changed. - ImGuiItemFlags_MixedValue = 1 << 12, // false // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets) - ImGuiItemFlags_NoWindowHoverableCheck = 1 << 13, // false // Disable hoverable check in ItemHoverable() - ImGuiItemFlags_AllowOverlap = 1 << 14, // false // Allow being overlapped by another widget. Not-hovered to Hovered transition deferred by a frame. - ImGuiItemFlags_NoNavDisableMouseHover = 1 << 15, // false // Nav keyboard/gamepad mode doesn't disable hover highlight (behave as if NavHighlightItemUnderNav==false). - ImGuiItemFlags_NoMarkEdited = 1 << 16, // false // Skip calling MarkItemEdited() - ImGuiItemFlags_NoFocus = 1 << 17, // false // [EXPERIMENTAL: Not very well specced] Clicking doesn't take focus. Automatically sets ImGuiButtonFlags_NoFocus + ImGuiButtonFlags_NoNavFocus in ButtonBehavior(). - - // Controlled by widget code - ImGuiItemFlags_Inputable = 1 << 20, // false // [WIP] Auto-activate input mode when tab focused. Currently only used and supported by a few items before it becomes a generic feature. - ImGuiItemFlags_HasSelectionUserData = 1 << 21, // false // Set by SetNextItemSelectionUserData() - ImGuiItemFlags_IsMultiSelect = 1 << 22, // false // Set by SetNextItemSelectionUserData() - - ImGuiItemFlags_Default_ = ImGuiItemFlags_AutoClosePopups, // Please don't change, use PushItemFlag() instead. - - // Obsolete - //ImGuiItemFlags_SelectableDontClosePopup = !ImGuiItemFlags_AutoClosePopups, // Can't have a redirect as we inverted the behavior -}; - -// Status flags for an already submitted item -// - output: stored in g.LastItemData.StatusFlags -enum ImGuiItemStatusFlags_ -{ - ImGuiItemStatusFlags_None = 0, - ImGuiItemStatusFlags_HoveredRect = 1 << 0, // Mouse position is within item rectangle (does NOT mean that the window is in correct z-order and can be hovered!, this is only one part of the most-common IsItemHovered test) - ImGuiItemStatusFlags_HasDisplayRect = 1 << 1, // g.LastItemData.DisplayRect is valid - ImGuiItemStatusFlags_Edited = 1 << 2, // Value exposed by item was edited in the current frame (should match the bool return value of most widgets) - ImGuiItemStatusFlags_ToggledSelection = 1 << 3, // Set when Selectable(), TreeNode() reports toggling a selection. We can't report "Selected", only state changes, in order to easily handle clipping with less issues. - ImGuiItemStatusFlags_ToggledOpen = 1 << 4, // Set when TreeNode() reports toggling their open state. - ImGuiItemStatusFlags_HasDeactivated = 1 << 5, // Set if the widget/group is able to provide data for the ImGuiItemStatusFlags_Deactivated flag. - ImGuiItemStatusFlags_Deactivated = 1 << 6, // Only valid if ImGuiItemStatusFlags_HasDeactivated is set. - ImGuiItemStatusFlags_HoveredWindow = 1 << 7, // Override the HoveredWindow test to allow cross-window hover testing. - ImGuiItemStatusFlags_Visible = 1 << 8, // [WIP] Set when item is overlapping the current clipping rectangle (Used internally. Please don't use yet: API/system will change as we refactor Itemadd()). - ImGuiItemStatusFlags_HasClipRect = 1 << 9, // g.LastItemData.ClipRect is valid. - ImGuiItemStatusFlags_HasShortcut = 1 << 10, // g.LastItemData.Shortcut valid. Set by SetNextItemShortcut() -> ItemAdd(). - //ImGuiItemStatusFlags_FocusedByTabbing = 1 << 8, // Removed IN 1.90.1 (Dec 2023). The trigger is part of g.NavActivateId. See commit 54c1bdeceb. - - // Additional status + semantic for ImGuiTestEngine -#ifdef IMGUI_ENABLE_TEST_ENGINE - ImGuiItemStatusFlags_Openable = 1 << 20, // Item is an openable (e.g. TreeNode) - ImGuiItemStatusFlags_Opened = 1 << 21, // Opened status - ImGuiItemStatusFlags_Checkable = 1 << 22, // Item is a checkable (e.g. CheckBox, MenuItem) - ImGuiItemStatusFlags_Checked = 1 << 23, // Checked status - ImGuiItemStatusFlags_Inputable = 1 << 24, // Item is a text-inputable (e.g. InputText, SliderXXX, DragXXX) -#endif -}; - -// Extend ImGuiHoveredFlags_ -enum ImGuiHoveredFlagsPrivate_ -{ - ImGuiHoveredFlags_DelayMask_ = ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_NoSharedDelay, - ImGuiHoveredFlags_AllowedMaskForIsWindowHovered = ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_Stationary, - ImGuiHoveredFlags_AllowedMaskForIsItemHovered = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped | ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_NoNavOverride | ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayMask_, -}; - -// Extend ImGuiInputTextFlags_ -enum ImGuiInputTextFlagsPrivate_ -{ - // [Internal] - ImGuiInputTextFlags_Multiline = 1 << 26, // For internal use by InputTextMultiline() - ImGuiInputTextFlags_MergedItem = 1 << 27, // For internal use by TempInputText(), will skip calling ItemAdd(). Require bounding-box to strictly match. - ImGuiInputTextFlags_LocalizeDecimalPoint= 1 << 28, // For internal use by InputScalar() and TempInputScalar() -}; - -// Extend ImGuiButtonFlags_ -enum ImGuiButtonFlagsPrivate_ -{ - ImGuiButtonFlags_PressedOnClick = 1 << 4, // return true on click (mouse down event) - ImGuiButtonFlags_PressedOnClickRelease = 1 << 5, // [Default] return true on click + release on same item <-- this is what the majority of Button are using - ImGuiButtonFlags_PressedOnClickReleaseAnywhere = 1 << 6, // return true on click + release even if the release event is not done while hovering the item - ImGuiButtonFlags_PressedOnRelease = 1 << 7, // return true on release (default requires click+release) - ImGuiButtonFlags_PressedOnDoubleClick = 1 << 8, // return true on double-click (default requires click+release) - ImGuiButtonFlags_PressedOnDragDropHold = 1 << 9, // return true when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers) - //ImGuiButtonFlags_Repeat = 1 << 10, // hold to repeat -> use ImGuiItemFlags_ButtonRepeat instead. - ImGuiButtonFlags_FlattenChildren = 1 << 11, // allow interactions even if a child window is overlapping - ImGuiButtonFlags_AllowOverlap = 1 << 12, // require previous frame HoveredId to either match id or be null before being usable. - //ImGuiButtonFlags_DontClosePopups = 1 << 13, // disable automatically closing parent popup on press - //ImGuiButtonFlags_Disabled = 1 << 14, // disable interactions -> use BeginDisabled() or ImGuiItemFlags_Disabled - ImGuiButtonFlags_AlignTextBaseLine = 1 << 15, // vertically align button to match text baseline - ButtonEx() only // FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine - ImGuiButtonFlags_NoKeyModsAllowed = 1 << 16, // disable mouse interaction if a key modifier is held - ImGuiButtonFlags_NoHoldingActiveId = 1 << 17, // don't set ActiveId while holding the mouse (ImGuiButtonFlags_PressedOnClick only) - ImGuiButtonFlags_NoNavFocus = 1 << 18, // don't override navigation focus when activated (FIXME: this is essentially used every time an item uses ImGuiItemFlags_NoNav, but because legacy specs don't requires LastItemData to be set ButtonBehavior(), we can't poll g.LastItemData.ItemFlags) - ImGuiButtonFlags_NoHoveredOnFocus = 1 << 19, // don't report as hovered when nav focus is on this item - ImGuiButtonFlags_NoSetKeyOwner = 1 << 20, // don't set key/input owner on the initial click (note: mouse buttons are keys! often, the key in question will be ImGuiKey_MouseLeft!) - ImGuiButtonFlags_NoTestKeyOwner = 1 << 21, // don't test key/input owner when polling the key (note: mouse buttons are keys! often, the key in question will be ImGuiKey_MouseLeft!) - ImGuiButtonFlags_NoFocus = 1 << 22, // [EXPERIMENTAL: Not very well specced]. Don't focus parent window when clicking. - ImGuiButtonFlags_PressedOnMask_ = ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_PressedOnDragDropHold, - ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease, - //ImGuiButtonFlags_NoKeyModifiers = ImGuiButtonFlags_NoKeyModsAllowed, // Renamed in 1.91.4 -}; - -// Extend ImGuiComboFlags_ -enum ImGuiComboFlagsPrivate_ -{ - ImGuiComboFlags_CustomPreview = 1 << 20, // enable BeginComboPreview() -}; - -// Extend ImGuiSliderFlags_ -enum ImGuiSliderFlagsPrivate_ -{ - ImGuiSliderFlags_Vertical = 1 << 20, // Should this slider be orientated vertically? - ImGuiSliderFlags_ReadOnly = 1 << 21, // Consider using g.NextItemData.ItemFlags |= ImGuiItemFlags_ReadOnly instead. -}; - -// Extend ImGuiSelectableFlags_ -enum ImGuiSelectableFlagsPrivate_ -{ - // NB: need to be in sync with last value of ImGuiSelectableFlags_ - ImGuiSelectableFlags_NoHoldingActiveID = 1 << 20, - ImGuiSelectableFlags_SelectOnNav = 1 << 21, // (WIP) Auto-select when moved into. This is not exposed in public API as to handle multi-select and modifiers we will need user to explicitly control focus scope. May be replaced with a BeginSelection() API. - ImGuiSelectableFlags_SelectOnClick = 1 << 22, // Override button behavior to react on Click (default is Click+Release) - ImGuiSelectableFlags_SelectOnRelease = 1 << 23, // Override button behavior to react on Release (default is Click+Release) - ImGuiSelectableFlags_SpanAvailWidth = 1 << 24, // Span all avail width even if we declared less for layout purpose. FIXME: We may be able to remove this (added in 6251d379, 2bcafc86 for menus) - ImGuiSelectableFlags_SetNavIdOnHover = 1 << 25, // Set Nav/Focus ID on mouse hover (used by MenuItem) - ImGuiSelectableFlags_NoPadWithHalfSpacing = 1 << 26, // Disable padding each side with ItemSpacing * 0.5f - ImGuiSelectableFlags_NoSetKeyOwner = 1 << 27, // Don't set key/input owner on the initial click (note: mouse buttons are keys! often, the key in question will be ImGuiKey_MouseLeft!) -}; - -// Extend ImGuiTreeNodeFlags_ -enum ImGuiTreeNodeFlagsPrivate_ -{ - ImGuiTreeNodeFlags_NoNavFocus = 1 << 27,// Don't claim nav focus when interacting with this item (#8551) - ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 28,// FIXME-WIP: Hard-coded for CollapsingHeader() - ImGuiTreeNodeFlags_UpsideDownArrow = 1 << 29,// FIXME-WIP: Turn Down arrow into an Up arrow, for reversed trees (#6517) - ImGuiTreeNodeFlags_OpenOnMask_ = ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_OpenOnArrow, - ImGuiTreeNodeFlags_DrawLinesMask_ = ImGuiTreeNodeFlags_DrawLinesNone | ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes, -}; - -enum ImGuiSeparatorFlags_ -{ - ImGuiSeparatorFlags_None = 0, - ImGuiSeparatorFlags_Horizontal = 1 << 0, // Axis default to current layout type, so generally Horizontal unless e.g. in a menu bar - ImGuiSeparatorFlags_Vertical = 1 << 1, - ImGuiSeparatorFlags_SpanAllColumns = 1 << 2, // Make separator cover all columns of a legacy Columns() set. -}; - -// Flags for FocusWindow(). This is not called ImGuiFocusFlags to avoid confusion with public-facing ImGuiFocusedFlags. -// FIXME: Once we finishing replacing more uses of GetTopMostPopupModal()+IsWindowWithinBeginStackOf() -// and FindBlockingModal() with this, we may want to change the flag to be opt-out instead of opt-in. -enum ImGuiFocusRequestFlags_ -{ - ImGuiFocusRequestFlags_None = 0, - ImGuiFocusRequestFlags_RestoreFocusedChild = 1 << 0, // Find last focused child (if any) and focus it instead. - ImGuiFocusRequestFlags_UnlessBelowModal = 1 << 1, // Do not set focus if the window is below a modal. -}; - -enum ImGuiTextFlags_ -{ - ImGuiTextFlags_None = 0, - ImGuiTextFlags_NoWidthForLargeClippedText = 1 << 0, -}; - -enum ImGuiTooltipFlags_ -{ - ImGuiTooltipFlags_None = 0, - ImGuiTooltipFlags_OverridePrevious = 1 << 1, // Clear/ignore previously submitted tooltip (defaults to append) -}; - -// FIXME: this is in development, not exposed/functional as a generic feature yet. -// Horizontal/Vertical enums are fixed to 0/1 so they may be used to index ImVec2 -enum ImGuiLayoutType_ -{ - ImGuiLayoutType_Horizontal = 0, - ImGuiLayoutType_Vertical = 1 -}; - -// Flags for LogBegin() text capturing function -enum ImGuiLogFlags_ -{ - ImGuiLogFlags_None = 0, - - ImGuiLogFlags_OutputTTY = 1 << 0, - ImGuiLogFlags_OutputFile = 1 << 1, - ImGuiLogFlags_OutputBuffer = 1 << 2, - ImGuiLogFlags_OutputClipboard = 1 << 3, - ImGuiLogFlags_OutputMask_ = ImGuiLogFlags_OutputTTY | ImGuiLogFlags_OutputFile | ImGuiLogFlags_OutputBuffer | ImGuiLogFlags_OutputClipboard, -}; - -// X/Y enums are fixed to 0/1 so they may be used to index ImVec2 -enum ImGuiAxis -{ - ImGuiAxis_None = -1, - ImGuiAxis_X = 0, - ImGuiAxis_Y = 1 -}; - -enum ImGuiPlotType -{ - ImGuiPlotType_Lines, - ImGuiPlotType_Histogram, -}; - -// Storage data for BeginComboPreview()/EndComboPreview() -struct IMGUI_API ImGuiComboPreviewData -{ - ImRect PreviewRect; - ImVec2 BackupCursorPos; - ImVec2 BackupCursorMaxPos; - ImVec2 BackupCursorPosPrevLine; - float BackupPrevLineTextBaseOffset; - ImGuiLayoutType BackupLayout; - - ImGuiComboPreviewData() { memset(this, 0, sizeof(*this)); } -}; - -// Stacked storage data for BeginGroup()/EndGroup() -struct IMGUI_API ImGuiGroupData -{ - ImGuiID WindowID; - ImVec2 BackupCursorPos; - ImVec2 BackupCursorMaxPos; - ImVec2 BackupCursorPosPrevLine; - ImVec1 BackupIndent; - ImVec1 BackupGroupOffset; - ImVec2 BackupCurrLineSize; - float BackupCurrLineTextBaseOffset; - ImGuiID BackupActiveIdIsAlive; - bool BackupDeactivatedIdIsAlive; - bool BackupHoveredIdIsAlive; - bool BackupIsSameLine; - bool EmitItem; -}; - -// Simple column measurement, currently used for MenuItem() only.. This is very short-sighted/throw-away code and NOT a generic helper. -struct IMGUI_API ImGuiMenuColumns -{ - ImU32 TotalWidth; - ImU32 NextTotalWidth; - ImU16 Spacing; - ImU16 OffsetIcon; // Always zero for now - ImU16 OffsetLabel; // Offsets are locked in Update() - ImU16 OffsetShortcut; - ImU16 OffsetMark; - ImU16 Widths[4]; // Width of: Icon, Label, Shortcut, Mark (accumulators for current frame) - - ImGuiMenuColumns() { memset(this, 0, sizeof(*this)); } - void Update(float spacing, bool window_reappearing); - float DeclColumns(float w_icon, float w_label, float w_shortcut, float w_mark); - void CalcNextTotalWidth(bool update_offsets); -}; - -// Internal temporary state for deactivating InputText() instances. -struct IMGUI_API ImGuiInputTextDeactivatedState -{ - ImGuiID ID; // widget id owning the text state (which just got deactivated) - ImVector TextA; // text buffer - - ImGuiInputTextDeactivatedState() { memset(this, 0, sizeof(*this)); } - void ClearFreeMemory() { ID = 0; TextA.clear(); } -}; - -// Forward declare imstb_textedit.h structure + make its main configuration define accessible -#undef IMSTB_TEXTEDIT_STRING -#undef IMSTB_TEXTEDIT_CHARTYPE -#define IMSTB_TEXTEDIT_STRING ImGuiInputTextState -#define IMSTB_TEXTEDIT_CHARTYPE char -#define IMSTB_TEXTEDIT_GETWIDTH_NEWLINE (-1.0f) -#define IMSTB_TEXTEDIT_UNDOSTATECOUNT 99 -#define IMSTB_TEXTEDIT_UNDOCHARCOUNT 999 -namespace ImStb { struct STB_TexteditState; } -typedef ImStb::STB_TexteditState ImStbTexteditState; - -// Internal state of the currently focused/edited text input box -// For a given item ID, access with ImGui::GetInputTextState() -struct IMGUI_API ImGuiInputTextState -{ - ImGuiContext* Ctx; // parent UI context (needs to be set explicitly by parent). - ImStbTexteditState* Stb; // State for stb_textedit.h - ImGuiInputTextFlags Flags; // copy of InputText() flags. may be used to check if e.g. ImGuiInputTextFlags_Password is set. - ImGuiID ID; // widget id owning the text state - int TextLen; // UTF-8 length of the string in TextA (in bytes) - const char* TextSrc; // == TextA.Data unless read-only, in which case == buf passed to InputText(). Field only set and valid _inside_ the call InputText() call. - ImVector TextA; // main UTF8 buffer. TextA.Size is a buffer size! Should always be >= buf_size passed by user (and of course >= CurLenA + 1). - ImVector TextToRevertTo; // value to revert to when pressing Escape = backup of end-user buffer at the time of focus (in UTF-8, unaltered) - ImVector CallbackTextBackup; // temporary storage for callback to support automatic reconcile of undo-stack - int BufCapacity; // end-user buffer capacity (include zero terminator) - ImVec2 Scroll; // horizontal offset (managed manually) + vertical scrolling (pulled from child window's own Scroll.y) - float CursorAnim; // timer for cursor blink, reset on every user action so the cursor reappears immediately - bool CursorFollow; // set when we want scrolling to follow the current cursor position (not always!) - bool SelectedAllMouseLock; // after a double-click to select all, we ignore further mouse drags to update selection - bool Edited; // edited this frame - bool WantReloadUserBuf; // force a reload of user buf so it may be modified externally. may be automatic in future version. - int ReloadSelectionStart; - int ReloadSelectionEnd; - - ImGuiInputTextState(); - ~ImGuiInputTextState(); - void ClearText() { TextLen = 0; TextA[0] = 0; CursorClamp(); } - void ClearFreeMemory() { TextA.clear(); TextToRevertTo.clear(); } - void OnKeyPressed(int key); // Cannot be inline because we call in code in stb_textedit.h implementation - void OnCharPressed(unsigned int c); - - // Cursor & Selection - void CursorAnimReset(); - void CursorClamp(); - bool HasSelection() const; - void ClearSelection(); - int GetCursorPos() const; - int GetSelectionStart() const; - int GetSelectionEnd() const; - void SelectAll(); - - // Reload user buf (WIP #2890) - // If you modify underlying user-passed const char* while active you need to call this (InputText V2 may lift this) - // strcpy(my_buf, "hello"); - // if (ImGuiInputTextState* state = ImGui::GetInputTextState(id)) // id may be ImGui::GetItemID() is last item - // state->ReloadUserBufAndSelectAll(); - void ReloadUserBufAndSelectAll(); - void ReloadUserBufAndKeepSelection(); - void ReloadUserBufAndMoveToEnd(); -}; - -enum ImGuiWindowRefreshFlags_ -{ - ImGuiWindowRefreshFlags_None = 0, - ImGuiWindowRefreshFlags_TryToAvoidRefresh = 1 << 0, // [EXPERIMENTAL] Try to keep existing contents, USER MUST NOT HONOR BEGIN() RETURNING FALSE AND NOT APPEND. - ImGuiWindowRefreshFlags_RefreshOnHover = 1 << 1, // [EXPERIMENTAL] Always refresh on hover - ImGuiWindowRefreshFlags_RefreshOnFocus = 1 << 2, // [EXPERIMENTAL] Always refresh on focus - // Refresh policy/frequency, Load Balancing etc. -}; - -enum ImGuiNextWindowDataFlags_ -{ - ImGuiNextWindowDataFlags_None = 0, - ImGuiNextWindowDataFlags_HasPos = 1 << 0, - ImGuiNextWindowDataFlags_HasSize = 1 << 1, - ImGuiNextWindowDataFlags_HasContentSize = 1 << 2, - ImGuiNextWindowDataFlags_HasCollapsed = 1 << 3, - ImGuiNextWindowDataFlags_HasSizeConstraint = 1 << 4, - ImGuiNextWindowDataFlags_HasFocus = 1 << 5, - ImGuiNextWindowDataFlags_HasBgAlpha = 1 << 6, - ImGuiNextWindowDataFlags_HasScroll = 1 << 7, - ImGuiNextWindowDataFlags_HasWindowFlags = 1 << 8, - ImGuiNextWindowDataFlags_HasChildFlags = 1 << 9, - ImGuiNextWindowDataFlags_HasRefreshPolicy = 1 << 10, -}; - -// Storage for SetNexWindow** functions -struct ImGuiNextWindowData -{ - ImGuiNextWindowDataFlags HasFlags; - - // Members below are NOT cleared. Always rely on HasFlags. - ImGuiCond PosCond; - ImGuiCond SizeCond; - ImGuiCond CollapsedCond; - ImVec2 PosVal; - ImVec2 PosPivotVal; - ImVec2 SizeVal; - ImVec2 ContentSizeVal; - ImVec2 ScrollVal; - ImGuiWindowFlags WindowFlags; // Only honored by BeginTable() - ImGuiChildFlags ChildFlags; - bool CollapsedVal; - ImRect SizeConstraintRect; - ImGuiSizeCallback SizeCallback; - void* SizeCallbackUserData; - float BgAlphaVal; // Override background alpha - ImVec2 MenuBarOffsetMinVal; // (Always on) This is not exposed publicly, so we don't clear it and it doesn't have a corresponding flag (could we? for consistency?) - ImGuiWindowRefreshFlags RefreshFlagsVal; - - ImGuiNextWindowData() { memset(this, 0, sizeof(*this)); } - inline void ClearFlags() { HasFlags = ImGuiNextWindowDataFlags_None; } -}; - -enum ImGuiNextItemDataFlags_ -{ - ImGuiNextItemDataFlags_None = 0, - ImGuiNextItemDataFlags_HasWidth = 1 << 0, - ImGuiNextItemDataFlags_HasOpen = 1 << 1, - ImGuiNextItemDataFlags_HasShortcut = 1 << 2, - ImGuiNextItemDataFlags_HasRefVal = 1 << 3, - ImGuiNextItemDataFlags_HasStorageID = 1 << 4, -}; - -struct ImGuiNextItemData -{ - ImGuiNextItemDataFlags HasFlags; // Called HasFlags instead of Flags to avoid mistaking this - ImGuiItemFlags ItemFlags; // Currently only tested/used for ImGuiItemFlags_AllowOverlap and ImGuiItemFlags_HasSelectionUserData. - - // Members below are NOT cleared by ItemAdd() meaning they are still valid during e.g. NavProcessItem(). Always rely on HasFlags. - ImGuiID FocusScopeId; // Set by SetNextItemSelectionUserData() - ImGuiSelectionUserData SelectionUserData; // Set by SetNextItemSelectionUserData() (note that NULL/0 is a valid value, we use -1 == ImGuiSelectionUserData_Invalid to mark invalid values) - float Width; // Set by SetNextItemWidth() - ImGuiKeyChord Shortcut; // Set by SetNextItemShortcut() - ImGuiInputFlags ShortcutFlags; // Set by SetNextItemShortcut() - bool OpenVal; // Set by SetNextItemOpen() - ImU8 OpenCond; // Set by SetNextItemOpen() - ImGuiDataTypeStorage RefVal; // Not exposed yet, for ImGuiInputTextFlags_ParseEmptyAsRefVal - ImGuiID StorageId; // Set by SetNextItemStorageID() - - ImGuiNextItemData() { memset(this, 0, sizeof(*this)); SelectionUserData = -1; } - inline void ClearFlags() { HasFlags = ImGuiNextItemDataFlags_None; ItemFlags = ImGuiItemFlags_None; } // Also cleared manually by ItemAdd()! -}; - -// Status storage for the last submitted item -struct ImGuiLastItemData -{ - ImGuiID ID; - ImGuiItemFlags ItemFlags; // See ImGuiItemFlags_ (called 'InFlags' before v1.91.4). - ImGuiItemStatusFlags StatusFlags; // See ImGuiItemStatusFlags_ - ImRect Rect; // Full rectangle - ImRect NavRect; // Navigation scoring rectangle (not displayed) - // Rarely used fields are not explicitly cleared, only valid when the corresponding ImGuiItemStatusFlags are set. - ImRect DisplayRect; // Display rectangle. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) is set. - ImRect ClipRect; // Clip rectangle at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags_HasClipRect) is set.. - ImGuiKeyChord Shortcut; // Shortcut at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags_HasShortcut) is set.. - - ImGuiLastItemData() { memset(this, 0, sizeof(*this)); } -}; - -// Store data emitted by TreeNode() for usage by TreePop() -// - To implement ImGuiTreeNodeFlags_NavLeftJumpsToParent: store the minimum amount of data -// which we can't infer in TreePop(), to perform the equivalent of NavApplyItemToResult(). -// Only stored when the node is a potential candidate for landing on a Left arrow jump. -struct ImGuiTreeNodeStackData -{ - ImGuiID ID; - ImGuiTreeNodeFlags TreeFlags; - ImGuiItemFlags ItemFlags; // Used for nav landing - ImRect NavRect; // Used for nav landing - float DrawLinesX1; - float DrawLinesToNodesY2; - ImGuiTableColumnIdx DrawLinesTableColumn; -}; - -// sizeof() = 20 -struct IMGUI_API ImGuiErrorRecoveryState -{ - short SizeOfWindowStack; - short SizeOfIDStack; - short SizeOfTreeStack; - short SizeOfColorStack; - short SizeOfStyleVarStack; - short SizeOfFontStack; - short SizeOfFocusScopeStack; - short SizeOfGroupStack; - short SizeOfItemFlagsStack; - short SizeOfBeginPopupStack; - short SizeOfDisabledStack; - - ImGuiErrorRecoveryState() { memset(this, 0, sizeof(*this)); } -}; - -// Data saved for each window pushed into the stack -struct ImGuiWindowStackData -{ - ImGuiWindow* Window; - ImGuiLastItemData ParentLastItemDataBackup; - ImGuiErrorRecoveryState StackSizesInBegin; // Store size of various stacks for asserting - bool DisabledOverrideReenable; // Non-child window override disabled flag - float DisabledOverrideReenableAlphaBackup; -}; - -struct ImGuiShrinkWidthItem -{ - int Index; - float Width; - float InitialWidth; -}; - -struct ImGuiPtrOrIndex -{ - void* Ptr; // Either field can be set, not both. e.g. Dock node tab bars are loose while BeginTabBar() ones are in a pool. - int Index; // Usually index in a main pool. - - ImGuiPtrOrIndex(void* ptr) { Ptr = ptr; Index = -1; } - ImGuiPtrOrIndex(int index) { Ptr = NULL; Index = index; } -}; - -// Data used by IsItemDeactivated()/IsItemDeactivatedAfterEdit() functions -struct ImGuiDeactivatedItemData -{ - ImGuiID ID; - int ElapseFrame; - bool HasBeenEditedBefore; - bool IsAlive; -}; - -//----------------------------------------------------------------------------- -// [SECTION] Popup support -//----------------------------------------------------------------------------- - -enum ImGuiPopupPositionPolicy -{ - ImGuiPopupPositionPolicy_Default, - ImGuiPopupPositionPolicy_ComboBox, - ImGuiPopupPositionPolicy_Tooltip, -}; - -// Storage for popup stacks (g.OpenPopupStack and g.BeginPopupStack) -struct ImGuiPopupData -{ - ImGuiID PopupId; // Set on OpenPopup() - ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup() - ImGuiWindow* RestoreNavWindow;// Set on OpenPopup(), a NavWindow that will be restored on popup close - int ParentNavLayer; // Resolved on BeginPopup(). Actually a ImGuiNavLayer type (declared down below), initialized to -1 which is not part of an enum, but serves well-enough as "not any of layers" value - int OpenFrameCount; // Set on OpenPopup() - ImGuiID OpenParentId; // Set on OpenPopup(), we need this to differentiate multiple menu sets from each others (e.g. inside menu bar vs loose menu items) - ImVec2 OpenPopupPos; // Set on OpenPopup(), preferred popup position (typically == OpenMousePos when using mouse) - ImVec2 OpenMousePos; // Set on OpenPopup(), copy of mouse position at the time of opening popup - - ImGuiPopupData() { memset(this, 0, sizeof(*this)); ParentNavLayer = OpenFrameCount = -1; } -}; - -//----------------------------------------------------------------------------- -// [SECTION] Inputs support -//----------------------------------------------------------------------------- - -// Bit array for named keys -typedef ImBitArray ImBitArrayForNamedKeys; - -// [Internal] Key ranges -#define ImGuiKey_LegacyNativeKey_BEGIN 0 -#define ImGuiKey_LegacyNativeKey_END 512 -#define ImGuiKey_Keyboard_BEGIN (ImGuiKey_NamedKey_BEGIN) -#define ImGuiKey_Keyboard_END (ImGuiKey_GamepadStart) -#define ImGuiKey_Gamepad_BEGIN (ImGuiKey_GamepadStart) -#define ImGuiKey_Gamepad_END (ImGuiKey_GamepadRStickDown + 1) -#define ImGuiKey_Mouse_BEGIN (ImGuiKey_MouseLeft) -#define ImGuiKey_Mouse_END (ImGuiKey_MouseWheelY + 1) -#define ImGuiKey_Aliases_BEGIN (ImGuiKey_Mouse_BEGIN) -#define ImGuiKey_Aliases_END (ImGuiKey_Mouse_END) - -// [Internal] Named shortcuts for Navigation -#define ImGuiKey_NavKeyboardTweakSlow ImGuiMod_Ctrl -#define ImGuiKey_NavKeyboardTweakFast ImGuiMod_Shift -#define ImGuiKey_NavGamepadTweakSlow ImGuiKey_GamepadL1 -#define ImGuiKey_NavGamepadTweakFast ImGuiKey_GamepadR1 -#define ImGuiKey_NavGamepadActivate (g.IO.ConfigNavSwapGamepadButtons ? ImGuiKey_GamepadFaceRight : ImGuiKey_GamepadFaceDown) -#define ImGuiKey_NavGamepadCancel (g.IO.ConfigNavSwapGamepadButtons ? ImGuiKey_GamepadFaceDown : ImGuiKey_GamepadFaceRight) -#define ImGuiKey_NavGamepadMenu ImGuiKey_GamepadFaceLeft -#define ImGuiKey_NavGamepadInput ImGuiKey_GamepadFaceUp - -enum ImGuiInputEventType -{ - ImGuiInputEventType_None = 0, - ImGuiInputEventType_MousePos, - ImGuiInputEventType_MouseWheel, - ImGuiInputEventType_MouseButton, - ImGuiInputEventType_Key, - ImGuiInputEventType_Text, - ImGuiInputEventType_Focus, - ImGuiInputEventType_COUNT -}; - -enum ImGuiInputSource -{ - ImGuiInputSource_None = 0, - ImGuiInputSource_Mouse, // Note: may be Mouse or TouchScreen or Pen. See io.MouseSource to distinguish them. - ImGuiInputSource_Keyboard, - ImGuiInputSource_Gamepad, - ImGuiInputSource_COUNT -}; - -// FIXME: Structures in the union below need to be declared as anonymous unions appears to be an extension? -// Using ImVec2() would fail on Clang 'union member 'MousePos' has a non-trivial default constructor' -struct ImGuiInputEventMousePos { float PosX, PosY; ImGuiMouseSource MouseSource; }; -struct ImGuiInputEventMouseWheel { float WheelX, WheelY; ImGuiMouseSource MouseSource; }; -struct ImGuiInputEventMouseButton { int Button; bool Down; ImGuiMouseSource MouseSource; }; -struct ImGuiInputEventKey { ImGuiKey Key; bool Down; float AnalogValue; }; -struct ImGuiInputEventText { unsigned int Char; }; -struct ImGuiInputEventAppFocused { bool Focused; }; - -struct ImGuiInputEvent -{ - ImGuiInputEventType Type; - ImGuiInputSource Source; - ImU32 EventId; // Unique, sequential increasing integer to identify an event (if you need to correlate them to other data). - union - { - ImGuiInputEventMousePos MousePos; // if Type == ImGuiInputEventType_MousePos - ImGuiInputEventMouseWheel MouseWheel; // if Type == ImGuiInputEventType_MouseWheel - ImGuiInputEventMouseButton MouseButton; // if Type == ImGuiInputEventType_MouseButton - ImGuiInputEventKey Key; // if Type == ImGuiInputEventType_Key - ImGuiInputEventText Text; // if Type == ImGuiInputEventType_Text - ImGuiInputEventAppFocused AppFocused; // if Type == ImGuiInputEventType_Focus - }; - bool AddedByTestEngine; - - ImGuiInputEvent() { memset(this, 0, sizeof(*this)); } -}; - -// Input function taking an 'ImGuiID owner_id' argument defaults to (ImGuiKeyOwner_Any == 0) aka don't test ownership, which matches legacy behavior. -#define ImGuiKeyOwner_Any ((ImGuiID)0) // Accept key that have an owner, UNLESS a call to SetKeyOwner() explicitly used ImGuiInputFlags_LockThisFrame or ImGuiInputFlags_LockUntilRelease. -#define ImGuiKeyOwner_NoOwner ((ImGuiID)-1) // Require key to have no owner. -//#define ImGuiKeyOwner_None ImGuiKeyOwner_NoOwner // We previously called this 'ImGuiKeyOwner_None' but it was inconsistent with our pattern that _None values == 0 and quite dangerous. Also using _NoOwner makes the IsKeyPressed() calls more explicit. - -typedef ImS16 ImGuiKeyRoutingIndex; - -// Routing table entry (sizeof() == 16 bytes) -struct ImGuiKeyRoutingData -{ - ImGuiKeyRoutingIndex NextEntryIndex; - ImU16 Mods; // Technically we'd only need 4-bits but for simplify we store ImGuiMod_ values which need 16-bits. - ImU8 RoutingCurrScore; // [DEBUG] For debug display - ImU8 RoutingNextScore; // Lower is better (0: perfect score) - ImGuiID RoutingCurr; - ImGuiID RoutingNext; - - ImGuiKeyRoutingData() { NextEntryIndex = -1; Mods = 0; RoutingCurrScore = RoutingNextScore = 255; RoutingCurr = RoutingNext = ImGuiKeyOwner_NoOwner; } -}; - -// Routing table: maintain a desired owner for each possible key-chord (key + mods), and setup owner in NewFrame() when mods are matching. -// Stored in main context (1 instance) -struct ImGuiKeyRoutingTable -{ - ImGuiKeyRoutingIndex Index[ImGuiKey_NamedKey_COUNT]; // Index of first entry in Entries[] - ImVector Entries; - ImVector EntriesNext; // Double-buffer to avoid reallocation (could use a shared buffer) - - ImGuiKeyRoutingTable() { Clear(); } - void Clear() { for (int n = 0; n < IM_ARRAYSIZE(Index); n++) Index[n] = -1; Entries.clear(); EntriesNext.clear(); } -}; - -// This extends ImGuiKeyData but only for named keys (legacy keys don't support the new features) -// Stored in main context (1 per named key). In the future it might be merged into ImGuiKeyData. -struct ImGuiKeyOwnerData -{ - ImGuiID OwnerCurr; - ImGuiID OwnerNext; - bool LockThisFrame; // Reading this key requires explicit owner id (until end of frame). Set by ImGuiInputFlags_LockThisFrame. - bool LockUntilRelease; // Reading this key requires explicit owner id (until key is released). Set by ImGuiInputFlags_LockUntilRelease. When this is true LockThisFrame is always true as well. - - ImGuiKeyOwnerData() { OwnerCurr = OwnerNext = ImGuiKeyOwner_NoOwner; LockThisFrame = LockUntilRelease = false; } -}; - -// Extend ImGuiInputFlags_ -// Flags for extended versions of IsKeyPressed(), IsMouseClicked(), Shortcut(), SetKeyOwner(), SetItemKeyOwner() -// Don't mistake with ImGuiInputTextFlags! (which is for ImGui::InputText() function) -enum ImGuiInputFlagsPrivate_ -{ - // Flags for IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(), Shortcut() - // - Repeat mode: Repeat rate selection - ImGuiInputFlags_RepeatRateDefault = 1 << 1, // Repeat rate: Regular (default) - ImGuiInputFlags_RepeatRateNavMove = 1 << 2, // Repeat rate: Fast - ImGuiInputFlags_RepeatRateNavTweak = 1 << 3, // Repeat rate: Faster - // - Repeat mode: Specify when repeating key pressed can be interrupted. - // - In theory ImGuiInputFlags_RepeatUntilOtherKeyPress may be a desirable default, but it would break too many behavior so everything is opt-in. - ImGuiInputFlags_RepeatUntilRelease = 1 << 4, // Stop repeating when released (default for all functions except Shortcut). This only exists to allow overriding Shortcut() default behavior. - ImGuiInputFlags_RepeatUntilKeyModsChange = 1 << 5, // Stop repeating when released OR if keyboard mods are changed (default for Shortcut) - ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone = 1 << 6, // Stop repeating when released OR if keyboard mods are leaving the None state. Allows going from Mod+Key to Key by releasing Mod. - ImGuiInputFlags_RepeatUntilOtherKeyPress = 1 << 7, // Stop repeating when released OR if any other keyboard key is pressed during the repeat - - // Flags for SetKeyOwner(), SetItemKeyOwner() - // - Locking key away from non-input aware code. Locking is useful to make input-owner-aware code steal keys from non-input-owner-aware code. If all code is input-owner-aware locking would never be necessary. - ImGuiInputFlags_LockThisFrame = 1 << 20, // Further accesses to key data will require EXPLICIT owner ID (ImGuiKeyOwner_Any/0 will NOT accepted for polling). Cleared at end of frame. - ImGuiInputFlags_LockUntilRelease = 1 << 21, // Further accesses to key data will require EXPLICIT owner ID (ImGuiKeyOwner_Any/0 will NOT accepted for polling). Cleared when the key is released or at end of each frame if key is released. - - // - Condition for SetItemKeyOwner() - ImGuiInputFlags_CondHovered = 1 << 22, // Only set if item is hovered (default to both) - ImGuiInputFlags_CondActive = 1 << 23, // Only set if item is active (default to both) - ImGuiInputFlags_CondDefault_ = ImGuiInputFlags_CondHovered | ImGuiInputFlags_CondActive, - - // [Internal] Mask of which function support which flags - ImGuiInputFlags_RepeatRateMask_ = ImGuiInputFlags_RepeatRateDefault | ImGuiInputFlags_RepeatRateNavMove | ImGuiInputFlags_RepeatRateNavTweak, - ImGuiInputFlags_RepeatUntilMask_ = ImGuiInputFlags_RepeatUntilRelease | ImGuiInputFlags_RepeatUntilKeyModsChange | ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone | ImGuiInputFlags_RepeatUntilOtherKeyPress, - ImGuiInputFlags_RepeatMask_ = ImGuiInputFlags_Repeat | ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_, - ImGuiInputFlags_CondMask_ = ImGuiInputFlags_CondHovered | ImGuiInputFlags_CondActive, - ImGuiInputFlags_RouteTypeMask_ = ImGuiInputFlags_RouteActive | ImGuiInputFlags_RouteFocused | ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteAlways, - ImGuiInputFlags_RouteOptionsMask_ = ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive | ImGuiInputFlags_RouteUnlessBgFocused | ImGuiInputFlags_RouteFromRootWindow, - ImGuiInputFlags_SupportedByIsKeyPressed = ImGuiInputFlags_RepeatMask_, - ImGuiInputFlags_SupportedByIsMouseClicked = ImGuiInputFlags_Repeat, - ImGuiInputFlags_SupportedByShortcut = ImGuiInputFlags_RepeatMask_ | ImGuiInputFlags_RouteTypeMask_ | ImGuiInputFlags_RouteOptionsMask_, - ImGuiInputFlags_SupportedBySetNextItemShortcut = ImGuiInputFlags_RepeatMask_ | ImGuiInputFlags_RouteTypeMask_ | ImGuiInputFlags_RouteOptionsMask_ | ImGuiInputFlags_Tooltip, - ImGuiInputFlags_SupportedBySetKeyOwner = ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease, - ImGuiInputFlags_SupportedBySetItemKeyOwner = ImGuiInputFlags_SupportedBySetKeyOwner | ImGuiInputFlags_CondMask_, -}; - -//----------------------------------------------------------------------------- -// [SECTION] Clipper support -//----------------------------------------------------------------------------- - -// Note that Max is exclusive, so perhaps should be using a Begin/End convention. -struct ImGuiListClipperRange -{ - int Min; - int Max; - bool PosToIndexConvert; // Begin/End are absolute position (will be converted to indices later) - ImS8 PosToIndexOffsetMin; // Add to Min after converting to indices - ImS8 PosToIndexOffsetMax; // Add to Min after converting to indices - - static ImGuiListClipperRange FromIndices(int min, int max) { ImGuiListClipperRange r = { min, max, false, 0, 0 }; return r; } - static ImGuiListClipperRange FromPositions(float y1, float y2, int off_min, int off_max) { ImGuiListClipperRange r = { (int)y1, (int)y2, true, (ImS8)off_min, (ImS8)off_max }; return r; } -}; - -// Temporary clipper data, buffers shared/reused between instances -struct ImGuiListClipperData -{ - ImGuiListClipper* ListClipper; - float LossynessOffset; - int StepNo; - int ItemsFrozen; - ImVector Ranges; - - ImGuiListClipperData() { memset(this, 0, sizeof(*this)); } - void Reset(ImGuiListClipper* clipper) { ListClipper = clipper; StepNo = ItemsFrozen = 0; Ranges.resize(0); } -}; - -//----------------------------------------------------------------------------- -// [SECTION] Navigation support -//----------------------------------------------------------------------------- - -enum ImGuiActivateFlags_ -{ - ImGuiActivateFlags_None = 0, - ImGuiActivateFlags_PreferInput = 1 << 0, // Favor activation that requires keyboard text input (e.g. for Slider/Drag). Default for Enter key. - ImGuiActivateFlags_PreferTweak = 1 << 1, // Favor activation for tweaking with arrows or gamepad (e.g. for Slider/Drag). Default for Space key and if keyboard is not used. - ImGuiActivateFlags_TryToPreserveState = 1 << 2, // Request widget to preserve state if it can (e.g. InputText will try to preserve cursor/selection) - ImGuiActivateFlags_FromTabbing = 1 << 3, // Activation requested by a tabbing request - ImGuiActivateFlags_FromShortcut = 1 << 4, // Activation requested by an item shortcut via SetNextItemShortcut() function. -}; - -// Early work-in-progress API for ScrollToItem() -enum ImGuiScrollFlags_ -{ - ImGuiScrollFlags_None = 0, - ImGuiScrollFlags_KeepVisibleEdgeX = 1 << 0, // If item is not visible: scroll as little as possible on X axis to bring item back into view [default for X axis] - ImGuiScrollFlags_KeepVisibleEdgeY = 1 << 1, // If item is not visible: scroll as little as possible on Y axis to bring item back into view [default for Y axis for windows that are already visible] - ImGuiScrollFlags_KeepVisibleCenterX = 1 << 2, // If item is not visible: scroll to make the item centered on X axis [rarely used] - ImGuiScrollFlags_KeepVisibleCenterY = 1 << 3, // If item is not visible: scroll to make the item centered on Y axis - ImGuiScrollFlags_AlwaysCenterX = 1 << 4, // Always center the result item on X axis [rarely used] - ImGuiScrollFlags_AlwaysCenterY = 1 << 5, // Always center the result item on Y axis [default for Y axis for appearing window) - ImGuiScrollFlags_NoScrollParent = 1 << 6, // Disable forwarding scrolling to parent window if required to keep item/rect visible (only scroll window the function was applied to). - ImGuiScrollFlags_MaskX_ = ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleCenterX | ImGuiScrollFlags_AlwaysCenterX, - ImGuiScrollFlags_MaskY_ = ImGuiScrollFlags_KeepVisibleEdgeY | ImGuiScrollFlags_KeepVisibleCenterY | ImGuiScrollFlags_AlwaysCenterY, -}; - -enum ImGuiNavRenderCursorFlags_ -{ - ImGuiNavRenderCursorFlags_None = 0, - ImGuiNavRenderCursorFlags_Compact = 1 << 1, // Compact highlight, no padding/distance from focused item - ImGuiNavRenderCursorFlags_AlwaysDraw = 1 << 2, // Draw rectangular highlight if (g.NavId == id) even when g.NavCursorVisible == false, aka even when using the mouse. - ImGuiNavRenderCursorFlags_NoRounding = 1 << 3, -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiNavHighlightFlags_None = ImGuiNavRenderCursorFlags_None, // Renamed in 1.91.4 - ImGuiNavHighlightFlags_Compact = ImGuiNavRenderCursorFlags_Compact, // Renamed in 1.91.4 - ImGuiNavHighlightFlags_AlwaysDraw = ImGuiNavRenderCursorFlags_AlwaysDraw, // Renamed in 1.91.4 - ImGuiNavHighlightFlags_NoRounding = ImGuiNavRenderCursorFlags_NoRounding, // Renamed in 1.91.4 - //ImGuiNavHighlightFlags_TypeThin = ImGuiNavRenderCursorFlags_Compact, // Renamed in 1.90.2 -#endif -}; - -enum ImGuiNavMoveFlags_ -{ - ImGuiNavMoveFlags_None = 0, - ImGuiNavMoveFlags_LoopX = 1 << 0, // On failed request, restart from opposite side - ImGuiNavMoveFlags_LoopY = 1 << 1, - ImGuiNavMoveFlags_WrapX = 1 << 2, // On failed request, request from opposite side one line down (when NavDir==right) or one line up (when NavDir==left) - ImGuiNavMoveFlags_WrapY = 1 << 3, // This is not super useful but provided for completeness - ImGuiNavMoveFlags_WrapMask_ = ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_WrapY, - ImGuiNavMoveFlags_AllowCurrentNavId = 1 << 4, // Allow scoring and considering the current NavId as a move target candidate. This is used when the move source is offset (e.g. pressing PageDown actually needs to send a Up move request, if we are pressing PageDown from the bottom-most item we need to stay in place) - ImGuiNavMoveFlags_AlsoScoreVisibleSet = 1 << 5, // Store alternate result in NavMoveResultLocalVisible that only comprise elements that are already fully visible (used by PageUp/PageDown) - ImGuiNavMoveFlags_ScrollToEdgeY = 1 << 6, // Force scrolling to min/max (used by Home/End) // FIXME-NAV: Aim to remove or reword, probably unnecessary - ImGuiNavMoveFlags_Forwarded = 1 << 7, - ImGuiNavMoveFlags_DebugNoResult = 1 << 8, // Dummy scoring for debug purpose, don't apply result - ImGuiNavMoveFlags_FocusApi = 1 << 9, // Requests from focus API can land/focus/activate items even if they are marked with _NoTabStop (see NavProcessItemForTabbingRequest() for details) - ImGuiNavMoveFlags_IsTabbing = 1 << 10, // == Focus + Activate if item is Inputable + DontChangeNavHighlight - ImGuiNavMoveFlags_IsPageMove = 1 << 11, // Identify a PageDown/PageUp request. - ImGuiNavMoveFlags_Activate = 1 << 12, // Activate/select target item. - ImGuiNavMoveFlags_NoSelect = 1 << 13, // Don't trigger selection by not setting g.NavJustMovedTo - ImGuiNavMoveFlags_NoSetNavCursorVisible = 1 << 14, // Do not alter the nav cursor visible state - ImGuiNavMoveFlags_NoClearActiveId = 1 << 15, // (Experimental) Do not clear active id when applying move result -}; - -enum ImGuiNavLayer -{ - ImGuiNavLayer_Main = 0, // Main scrolling layer - ImGuiNavLayer_Menu = 1, // Menu layer (access with Alt) - ImGuiNavLayer_COUNT -}; - -// Storage for navigation query/results -struct ImGuiNavItemData -{ - ImGuiWindow* Window; // Init,Move // Best candidate window (result->ItemWindow->RootWindowForNav == request->Window) - ImGuiID ID; // Init,Move // Best candidate item ID - ImGuiID FocusScopeId; // Init,Move // Best candidate focus scope ID - ImRect RectRel; // Init,Move // Best candidate bounding box in window relative space - ImGuiItemFlags ItemFlags; // ????,Move // Best candidate item flags - float DistBox; // Move // Best candidate box distance to current NavId - float DistCenter; // Move // Best candidate center distance to current NavId - float DistAxial; // Move // Best candidate axial distance to current NavId - ImGuiSelectionUserData SelectionUserData;//I+Mov // Best candidate SetNextItemSelectionUserData() value. Valid if (ItemFlags & ImGuiItemFlags_HasSelectionUserData) - - ImGuiNavItemData() { Clear(); } - void Clear() { Window = NULL; ID = FocusScopeId = 0; ItemFlags = 0; SelectionUserData = -1; DistBox = DistCenter = DistAxial = FLT_MAX; } -}; - -// Storage for PushFocusScope(), g.FocusScopeStack[], g.NavFocusRoute[] -struct ImGuiFocusScopeData -{ - ImGuiID ID; - ImGuiID WindowID; -}; - -//----------------------------------------------------------------------------- -// [SECTION] Typing-select support -//----------------------------------------------------------------------------- - -// Flags for GetTypingSelectRequest() -enum ImGuiTypingSelectFlags_ -{ - ImGuiTypingSelectFlags_None = 0, - ImGuiTypingSelectFlags_AllowBackspace = 1 << 0, // Backspace to delete character inputs. If using: ensure GetTypingSelectRequest() is not called more than once per frame (filter by e.g. focus state) - ImGuiTypingSelectFlags_AllowSingleCharMode = 1 << 1, // Allow "single char" search mode which is activated when pressing the same character multiple times. -}; - -// Returned by GetTypingSelectRequest(), designed to eventually be public. -struct IMGUI_API ImGuiTypingSelectRequest -{ - ImGuiTypingSelectFlags Flags; // Flags passed to GetTypingSelectRequest() - int SearchBufferLen; - const char* SearchBuffer; // Search buffer contents (use full string. unless SingleCharMode is set, in which case use SingleCharSize). - bool SelectRequest; // Set when buffer was modified this frame, requesting a selection. - bool SingleCharMode; // Notify when buffer contains same character repeated, to implement special mode. In this situation it preferred to not display any on-screen search indication. - ImS8 SingleCharSize; // Length in bytes of first letter codepoint (1 for ascii, 2-4 for UTF-8). If (SearchBufferLen==RepeatCharSize) only 1 letter has been input. -}; - -// Storage for GetTypingSelectRequest() -struct IMGUI_API ImGuiTypingSelectState -{ - ImGuiTypingSelectRequest Request; // User-facing data - char SearchBuffer[64]; // Search buffer: no need to make dynamic as this search is very transient. - ImGuiID FocusScope; - int LastRequestFrame = 0; - float LastRequestTime = 0.0f; - bool SingleCharModeLock = false; // After a certain single char repeat count we lock into SingleCharMode. Two benefits: 1) buffer never fill, 2) we can provide an immediate SingleChar mode without timer elapsing. - - ImGuiTypingSelectState() { memset(this, 0, sizeof(*this)); } - void Clear() { SearchBuffer[0] = 0; SingleCharModeLock = false; } // We preserve remaining data for easier debugging -}; - -//----------------------------------------------------------------------------- -// [SECTION] Columns support -//----------------------------------------------------------------------------- - -// Flags for internal's BeginColumns(). This is an obsolete API. Prefer using BeginTable() nowadays! -enum ImGuiOldColumnFlags_ -{ - ImGuiOldColumnFlags_None = 0, - ImGuiOldColumnFlags_NoBorder = 1 << 0, // Disable column dividers - ImGuiOldColumnFlags_NoResize = 1 << 1, // Disable resizing columns when clicking on the dividers - ImGuiOldColumnFlags_NoPreserveWidths = 1 << 2, // Disable column width preservation when adjusting columns - ImGuiOldColumnFlags_NoForceWithinWindow = 1 << 3, // Disable forcing columns to fit within window - ImGuiOldColumnFlags_GrowParentContentsSize = 1 << 4, // Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove. - - // Obsolete names (will be removed) -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - //ImGuiColumnsFlags_None = ImGuiOldColumnFlags_None, - //ImGuiColumnsFlags_NoBorder = ImGuiOldColumnFlags_NoBorder, - //ImGuiColumnsFlags_NoResize = ImGuiOldColumnFlags_NoResize, - //ImGuiColumnsFlags_NoPreserveWidths = ImGuiOldColumnFlags_NoPreserveWidths, - //ImGuiColumnsFlags_NoForceWithinWindow = ImGuiOldColumnFlags_NoForceWithinWindow, - //ImGuiColumnsFlags_GrowParentContentsSize = ImGuiOldColumnFlags_GrowParentContentsSize, -#endif -}; - -struct ImGuiOldColumnData -{ - float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right) - float OffsetNormBeforeResize; - ImGuiOldColumnFlags Flags; // Not exposed - ImRect ClipRect; - - ImGuiOldColumnData() { memset(this, 0, sizeof(*this)); } -}; - -struct ImGuiOldColumns -{ - ImGuiID ID; - ImGuiOldColumnFlags Flags; - bool IsFirstFrame; - bool IsBeingResized; - int Current; - int Count; - float OffMinX, OffMaxX; // Offsets from HostWorkRect.Min.x - float LineMinY, LineMaxY; - float HostCursorPosY; // Backup of CursorPos at the time of BeginColumns() - float HostCursorMaxPosX; // Backup of CursorMaxPos at the time of BeginColumns() - ImRect HostInitialClipRect; // Backup of ClipRect at the time of BeginColumns() - ImRect HostBackupClipRect; // Backup of ClipRect during PushColumnsBackground()/PopColumnsBackground() - ImRect HostBackupParentWorkRect;//Backup of WorkRect at the time of BeginColumns() - ImVector Columns; - ImDrawListSplitter Splitter; - - ImGuiOldColumns() { memset(this, 0, sizeof(*this)); } -}; - -//----------------------------------------------------------------------------- -// [SECTION] Box-select support -//----------------------------------------------------------------------------- - -struct ImGuiBoxSelectState -{ - // Active box-selection data (persistent, 1 active at a time) - ImGuiID ID; - bool IsActive; - bool IsStarting; - bool IsStartedFromVoid; // Starting click was not from an item. - bool IsStartedSetNavIdOnce; - bool RequestClear; - ImGuiKeyChord KeyMods : 16; // Latched key-mods for box-select logic. - ImVec2 StartPosRel; // Start position in window-contents relative space (to support scrolling) - ImVec2 EndPosRel; // End position in window-contents relative space - ImVec2 ScrollAccum; // Scrolling accumulator (to behave at high-frame spaces) - ImGuiWindow* Window; - - // Temporary/Transient data - bool UnclipMode; // (Temp/Transient, here in hot area). Set/cleared by the BeginMultiSelect()/EndMultiSelect() owning active box-select. - ImRect UnclipRect; // Rectangle where ItemAdd() clipping may be temporarily disabled. Need support by multi-select supporting widgets. - ImRect BoxSelectRectPrev; // Selection rectangle in absolute coordinates (derived every frame from BoxSelectStartPosRel and MousePos) - ImRect BoxSelectRectCurr; - - ImGuiBoxSelectState() { memset(this, 0, sizeof(*this)); } -}; - -//----------------------------------------------------------------------------- -// [SECTION] Multi-select support -//----------------------------------------------------------------------------- - -// We always assume that -1 is an invalid value (which works for indices and pointers) -#define ImGuiSelectionUserData_Invalid ((ImGuiSelectionUserData)-1) - -// Temporary storage for multi-select -struct IMGUI_API ImGuiMultiSelectTempData -{ - ImGuiMultiSelectIO IO; // MUST BE FIRST FIELD. Requests are set and returned by BeginMultiSelect()/EndMultiSelect() + written to by user during the loop. - ImGuiMultiSelectState* Storage; - ImGuiID FocusScopeId; // Copied from g.CurrentFocusScopeId (unless another selection scope was pushed manually) - ImGuiMultiSelectFlags Flags; - ImVec2 ScopeRectMin; - ImVec2 BackupCursorMaxPos; - ImGuiSelectionUserData LastSubmittedItem; // Copy of last submitted item data, used to merge output ranges. - ImGuiID BoxSelectId; - ImGuiKeyChord KeyMods; - ImS8 LoopRequestSetAll; // -1: no operation, 0: clear all, 1: select all. - bool IsEndIO; // Set when switching IO from BeginMultiSelect() to EndMultiSelect() state. - bool IsFocused; // Set if currently focusing the selection scope (any item of the selection). May be used if you have custom shortcut associated to selection. - bool IsKeyboardSetRange; // Set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. - bool NavIdPassedBy; - bool RangeSrcPassedBy; // Set by the item that matches RangeSrcItem. - bool RangeDstPassedBy; // Set by the item that matches NavJustMovedToId when IsSetRange is set. - - ImGuiMultiSelectTempData() { Clear(); } - void Clear() { size_t io_sz = sizeof(IO); ClearIO(); memset((void*)(&IO + 1), 0, sizeof(*this) - io_sz); } // Zero-clear except IO as we preserve IO.Requests[] buffer allocation. - void ClearIO() { IO.Requests.resize(0); IO.RangeSrcItem = IO.NavIdItem = ImGuiSelectionUserData_Invalid; IO.NavIdSelected = IO.RangeSrcReset = false; } -}; - -// Persistent storage for multi-select (as long as selection is alive) -struct IMGUI_API ImGuiMultiSelectState -{ - ImGuiWindow* Window; - ImGuiID ID; - int LastFrameActive; // Last used frame-count, for GC. - int LastSelectionSize; // Set by BeginMultiSelect() based on optional info provided by user. May be -1 if unknown. - ImS8 RangeSelected; // -1 (don't have) or true/false - ImS8 NavIdSelected; // -1 (don't have) or true/false - ImGuiSelectionUserData RangeSrcItem; // - ImGuiSelectionUserData NavIdItem; // SetNextItemSelectionUserData() value for NavId (if part of submitted items) - - ImGuiMultiSelectState() { Window = NULL; ID = 0; LastFrameActive = LastSelectionSize = 0; RangeSelected = NavIdSelected = -1; RangeSrcItem = NavIdItem = ImGuiSelectionUserData_Invalid; } -}; - -//----------------------------------------------------------------------------- -// [SECTION] Docking support -//----------------------------------------------------------------------------- - -#ifdef IMGUI_HAS_DOCK -// -#endif // #ifdef IMGUI_HAS_DOCK - -//----------------------------------------------------------------------------- -// [SECTION] Viewport support -//----------------------------------------------------------------------------- - -// ImGuiViewport Private/Internals fields (cardinal sin: we are using inheritance!) -// Every instance of ImGuiViewport is in fact a ImGuiViewportP. -struct ImGuiViewportP : public ImGuiViewport -{ - int BgFgDrawListsLastFrame[2]; // Last frame number the background (0) and foreground (1) draw lists were used - ImDrawList* BgFgDrawLists[2]; // Convenience background (0) and foreground (1) draw lists. We use them to draw software mouser cursor when io.MouseDrawCursor is set and to draw most debug overlays. - ImDrawData DrawDataP; - ImDrawDataBuilder DrawDataBuilder; // Temporary data while building final ImDrawData - - // Per-viewport work area - // - Insets are >= 0.0f values, distance from viewport corners to work area. - // - BeginMainMenuBar() and DockspaceOverViewport() tend to use work area to avoid stepping over existing contents. - // - Generally 'safeAreaInsets' in iOS land, 'DisplayCutout' in Android land. - ImVec2 WorkInsetMin; // Work Area inset locked for the frame. GetWorkRect() always fits within GetMainRect(). - ImVec2 WorkInsetMax; // " - ImVec2 BuildWorkInsetMin; // Work Area inset accumulator for current frame, to become next frame's WorkInset - ImVec2 BuildWorkInsetMax; // " - - ImGuiViewportP() { BgFgDrawListsLastFrame[0] = BgFgDrawListsLastFrame[1] = -1; BgFgDrawLists[0] = BgFgDrawLists[1] = NULL; } - ~ImGuiViewportP() { if (BgFgDrawLists[0]) IM_DELETE(BgFgDrawLists[0]); if (BgFgDrawLists[1]) IM_DELETE(BgFgDrawLists[1]); } - - // Calculate work rect pos/size given a set of offset (we have 1 pair of offset for rect locked from last frame data, and 1 pair for currently building rect) - ImVec2 CalcWorkRectPos(const ImVec2& inset_min) const { return ImVec2(Pos.x + inset_min.x, Pos.y + inset_min.y); } - ImVec2 CalcWorkRectSize(const ImVec2& inset_min, const ImVec2& inset_max) const { return ImVec2(ImMax(0.0f, Size.x - inset_min.x - inset_max.x), ImMax(0.0f, Size.y - inset_min.y - inset_max.y)); } - void UpdateWorkRect() { WorkPos = CalcWorkRectPos(WorkInsetMin); WorkSize = CalcWorkRectSize(WorkInsetMin, WorkInsetMax); } // Update public fields - - // Helpers to retrieve ImRect (we don't need to store BuildWorkRect as every access tend to change it, hence the code asymmetry) - ImRect GetMainRect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } - ImRect GetWorkRect() const { return ImRect(WorkPos.x, WorkPos.y, WorkPos.x + WorkSize.x, WorkPos.y + WorkSize.y); } - ImRect GetBuildWorkRect() const { ImVec2 pos = CalcWorkRectPos(BuildWorkInsetMin); ImVec2 size = CalcWorkRectSize(BuildWorkInsetMin, BuildWorkInsetMax); return ImRect(pos.x, pos.y, pos.x + size.x, pos.y + size.y); } -}; - -//----------------------------------------------------------------------------- -// [SECTION] Settings support -//----------------------------------------------------------------------------- - -// Windows data saved in imgui.ini file -// Because we never destroy or rename ImGuiWindowSettings, we can store the names in a separate buffer easily. -// (this is designed to be stored in a ImChunkStream buffer, with the variable-length Name following our structure) -struct ImGuiWindowSettings -{ - ImGuiID ID; - ImVec2ih Pos; - ImVec2ih Size; - bool Collapsed; - bool IsChild; - bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) - bool WantDelete; // Set to invalidate/delete the settings entry - - ImGuiWindowSettings() { memset(this, 0, sizeof(*this)); } - char* GetName() { return (char*)(this + 1); } -}; - -struct ImGuiSettingsHandler -{ - const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']' - ImGuiID TypeHash; // == ImHashStr(TypeName) - void (*ClearAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Clear all settings data - void (*ReadInitFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called before reading (in registration order) - void* (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name); // Read: Called when entering into a new ini entry e.g. "[Window][Name]" - void (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line); // Read: Called for every line of text within an ini entry - void (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called after reading (in registration order) - void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); // Write: Output every entries into 'out_buf' - void* UserData; - - ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); } -}; - -//----------------------------------------------------------------------------- -// [SECTION] Localization support -//----------------------------------------------------------------------------- - -// This is experimental and not officially supported, it'll probably fall short of features, if/when it does we may backtrack. -enum ImGuiLocKey : int -{ - ImGuiLocKey_VersionStr, - ImGuiLocKey_TableSizeOne, - ImGuiLocKey_TableSizeAllFit, - ImGuiLocKey_TableSizeAllDefault, - ImGuiLocKey_TableResetOrder, - ImGuiLocKey_WindowingMainMenuBar, - ImGuiLocKey_WindowingPopup, - ImGuiLocKey_WindowingUntitled, - ImGuiLocKey_OpenLink_s, - ImGuiLocKey_CopyLink, - ImGuiLocKey_COUNT -}; - -struct ImGuiLocEntry -{ - ImGuiLocKey Key; - const char* Text; -}; - -//----------------------------------------------------------------------------- -// [SECTION] Error handling, State recovery support -//----------------------------------------------------------------------------- - -// Macros used by Recoverable Error handling -// - Only dispatch error if _EXPR: evaluate as assert (similar to an assert macro). -// - The message will always be a string literal, in order to increase likelihood of being display by an assert handler. -// - See 'Demo->Configuration->Error Handling' and ImGuiIO definitions for details on error handling. -// - Read https://github.com/ocornut/imgui/wiki/Error-Handling for details on error handling. -#ifndef IM_ASSERT_USER_ERROR -#define IM_ASSERT_USER_ERROR(_EXPR,_MSG) do { if (!(_EXPR) && ImGui::ErrorLog(_MSG)) { IM_ASSERT((_EXPR) && _MSG); } } while (0) // Recoverable User Error -#endif - -// The error callback is currently not public, as it is expected that only advanced users will rely on it. -typedef void (*ImGuiErrorCallback)(ImGuiContext* ctx, void* user_data, const char* msg); // Function signature for g.ErrorCallback - -//----------------------------------------------------------------------------- -// [SECTION] Metrics, Debug Tools -//----------------------------------------------------------------------------- - -// See IMGUI_DEBUG_LOG() and IMGUI_DEBUG_LOG_XXX() macros. -enum ImGuiDebugLogFlags_ -{ - // Event types - ImGuiDebugLogFlags_None = 0, - ImGuiDebugLogFlags_EventError = 1 << 0, // Error submitted by IM_ASSERT_USER_ERROR() - ImGuiDebugLogFlags_EventActiveId = 1 << 1, - ImGuiDebugLogFlags_EventFocus = 1 << 2, - ImGuiDebugLogFlags_EventPopup = 1 << 3, - ImGuiDebugLogFlags_EventNav = 1 << 4, - ImGuiDebugLogFlags_EventClipper = 1 << 5, - ImGuiDebugLogFlags_EventSelection = 1 << 6, - ImGuiDebugLogFlags_EventIO = 1 << 7, - ImGuiDebugLogFlags_EventFont = 1 << 8, - ImGuiDebugLogFlags_EventInputRouting = 1 << 9, - ImGuiDebugLogFlags_EventDocking = 1 << 10, // Unused in this branch - ImGuiDebugLogFlags_EventViewport = 1 << 11, // Unused in this branch - - ImGuiDebugLogFlags_EventMask_ = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_EventActiveId | ImGuiDebugLogFlags_EventFocus | ImGuiDebugLogFlags_EventPopup | ImGuiDebugLogFlags_EventNav | ImGuiDebugLogFlags_EventClipper | ImGuiDebugLogFlags_EventSelection | ImGuiDebugLogFlags_EventIO | ImGuiDebugLogFlags_EventFont | ImGuiDebugLogFlags_EventInputRouting | ImGuiDebugLogFlags_EventDocking | ImGuiDebugLogFlags_EventViewport, - ImGuiDebugLogFlags_OutputToTTY = 1 << 20, // Also send output to TTY - ImGuiDebugLogFlags_OutputToTestEngine = 1 << 21, // Also send output to Test Engine -}; - -struct ImGuiDebugAllocEntry -{ - int FrameCount; - ImS16 AllocCount; - ImS16 FreeCount; -}; - -struct ImGuiDebugAllocInfo -{ - int TotalAllocCount; // Number of call to MemAlloc(). - int TotalFreeCount; - ImS16 LastEntriesIdx; // Current index in buffer - ImGuiDebugAllocEntry LastEntriesBuf[6]; // Track last 6 frames that had allocations - - ImGuiDebugAllocInfo() { memset(this, 0, sizeof(*this)); } -}; - -struct ImGuiMetricsConfig -{ - bool ShowDebugLog = false; - bool ShowIDStackTool = false; - bool ShowWindowsRects = false; - bool ShowWindowsBeginOrder = false; - bool ShowTablesRects = false; - bool ShowDrawCmdMesh = true; - bool ShowDrawCmdBoundingBoxes = true; - bool ShowTextEncodingViewer = false; - bool ShowTextureUsedRect = false; - int ShowWindowsRectsType = -1; - int ShowTablesRectsType = -1; - int HighlightMonitorIdx = -1; - ImGuiID HighlightViewportID = 0; - bool ShowFontPreview = true; -}; - -struct ImGuiStackLevelInfo -{ - ImGuiID ID; - ImS8 QueryFrameCount; // >= 1: Query in progress - bool QuerySuccess; // Obtained result from DebugHookIdInfo() - ImGuiDataType DataType : 8; - char Desc[57]; // Arbitrarily sized buffer to hold a result (FIXME: could replace Results[] with a chunk stream?) FIXME: Now that we added CTRL+C this should be fixed. - - ImGuiStackLevelInfo() { memset(this, 0, sizeof(*this)); } -}; - -// State for ID Stack tool queries -struct ImGuiIDStackTool -{ - int LastActiveFrame; - int StackLevel; // -1: query stack and resize Results, >= 0: individual stack level - ImGuiID QueryId; // ID to query details for - ImVector Results; - bool CopyToClipboardOnCtrlC; - float CopyToClipboardLastTime; - ImGuiTextBuffer ResultPathBuf; - - ImGuiIDStackTool() { memset(this, 0, sizeof(*this)); CopyToClipboardLastTime = -FLT_MAX; } -}; - -//----------------------------------------------------------------------------- -// [SECTION] Generic context hooks -//----------------------------------------------------------------------------- - -typedef void (*ImGuiContextHookCallback)(ImGuiContext* ctx, ImGuiContextHook* hook); -enum ImGuiContextHookType { ImGuiContextHookType_NewFramePre, ImGuiContextHookType_NewFramePost, ImGuiContextHookType_EndFramePre, ImGuiContextHookType_EndFramePost, ImGuiContextHookType_RenderPre, ImGuiContextHookType_RenderPost, ImGuiContextHookType_Shutdown, ImGuiContextHookType_PendingRemoval_ }; - -struct ImGuiContextHook -{ - ImGuiID HookId; // A unique ID assigned by AddContextHook() - ImGuiContextHookType Type; - ImGuiID Owner; - ImGuiContextHookCallback Callback; - void* UserData; - - ImGuiContextHook() { memset(this, 0, sizeof(*this)); } -}; - -//----------------------------------------------------------------------------- -// [SECTION] ImGuiContext (main Dear ImGui context) -//----------------------------------------------------------------------------- - -struct ImGuiContext -{ - bool Initialized; - ImGuiIO IO; - ImGuiPlatformIO PlatformIO; - ImGuiStyle Style; - ImVector FontAtlases; // List of font atlases used by the context (generally only contains g.IO.Fonts aka the main font atlas) - ImFont* Font; // Currently bound font. (== FontStack.back().Font) - ImFontBaked* FontBaked; // Currently bound font at currently bound size. (== Font->GetFontBaked(FontSize)) - float FontSize; // Currently bound font size == line height (== FontSizeBase + externals scales applied in the UpdateCurrentFontSize() function). - float FontSizeBase; // Font size before scaling == style.FontSizeBase == value passed to PushFont() when specified. - float FontBakedScale; // == FontBaked->Size / FontSize. Scale factor over baked size. Rarely used nowadays, very often == 1.0f. - float FontRasterizerDensity; // Current font density. Used by all calls to GetFontBaked(). - float CurrentDpiScale; // Current window/viewport DpiScale == CurrentViewport->DpiScale - ImDrawListSharedData DrawListSharedData; - double Time; - int FrameCount; - int FrameCountEnded; - int FrameCountRendered; - ImGuiID WithinEndChildID; // Set within EndChild() - bool WithinFrameScope; // Set by NewFrame(), cleared by EndFrame() - bool WithinFrameScopeWithImplicitWindow; // Set by NewFrame(), cleared by EndFrame() when the implicit debug window has been pushed - bool GcCompactAll; // Request full GC - bool TestEngineHookItems; // Will call test engine hooks: ImGuiTestEngineHook_ItemAdd(), ImGuiTestEngineHook_ItemInfo(), ImGuiTestEngineHook_Log() - void* TestEngine; // Test engine user data - char ContextName[16]; // Storage for a context name (to facilitate debugging multi-context setups) - - // Inputs - ImVector InputEventsQueue; // Input events which will be trickled/written into IO structure. - ImVector InputEventsTrail; // Past input events processed in NewFrame(). This is to allow domain-specific application to access e.g mouse/pen trail. - ImGuiMouseSource InputEventsNextMouseSource; - ImU32 InputEventsNextEventId; - - // Windows state - ImVector Windows; // Windows, sorted in display order, back to front - ImVector WindowsFocusOrder; // Root windows, sorted in focus order, back to front. - ImVector WindowsTempSortBuffer; // Temporary buffer used in EndFrame() to reorder windows so parents are kept before their child - ImVector CurrentWindowStack; - ImGuiStorage WindowsById; // Map window's ImGuiID to ImGuiWindow* - int WindowsActiveCount; // Number of unique windows submitted by frame - float WindowsBorderHoverPadding; // Padding around resizable windows for which hovering on counts as hovering the window == ImMax(style.TouchExtraPadding, style.WindowBorderHoverPadding). This isn't so multi-dpi friendly. - ImGuiID DebugBreakInWindow; // Set to break in Begin() call. - ImGuiWindow* CurrentWindow; // Window being drawn into - ImGuiWindow* HoveredWindow; // Window the mouse is hovering. Will typically catch mouse inputs. - ImGuiWindow* HoveredWindowUnderMovingWindow; // Hovered window ignoring MovingWindow. Only set if MovingWindow is set. - ImGuiWindow* HoveredWindowBeforeClear; // Window the mouse is hovering. Filled even with _NoMouse. This is currently useful for multi-context compositors. - ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actual window that is moved is generally MovingWindow->RootWindow. - ImGuiWindow* WheelingWindow; // Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window. - ImVec2 WheelingWindowRefMousePos; - int WheelingWindowStartFrame; // This may be set one frame before WheelingWindow is != NULL - int WheelingWindowScrolledFrame; - float WheelingWindowReleaseTimer; - ImVec2 WheelingWindowWheelRemainder; - ImVec2 WheelingAxisAvg; - - // Item/widgets state and tracking information - ImGuiID DebugDrawIdConflictsId; // Set when we detect multiple items with the same identifier - ImGuiID DebugHookIdInfo; // Will call core hooks: DebugHookIdInfo() from GetID functions, used by ID Stack Tool [next HoveredId/ActiveId to not pull in an extra cache-line] - ImGuiID HoveredId; // Hovered widget, filled during the frame - ImGuiID HoveredIdPreviousFrame; - int HoveredIdPreviousFrameItemCount; // Count numbers of items using the same ID as last frame's hovered id - float HoveredIdTimer; // Measure contiguous hovering time - float HoveredIdNotActiveTimer; // Measure contiguous hovering time where the item has not been active - bool HoveredIdAllowOverlap; - bool HoveredIdIsDisabled; // At least one widget passed the rect test, but has been discarded by disabled flag or popup inhibit. May be true even if HoveredId == 0. - bool ItemUnclipByLog; // Disable ItemAdd() clipping, essentially a memory-locality friendly copy of LogEnabled - ImGuiID ActiveId; // Active widget - ImGuiID ActiveIdIsAlive; // Active widget has been seen this frame (we can't use a bool as the ActiveId may change within the frame) - float ActiveIdTimer; - bool ActiveIdIsJustActivated; // Set at the time of activation for one frame - bool ActiveIdAllowOverlap; // Active widget allows another widget to steal active id (generally for overlapping widgets, but not always) - bool ActiveIdNoClearOnFocusLoss; // Disable losing active id if the active id window gets unfocused. - bool ActiveIdHasBeenPressedBefore; // Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease without pressing twice). Used by range_select branch. - bool ActiveIdHasBeenEditedBefore; // Was the value associated to the widget Edited over the course of the Active state. - bool ActiveIdHasBeenEditedThisFrame; - bool ActiveIdFromShortcut; - int ActiveIdMouseButton : 8; - ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) - ImGuiWindow* ActiveIdWindow; - ImGuiInputSource ActiveIdSource; // Activating source: ImGuiInputSource_Mouse OR ImGuiInputSource_Keyboard OR ImGuiInputSource_Gamepad - ImGuiID ActiveIdPreviousFrame; - ImGuiDeactivatedItemData DeactivatedItemData; - ImGuiDataTypeStorage ActiveIdValueOnActivation; // Backup of initial value at the time of activation. ONLY SET BY SPECIFIC WIDGETS: DragXXX and SliderXXX. - ImGuiID LastActiveId; // Store the last non-zero ActiveId, useful for animation. - float LastActiveIdTimer; // Store the last non-zero ActiveId timer since the beginning of activation, useful for animation. - - // Key/Input Ownership + Shortcut Routing system - // - The idea is that instead of "eating" a given key, we can link to an owner. - // - Input query can then read input by specifying ImGuiKeyOwner_Any (== 0), ImGuiKeyOwner_NoOwner (== -1) or a custom ID. - // - Routing is requested ahead of time for a given chord (Key + Mods) and granted in NewFrame(). - double LastKeyModsChangeTime; // Record the last time key mods changed (affect repeat delay when using shortcut logic) - double LastKeyModsChangeFromNoneTime; // Record the last time key mods changed away from being 0 (affect repeat delay when using shortcut logic) - double LastKeyboardKeyPressTime; // Record the last time a keyboard key (ignore mouse/gamepad ones) was pressed. - ImBitArrayForNamedKeys KeysMayBeCharInput; // Lookup to tell if a key can emit char input, see IsKeyChordPotentiallyCharInput(). sizeof() = 20 bytes - ImGuiKeyOwnerData KeysOwnerData[ImGuiKey_NamedKey_COUNT]; - ImGuiKeyRoutingTable KeysRoutingTable; - ImU32 ActiveIdUsingNavDirMask; // Active widget will want to read those nav move requests (e.g. can activate a button and move away from it) - bool ActiveIdUsingAllKeyboardKeys; // Active widget will want to read all keyboard keys inputs. (this is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations) - ImGuiKeyChord DebugBreakInShortcutRouting; // Set to break in SetShortcutRouting()/Shortcut() calls. - //ImU32 ActiveIdUsingNavInputMask; // [OBSOLETE] Since (IMGUI_VERSION_NUM >= 18804) : 'g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel);' becomes --> 'SetKeyOwner(ImGuiKey_Escape, g.ActiveId) and/or SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId);' - - // Next window/item data - ImGuiID CurrentFocusScopeId; // Value for currently appending items == g.FocusScopeStack.back(). Not to be mistaken with g.NavFocusScopeId. - ImGuiItemFlags CurrentItemFlags; // Value for currently appending items == g.ItemFlagsStack.back() - ImGuiID DebugLocateId; // Storage for DebugLocateItemOnHover() feature: this is read by ItemAdd() so we keep it in a hot/cached location - ImGuiNextItemData NextItemData; // Storage for SetNextItem** functions - ImGuiLastItemData LastItemData; // Storage for last submitted item (setup by ItemAdd) - ImGuiNextWindowData NextWindowData; // Storage for SetNextWindow** functions - bool DebugShowGroupRects; - - // Shared stacks - ImGuiCol DebugFlashStyleColorIdx; // (Keep close to ColorStack to share cache line) - ImVector ColorStack; // Stack for PushStyleColor()/PopStyleColor() - inherited by Begin() - ImVector StyleVarStack; // Stack for PushStyleVar()/PopStyleVar() - inherited by Begin() - ImVector FontStack; // Stack for PushFont()/PopFont() - inherited by Begin() - ImVector FocusScopeStack; // Stack for PushFocusScope()/PopFocusScope() - inherited by BeginChild(), pushed into by Begin() - ImVector ItemFlagsStack; // Stack for PushItemFlag()/PopItemFlag() - inherited by Begin() - ImVector GroupStack; // Stack for BeginGroup()/EndGroup() - not inherited by Begin() - ImVector OpenPopupStack; // Which popups are open (persistent) - ImVector BeginPopupStack; // Which level of BeginPopup() we are in (reset every frame) - ImVectorTreeNodeStack; // Stack for TreeNode() - - // Viewports - ImVector Viewports; // Active viewports (Size==1 in 'master' branch). Each viewports hold their copy of ImDrawData. - - // Keyboard/Gamepad Navigation - bool NavCursorVisible; // Nav focus cursor/rectangle is visible? We hide it after a mouse click. We show it after a nav move. - bool NavHighlightItemUnderNav; // Disable mouse hovering highlight. Highlight navigation focused item instead of mouse hovered item. - //bool NavDisableHighlight; // Old name for !g.NavCursorVisible before 1.91.4 (2024/10/18). OPPOSITE VALUE (g.NavDisableHighlight == !g.NavCursorVisible) - //bool NavDisableMouseHover; // Old name for g.NavHighlightItemUnderNav before 1.91.1 (2024/10/18) this was called When user starts using keyboard/gamepad, we hide mouse hovering highlight until mouse is touched again. - bool NavMousePosDirty; // When set we will update mouse position if io.ConfigNavMoveSetMousePos is set (not enabled by default) - bool NavIdIsAlive; // Nav widget has been seen this frame ~~ NavRectRel is valid - ImGuiID NavId; // Focused item for navigation - ImGuiWindow* NavWindow; // Focused window for navigation. Could be called 'FocusedWindow' - ImGuiID NavFocusScopeId; // Focused focus scope (e.g. selection code often wants to "clear other items" when landing on an item of the same scope) - ImGuiNavLayer NavLayer; // Focused layer (main scrolling layer, or menu/title bar layer) - ImGuiID NavActivateId; // ~~ (g.ActiveId == 0) && (IsKeyPressed(ImGuiKey_Space) || IsKeyDown(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_NavGamepadActivate)) ? NavId : 0, also set when calling ActivateItemByID() - ImGuiID NavActivateDownId; // ~~ IsKeyDown(ImGuiKey_Space) || IsKeyDown(ImGuiKey_Enter) || IsKeyDown(ImGuiKey_NavGamepadActivate) ? NavId : 0 - ImGuiID NavActivatePressedId; // ~~ IsKeyPressed(ImGuiKey_Space) || IsKeyPressed(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_NavGamepadActivate) ? NavId : 0 (no repeat) - ImGuiActivateFlags NavActivateFlags; - ImVector NavFocusRoute; // Reversed copy focus scope stack for NavId (should contains NavFocusScopeId). This essentially follow the window->ParentWindowForFocusRoute chain. - ImGuiID NavHighlightActivatedId; - float NavHighlightActivatedTimer; - ImGuiID NavNextActivateId; // Set by ActivateItemByID(), queued until next frame. - ImGuiActivateFlags NavNextActivateFlags; - ImGuiInputSource NavInputSource; // Keyboard or Gamepad mode? THIS CAN ONLY BE ImGuiInputSource_Keyboard or ImGuiInputSource_Mouse - ImGuiSelectionUserData NavLastValidSelectionUserData; // Last valid data passed to SetNextItemSelectionUser(), or -1. For current window. Not reset when focusing an item that doesn't have selection data. - ImS8 NavCursorHideFrames; - //ImGuiID NavActivateInputId; // Removed in 1.89.4 (July 2023). This is now part of g.NavActivateId and sets g.NavActivateFlags |= ImGuiActivateFlags_PreferInput. See commit c9a53aa74, issue #5606. - - // Navigation: Init & Move Requests - bool NavAnyRequest; // ~~ NavMoveRequest || NavInitRequest this is to perform early out in ItemAdd() - bool NavInitRequest; // Init request for appearing window to select first item - bool NavInitRequestFromMove; - ImGuiNavItemData NavInitResult; // Init request result (first item of the window, or one for which SetItemDefaultFocus() was called) - bool NavMoveSubmitted; // Move request submitted, will process result on next NewFrame() - bool NavMoveScoringItems; // Move request submitted, still scoring incoming items - bool NavMoveForwardToNextFrame; - ImGuiNavMoveFlags NavMoveFlags; - ImGuiScrollFlags NavMoveScrollFlags; - ImGuiKeyChord NavMoveKeyMods; - ImGuiDir NavMoveDir; // Direction of the move request (left/right/up/down) - ImGuiDir NavMoveDirForDebug; - ImGuiDir NavMoveClipDir; // FIXME-NAV: Describe the purpose of this better. Might want to rename? - ImRect NavScoringRect; // Rectangle used for scoring, in screen space. Based of window->NavRectRel[], modified for directional navigation scoring. - ImRect NavScoringNoClipRect; // Some nav operations (such as PageUp/PageDown) enforce a region which clipper will attempt to always keep submitted - int NavScoringDebugCount; // Metrics for debugging - int NavTabbingDir; // Generally -1 or +1, 0 when tabbing without a nav id - int NavTabbingCounter; // >0 when counting items for tabbing - ImGuiNavItemData NavMoveResultLocal; // Best move request candidate within NavWindow - ImGuiNavItemData NavMoveResultLocalVisible; // Best move request candidate within NavWindow that are mostly visible (when using ImGuiNavMoveFlags_AlsoScoreVisibleSet flag) - ImGuiNavItemData NavMoveResultOther; // Best move request candidate within NavWindow's flattened hierarchy (when using ImGuiWindowFlags_NavFlattened flag) - ImGuiNavItemData NavTabbingResultFirst; // First tabbing request candidate within NavWindow and flattened hierarchy - - // Navigation: record of last move request - ImGuiID NavJustMovedFromFocusScopeId; // Just navigated from this focus scope id (result of a successfully MoveRequest). - ImGuiID NavJustMovedToId; // Just navigated to this id (result of a successfully MoveRequest). - ImGuiID NavJustMovedToFocusScopeId; // Just navigated to this focus scope id (result of a successfully MoveRequest). - ImGuiKeyChord NavJustMovedToKeyMods; - bool NavJustMovedToIsTabbing; // Copy of ImGuiNavMoveFlags_IsTabbing. Maybe we should store whole flags. - bool NavJustMovedToHasSelectionData; // Copy of move result's ItemFlags & ImGuiItemFlags_HasSelectionUserData). Maybe we should just store ImGuiNavItemData. - - // Navigation: Windowing (CTRL+TAB for list, or Menu button + keys or directional pads to move/resize) - bool ConfigNavWindowingWithGamepad; // = true. Enable CTRL+TAB by holding ImGuiKey_GamepadFaceLeft (== ImGuiKey_NavGamepadMenu). When false, the button may still be used to toggle Menu layer. - ImGuiKeyChord ConfigNavWindowingKeyNext; // = ImGuiMod_Ctrl | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiKey_Tab on OS X). For reconfiguration (see #4828) - ImGuiKeyChord ConfigNavWindowingKeyPrev; // = ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab on OS X) - ImGuiWindow* NavWindowingTarget; // Target window when doing CTRL+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most! - ImGuiWindow* NavWindowingTargetAnim; // Record of last valid NavWindowingTarget until DimBgRatio and NavWindowingHighlightAlpha becomes 0.0f, so the fade-out can stay on it. - ImGuiWindow* NavWindowingListWindow; // Internal window actually listing the CTRL+Tab contents - float NavWindowingTimer; - float NavWindowingHighlightAlpha; - ImGuiInputSource NavWindowingInputSource; - bool NavWindowingToggleLayer; - ImGuiKey NavWindowingToggleKey; - ImVec2 NavWindowingAccumDeltaPos; - ImVec2 NavWindowingAccumDeltaSize; - - // Render - float DimBgRatio; // 0.0..1.0 animation when fading in a dimming background (for modal window and CTRL+TAB list) - - // Drag and Drop - bool DragDropActive; - bool DragDropWithinSource; // Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag source. - bool DragDropWithinTarget; // Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag target. - ImGuiDragDropFlags DragDropSourceFlags; - int DragDropSourceFrameCount; - int DragDropMouseButton; - ImGuiPayload DragDropPayload; - ImRect DragDropTargetRect; // Store rectangle of current target candidate (we favor small targets when overlapping) - ImRect DragDropTargetClipRect; // Store ClipRect at the time of item's drawing - ImGuiID DragDropTargetId; - ImGuiDragDropFlags DragDropAcceptFlags; - float DragDropAcceptIdCurrRectSurface; // Target item surface (we resolve overlapping targets by prioritizing the smaller surface) - ImGuiID DragDropAcceptIdCurr; // Target item id (set at the time of accepting the payload) - ImGuiID DragDropAcceptIdPrev; // Target item id from previous frame (we need to store this to allow for overlapping drag and drop targets) - int DragDropAcceptFrameCount; // Last time a target expressed a desire to accept the source - ImGuiID DragDropHoldJustPressedId; // Set when holding a payload just made ButtonBehavior() return a press. - ImVector DragDropPayloadBufHeap; // We don't expose the ImVector<> directly, ImGuiPayload only holds pointer+size - unsigned char DragDropPayloadBufLocal[16]; // Local buffer for small payloads - - // Clipper - int ClipperTempDataStacked; - ImVector ClipperTempData; - - // Tables - ImGuiTable* CurrentTable; - ImGuiID DebugBreakInTable; // Set to break in BeginTable() call. - int TablesTempDataStacked; // Temporary table data size (because we leave previous instances undestructed, we generally don't use TablesTempData.Size) - ImVector TablesTempData; // Temporary table data (buffers reused/shared across instances, support nesting) - ImPool Tables; // Persistent table data - ImVector TablesLastTimeActive; // Last used timestamp of each tables (SOA, for efficient GC) - ImVector DrawChannelsTempMergeBuffer; - - // Tab bars - ImGuiTabBar* CurrentTabBar; - ImPool TabBars; - ImVector CurrentTabBarStack; - ImVector ShrinkWidthBuffer; - - // Multi-Select state - ImGuiBoxSelectState BoxSelectState; - ImGuiMultiSelectTempData* CurrentMultiSelect; - int MultiSelectTempDataStacked; // Temporary multi-select data size (because we leave previous instances undestructed, we generally don't use MultiSelectTempData.Size) - ImVector MultiSelectTempData; - ImPool MultiSelectStorage; - - // Hover Delay system - ImGuiID HoverItemDelayId; - ImGuiID HoverItemDelayIdPreviousFrame; - float HoverItemDelayTimer; // Currently used by IsItemHovered() - float HoverItemDelayClearTimer; // Currently used by IsItemHovered(): grace time before g.TooltipHoverTimer gets cleared. - ImGuiID HoverItemUnlockedStationaryId; // Mouse has once been stationary on this item. Only reset after departing the item. - ImGuiID HoverWindowUnlockedStationaryId; // Mouse has once been stationary on this window. Only reset after departing the window. - - // Mouse state - ImGuiMouseCursor MouseCursor; - float MouseStationaryTimer; // Time the mouse has been stationary (with some loose heuristic) - ImVec2 MouseLastValidPos; - - // Widget state - ImGuiInputTextState InputTextState; - ImGuiInputTextDeactivatedState InputTextDeactivatedState; - ImFontBaked InputTextPasswordFontBackupBaked; - ImFontFlags InputTextPasswordFontBackupFlags; - ImGuiID TempInputId; // Temporary text input when CTRL+clicking on a slider, etc. - ImGuiDataTypeStorage DataTypeZeroValue; // 0 for all data types - int BeginMenuDepth; - int BeginComboDepth; - ImGuiColorEditFlags ColorEditOptions; // Store user options for color edit widgets - ImGuiID ColorEditCurrentID; // Set temporarily while inside of the parent-most ColorEdit4/ColorPicker4 (because they call each others). - ImGuiID ColorEditSavedID; // ID we are saving/restoring HS for - float ColorEditSavedHue; // Backup of last Hue associated to LastColor, so we can restore Hue in lossy RGB<>HSV round trips - float ColorEditSavedSat; // Backup of last Saturation associated to LastColor, so we can restore Saturation in lossy RGB<>HSV round trips - ImU32 ColorEditSavedColor; // RGB value with alpha set to 0. - ImVec4 ColorPickerRef; // Initial/reference color at the time of opening the color picker. - ImGuiComboPreviewData ComboPreviewData; - ImRect WindowResizeBorderExpectedRect; // Expected border rect, switch to relative edit if moving - bool WindowResizeRelativeMode; - short ScrollbarSeekMode; // 0: scroll to clicked location, -1/+1: prev/next page. - float ScrollbarClickDeltaToGrabCenter; // When scrolling to mouse location: distance between mouse and center of grab box, normalized in parent space. - float SliderGrabClickOffset; - float SliderCurrentAccum; // Accumulated slider delta when using navigation controls. - bool SliderCurrentAccumDirty; // Has the accumulated slider delta changed since last time we tried to apply it? - bool DragCurrentAccumDirty; - float DragCurrentAccum; // Accumulator for dragging modification. Always high-precision, not rounded by end-user precision settings - float DragSpeedDefaultRatio; // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio - float DisabledAlphaBackup; // Backup for style.Alpha for BeginDisabled() - short DisabledStackSize; - short TooltipOverrideCount; - ImGuiWindow* TooltipPreviousWindow; // Window of last tooltip submitted during the frame - ImVector ClipboardHandlerData; // If no custom clipboard handler is defined - ImVector MenusIdSubmittedThisFrame; // A list of menu IDs that were rendered at least once - ImGuiTypingSelectState TypingSelectState; // State for GetTypingSelectRequest() - - // Platform support - ImGuiPlatformImeData PlatformImeData; // Data updated by current frame. Will be applied at end of the frame. For some backends, this is required to have WantVisible=true in order to receive text message. - ImGuiPlatformImeData PlatformImeDataPrev; // Previous frame data. When changed we call the platform_io.Platform_SetImeDataFn() handler. - - // Extensions - // FIXME: We could provide an API to register one slot in an array held in ImGuiContext? - ImVector UserTextures; // List of textures created/managed by user or third-party extension. Automatically appended into platform_io.Textures[]. - - // Settings - bool SettingsLoaded; - float SettingsDirtyTimer; // Save .ini Settings to memory when time reaches zero - ImGuiTextBuffer SettingsIniData; // In memory .ini settings - ImVector SettingsHandlers; // List of .ini settings handlers - ImChunkStream SettingsWindows; // ImGuiWindow .ini settings entries - ImChunkStream SettingsTables; // ImGuiTable .ini settings entries - ImVector Hooks; // Hooks for extensions (e.g. test engine) - ImGuiID HookIdNext; // Next available HookId - - // Localization - const char* LocalizationTable[ImGuiLocKey_COUNT]; - - // Capture/Logging - bool LogEnabled; // Currently capturing - ImGuiLogFlags LogFlags; // Capture flags/type - ImGuiWindow* LogWindow; - ImFileHandle LogFile; // If != NULL log to stdout/ file - ImGuiTextBuffer LogBuffer; // Accumulation buffer when log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators. - const char* LogNextPrefix; - const char* LogNextSuffix; - float LogLinePosY; - bool LogLineFirstItem; - int LogDepthRef; - int LogDepthToExpand; - int LogDepthToExpandDefault; // Default/stored value for LogDepthMaxExpand if not specified in the LogXXX function call. - - // Error Handling - ImGuiErrorCallback ErrorCallback; // = NULL. May be exposed in public API eventually. - void* ErrorCallbackUserData; // = NULL - ImVec2 ErrorTooltipLockedPos; - bool ErrorFirst; - int ErrorCountCurrentFrame; // [Internal] Number of errors submitted this frame. - ImGuiErrorRecoveryState StackSizesInNewFrame; // [Internal] - ImGuiErrorRecoveryState*StackSizesInBeginForCurrentWindow; // [Internal] - - // Debug Tools - // (some of the highly frequently used data are interleaved in other structures above: DebugBreakXXX fields, DebugHookIdInfo, DebugLocateId etc.) - int DebugDrawIdConflictsCount; // Locked count (preserved when holding CTRL) - ImGuiDebugLogFlags DebugLogFlags; - ImGuiTextBuffer DebugLogBuf; - ImGuiTextIndex DebugLogIndex; - int DebugLogSkippedErrors; - ImGuiDebugLogFlags DebugLogAutoDisableFlags; - ImU8 DebugLogAutoDisableFrames; - ImU8 DebugLocateFrames; // For DebugLocateItemOnHover(). This is used together with DebugLocateId which is in a hot/cached spot above. - bool DebugBreakInLocateId; // Debug break in ItemAdd() call for g.DebugLocateId. - ImGuiKeyChord DebugBreakKeyChord; // = ImGuiKey_Pause - ImS8 DebugBeginReturnValueCullDepth; // Cycle between 0..9 then wrap around. - bool DebugItemPickerActive; // Item picker is active (started with DebugStartItemPicker()) - ImU8 DebugItemPickerMouseButton; - ImGuiID DebugItemPickerBreakId; // Will call IM_DEBUG_BREAK() when encountering this ID - float DebugFlashStyleColorTime; - ImVec4 DebugFlashStyleColorBackup; - ImGuiMetricsConfig DebugMetricsConfig; - ImGuiIDStackTool DebugIDStackTool; - ImGuiDebugAllocInfo DebugAllocInfo; -#if defined(IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS) && !defined(IMGUI_DISABLE_DEBUG_TOOLS) - ImGuiStorage DebugDrawIdConflictsAliveCount; - ImGuiStorage DebugDrawIdConflictsHighlightSet; -#endif - - // Misc - float FramerateSecPerFrame[60]; // Calculate estimate of framerate for user over the last 60 frames.. - int FramerateSecPerFrameIdx; - int FramerateSecPerFrameCount; - float FramerateSecPerFrameAccum; - int WantCaptureMouseNextFrame; // Explicit capture override via SetNextFrameWantCaptureMouse()/SetNextFrameWantCaptureKeyboard(). Default to -1. - int WantCaptureKeyboardNextFrame; // " - int WantTextInputNextFrame; // Copied in EndFrame() from g.PlatformImeData.WantTextInput. Needs to be set for some backends (SDL3) to emit character inputs. - ImVector TempBuffer; // Temporary text buffer - char TempKeychordName[64]; - - ImGuiContext(ImFontAtlas* shared_font_atlas); -}; - -//----------------------------------------------------------------------------- -// [SECTION] ImGuiWindowTempData, ImGuiWindow -//----------------------------------------------------------------------------- - -// Transient per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the DC variable name in ImGuiWindow. -// (That's theory, in practice the delimitation between ImGuiWindow and ImGuiWindowTempData is quite tenuous and could be reconsidered..) -// (This doesn't need a constructor because we zero-clear it as part of ImGuiWindow and all frame-temporary data are setup on Begin) -struct IMGUI_API ImGuiWindowTempData -{ - // Layout - ImVec2 CursorPos; // Current emitting position, in absolute coordinates. - ImVec2 CursorPosPrevLine; - ImVec2 CursorStartPos; // Initial position after Begin(), generally ~ window position + WindowPadding. - ImVec2 CursorMaxPos; // Used to implicitly calculate ContentSize at the beginning of next frame, for scrolling range and auto-resize. Always growing during the frame. - ImVec2 IdealMaxPos; // Used to implicitly calculate ContentSizeIdeal at the beginning of next frame, for auto-resize only. Always growing during the frame. - ImVec2 CurrLineSize; - ImVec2 PrevLineSize; - float CurrLineTextBaseOffset; // Baseline offset (0.0f by default on a new line, generally == style.FramePadding.y when a framed item has been added). - float PrevLineTextBaseOffset; - bool IsSameLine; - bool IsSetPos; - ImVec1 Indent; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.) - ImVec1 ColumnsOffset; // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API. - ImVec1 GroupOffset; - ImVec2 CursorStartPosLossyness;// Record the loss of precision of CursorStartPos due to really large scrolling amount. This is used by clipper to compensate and fix the most common use case of large scroll area. - - // Keyboard/Gamepad navigation - ImGuiNavLayer NavLayerCurrent; // Current layer, 0..31 (we currently only use 0..1) - short NavLayersActiveMask; // Which layers have been written to (result from previous frame) - short NavLayersActiveMaskNext;// Which layers have been written to (accumulator for current frame) - bool NavIsScrollPushableX; // Set when current work location may be scrolled horizontally when moving left / right. This is generally always true UNLESS within a column. - bool NavHideHighlightOneFrame; - bool NavWindowHasScrollY; // Set per window when scrolling can be used (== ScrollMax.y > 0.0f) - - // Miscellaneous - bool MenuBarAppending; // FIXME: Remove this - ImVec2 MenuBarOffset; // MenuBarOffset.x is sort of equivalent of a per-layer CursorPos.x, saved/restored as we switch to the menu bar. The only situation when MenuBarOffset.y is > 0 if when (SafeAreaPadding.y > FramePadding.y), often used on TVs. - ImGuiMenuColumns MenuColumns; // Simplified columns storage for menu items measurement - int TreeDepth; // Current tree depth. - ImU32 TreeHasStackDataDepthMask; // Store whether given depth has ImGuiTreeNodeStackData data. Could be turned into a ImU64 if necessary. - ImU32 TreeRecordsClippedNodesY2Mask; // Store whether we should keep recording Y2. Cleared when passing clip max. Equivalent TreeHasStackDataDepthMask value should always be set. - ImVector ChildWindows; - ImGuiStorage* StateStorage; // Current persistent per-window storage (store e.g. tree node open/close state) - ImGuiOldColumns* CurrentColumns; // Current columns set - int CurrentTableIdx; // Current table index (into g.Tables) - ImGuiLayoutType LayoutType; - ImGuiLayoutType ParentLayoutType; // Layout type of parent window at the time of Begin() - ImU32 ModalDimBgColor; - ImGuiItemStatusFlags WindowItemStatusFlags; - ImGuiItemStatusFlags ChildItemStatusFlags; - - // Local parameters stacks - // We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings. - float ItemWidth; // Current item width (>0.0: width in pixels, <0.0: align xx pixels to the right of window). - float TextWrapPos; // Current text wrap pos. - ImVector ItemWidthStack; // Store item widths to restore (attention: .back() is not == ItemWidth) - ImVector TextWrapPosStack; // Store text wrap pos to restore (attention: .back() is not == TextWrapPos) -}; - -// Storage for one window -struct IMGUI_API ImGuiWindow -{ - ImGuiContext* Ctx; // Parent UI context (needs to be set explicitly by parent). - char* Name; // Window name, owned by the window. - ImGuiID ID; // == ImHashStr(Name) - ImGuiWindowFlags Flags; // See enum ImGuiWindowFlags_ - ImGuiChildFlags ChildFlags; // Set when window is a child window. See enum ImGuiChildFlags_ - ImGuiViewportP* Viewport; // Always set in Begin(). Inactive windows may have a NULL value here if their viewport was discarded. - ImVec2 Pos; // Position (always rounded-up to nearest pixel) - ImVec2 Size; // Current size (==SizeFull or collapsed title bar size) - ImVec2 SizeFull; // Size when non collapsed - ImVec2 ContentSize; // Size of contents/scrollable client area (calculated from the extents reach of the cursor) from previous frame. Does not include window decoration or window padding. - ImVec2 ContentSizeIdeal; - ImVec2 ContentSizeExplicit; // Size of contents/scrollable client area explicitly request by the user via SetNextWindowContentSize(). - ImVec2 WindowPadding; // Window padding at the time of Begin(). - float WindowRounding; // Window rounding at the time of Begin(). May be clamped lower to avoid rendering artifacts with title bar, menu bar etc. - float WindowBorderSize; // Window border size at the time of Begin(). - float TitleBarHeight, MenuBarHeight; // Note that those used to be function before 2024/05/28. If you have old code calling TitleBarHeight() you can change it to TitleBarHeight. - float DecoOuterSizeX1, DecoOuterSizeY1; // Left/Up offsets. Sum of non-scrolling outer decorations (X1 generally == 0.0f. Y1 generally = TitleBarHeight + MenuBarHeight). Locked during Begin(). - float DecoOuterSizeX2, DecoOuterSizeY2; // Right/Down offsets (X2 generally == ScrollbarSize.x, Y2 == ScrollbarSizes.y). - float DecoInnerSizeX1, DecoInnerSizeY1; // Applied AFTER/OVER InnerRect. Specialized for Tables as they use specialized form of clipping and frozen rows/columns are inside InnerRect (and not part of regular decoration sizes). - int NameBufLen; // Size of buffer storing Name. May be larger than strlen(Name)! - ImGuiID MoveId; // == window->GetID("#MOVE") - ImGuiID ChildId; // ID of corresponding item in parent window (for navigation to return from child window to parent window) - ImGuiID PopupId; // ID in the popup stack when this window is used as a popup/menu (because we use generic Name/ID for recycling) - ImVec2 Scroll; - ImVec2 ScrollMax; - ImVec2 ScrollTarget; // target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0f. (FLT_MAX for no change) - ImVec2 ScrollTargetCenterRatio; // 0.0f = scroll so that target position is at top, 0.5f = scroll so that target position is centered - ImVec2 ScrollTargetEdgeSnapDist; // 0.0f = no snapping, >0.0f snapping threshold - ImVec2 ScrollbarSizes; // Size taken by each scrollbars on their smaller axis. Pay attention! ScrollbarSizes.x == width of the vertical scrollbar, ScrollbarSizes.y = height of the horizontal scrollbar. - bool ScrollbarX, ScrollbarY; // Are scrollbars visible? - bool ScrollbarXStabilizeEnabled; // Was ScrollbarX previously auto-stabilized? - ImU8 ScrollbarXStabilizeToggledHistory; // Used to stabilize scrollbar visibility in case of feedback loops - bool Active; // Set to true on Begin(), unless Collapsed - bool WasActive; - bool WriteAccessed; // Set to true when any widget access the current window - bool Collapsed; // Set when collapsing window to become only title-bar - bool WantCollapseToggle; - bool SkipItems; // Set when items can safely be all clipped (e.g. window not visible or collapsed) - bool SkipRefresh; // [EXPERIMENTAL] Reuse previous frame drawn contents, Begin() returns false. - bool Appearing; // Set during the frame where the window is appearing (or re-appearing) - bool Hidden; // Do not display (== HiddenFrames*** > 0) - bool IsFallbackWindow; // Set on the "Debug##Default" window. - bool IsExplicitChild; // Set when passed _ChildWindow, left to false by BeginDocked() - bool HasCloseButton; // Set when the window has a close button (p_open != NULL) - signed char ResizeBorderHovered; // Current border being hovered for resize (-1: none, otherwise 0-3) - signed char ResizeBorderHeld; // Current border being held for resize (-1: none, otherwise 0-3) - short BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs) - short BeginCountPreviousFrame; // Number of Begin() during the previous frame - short BeginOrderWithinParent; // Begin() order within immediate parent window, if we are a child window. Otherwise 0. - short BeginOrderWithinContext; // Begin() order within entire imgui context. This is mostly used for debugging submission order related issues. - short FocusOrder; // Order within WindowsFocusOrder[], altered when windows are focused. - ImS8 AutoFitFramesX, AutoFitFramesY; - bool AutoFitOnlyGrows; - ImGuiDir AutoPosLastDirection; - ImS8 HiddenFramesCanSkipItems; // Hide the window for N frames - ImS8 HiddenFramesCannotSkipItems; // Hide the window for N frames while allowing items to be submitted so we can measure their size - ImS8 HiddenFramesForRenderOnly; // Hide the window until frame N at Render() time only - ImS8 DisableInputsFrames; // Disable window interactions for N frames - ImGuiCond SetWindowPosAllowFlags : 8; // store acceptable condition flags for SetNextWindowPos() use. - ImGuiCond SetWindowSizeAllowFlags : 8; // store acceptable condition flags for SetNextWindowSize() use. - ImGuiCond SetWindowCollapsedAllowFlags : 8; // store acceptable condition flags for SetNextWindowCollapsed() use. - ImVec2 SetWindowPosVal; // store window position when using a non-zero Pivot (position set needs to be processed when we know the window size) - ImVec2 SetWindowPosPivot; // store window pivot for positioning. ImVec2(0, 0) when positioning from top-left corner; ImVec2(0.5f, 0.5f) for centering; ImVec2(1, 1) for bottom right. - - ImVector IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack. (In theory this should be in the TempData structure) - ImGuiWindowTempData DC; // Temporary per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the "DC" variable name. - - // The best way to understand what those rectangles are is to use the 'Metrics->Tools->Show Windows Rectangles' viewer. - // The main 'OuterRect', omitted as a field, is window->Rect(). - ImRect OuterRectClipped; // == Window->Rect() just after setup in Begin(). == window->Rect() for root window. - ImRect InnerRect; // Inner rectangle (omit title bar, menu bar, scroll bar) - ImRect InnerClipRect; // == InnerRect shrunk by WindowPadding*0.5f on each side, clipped within viewport or parent clip rect. - ImRect WorkRect; // Initially covers the whole scrolling region. Reduced by containers e.g columns/tables when active. Shrunk by WindowPadding*1.0f on each side. This is meant to replace ContentRegionRect over time (from 1.71+ onward). - ImRect ParentWorkRect; // Backup of WorkRect before entering a container such as columns/tables. Used by e.g. SpanAllColumns functions to easily access. Stacked containers are responsible for maintaining this. // FIXME-WORKRECT: Could be a stack? - ImRect ClipRect; // Current clipping/scissoring rectangle, evolve as we are using PushClipRect(), etc. == DrawList->clip_rect_stack.back(). - ImRect ContentRegionRect; // FIXME: This is currently confusing/misleading. It is essentially WorkRect but not handling of scrolling. We currently rely on it as right/bottom aligned sizing operation need some size to rely on. - ImVec2ih HitTestHoleSize; // Define an optional rectangular hole where mouse will pass-through the window. - ImVec2ih HitTestHoleOffset; - - int LastFrameActive; // Last frame number the window was Active. - float LastTimeActive; // Last timestamp the window was Active (using float as we don't need high precision there) - float ItemWidthDefault; - ImGuiStorage StateStorage; - ImVector ColumnsStorage; - float FontWindowScale; // User scale multiplier per-window, via SetWindowFontScale() - float FontWindowScaleParents; - float FontRefSize; // This is a copy of window->CalcFontSize() at the time of Begin(), trying to phase out CalcFontSize() especially as it may be called on non-current window. - int SettingsOffset; // Offset into SettingsWindows[] (offsets are always valid as we only grow the array from the back) - - ImDrawList* DrawList; // == &DrawListInst (for backward compatibility reason with code using imgui_internal.h we keep this a pointer) - ImDrawList DrawListInst; - ImGuiWindow* ParentWindow; // If we are a child _or_ popup _or_ docked window, this is pointing to our parent. Otherwise NULL. - ImGuiWindow* ParentWindowInBeginStack; - ImGuiWindow* RootWindow; // Point to ourself or first ancestor that is not a child window. Doesn't cross through popups/dock nodes. - ImGuiWindow* RootWindowPopupTree; // Point to ourself or first ancestor that is not a child window. Cross through popups parent<>child. - ImGuiWindow* RootWindowForTitleBarHighlight; // Point to ourself or first ancestor which will display TitleBgActive color when this window is active. - ImGuiWindow* RootWindowForNav; // Point to ourself or first ancestor which doesn't have the NavFlattened flag. - ImGuiWindow* ParentWindowForFocusRoute; // Set to manual link a window to its logical parent so that Shortcut() chain are honoerd (e.g. Tool linked to Document) - - ImGuiWindow* NavLastChildNavWindow; // When going to the menu bar, we remember the child window we came from. (This could probably be made implicit if we kept g.Windows sorted by last focused including child window.) - ImGuiID NavLastIds[ImGuiNavLayer_COUNT]; // Last known NavId for this window, per layer (0/1) - ImRect NavRectRel[ImGuiNavLayer_COUNT]; // Reference rectangle, in window relative space - ImVec2 NavPreferredScoringPosRel[ImGuiNavLayer_COUNT]; // Preferred X/Y position updated when moving on a given axis, reset to FLT_MAX. - ImGuiID NavRootFocusScopeId; // Focus Scope ID at the time of Begin() - - int MemoryDrawListIdxCapacity; // Backup of last idx/vtx count, so when waking up the window we can preallocate and avoid iterative alloc/copy - int MemoryDrawListVtxCapacity; - bool MemoryCompacted; // Set when window extraneous data have been garbage collected - -public: - ImGuiWindow(ImGuiContext* context, const char* name); - ~ImGuiWindow(); - - ImGuiID GetID(const char* str, const char* str_end = NULL); - ImGuiID GetID(const void* ptr); - ImGuiID GetID(int n); - ImGuiID GetIDFromPos(const ImVec2& p_abs); - ImGuiID GetIDFromRectangle(const ImRect& r_abs); - - // We don't use g.FontSize because the window may be != g.CurrentWindow. - ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } - ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight)); } - ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight; return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight); } - - // [Obsolete] ImGuiWindow::CalcFontSize() was removed in 1.92.x because error-prone/misleading. You can use window->FontRefSize for a copy of g.FontSize at the time of the last Begin() call for this window. - //float CalcFontSize() const { ImGuiContext& g = *Ctx; return g.FontSizeBase * FontWindowScale * FontWindowScaleParents; -}; - -//----------------------------------------------------------------------------- -// [SECTION] Tab bar, Tab item support -//----------------------------------------------------------------------------- - -// Extend ImGuiTabBarFlags_ -enum ImGuiTabBarFlagsPrivate_ -{ - ImGuiTabBarFlags_DockNode = 1 << 20, // Part of a dock node [we don't use this in the master branch but it facilitate branch syncing to keep this around] - ImGuiTabBarFlags_IsFocused = 1 << 21, - ImGuiTabBarFlags_SaveSettings = 1 << 22, // FIXME: Settings are handled by the docking system, this only request the tab bar to mark settings dirty when reordering tabs -}; - -// Extend ImGuiTabItemFlags_ -enum ImGuiTabItemFlagsPrivate_ -{ - ImGuiTabItemFlags_SectionMask_ = ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing, - ImGuiTabItemFlags_NoCloseButton = 1 << 20, // Track whether p_open was set or not (we'll need this info on the next frame to recompute ContentWidth during layout) - ImGuiTabItemFlags_Button = 1 << 21, // Used by TabItemButton, change the tab item behavior to mimic a button - ImGuiTabItemFlags_Invisible = 1 << 22, // To reserve space e.g. with ImGuiTabItemFlags_Leading - //ImGuiTabItemFlags_Unsorted = 1 << 23, // [Docking] Trailing tabs with the _Unsorted flag will be sorted based on the DockOrder of their Window. -}; - -// Storage for one active tab item (sizeof() 40 bytes) -struct ImGuiTabItem -{ - ImGuiID ID; - ImGuiTabItemFlags Flags; - int LastFrameVisible; - int LastFrameSelected; // This allows us to infer an ordered list of the last activated tabs with little maintenance - float Offset; // Position relative to beginning of tab - float Width; // Width currently displayed - float ContentWidth; // Width of label, stored during BeginTabItem() call - float RequestedWidth; // Width optionally requested by caller, -1.0f is unused - ImS32 NameOffset; // When Window==NULL, offset to name within parent ImGuiTabBar::TabsNames - ImS16 BeginOrder; // BeginTabItem() order, used to re-order tabs after toggling ImGuiTabBarFlags_Reorderable - ImS16 IndexDuringLayout; // Index only used during TabBarLayout(). Tabs gets reordered so 'Tabs[n].IndexDuringLayout == n' but may mismatch during additions. - bool WantClose; // Marked as closed by SetTabItemClosed() - - ImGuiTabItem() { memset(this, 0, sizeof(*this)); LastFrameVisible = LastFrameSelected = -1; RequestedWidth = -1.0f; NameOffset = -1; BeginOrder = IndexDuringLayout = -1; } -}; - -// Storage for a tab bar (sizeof() 160 bytes) -struct IMGUI_API ImGuiTabBar -{ - ImGuiWindow* Window; - ImVector Tabs; - ImGuiTabBarFlags Flags; - ImGuiID ID; // Zero for tab-bars used by docking - ImGuiID SelectedTabId; // Selected tab/window - ImGuiID NextSelectedTabId; // Next selected tab/window. Will also trigger a scrolling animation - ImGuiID VisibleTabId; // Can occasionally be != SelectedTabId (e.g. when previewing contents for CTRL+TAB preview) - int CurrFrameVisible; - int PrevFrameVisible; - ImRect BarRect; - float CurrTabsContentsHeight; - float PrevTabsContentsHeight; // Record the height of contents submitted below the tab bar - float WidthAllTabs; // Actual width of all tabs (locked during layout) - float WidthAllTabsIdeal; // Ideal width if all tabs were visible and not clipped - float ScrollingAnim; - float ScrollingTarget; - float ScrollingTargetDistToVisibility; - float ScrollingSpeed; - float ScrollingRectMinX; - float ScrollingRectMaxX; - float SeparatorMinX; - float SeparatorMaxX; - ImGuiID ReorderRequestTabId; - ImS16 ReorderRequestOffset; - ImS8 BeginCount; - bool WantLayout; - bool VisibleTabWasSubmitted; - bool TabsAddedNew; // Set to true when a new tab item or button has been added to the tab bar during last frame - ImS16 TabsActiveCount; // Number of tabs submitted this frame. - ImS16 LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() - float ItemSpacingY; - ImVec2 FramePadding; // style.FramePadding locked at the time of BeginTabBar() - ImVec2 BackupCursorPos; - ImGuiTextBuffer TabsNames; // For non-docking tab bar we re-append names in a contiguous buffer. - - ImGuiTabBar(); -}; - -//----------------------------------------------------------------------------- -// [SECTION] Table support -//----------------------------------------------------------------------------- - -#define IM_COL32_DISABLE IM_COL32(0,0,0,1) // Special sentinel code which cannot be used as a regular color. -#define IMGUI_TABLE_MAX_COLUMNS 512 // Arbitrary "safety" maximum, may be lifted in the future if needed. Must fit in ImGuiTableColumnIdx/ImGuiTableDrawChannelIdx. - -// [Internal] sizeof() ~ 112 -// We use the terminology "Enabled" to refer to a column that is not Hidden by user/api. -// We use the terminology "Clipped" to refer to a column that is out of sight because of scrolling/clipping. -// This is in contrast with some user-facing api such as IsItemVisible() / IsRectVisible() which use "Visible" to mean "not clipped". -struct ImGuiTableColumn -{ - ImGuiTableColumnFlags Flags; // Flags after some patching (not directly same as provided by user). See ImGuiTableColumnFlags_ - float WidthGiven; // Final/actual width visible == (MaxX - MinX), locked in TableUpdateLayout(). May be > WidthRequest to honor minimum width, may be < WidthRequest to honor shrinking columns down in tight space. - float MinX; // Absolute positions - float MaxX; - float WidthRequest; // Master width absolute value when !(Flags & _WidthStretch). When Stretch this is derived every frame from StretchWeight in TableUpdateLayout() - float WidthAuto; // Automatic width - float WidthMax; // Maximum width (FIXME: overwritten by each instance) - float StretchWeight; // Master width weight when (Flags & _WidthStretch). Often around ~1.0f initially. - float InitStretchWeightOrWidth; // Value passed to TableSetupColumn(). For Width it is a content width (_without padding_). - ImRect ClipRect; // Clipping rectangle for the column - ImGuiID UserID; // Optional, value passed to TableSetupColumn() - float WorkMinX; // Contents region min ~(MinX + CellPaddingX + CellSpacingX1) == cursor start position when entering column - float WorkMaxX; // Contents region max ~(MaxX - CellPaddingX - CellSpacingX2) - float ItemWidth; // Current item width for the column, preserved across rows - float ContentMaxXFrozen; // Contents maximum position for frozen rows (apart from headers), from which we can infer content width. - float ContentMaxXUnfrozen; - float ContentMaxXHeadersUsed; // Contents maximum position for headers rows (regardless of freezing). TableHeader() automatically softclip itself + report ideal desired size, to avoid creating extraneous draw calls - float ContentMaxXHeadersIdeal; - ImS16 NameOffset; // Offset into parent ColumnsNames[] - ImGuiTableColumnIdx DisplayOrder; // Index within Table's IndexToDisplayOrder[] (column may be reordered by users) - ImGuiTableColumnIdx IndexWithinEnabledSet; // Index within enabled/visible set (<= IndexToDisplayOrder) - ImGuiTableColumnIdx PrevEnabledColumn; // Index of prev enabled/visible column within Columns[], -1 if first enabled/visible column - ImGuiTableColumnIdx NextEnabledColumn; // Index of next enabled/visible column within Columns[], -1 if last enabled/visible column - ImGuiTableColumnIdx SortOrder; // Index of this column within sort specs, -1 if not sorting on this column, 0 for single-sort, may be >0 on multi-sort - ImGuiTableDrawChannelIdx DrawChannelCurrent; // Index within DrawSplitter.Channels[] - ImGuiTableDrawChannelIdx DrawChannelFrozen; // Draw channels for frozen rows (often headers) - ImGuiTableDrawChannelIdx DrawChannelUnfrozen; // Draw channels for unfrozen rows - bool IsEnabled; // IsUserEnabled && (Flags & ImGuiTableColumnFlags_Disabled) == 0 - bool IsUserEnabled; // Is the column not marked Hidden by the user? (unrelated to being off view, e.g. clipped by scrolling). - bool IsUserEnabledNextFrame; - bool IsVisibleX; // Is actually in view (e.g. overlapping the host window clipping rectangle, not scrolled). - bool IsVisibleY; - bool IsRequestOutput; // Return value for TableSetColumnIndex() / TableNextColumn(): whether we request user to output contents or not. - bool IsSkipItems; // Do we want item submissions to this column to be completely ignored (no layout will happen). - bool IsPreserveWidthAuto; - ImS8 NavLayerCurrent; // ImGuiNavLayer in 1 byte - ImU8 AutoFitQueue; // Queue of 8 values for the next 8 frames to request auto-fit - ImU8 CannotSkipItemsQueue; // Queue of 8 values for the next 8 frames to disable Clipped/SkipItem - ImU8 SortDirection : 2; // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending - ImU8 SortDirectionsAvailCount : 2; // Number of available sort directions (0 to 3) - ImU8 SortDirectionsAvailMask : 4; // Mask of available sort directions (1-bit each) - ImU8 SortDirectionsAvailList; // Ordered list of available sort directions (2-bits each, total 8-bits) - - ImGuiTableColumn() - { - memset(this, 0, sizeof(*this)); - StretchWeight = WidthRequest = -1.0f; - NameOffset = -1; - DisplayOrder = IndexWithinEnabledSet = -1; - PrevEnabledColumn = NextEnabledColumn = -1; - SortOrder = -1; - SortDirection = ImGuiSortDirection_None; - DrawChannelCurrent = DrawChannelFrozen = DrawChannelUnfrozen = (ImU8)-1; - } -}; - -// Transient cell data stored per row. -// sizeof() ~ 6 bytes -struct ImGuiTableCellData -{ - ImU32 BgColor; // Actual color - ImGuiTableColumnIdx Column; // Column number -}; - -// Parameters for TableAngledHeadersRowEx() -// This may end up being refactored for more general purpose. -// sizeof() ~ 12 bytes -struct ImGuiTableHeaderData -{ - ImGuiTableColumnIdx Index; // Column index - ImU32 TextColor; - ImU32 BgColor0; - ImU32 BgColor1; -}; - -// Per-instance data that needs preserving across frames (seemingly most others do not need to be preserved aside from debug needs. Does that means they could be moved to ImGuiTableTempData?) -// sizeof() ~ 24 bytes -struct ImGuiTableInstanceData -{ - ImGuiID TableInstanceID; - float LastOuterHeight; // Outer height from last frame - float LastTopHeadersRowHeight; // Height of first consecutive header rows from last frame (FIXME: this is used assuming consecutive headers are in same frozen set) - float LastFrozenHeight; // Height of frozen section from last frame - int HoveredRowLast; // Index of row which was hovered last frame. - int HoveredRowNext; // Index of row hovered this frame, set after encountering it. - - ImGuiTableInstanceData() { TableInstanceID = 0; LastOuterHeight = LastTopHeadersRowHeight = LastFrozenHeight = 0.0f; HoveredRowLast = HoveredRowNext = -1; } -}; - -// sizeof() ~ 592 bytes + heap allocs described in TableBeginInitMemory() -struct IMGUI_API ImGuiTable -{ - ImGuiID ID; - ImGuiTableFlags Flags; - void* RawData; // Single allocation to hold Columns[], DisplayOrderToIndex[], and RowCellData[] - ImGuiTableTempData* TempData; // Transient data while table is active. Point within g.CurrentTableStack[] - ImSpan Columns; // Point within RawData[] - ImSpan DisplayOrderToIndex; // Point within RawData[]. Store display order of columns (when not reordered, the values are 0...Count-1) - ImSpan RowCellData; // Point within RawData[]. Store cells background requests for current row. - ImBitArrayPtr EnabledMaskByDisplayOrder; // Column DisplayOrder -> IsEnabled map - ImBitArrayPtr EnabledMaskByIndex; // Column Index -> IsEnabled map (== not hidden by user/api) in a format adequate for iterating column without touching cold data - ImBitArrayPtr VisibleMaskByIndex; // Column Index -> IsVisibleX|IsVisibleY map (== not hidden by user/api && not hidden by scrolling/cliprect) - ImGuiTableFlags SettingsLoadedFlags; // Which data were loaded from the .ini file (e.g. when order is not altered we won't save order) - int SettingsOffset; // Offset in g.SettingsTables - int LastFrameActive; - int ColumnsCount; // Number of columns declared in BeginTable() - int CurrentRow; - int CurrentColumn; - ImS16 InstanceCurrent; // Count of BeginTable() calls with same ID in the same frame (generally 0). This is a little bit similar to BeginCount for a window, but multiple tables with the same ID are multiple tables, they are just synced. - ImS16 InstanceInteracted; // Mark which instance (generally 0) of the same ID is being interacted with - float RowPosY1; - float RowPosY2; - float RowMinHeight; // Height submitted to TableNextRow() - float RowCellPaddingY; // Top and bottom padding. Reloaded during row change. - float RowTextBaseline; - float RowIndentOffsetX; - ImGuiTableRowFlags RowFlags : 16; // Current row flags, see ImGuiTableRowFlags_ - ImGuiTableRowFlags LastRowFlags : 16; - int RowBgColorCounter; // Counter for alternating background colors (can be fast-forwarded by e.g clipper), not same as CurrentRow because header rows typically don't increase this. - ImU32 RowBgColor[2]; // Background color override for current row. - ImU32 BorderColorStrong; - ImU32 BorderColorLight; - float BorderX1; - float BorderX2; - float HostIndentX; - float MinColumnWidth; - float OuterPaddingX; - float CellPaddingX; // Padding from each borders. Locked in BeginTable()/Layout. - float CellSpacingX1; // Spacing between non-bordered cells. Locked in BeginTable()/Layout. - float CellSpacingX2; - float InnerWidth; // User value passed to BeginTable(), see comments at the top of BeginTable() for details. - float ColumnsGivenWidth; // Sum of current column width - float ColumnsAutoFitWidth; // Sum of ideal column width in order nothing to be clipped, used for auto-fitting and content width submission in outer window - float ColumnsStretchSumWeights; // Sum of weight of all enabled stretching columns - float ResizedColumnNextWidth; - float ResizeLockMinContentsX2; // Lock minimum contents width while resizing down in order to not create feedback loops. But we allow growing the table. - float RefScale; // Reference scale to be able to rescale columns on font/dpi changes. - float AngledHeadersHeight; // Set by TableAngledHeadersRow(), used in TableUpdateLayout() - float AngledHeadersSlope; // Set by TableAngledHeadersRow(), used in TableUpdateLayout() - ImRect OuterRect; // Note: for non-scrolling table, OuterRect.Max.y is often FLT_MAX until EndTable(), unless a height has been specified in BeginTable(). - ImRect InnerRect; // InnerRect but without decoration. As with OuterRect, for non-scrolling tables, InnerRect.Max.y is " - ImRect WorkRect; - ImRect InnerClipRect; - ImRect BgClipRect; // We use this to cpu-clip cell background color fill, evolve during the frame as we cross frozen rows boundaries - ImRect Bg0ClipRectForDrawCmd; // Actual ImDrawCmd clip rect for BG0/1 channel. This tends to be == OuterWindow->ClipRect at BeginTable() because output in BG0/BG1 is cpu-clipped - ImRect Bg2ClipRectForDrawCmd; // Actual ImDrawCmd clip rect for BG2 channel. This tends to be a correct, tight-fit, because output to BG2 are done by widgets relying on regular ClipRect. - ImRect HostClipRect; // This is used to check if we can eventually merge our columns draw calls into the current draw call of the current window. - ImRect HostBackupInnerClipRect; // Backup of InnerWindow->ClipRect during PushTableBackground()/PopTableBackground() - ImGuiWindow* OuterWindow; // Parent window for the table - ImGuiWindow* InnerWindow; // Window holding the table data (== OuterWindow or a child window) - ImGuiTextBuffer ColumnsNames; // Contiguous buffer holding columns names - ImDrawListSplitter* DrawSplitter; // Shortcut to TempData->DrawSplitter while in table. Isolate draw commands per columns to avoid switching clip rect constantly - ImGuiTableInstanceData InstanceDataFirst; - ImVector InstanceDataExtra; // FIXME-OPT: Using a small-vector pattern would be good. - ImGuiTableColumnSortSpecs SortSpecsSingle; - ImVector SortSpecsMulti; // FIXME-OPT: Using a small-vector pattern would be good. - ImGuiTableSortSpecs SortSpecs; // Public facing sorts specs, this is what we return in TableGetSortSpecs() - ImGuiTableColumnIdx SortSpecsCount; - ImGuiTableColumnIdx ColumnsEnabledCount; // Number of enabled columns (<= ColumnsCount) - ImGuiTableColumnIdx ColumnsEnabledFixedCount; // Number of enabled columns using fixed width (<= ColumnsCount) - ImGuiTableColumnIdx DeclColumnsCount; // Count calls to TableSetupColumn() - ImGuiTableColumnIdx AngledHeadersCount; // Count columns with angled headers - ImGuiTableColumnIdx HoveredColumnBody; // Index of column whose visible region is being hovered. Important: == ColumnsCount when hovering empty region after the right-most column! - ImGuiTableColumnIdx HoveredColumnBorder; // Index of column whose right-border is being hovered (for resizing). - ImGuiTableColumnIdx HighlightColumnHeader; // Index of column which should be highlighted. - ImGuiTableColumnIdx AutoFitSingleColumn; // Index of single column requesting auto-fit. - ImGuiTableColumnIdx ResizedColumn; // Index of column being resized. Reset when InstanceCurrent==0. - ImGuiTableColumnIdx LastResizedColumn; // Index of column being resized from previous frame. - ImGuiTableColumnIdx HeldHeaderColumn; // Index of column header being held. - ImGuiTableColumnIdx ReorderColumn; // Index of column being reordered. (not cleared) - ImGuiTableColumnIdx ReorderColumnDir; // -1 or +1 - ImGuiTableColumnIdx LeftMostEnabledColumn; // Index of left-most non-hidden column. - ImGuiTableColumnIdx RightMostEnabledColumn; // Index of right-most non-hidden column. - ImGuiTableColumnIdx LeftMostStretchedColumn; // Index of left-most stretched column. - ImGuiTableColumnIdx RightMostStretchedColumn; // Index of right-most stretched column. - ImGuiTableColumnIdx ContextPopupColumn; // Column right-clicked on, of -1 if opening context menu from a neutral/empty spot - ImGuiTableColumnIdx FreezeRowsRequest; // Requested frozen rows count - ImGuiTableColumnIdx FreezeRowsCount; // Actual frozen row count (== FreezeRowsRequest, or == 0 when no scrolling offset) - ImGuiTableColumnIdx FreezeColumnsRequest; // Requested frozen columns count - ImGuiTableColumnIdx FreezeColumnsCount; // Actual frozen columns count (== FreezeColumnsRequest, or == 0 when no scrolling offset) - ImGuiTableColumnIdx RowCellDataCurrent; // Index of current RowCellData[] entry in current row - ImGuiTableDrawChannelIdx DummyDrawChannel; // Redirect non-visible columns here. - ImGuiTableDrawChannelIdx Bg2DrawChannelCurrent; // For Selectable() and other widgets drawing across columns after the freezing line. Index within DrawSplitter.Channels[] - ImGuiTableDrawChannelIdx Bg2DrawChannelUnfrozen; - ImS8 NavLayer; // ImGuiNavLayer at the time of BeginTable(). - bool IsLayoutLocked; // Set by TableUpdateLayout() which is called when beginning the first row. - bool IsInsideRow; // Set when inside TableBeginRow()/TableEndRow(). - bool IsInitializing; - bool IsSortSpecsDirty; - bool IsUsingHeaders; // Set when the first row had the ImGuiTableRowFlags_Headers flag. - bool IsContextPopupOpen; // Set when default context menu is open (also see: ContextPopupColumn, InstanceInteracted). - bool DisableDefaultContextMenu; // Disable default context menu. You may submit your own using TableBeginContextMenuPopup()/EndPopup() - bool IsSettingsRequestLoad; - bool IsSettingsDirty; // Set when table settings have changed and needs to be reported into ImGuiTableSetttings data. - bool IsDefaultDisplayOrder; // Set when display order is unchanged from default (DisplayOrder contains 0...Count-1) - bool IsResetAllRequest; - bool IsResetDisplayOrderRequest; - bool IsUnfrozenRows; // Set when we got past the frozen row. - bool IsDefaultSizingPolicy; // Set if user didn't explicitly set a sizing policy in BeginTable() - bool IsActiveIdAliveBeforeTable; - bool IsActiveIdInTable; - bool HasScrollbarYCurr; // Whether ANY instance of this table had a vertical scrollbar during the current frame. - bool HasScrollbarYPrev; // Whether ANY instance of this table had a vertical scrollbar during the previous. - bool MemoryCompacted; - bool HostSkipItems; // Backup of InnerWindow->SkipItem at the end of BeginTable(), because we will overwrite InnerWindow->SkipItem on a per-column basis - - ImGuiTable() { memset(this, 0, sizeof(*this)); LastFrameActive = -1; } - ~ImGuiTable() { IM_FREE(RawData); } -}; - -// Transient data that are only needed between BeginTable() and EndTable(), those buffers are shared (1 per level of stacked table). -// - Accessing those requires chasing an extra pointer so for very frequently used data we leave them in the main table structure. -// - We also leave out of this structure data that tend to be particularly useful for debugging/metrics. -// FIXME-TABLE: more transient data could be stored in a stacked ImGuiTableTempData: e.g. SortSpecs. -// sizeof() ~ 136 bytes. -struct IMGUI_API ImGuiTableTempData -{ - int TableIndex; // Index in g.Tables.Buf[] pool - float LastTimeActive; // Last timestamp this structure was used - float AngledHeadersExtraWidth; // Used in EndTable() - ImVector AngledHeadersRequests; // Used in TableAngledHeadersRow() - - ImVec2 UserOuterSize; // outer_size.x passed to BeginTable() - ImDrawListSplitter DrawSplitter; - - ImRect HostBackupWorkRect; // Backup of InnerWindow->WorkRect at the end of BeginTable() - ImRect HostBackupParentWorkRect; // Backup of InnerWindow->ParentWorkRect at the end of BeginTable() - ImVec2 HostBackupPrevLineSize; // Backup of InnerWindow->DC.PrevLineSize at the end of BeginTable() - ImVec2 HostBackupCurrLineSize; // Backup of InnerWindow->DC.CurrLineSize at the end of BeginTable() - ImVec2 HostBackupCursorMaxPos; // Backup of InnerWindow->DC.CursorMaxPos at the end of BeginTable() - ImVec1 HostBackupColumnsOffset; // Backup of OuterWindow->DC.ColumnsOffset at the end of BeginTable() - float HostBackupItemWidth; // Backup of OuterWindow->DC.ItemWidth at the end of BeginTable() - int HostBackupItemWidthStackSize;//Backup of OuterWindow->DC.ItemWidthStack.Size at the end of BeginTable() - - ImGuiTableTempData() { memset(this, 0, sizeof(*this)); LastTimeActive = -1.0f; } -}; - -// sizeof() ~ 16 -struct ImGuiTableColumnSettings -{ - float WidthOrWeight; - ImGuiID UserID; - ImGuiTableColumnIdx Index; - ImGuiTableColumnIdx DisplayOrder; - ImGuiTableColumnIdx SortOrder; - ImU8 SortDirection : 2; - ImS8 IsEnabled : 2; // "Visible" in ini file - ImU8 IsStretch : 1; - - ImGuiTableColumnSettings() - { - WidthOrWeight = 0.0f; - UserID = 0; - Index = -1; - DisplayOrder = SortOrder = -1; - SortDirection = ImGuiSortDirection_None; - IsEnabled = -1; - IsStretch = 0; - } -}; - -// This is designed to be stored in a single ImChunkStream (1 header followed by N ImGuiTableColumnSettings, etc.) -struct ImGuiTableSettings -{ - ImGuiID ID; // Set to 0 to invalidate/delete the setting - ImGuiTableFlags SaveFlags; // Indicate data we want to save using the Resizable/Reorderable/Sortable/Hideable flags (could be using its own flags..) - float RefScale; // Reference scale to be able to rescale columns on font/dpi changes. - ImGuiTableColumnIdx ColumnsCount; - ImGuiTableColumnIdx ColumnsCountMax; // Maximum number of columns this settings instance can store, we can recycle a settings instance with lower number of columns but not higher - bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) - - ImGuiTableSettings() { memset(this, 0, sizeof(*this)); } - ImGuiTableColumnSettings* GetColumnSettings() { return (ImGuiTableColumnSettings*)(this + 1); } -}; - -//----------------------------------------------------------------------------- -// [SECTION] ImGui internal API -// No guarantee of forward compatibility here! -//----------------------------------------------------------------------------- - -namespace ImGui -{ - // Windows - // We should always have a CurrentWindow in the stack (there is an implicit "Debug" window) - // If this ever crashes because g.CurrentWindow is NULL, it means that either: - // - ImGui::NewFrame() has never been called, which is illegal. - // - You are calling ImGui functions after ImGui::EndFrame()/ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal. - IMGUI_API ImGuiIO& GetIO(ImGuiContext* ctx); - IMGUI_API ImGuiPlatformIO& GetPlatformIO(ImGuiContext* ctx); - inline ImGuiWindow* GetCurrentWindowRead() { ImGuiContext& g = *GImGui; return g.CurrentWindow; } - inline ImGuiWindow* GetCurrentWindow() { ImGuiContext& g = *GImGui; g.CurrentWindow->WriteAccessed = true; return g.CurrentWindow; } - IMGUI_API ImGuiWindow* FindWindowByID(ImGuiID id); - IMGUI_API ImGuiWindow* FindWindowByName(const char* name); - IMGUI_API void UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window); - IMGUI_API void UpdateWindowSkipRefresh(ImGuiWindow* window); - IMGUI_API ImVec2 CalcWindowNextAutoFitSize(ImGuiWindow* window); - IMGUI_API bool IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy); - IMGUI_API bool IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent); - IMGUI_API bool IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below); - IMGUI_API bool IsWindowNavFocusable(ImGuiWindow* window); - IMGUI_API void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond = 0); - IMGUI_API void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond = 0); - IMGUI_API void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond = 0); - IMGUI_API void SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size); - IMGUI_API void SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window); - inline void SetWindowParentWindowForFocusRoute(ImGuiWindow* window, ImGuiWindow* parent_window) { window->ParentWindowForFocusRoute = parent_window; } - inline ImRect WindowRectAbsToRel(ImGuiWindow* window, const ImRect& r) { ImVec2 off = window->DC.CursorStartPos; return ImRect(r.Min.x - off.x, r.Min.y - off.y, r.Max.x - off.x, r.Max.y - off.y); } - inline ImRect WindowRectRelToAbs(ImGuiWindow* window, const ImRect& r) { ImVec2 off = window->DC.CursorStartPos; return ImRect(r.Min.x + off.x, r.Min.y + off.y, r.Max.x + off.x, r.Max.y + off.y); } - inline ImVec2 WindowPosAbsToRel(ImGuiWindow* window, const ImVec2& p) { ImVec2 off = window->DC.CursorStartPos; return ImVec2(p.x - off.x, p.y - off.y); } - inline ImVec2 WindowPosRelToAbs(ImGuiWindow* window, const ImVec2& p) { ImVec2 off = window->DC.CursorStartPos; return ImVec2(p.x + off.x, p.y + off.y); } - - // Windows: Display Order and Focus Order - IMGUI_API void FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags = 0); - IMGUI_API void FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags); - IMGUI_API void BringWindowToFocusFront(ImGuiWindow* window); - IMGUI_API void BringWindowToDisplayFront(ImGuiWindow* window); - IMGUI_API void BringWindowToDisplayBack(ImGuiWindow* window); - IMGUI_API void BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* above_window); - IMGUI_API int FindWindowDisplayIndex(ImGuiWindow* window); - IMGUI_API ImGuiWindow* FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* window); - - // Windows: Idle, Refresh Policies [EXPERIMENTAL] - IMGUI_API void SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags); - - // Fonts, drawing - IMGUI_API void RegisterUserTexture(ImTextureData* tex); // Register external texture - IMGUI_API void UnregisterUserTexture(ImTextureData* tex); - IMGUI_API void RegisterFontAtlas(ImFontAtlas* atlas); - IMGUI_API void UnregisterFontAtlas(ImFontAtlas* atlas); - IMGUI_API void SetCurrentFont(ImFont* font, float font_size_before_scaling, float font_size_after_scaling); - IMGUI_API void UpdateCurrentFontSize(float restore_font_size_after_scaling); - IMGUI_API void SetFontRasterizerDensity(float rasterizer_density); - inline float GetFontRasterizerDensity() { return GImGui->FontRasterizerDensity; } - inline float GetRoundedFontSize(float size) { return IM_ROUND(size); } - IMGUI_API ImFont* GetDefaultFont(); - IMGUI_API void PushPasswordFont(); - IMGUI_API void PopPasswordFont(); - inline ImDrawList* GetForegroundDrawList(ImGuiWindow* window) { IM_UNUSED(window); return GetForegroundDrawList(); } // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'docking' branches. - IMGUI_API ImDrawList* GetBackgroundDrawList(ImGuiViewport* viewport); // get background draw list for the given viewport. this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents. - IMGUI_API ImDrawList* GetForegroundDrawList(ImGuiViewport* viewport); // get foreground draw list for the given viewport. this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents. - IMGUI_API void AddDrawListToDrawDataEx(ImDrawData* draw_data, ImVector* out_list, ImDrawList* draw_list); - - // Init - IMGUI_API void Initialize(); - IMGUI_API void Shutdown(); // Since 1.60 this is a _private_ function. You can call DestroyContext() to destroy the context created by CreateContext(). - - // NewFrame - IMGUI_API void UpdateInputEvents(bool trickle_fast_inputs); - IMGUI_API void UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos); - IMGUI_API void FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window); - IMGUI_API void StartMouseMovingWindow(ImGuiWindow* window); - IMGUI_API void UpdateMouseMovingWindowNewFrame(); - IMGUI_API void UpdateMouseMovingWindowEndFrame(); - - // Generic context hooks - IMGUI_API ImGuiID AddContextHook(ImGuiContext* context, const ImGuiContextHook* hook); - IMGUI_API void RemoveContextHook(ImGuiContext* context, ImGuiID hook_to_remove); - IMGUI_API void CallContextHooks(ImGuiContext* context, ImGuiContextHookType type); - - // Viewports - IMGUI_API void ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale); - IMGUI_API void SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport); - - // Settings - IMGUI_API void MarkIniSettingsDirty(); - IMGUI_API void MarkIniSettingsDirty(ImGuiWindow* window); - IMGUI_API void ClearIniSettings(); - IMGUI_API void AddSettingsHandler(const ImGuiSettingsHandler* handler); - IMGUI_API void RemoveSettingsHandler(const char* type_name); - IMGUI_API ImGuiSettingsHandler* FindSettingsHandler(const char* type_name); - - // Settings - Windows - IMGUI_API ImGuiWindowSettings* CreateNewWindowSettings(const char* name); - IMGUI_API ImGuiWindowSettings* FindWindowSettingsByID(ImGuiID id); - IMGUI_API ImGuiWindowSettings* FindWindowSettingsByWindow(ImGuiWindow* window); - IMGUI_API void ClearWindowSettings(const char* name); - - // Localization - IMGUI_API void LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count); - inline const char* LocalizeGetMsg(ImGuiLocKey key) { ImGuiContext& g = *GImGui; const char* msg = g.LocalizationTable[key]; return msg ? msg : "*Missing Text*"; } - - // Scrolling - IMGUI_API void SetScrollX(ImGuiWindow* window, float scroll_x); - IMGUI_API void SetScrollY(ImGuiWindow* window, float scroll_y); - IMGUI_API void SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio); - IMGUI_API void SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio); - - // Early work-in-progress API (ScrollToItem() will become public) - IMGUI_API void ScrollToItem(ImGuiScrollFlags flags = 0); - IMGUI_API void ScrollToRect(ImGuiWindow* window, const ImRect& rect, ImGuiScrollFlags flags = 0); - IMGUI_API ImVec2 ScrollToRectEx(ImGuiWindow* window, const ImRect& rect, ImGuiScrollFlags flags = 0); -//#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - inline void ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& rect) { ScrollToRect(window, rect, ImGuiScrollFlags_KeepVisibleEdgeY); } -//#endif - - // Basic Accessors - inline ImGuiItemStatusFlags GetItemStatusFlags() { ImGuiContext& g = *GImGui; return g.LastItemData.StatusFlags; } - inline ImGuiItemFlags GetItemFlags() { ImGuiContext& g = *GImGui; return g.LastItemData.ItemFlags; } - inline ImGuiID GetActiveID() { ImGuiContext& g = *GImGui; return g.ActiveId; } - inline ImGuiID GetFocusID() { ImGuiContext& g = *GImGui; return g.NavId; } - IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window); - IMGUI_API void SetFocusID(ImGuiID id, ImGuiWindow* window); - IMGUI_API void ClearActiveID(); - IMGUI_API ImGuiID GetHoveredID(); - IMGUI_API void SetHoveredID(ImGuiID id); - IMGUI_API void KeepAliveID(ImGuiID id); - IMGUI_API void MarkItemEdited(ImGuiID id); // Mark data associated to given item as "edited", used by IsItemDeactivatedAfterEdit() function. - IMGUI_API void PushOverrideID(ImGuiID id); // Push given value as-is at the top of the ID stack (whereas PushID combines old and new hashes) - IMGUI_API ImGuiID GetIDWithSeed(const char* str_id_begin, const char* str_id_end, ImGuiID seed); - IMGUI_API ImGuiID GetIDWithSeed(int n, ImGuiID seed); - - // Basic Helpers for widget code - IMGUI_API void ItemSize(const ImVec2& size, float text_baseline_y = -1.0f); - inline void ItemSize(const ImRect& bb, float text_baseline_y = -1.0f) { ItemSize(bb.GetSize(), text_baseline_y); } // FIXME: This is a misleading API since we expect CursorPos to be bb.Min. - IMGUI_API bool ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb = NULL, ImGuiItemFlags extra_flags = 0); - IMGUI_API bool ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags); - IMGUI_API bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags = 0); - IMGUI_API bool IsClippedEx(const ImRect& bb, ImGuiID id); - IMGUI_API void SetLastItemData(ImGuiID item_id, ImGuiItemFlags item_flags, ImGuiItemStatusFlags status_flags, const ImRect& item_rect); - IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_w, float default_h); - IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x); - IMGUI_API void PushMultiItemsWidths(int components, float width_full); - IMGUI_API void ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess); - - // Parameter stacks (shared) - IMGUI_API const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx); - IMGUI_API void BeginDisabledOverrideReenable(); - IMGUI_API void EndDisabledOverrideReenable(); - - // Logging/Capture - IMGUI_API void LogBegin(ImGuiLogFlags flags, int auto_open_depth); // -> BeginCapture() when we design v2 api, for now stay under the radar by using the old name. - IMGUI_API void LogToBuffer(int auto_open_depth = -1); // Start logging/capturing to internal buffer - IMGUI_API void LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end = NULL); - IMGUI_API void LogSetNextTextDecoration(const char* prefix, const char* suffix); - - // Childs - IMGUI_API bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags); - - // Popups, Modals - IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags); - IMGUI_API bool BeginPopupMenuEx(ImGuiID id, const char* label, ImGuiWindowFlags extra_window_flags); - IMGUI_API void OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags = ImGuiPopupFlags_None); - IMGUI_API void ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup); - IMGUI_API void ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup); - IMGUI_API void ClosePopupsExceptModals(); - IMGUI_API bool IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags); - IMGUI_API ImRect GetPopupAllowedExtentRect(ImGuiWindow* window); - IMGUI_API ImGuiWindow* GetTopMostPopupModal(); - IMGUI_API ImGuiWindow* GetTopMostAndVisiblePopupModal(); - IMGUI_API ImGuiWindow* FindBlockingModal(ImGuiWindow* window); - IMGUI_API ImVec2 FindBestWindowPosForPopup(ImGuiWindow* window); - IMGUI_API ImVec2 FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy); - - // Tooltips - IMGUI_API bool BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags); - IMGUI_API bool BeginTooltipHidden(); - - // Menus - IMGUI_API bool BeginViewportSideBar(const char* name, ImGuiViewport* viewport, ImGuiDir dir, float size, ImGuiWindowFlags window_flags); - IMGUI_API bool BeginMenuEx(const char* label, const char* icon, bool enabled = true); - IMGUI_API bool MenuItemEx(const char* label, const char* icon, const char* shortcut = NULL, bool selected = false, bool enabled = true); - - // Combos - IMGUI_API bool BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags flags); - IMGUI_API bool BeginComboPreview(); - IMGUI_API void EndComboPreview(); - - // Keyboard/Gamepad Navigation - IMGUI_API void NavInitWindow(ImGuiWindow* window, bool force_reinit); - IMGUI_API void NavInitRequestApplyResult(); - IMGUI_API bool NavMoveRequestButNoResultYet(); - IMGUI_API void NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags); - IMGUI_API void NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags); - IMGUI_API void NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result); - IMGUI_API void NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, const ImGuiTreeNodeStackData* tree_node_data); - IMGUI_API void NavMoveRequestCancel(); - IMGUI_API void NavMoveRequestApplyResult(); - IMGUI_API void NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags); - IMGUI_API void NavHighlightActivated(ImGuiID id); - IMGUI_API void NavClearPreferredPosForAxis(ImGuiAxis axis); - IMGUI_API void SetNavCursorVisibleAfterMove(); - IMGUI_API void NavUpdateCurrentWindowIsScrollPushableX(); - IMGUI_API void SetNavWindow(ImGuiWindow* window); - IMGUI_API void SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel); - IMGUI_API void SetNavFocusScope(ImGuiID focus_scope_id); - - // Focus/Activation - // This should be part of a larger set of API: FocusItem(offset = -1), FocusItemByID(id), ActivateItem(offset = -1), ActivateItemByID(id) etc. which are - // much harder to design and implement than expected. I have a couple of private branches on this matter but it's not simple. For now implementing the easy ones. - IMGUI_API void FocusItem(); // Focus last item (no selection/activation). - IMGUI_API void ActivateItemByID(ImGuiID id); // Activate an item by ID (button, checkbox, tree node etc.). Activation is queued and processed on the next frame when the item is encountered again. Was called 'ActivateItem()' before 1.89.7. - - // Inputs - // FIXME: Eventually we should aim to move e.g. IsActiveIdUsingKey() into IsKeyXXX functions. - inline bool IsNamedKey(ImGuiKey key) { return key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END; } - inline bool IsNamedKeyOrMod(ImGuiKey key) { return (key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END) || key == ImGuiMod_Ctrl || key == ImGuiMod_Shift || key == ImGuiMod_Alt || key == ImGuiMod_Super; } - inline bool IsLegacyKey(ImGuiKey key) { return key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_LegacyNativeKey_END; } - inline bool IsKeyboardKey(ImGuiKey key) { return key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END; } - inline bool IsGamepadKey(ImGuiKey key) { return key >= ImGuiKey_Gamepad_BEGIN && key < ImGuiKey_Gamepad_END; } - inline bool IsMouseKey(ImGuiKey key) { return key >= ImGuiKey_Mouse_BEGIN && key < ImGuiKey_Mouse_END; } - inline bool IsAliasKey(ImGuiKey key) { return key >= ImGuiKey_Aliases_BEGIN && key < ImGuiKey_Aliases_END; } - inline bool IsLRModKey(ImGuiKey key) { return key >= ImGuiKey_LeftCtrl && key <= ImGuiKey_RightSuper; } - ImGuiKeyChord FixupKeyChord(ImGuiKeyChord key_chord); - inline ImGuiKey ConvertSingleModFlagToKey(ImGuiKey key) - { - if (key == ImGuiMod_Ctrl) return ImGuiKey_ReservedForModCtrl; - if (key == ImGuiMod_Shift) return ImGuiKey_ReservedForModShift; - if (key == ImGuiMod_Alt) return ImGuiKey_ReservedForModAlt; - if (key == ImGuiMod_Super) return ImGuiKey_ReservedForModSuper; - return key; - } - - IMGUI_API ImGuiKeyData* GetKeyData(ImGuiContext* ctx, ImGuiKey key); - inline ImGuiKeyData* GetKeyData(ImGuiKey key) { ImGuiContext& g = *GImGui; return GetKeyData(&g, key); } - IMGUI_API const char* GetKeyChordName(ImGuiKeyChord key_chord); - inline ImGuiKey MouseButtonToKey(ImGuiMouseButton button) { IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT); return (ImGuiKey)(ImGuiKey_MouseLeft + button); } - IMGUI_API bool IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold = -1.0f); - IMGUI_API ImVec2 GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down); - IMGUI_API float GetNavTweakPressedAmount(ImGuiAxis axis); - IMGUI_API int CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate); - IMGUI_API void GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate); - IMGUI_API void TeleportMousePos(const ImVec2& pos); - IMGUI_API void SetActiveIdUsingAllKeyboardKeys(); - inline bool IsActiveIdUsingNavDir(ImGuiDir dir) { ImGuiContext& g = *GImGui; return (g.ActiveIdUsingNavDirMask & (1 << dir)) != 0; } - - // [EXPERIMENTAL] Low-Level: Key/Input Ownership - // - The idea is that instead of "eating" a given input, we can link to an owner id. - // - Ownership is most often claimed as a result of reacting to a press/down event (but occasionally may be claimed ahead). - // - Input queries can then read input by specifying ImGuiKeyOwner_Any (== 0), ImGuiKeyOwner_NoOwner (== -1) or a custom ID. - // - Legacy input queries (without specifying an owner or _Any or _None) are equivalent to using ImGuiKeyOwner_Any (== 0). - // - Input ownership is automatically released on the frame after a key is released. Therefore: - // - for ownership registration happening as a result of a down/press event, the SetKeyOwner() call may be done once (common case). - // - for ownership registration happening ahead of a down/press event, the SetKeyOwner() call needs to be made every frame (happens if e.g. claiming ownership on hover). - // - SetItemKeyOwner() is a shortcut for common simple case. A custom widget will probably want to call SetKeyOwner() multiple times directly based on its interaction state. - // - This is marked experimental because not all widgets are fully honoring the Set/Test idioms. We will need to move forward step by step. - // Please open a GitHub Issue to submit your usage scenario or if there's a use case you need solved. - IMGUI_API ImGuiID GetKeyOwner(ImGuiKey key); - IMGUI_API void SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags = 0); - IMGUI_API void SetKeyOwnersForKeyChord(ImGuiKeyChord key, ImGuiID owner_id, ImGuiInputFlags flags = 0); - IMGUI_API void SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags); // Set key owner to last item if it is hovered or active. Equivalent to 'if (IsItemHovered() || IsItemActive()) { SetKeyOwner(key, GetItemID());'. - IMGUI_API bool TestKeyOwner(ImGuiKey key, ImGuiID owner_id); // Test that key is either not owned, either owned by 'owner_id' - inline ImGuiKeyOwnerData* GetKeyOwnerData(ImGuiContext* ctx, ImGuiKey key) { if (key & ImGuiMod_Mask_) key = ConvertSingleModFlagToKey(key); IM_ASSERT(IsNamedKey(key)); return &ctx->KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN]; } - - // [EXPERIMENTAL] High-Level: Input Access functions w/ support for Key/Input Ownership - // - Important: legacy IsKeyPressed(ImGuiKey, bool repeat=true) _DEFAULTS_ to repeat, new IsKeyPressed() requires _EXPLICIT_ ImGuiInputFlags_Repeat flag. - // - Expected to be later promoted to public API, the prototypes are designed to replace existing ones (since owner_id can default to Any == 0) - // - Specifying a value for 'ImGuiID owner' will test that EITHER the key is NOT owned (UNLESS locked), EITHER the key is owned by 'owner'. - // Legacy functions use ImGuiKeyOwner_Any meaning that they typically ignore ownership, unless a call to SetKeyOwner() explicitly used ImGuiInputFlags_LockThisFrame or ImGuiInputFlags_LockUntilRelease. - // - Binding generators may want to ignore those for now, or suffix them with Ex() until we decide if this gets moved into public API. - IMGUI_API bool IsKeyDown(ImGuiKey key, ImGuiID owner_id); - IMGUI_API bool IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id = 0); // Important: when transitioning from old to new IsKeyPressed(): old API has "bool repeat = true", so would default to repeat. New API requiress explicit ImGuiInputFlags_Repeat. - IMGUI_API bool IsKeyReleased(ImGuiKey key, ImGuiID owner_id); - IMGUI_API bool IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id = 0); - IMGUI_API bool IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id); - IMGUI_API bool IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id = 0); - IMGUI_API bool IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id); - IMGUI_API bool IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id); - - // Shortcut Testing & Routing - // - Set Shortcut() and SetNextItemShortcut() in imgui.h - // - When a policy (except for ImGuiInputFlags_RouteAlways *) is set, Shortcut() will register itself with SetShortcutRouting(), - // allowing the system to decide where to route the input among other route-aware calls. - // (* using ImGuiInputFlags_RouteAlways is roughly equivalent to calling IsKeyChordPressed(key) and bypassing route registration and check) - // - When using one of the routing option: - // - The default route is ImGuiInputFlags_RouteFocused (accept inputs if window is in focus stack. Deep-most focused window takes inputs. ActiveId takes inputs over deep-most focused window.) - // - Routes are requested given a chord (key + modifiers) and a routing policy. - // - Routes are resolved during NewFrame(): if keyboard modifiers are matching current ones: SetKeyOwner() is called + route is granted for the frame. - // - Each route may be granted to a single owner. When multiple requests are made we have policies to select the winning route (e.g. deep most window). - // - Multiple read sites may use the same owner id can all access the granted route. - // - When owner_id is 0 we use the current Focus Scope ID as a owner ID in order to identify our location. - // - You can chain two unrelated windows in the focus stack using SetWindowParentWindowForFocusRoute() - // e.g. if you have a tool window associated to a document, and you want document shortcuts to run when the tool is focused. - IMGUI_API bool Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id); - IMGUI_API bool SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id); // owner_id needs to be explicit and cannot be 0 - IMGUI_API bool TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id); - IMGUI_API ImGuiKeyRoutingData* GetShortcutRoutingData(ImGuiKeyChord key_chord); - - // [EXPERIMENTAL] Focus Scope - // This is generally used to identify a unique input location (for e.g. a selection set) - // There is one per window (automatically set in Begin), but: - // - Selection patterns generally need to react (e.g. clear a selection) when landing on one item of the set. - // So in order to identify a set multiple lists in same window may each need a focus scope. - // If you imagine an hypothetical BeginSelectionGroup()/EndSelectionGroup() api, it would likely call PushFocusScope()/EndFocusScope() - // - Shortcut routing also use focus scope as a default location identifier if an owner is not provided. - // We don't use the ID Stack for this as it is common to want them separate. - IMGUI_API void PushFocusScope(ImGuiID id); - IMGUI_API void PopFocusScope(); - inline ImGuiID GetCurrentFocusScope() { ImGuiContext& g = *GImGui; return g.CurrentFocusScopeId; } // Focus scope we are outputting into, set by PushFocusScope() - - // Drag and Drop - IMGUI_API bool IsDragDropActive(); - IMGUI_API bool BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id); - IMGUI_API void ClearDragDrop(); - IMGUI_API bool IsDragDropPayloadBeingAccepted(); - IMGUI_API void RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect); - - // Typing-Select API - // (provide Windows Explorer style "select items by typing partial name" + "cycle through items by typing same letter" feature) - // (this is currently not documented nor used by main library, but should work. See "widgets_typingselect" in imgui_test_suite for usage code. Please let us know if you use this!) - IMGUI_API ImGuiTypingSelectRequest* GetTypingSelectRequest(ImGuiTypingSelectFlags flags = ImGuiTypingSelectFlags_None); - IMGUI_API int TypingSelectFindMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx); - IMGUI_API int TypingSelectFindNextSingleCharMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx); - IMGUI_API int TypingSelectFindBestLeadingMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data); - - // Box-Select API - IMGUI_API bool BeginBoxSelect(const ImRect& scope_rect, ImGuiWindow* window, ImGuiID box_select_id, ImGuiMultiSelectFlags ms_flags); - IMGUI_API void EndBoxSelect(const ImRect& scope_rect, ImGuiMultiSelectFlags ms_flags); - - // Multi-Select API - IMGUI_API void MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags* p_button_flags); - IMGUI_API void MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed); - IMGUI_API void MultiSelectAddSetAll(ImGuiMultiSelectTempData* ms, bool selected); - IMGUI_API void MultiSelectAddSetRange(ImGuiMultiSelectTempData* ms, bool selected, int range_dir, ImGuiSelectionUserData first_item, ImGuiSelectionUserData last_item); - inline ImGuiBoxSelectState* GetBoxSelectState(ImGuiID id) { ImGuiContext& g = *GImGui; return (id != 0 && g.BoxSelectState.ID == id && g.BoxSelectState.IsActive) ? &g.BoxSelectState : NULL; } - inline ImGuiMultiSelectState* GetMultiSelectState(ImGuiID id) { ImGuiContext& g = *GImGui; return g.MultiSelectStorage.GetByKey(id); } - - // Internal Columns API (this is not exposed because we will encourage transitioning to the Tables API) - IMGUI_API void SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect); - IMGUI_API void BeginColumns(const char* str_id, int count, ImGuiOldColumnFlags flags = 0); // setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns(). - IMGUI_API void EndColumns(); // close columns - IMGUI_API void PushColumnClipRect(int column_index); - IMGUI_API void PushColumnsBackground(); - IMGUI_API void PopColumnsBackground(); - IMGUI_API ImGuiID GetColumnsID(const char* str_id, int count); - IMGUI_API ImGuiOldColumns* FindOrCreateColumns(ImGuiWindow* window, ImGuiID id); - IMGUI_API float GetColumnOffsetFromNorm(const ImGuiOldColumns* columns, float offset_norm); - IMGUI_API float GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset); - - // Tables: Candidates for public API - IMGUI_API void TableOpenContextMenu(int column_n = -1); - IMGUI_API void TableSetColumnWidth(int column_n, float width); - IMGUI_API void TableSetColumnSortDirection(int column_n, ImGuiSortDirection sort_direction, bool append_to_sort_specs); - IMGUI_API int TableGetHoveredRow(); // Retrieve *PREVIOUS FRAME* hovered row. This difference with TableGetHoveredColumn() is the reason why this is not public yet. - IMGUI_API float TableGetHeaderRowHeight(); - IMGUI_API float TableGetHeaderAngledMaxLabelWidth(); - IMGUI_API void TablePushBackgroundChannel(); - IMGUI_API void TablePopBackgroundChannel(); - IMGUI_API void TablePushColumnChannel(int column_n); - IMGUI_API void TablePopColumnChannel(); - IMGUI_API void TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label_width, const ImGuiTableHeaderData* data, int data_count); - - // Tables: Internals - inline ImGuiTable* GetCurrentTable() { ImGuiContext& g = *GImGui; return g.CurrentTable; } - IMGUI_API ImGuiTable* TableFindByID(ImGuiID id); - IMGUI_API bool BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0, 0), float inner_width = 0.0f); - IMGUI_API void TableBeginInitMemory(ImGuiTable* table, int columns_count); - IMGUI_API void TableBeginApplyRequests(ImGuiTable* table); - IMGUI_API void TableSetupDrawChannels(ImGuiTable* table); - IMGUI_API void TableUpdateLayout(ImGuiTable* table); - IMGUI_API void TableUpdateBorders(ImGuiTable* table); - IMGUI_API void TableUpdateColumnsWeightFromWidth(ImGuiTable* table); - IMGUI_API void TableDrawBorders(ImGuiTable* table); - IMGUI_API void TableDrawDefaultContextMenu(ImGuiTable* table, ImGuiTableFlags flags_for_section_to_display); - IMGUI_API bool TableBeginContextMenuPopup(ImGuiTable* table); - IMGUI_API void TableMergeDrawChannels(ImGuiTable* table); - inline ImGuiTableInstanceData* TableGetInstanceData(ImGuiTable* table, int instance_no) { if (instance_no == 0) return &table->InstanceDataFirst; return &table->InstanceDataExtra[instance_no - 1]; } - inline ImGuiID TableGetInstanceID(ImGuiTable* table, int instance_no) { return TableGetInstanceData(table, instance_no)->TableInstanceID; } - IMGUI_API void TableSortSpecsSanitize(ImGuiTable* table); - IMGUI_API void TableSortSpecsBuild(ImGuiTable* table); - IMGUI_API ImGuiSortDirection TableGetColumnNextSortDirection(ImGuiTableColumn* column); - IMGUI_API void TableFixColumnSortDirection(ImGuiTable* table, ImGuiTableColumn* column); - IMGUI_API float TableGetColumnWidthAuto(ImGuiTable* table, ImGuiTableColumn* column); - IMGUI_API void TableBeginRow(ImGuiTable* table); - IMGUI_API void TableEndRow(ImGuiTable* table); - IMGUI_API void TableBeginCell(ImGuiTable* table, int column_n); - IMGUI_API void TableEndCell(ImGuiTable* table); - IMGUI_API ImRect TableGetCellBgRect(const ImGuiTable* table, int column_n); - IMGUI_API const char* TableGetColumnName(const ImGuiTable* table, int column_n); - IMGUI_API ImGuiID TableGetColumnResizeID(ImGuiTable* table, int column_n, int instance_no = 0); - IMGUI_API float TableCalcMaxColumnWidth(const ImGuiTable* table, int column_n); - IMGUI_API void TableSetColumnWidthAutoSingle(ImGuiTable* table, int column_n); - IMGUI_API void TableSetColumnWidthAutoAll(ImGuiTable* table); - IMGUI_API void TableRemove(ImGuiTable* table); - IMGUI_API void TableGcCompactTransientBuffers(ImGuiTable* table); - IMGUI_API void TableGcCompactTransientBuffers(ImGuiTableTempData* table); - IMGUI_API void TableGcCompactSettings(); - - // Tables: Settings - IMGUI_API void TableLoadSettings(ImGuiTable* table); - IMGUI_API void TableSaveSettings(ImGuiTable* table); - IMGUI_API void TableResetSettings(ImGuiTable* table); - IMGUI_API ImGuiTableSettings* TableGetBoundSettings(ImGuiTable* table); - IMGUI_API void TableSettingsAddSettingsHandler(); - IMGUI_API ImGuiTableSettings* TableSettingsCreate(ImGuiID id, int columns_count); - IMGUI_API ImGuiTableSettings* TableSettingsFindByID(ImGuiID id); - - // Tab Bars - inline ImGuiTabBar* GetCurrentTabBar() { ImGuiContext& g = *GImGui; return g.CurrentTabBar; } - IMGUI_API bool BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& bb, ImGuiTabBarFlags flags); - IMGUI_API ImGuiTabItem* TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id); - IMGUI_API ImGuiTabItem* TabBarFindTabByOrder(ImGuiTabBar* tab_bar, int order); - IMGUI_API ImGuiTabItem* TabBarGetCurrentTab(ImGuiTabBar* tab_bar); - inline int TabBarGetTabOrder(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) { return tab_bar->Tabs.index_from_ptr(tab); } - IMGUI_API const char* TabBarGetTabName(ImGuiTabBar* tab_bar, ImGuiTabItem* tab); - IMGUI_API void TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id); - IMGUI_API void TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab); - IMGUI_API void TabBarQueueFocus(ImGuiTabBar* tab_bar, ImGuiTabItem* tab); - IMGUI_API void TabBarQueueFocus(ImGuiTabBar* tab_bar, const char* tab_name); - IMGUI_API void TabBarQueueReorder(ImGuiTabBar* tab_bar, ImGuiTabItem* tab, int offset); - IMGUI_API void TabBarQueueReorderFromMousePos(ImGuiTabBar* tab_bar, ImGuiTabItem* tab, ImVec2 mouse_pos); - IMGUI_API bool TabBarProcessReorder(ImGuiTabBar* tab_bar); - IMGUI_API bool TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags, ImGuiWindow* docked_window); - IMGUI_API void TabItemSpacing(const char* str_id, ImGuiTabItemFlags flags, float width); - IMGUI_API ImVec2 TabItemCalcSize(const char* label, bool has_close_button_or_unsaved_marker); - IMGUI_API ImVec2 TabItemCalcSize(ImGuiWindow* window); - IMGUI_API void TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col); - IMGUI_API void TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible, bool* out_just_closed, bool* out_text_clipped); - - // Render helpers - // AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. THOSE FUNCTIONS ARE A MESS. THEIR SIGNATURE AND BEHAVIOR WILL CHANGE, THEY NEED TO BE REFACTORED INTO SOMETHING DECENT. - // NB: All position are in absolute pixels coordinates (we are never using window coordinates internally) - IMGUI_API void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true); - IMGUI_API void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width); - IMGUI_API void RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0, 0), const ImRect* clip_rect = NULL); - IMGUI_API void RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0, 0), const ImRect* clip_rect = NULL); - IMGUI_API void RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float ellipsis_max_x, const char* text, const char* text_end, const ImVec2* text_size_if_known); - IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool borders = true, float rounding = 0.0f); - IMGUI_API void RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding = 0.0f); - IMGUI_API void RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, float grid_step, ImVec2 grid_off, float rounding = 0.0f, ImDrawFlags flags = 0); - IMGUI_API void RenderNavCursor(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFlags flags = ImGuiNavRenderCursorFlags_None); // Navigation highlight -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - inline void RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavRenderCursorFlags flags = ImGuiNavRenderCursorFlags_None) { RenderNavCursor(bb, id, flags); } // Renamed in 1.91.4 -#endif - IMGUI_API const char* FindRenderedTextEnd(const char* text, const char* text_end = NULL); // Find the optional ## from which we stop displaying text. - IMGUI_API void RenderMouseCursor(ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow); - - // Render helpers (those functions don't access any ImGui state!) - IMGUI_API void RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale = 1.0f); - IMGUI_API void RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col); - IMGUI_API void RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float sz); - IMGUI_API void RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col); - IMGUI_API void RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding); - IMGUI_API void RenderRectFilledWithHole(ImDrawList* draw_list, const ImRect& outer, const ImRect& inner, ImU32 col, float rounding); - - // Widgets: Text - IMGUI_API void TextEx(const char* text, const char* text_end = NULL, ImGuiTextFlags flags = 0); - IMGUI_API void TextAligned(float align_x, float size_x, const char* fmt, ...); // FIXME-WIP: Works but API is likely to be reworked. This is designed for 1 item on the line. (#7024) - IMGUI_API void TextAlignedV(float align_x, float size_x, const char* fmt, va_list args); - - // Widgets - IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); - IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags = 0); - IMGUI_API bool ImageButtonEx(ImGuiID id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags = 0); - IMGUI_API void SeparatorEx(ImGuiSeparatorFlags flags, float thickness = 1.0f); - IMGUI_API void SeparatorTextEx(ImGuiID id, const char* label, const char* label_end, float extra_width); - IMGUI_API bool CheckboxFlags(const char* label, ImS64* flags, ImS64 flags_value); - IMGUI_API bool CheckboxFlags(const char* label, ImU64* flags, ImU64 flags_value); - - // Widgets: Window Decorations - IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos); - IMGUI_API bool CollapseButton(ImGuiID id, const ImVec2& pos); - IMGUI_API void Scrollbar(ImGuiAxis axis); - IMGUI_API bool ScrollbarEx(const ImRect& bb, ImGuiID id, ImGuiAxis axis, ImS64* p_scroll_v, ImS64 avail_v, ImS64 contents_v, ImDrawFlags draw_rounding_flags = 0); - IMGUI_API ImRect GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis); - IMGUI_API ImGuiID GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis); - IMGUI_API ImGuiID GetWindowResizeCornerID(ImGuiWindow* window, int n); // 0..3: corners - IMGUI_API ImGuiID GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir); - - // Widgets low-level behaviors - IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0); - IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags); - IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb); - IMGUI_API bool SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend = 0.0f, float hover_visibility_delay = 0.0f, ImU32 bg_col = 0); - - // Widgets: Tree Nodes - IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); - IMGUI_API void TreeNodeDrawLineToChildNode(const ImVec2& target_pos); - IMGUI_API void TreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data); - IMGUI_API void TreePushOverrideID(ImGuiID id); - IMGUI_API bool TreeNodeGetOpen(ImGuiID storage_id); - IMGUI_API void TreeNodeSetOpen(ImGuiID storage_id, bool open); - IMGUI_API bool TreeNodeUpdateNextOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags); // Return open state. Consume previous SetNextItemOpen() data, if any. May return true when logging. - - // Template functions are instantiated in imgui_widgets.cpp for a finite number of types. - // To use them externally (for custom widget) you may need an "extern template" statement in your code in order to link to existing instances and silence Clang warnings (see #2036). - // e.g. " extern template IMGUI_API float RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, float v); " - template IMGUI_API float ScaleRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); - template IMGUI_API T ScaleValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); - template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, ImGuiSliderFlags flags); - template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb); - template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); - template IMGUI_API bool CheckboxFlagsT(const char* label, T* flags, T flags_value); - - // Data type helpers - IMGUI_API const ImGuiDataTypeInfo* DataTypeGetInfo(ImGuiDataType data_type); - IMGUI_API int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* p_data, const char* format); - IMGUI_API void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, const void* arg_1, const void* arg_2); - IMGUI_API bool DataTypeApplyFromText(const char* buf, ImGuiDataType data_type, void* p_data, const char* format, void* p_data_when_empty = NULL); - IMGUI_API int DataTypeCompare(ImGuiDataType data_type, const void* arg_1, const void* arg_2); - IMGUI_API bool DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max); - IMGUI_API bool DataTypeIsZero(ImGuiDataType data_type, const void* p_data); - - // InputText - IMGUI_API bool InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); - IMGUI_API void InputTextDeactivateHook(ImGuiID id); - IMGUI_API bool TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags); - IMGUI_API bool TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min = NULL, const void* p_clamp_max = NULL); - inline bool TempInputIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.ActiveId == id && g.TempInputId == id); } - inline ImGuiInputTextState* GetInputTextState(ImGuiID id) { ImGuiContext& g = *GImGui; return (id != 0 && g.InputTextState.ID == id) ? &g.InputTextState : NULL; } // Get input text state if active - IMGUI_API void SetNextItemRefVal(ImGuiDataType data_type, void* p_data); - inline bool IsItemActiveAsInputText() { ImGuiContext& g = *GImGui; return g.ActiveId != 0 && g.ActiveId == g.LastItemData.ID && g.InputTextState.ID == g.LastItemData.ID; } // This may be useful to apply workaround that a based on distinguish whenever an item is active as a text input field. - - // Color - IMGUI_API void ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags); - IMGUI_API void ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags); - IMGUI_API void ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags); - - // Plot - IMGUI_API int PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, const ImVec2& size_arg); - - // Shade functions (write over already created vertices) - IMGUI_API void ShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1); - IMGUI_API void ShadeVertsLinearUV(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp); - IMGUI_API void ShadeVertsTransformPos(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& pivot_in, float cos_a, float sin_a, const ImVec2& pivot_out); - - // Garbage collection - IMGUI_API void GcCompactTransientMiscBuffers(); - IMGUI_API void GcCompactTransientWindowBuffers(ImGuiWindow* window); - IMGUI_API void GcAwakeTransientWindowBuffers(ImGuiWindow* window); - - // Error handling, State Recovery - IMGUI_API bool ErrorLog(const char* msg); - IMGUI_API void ErrorRecoveryStoreState(ImGuiErrorRecoveryState* state_out); - IMGUI_API void ErrorRecoveryTryToRecoverState(const ImGuiErrorRecoveryState* state_in); - IMGUI_API void ErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryState* state_in); - IMGUI_API void ErrorCheckUsingSetCursorPosToExtendParentBoundaries(); - IMGUI_API void ErrorCheckEndFrameFinalizeErrorTooltip(); - IMGUI_API bool BeginErrorTooltip(); - IMGUI_API void EndErrorTooltip(); - - // Debug Tools - IMGUI_API void DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size); // size >= 0 : alloc, size = -1 : free - IMGUI_API void DebugDrawCursorPos(ImU32 col = IM_COL32(255, 0, 0, 255)); - IMGUI_API void DebugDrawLineExtents(ImU32 col = IM_COL32(255, 0, 0, 255)); - IMGUI_API void DebugDrawItemRect(ImU32 col = IM_COL32(255, 0, 0, 255)); - IMGUI_API void DebugTextUnformattedWithLocateItem(const char* line_begin, const char* line_end); - IMGUI_API void DebugLocateItem(ImGuiID target_id); // Call sparingly: only 1 at the same time! - IMGUI_API void DebugLocateItemOnHover(ImGuiID target_id); // Only call on reaction to a mouse Hover: because only 1 at the same time! - IMGUI_API void DebugLocateItemResolveWithLastItem(); - IMGUI_API void DebugBreakClearData(); - IMGUI_API bool DebugBreakButton(const char* label, const char* description_of_location); - IMGUI_API void DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location); - IMGUI_API void ShowFontAtlas(ImFontAtlas* atlas); - IMGUI_API void DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end); - IMGUI_API void DebugNodeColumns(ImGuiOldColumns* columns); - IMGUI_API void DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label); - IMGUI_API void DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb); - IMGUI_API void DebugNodeFont(ImFont* font); - IMGUI_API void DebugNodeFontGlyphesForSrcMask(ImFont* font, ImFontBaked* baked, int src_mask); - IMGUI_API void DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph); - IMGUI_API void DebugNodeTexture(ImTextureData* tex, int int_id, const ImFontAtlasRect* highlight_rect = NULL); // ID used to facilitate persisting the "current" texture. - IMGUI_API void DebugNodeStorage(ImGuiStorage* storage, const char* label); - IMGUI_API void DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label); - IMGUI_API void DebugNodeTable(ImGuiTable* table); - IMGUI_API void DebugNodeTableSettings(ImGuiTableSettings* settings); - IMGUI_API void DebugNodeInputTextState(ImGuiInputTextState* state); - IMGUI_API void DebugNodeTypingSelectState(ImGuiTypingSelectState* state); - IMGUI_API void DebugNodeMultiSelectState(ImGuiMultiSelectState* state); - IMGUI_API void DebugNodeWindow(ImGuiWindow* window, const char* label); - IMGUI_API void DebugNodeWindowSettings(ImGuiWindowSettings* settings); - IMGUI_API void DebugNodeWindowsList(ImVector* windows, const char* label); - IMGUI_API void DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack); - IMGUI_API void DebugNodeViewport(ImGuiViewportP* viewport); - IMGUI_API void DebugRenderKeyboardPreview(ImDrawList* draw_list); - IMGUI_API void DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb); - - // Obsolete functions -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - //inline void SetItemUsingMouseWheel() { SetItemKeyOwner(ImGuiKey_MouseWheelY); } // Changed in 1.89 - //inline bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0) { return TreeNodeUpdateNextOpen(id, flags); } // Renamed in 1.89 - //inline bool IsKeyPressedMap(ImGuiKey key, bool repeat = true) { IM_ASSERT(IsNamedKey(key)); return IsKeyPressed(key, repeat); } // Removed in 1.87: Mapping from named key is always identity! - - // Refactored focus/nav/tabbing system in 1.82 and 1.84. If you have old/custom copy-and-pasted widgets which used FocusableItemRegister(): - // Refactored focus/nav/tabbing system in 1.82 and 1.84. If you have old/custom copy-and-pasted widgets which used FocusableItemRegister(): - // (Old) IMGUI_VERSION_NUM < 18209: using 'ItemAdd(....)' and 'bool tab_focused = FocusableItemRegister(...)' - // (Old) IMGUI_VERSION_NUM >= 18209: using 'ItemAdd(..., ImGuiItemAddFlags_Focusable)' and 'bool tab_focused = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Focused) != 0' - // (New) IMGUI_VERSION_NUM >= 18413: using 'ItemAdd(..., ImGuiItemFlags_Inputable)' and 'bool tab_focused = (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput))' - //inline bool FocusableItemRegister(ImGuiWindow* window, ImGuiID id) // -> pass ImGuiItemAddFlags_Inputable flag to ItemAdd() - //inline void FocusableItemUnregister(ImGuiWindow* window) // -> unnecessary: TempInputText() uses ImGuiInputTextFlags_MergedItem -#endif - -} // namespace ImGui - - -//----------------------------------------------------------------------------- -// [SECTION] ImFontLoader -//----------------------------------------------------------------------------- - -// Hooks and storage for a given font backend. -// This structure is likely to evolve as we add support for incremental atlas updates. -// Conceptually this could be public, but API is still going to be evolve. -struct ImFontLoader -{ - const char* Name; - bool (*LoaderInit)(ImFontAtlas* atlas); - void (*LoaderShutdown)(ImFontAtlas* atlas); - bool (*FontSrcInit)(ImFontAtlas* atlas, ImFontConfig* src); - void (*FontSrcDestroy)(ImFontAtlas* atlas, ImFontConfig* src); - bool (*FontSrcContainsGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint); - bool (*FontBakedInit)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); - void (*FontBakedDestroy)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); - bool (*FontBakedLoadGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x); - - // Size of backend data, Per Baked * Per Source. Buffers are managed by core to avoid excessive allocations. - // FIXME: At this point the two other types of buffers may be managed by core to be consistent? - size_t FontBakedSrcLoaderDataSize; - - ImFontLoader() { memset(this, 0, sizeof(*this)); } -}; - -#ifdef IMGUI_ENABLE_STB_TRUETYPE -IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); -#endif -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -typedef ImFontLoader ImFontBuilderIO; // [renamed/changed in 1.92] The types are not actually compatible but we provide this as a compile-time error report helper. -#endif - -//----------------------------------------------------------------------------- -// [SECTION] ImFontAtlas internal API -//----------------------------------------------------------------------------- - -#define IMGUI_FONT_SIZE_MAX (512.0f) -#define IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE (128.0f) - -// Helpers: ImTextureRef ==/!= operators provided as convenience -// (note that _TexID and _TexData are never set simultaneously) -inline bool operator==(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID == rhs._TexID && lhs._TexData == rhs._TexData; } -inline bool operator!=(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID != rhs._TexID || lhs._TexData != rhs._TexData; } - -// Refer to ImFontAtlasPackGetRect() to better understand how this works. -#define ImFontAtlasRectId_IndexMask_ (0x000FFFFF) // 20-bits: index to access builder->RectsIndex[]. -#define ImFontAtlasRectId_GenerationMask_ (0x3FF00000) // 10-bits: entry generation, so each ID is unique and get can safely detected old identifiers. -#define ImFontAtlasRectId_GenerationShift_ (20) -inline int ImFontAtlasRectId_GetIndex(ImFontAtlasRectId id) { return id & ImFontAtlasRectId_IndexMask_; } -inline int ImFontAtlasRectId_GetGeneration(ImFontAtlasRectId id) { return (id & ImFontAtlasRectId_GenerationMask_) >> ImFontAtlasRectId_GenerationShift_; } -inline ImFontAtlasRectId ImFontAtlasRectId_Make(int index_idx, int gen_idx) { IM_ASSERT(index_idx < ImFontAtlasRectId_IndexMask_ && gen_idx < (ImFontAtlasRectId_GenerationMask_ >> ImFontAtlasRectId_GenerationShift_)); return (ImFontAtlasRectId)(index_idx | (gen_idx << ImFontAtlasRectId_GenerationShift_)); } - -// Packed rectangle lookup entry (we need an indirection to allow removing/reordering rectangles) -// User are returned ImFontAtlasRectId values which are meant to be persistent. -// We handle this with an indirection. While Rects[] may be in theory shuffled, compacted etc., RectsIndex[] cannot it is keyed by ImFontAtlasRectId. -// RectsIndex[] is used both as an index into Rects[] and an index into itself. This is basically a free-list. See ImFontAtlasBuildAllocRectIndexEntry() code. -// Having this also makes it easier to e.g. sort rectangles during repack. -struct ImFontAtlasRectEntry -{ - int TargetIndex : 20; // When Used: ImFontAtlasRectId -> into Rects[]. When unused: index to next unused RectsIndex[] slot to consume free-list. - int Generation : 10; // Increased each time the entry is reused for a new rectangle. - unsigned int IsUsed : 1; -}; - -// Data available to potential texture post-processing functions -struct ImFontAtlasPostProcessData -{ - ImFontAtlas* FontAtlas; - ImFont* Font; - ImFontConfig* FontSrc; - ImFontBaked* FontBaked; - ImFontGlyph* Glyph; - - // Pixel data - void* Pixels; - ImTextureFormat Format; - int Pitch; - int Width; - int Height; -}; - -// We avoid dragging imstb_rectpack.h into public header (partly because binding generators are having issues with it) -#ifdef IMGUI_STB_NAMESPACE -namespace IMGUI_STB_NAMESPACE { struct stbrp_node; } -typedef IMGUI_STB_NAMESPACE::stbrp_node stbrp_node_im; -#else -struct stbrp_node; -typedef stbrp_node stbrp_node_im; -#endif -struct stbrp_context_opaque { char data[80]; }; - -// Internal storage for incrementally packing and building a ImFontAtlas -struct ImFontAtlasBuilder -{ - stbrp_context_opaque PackContext; // Actually 'stbrp_context' but we don't want to define this in the header file. - ImVector PackNodes; - ImVector Rects; - ImVector RectsIndex; // ImFontAtlasRectId -> index into Rects[] - ImVector TempBuffer; // Misc scratch buffer - int RectsIndexFreeListStart;// First unused entry - int RectsPackedCount; // Number of packed rectangles. - int RectsPackedSurface; // Number of packed pixels. Used when compacting to heuristically find the ideal texture size. - int RectsDiscardedCount; - int RectsDiscardedSurface; - int FrameCount; // Current frame count - ImVec2i MaxRectSize; // Largest rectangle to pack (de-facto used as a "minimum texture size") - ImVec2i MaxRectBounds; // Bottom-right most used pixels - bool LockDisableResize; // Disable resizing texture - bool PreloadedAllGlyphsRanges; // Set when missing ImGuiBackendFlags_RendererHasTextures features forces atlas to preload everything. - - // Cache of all ImFontBaked - ImStableVector BakedPool; - ImGuiStorage BakedMap; // BakedId --> ImFontBaked* - int BakedDiscardedCount; - - // Custom rectangle identifiers - ImFontAtlasRectId PackIdMouseCursors; // White pixel + mouse cursors. Also happen to be fallback in case of packing failure. - ImFontAtlasRectId PackIdLinesTexData; - - ImFontAtlasBuilder() { memset(this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = -1; } -}; - -IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); -IMGUI_API void ImFontAtlasBuildDestroy(ImFontAtlas* atlas); -IMGUI_API void ImFontAtlasBuildMain(ImFontAtlas* atlas); -IMGUI_API void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* font_loader); -IMGUI_API void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas); -IMGUI_API void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char); -IMGUI_API void ImFontAtlasBuildClear(ImFontAtlas* atlas); // Clear output and custom rects - -IMGUI_API ImTextureData* ImFontAtlasTextureAdd(ImFontAtlas* atlas, int w, int h); -IMGUI_API void ImFontAtlasTextureMakeSpace(ImFontAtlas* atlas); -IMGUI_API void ImFontAtlasTextureRepack(ImFontAtlas* atlas, int w, int h); -IMGUI_API void ImFontAtlasTextureGrow(ImFontAtlas* atlas, int old_w = -1, int old_h = -1); -IMGUI_API void ImFontAtlasTextureCompact(ImFontAtlas* atlas); -IMGUI_API ImVec2i ImFontAtlasTextureGetSizeEstimate(ImFontAtlas* atlas); - -IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); -IMGUI_API void ImFontAtlasBuildLegacyPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy -IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, ImFontBaked* baked, int* out_oversample_h, int* out_oversample_v); -IMGUI_API void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames); - -IMGUI_API bool ImFontAtlasFontSourceInit(ImFontAtlas* atlas, ImFontConfig* src); -IMGUI_API void ImFontAtlasFontSourceAddToFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); -IMGUI_API void ImFontAtlasFontDestroySourceData(ImFontAtlas* atlas, ImFontConfig* src); -IMGUI_API bool ImFontAtlasFontInitOutput(ImFontAtlas* atlas, ImFont* font); // Using FontDestroyOutput/FontInitOutput sequence useful notably if font loader params have changed -IMGUI_API void ImFontAtlasFontDestroyOutput(ImFontAtlas* atlas, ImFont* font); -IMGUI_API void ImFontAtlasFontDiscardBakes(ImFontAtlas* atlas, ImFont* font, int unused_frames); - -IMGUI_API ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size, float rasterizer_density); -IMGUI_API ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density); -IMGUI_API ImFontBaked* ImFontAtlasBakedGetClosestMatch(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density); -IMGUI_API ImFontBaked* ImFontAtlasBakedAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density, ImGuiID baked_id); -IMGUI_API void ImFontAtlasBakedDiscard(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked); -IMGUI_API ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, const ImFontGlyph* in_glyph); -IMGUI_API void ImFontAtlasBakedAddFontGlyphAdvancedX(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImWchar codepoint, float advance_x); -IMGUI_API void ImFontAtlasBakedDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph); -IMGUI_API void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImTextureRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch); - -IMGUI_API void ImFontAtlasPackInit(ImFontAtlas* atlas); -IMGUI_API ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFontAtlasRectEntry* overwrite_entry = NULL); -IMGUI_API ImTextureRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id); -IMGUI_API ImTextureRect* ImFontAtlasPackGetRectSafe(ImFontAtlas* atlas, ImFontAtlasRectId id); -IMGUI_API void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id); - -IMGUI_API void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count, bool renderer_has_textures); -IMGUI_API void ImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data); -IMGUI_API void ImFontAtlasRemoveDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data); -IMGUI_API void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex, ImTextureRef new_tex); -IMGUI_API void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas); - -IMGUI_API void ImFontAtlasTextureBlockConvert(const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch, unsigned char* dst_pixels, ImTextureFormat dst_fmt, int dst_pitch, int w, int h); -IMGUI_API void ImFontAtlasTextureBlockPostProcess(ImFontAtlasPostProcessData* data); -IMGUI_API void ImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlasPostProcessData* data, float multiply_factor); -IMGUI_API void ImFontAtlasTextureBlockFill(ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h, ImU32 col); -IMGUI_API void ImFontAtlasTextureBlockCopy(ImTextureData* src_tex, int src_x, int src_y, ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h); -IMGUI_API void ImFontAtlasTextureBlockQueueUpload(ImFontAtlas* atlas, ImTextureData* tex, int x, int y, int w, int h); - -IMGUI_API int ImTextureDataGetFormatBytesPerPixel(ImTextureFormat format); -IMGUI_API const char* ImTextureDataGetStatusName(ImTextureStatus status); -IMGUI_API const char* ImTextureDataGetFormatName(ImTextureFormat format); - -#ifndef IMGUI_DISABLE_DEBUG_TOOLS -IMGUI_API void ImFontAtlasDebugLogTextureRequests(ImFontAtlas* atlas); -#endif - -IMGUI_API bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]); - -//----------------------------------------------------------------------------- -// [SECTION] Test Engine specific hooks (imgui_test_engine) -//----------------------------------------------------------------------------- - -#ifdef IMGUI_ENABLE_TEST_ENGINE -extern void ImGuiTestEngineHook_ItemAdd(ImGuiContext* ctx, ImGuiID id, const ImRect& bb, const ImGuiLastItemData* item_data); // item_data may be NULL -extern void ImGuiTestEngineHook_ItemInfo(ImGuiContext* ctx, ImGuiID id, const char* label, ImGuiItemStatusFlags flags); -extern void ImGuiTestEngineHook_Log(ImGuiContext* ctx, const char* fmt, ...); -extern const char* ImGuiTestEngine_FindItemDebugLabel(ImGuiContext* ctx, ImGuiID id); - -// In IMGUI_VERSION_NUM >= 18934: changed IMGUI_TEST_ENGINE_ITEM_ADD(bb,id) to IMGUI_TEST_ENGINE_ITEM_ADD(id,bb,item_data); -#define IMGUI_TEST_ENGINE_ITEM_ADD(_ID,_BB,_ITEM_DATA) if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemAdd(&g, _ID, _BB, _ITEM_DATA) // Register item bounding box -#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS) if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS) // Register item label and status flags (optional) -#define IMGUI_TEST_ENGINE_LOG(_FMT,...) ImGuiTestEngineHook_Log(&g, _FMT, __VA_ARGS__) // Custom log entry from user land into test log -#else -#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB,_ID) ((void)0) -#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS) ((void)g) -#endif - -//----------------------------------------------------------------------------- - -#if defined(__clang__) -#pragma clang diagnostic pop -#elif defined(__GNUC__) -#pragma GCC diagnostic pop -#endif - -#ifdef _MSC_VER -#pragma warning (pop) -#endif - -#endif // #ifndef IMGUI_DISABLE diff --git a/include/imgui/imgui_stdlib.h b/include/imgui/imgui_stdlib.h deleted file mode 100644 index 697fc34..0000000 --- a/include/imgui/imgui_stdlib.h +++ /dev/null @@ -1,25 +0,0 @@ -// dear imgui: wrappers for C++ standard library (STL) types (std::string, etc.) -// This is also an example of how you may wrap your own similar types. - -// Changelog: -// - v0.10: Initial version. Added InputText() / InputTextMultiline() calls with std::string - -// See more C++ related extension (fmt, RAII, syntaxis sugar) on Wiki: -// https://github.com/ocornut/imgui/wiki/Useful-Extensions#cness - -#pragma once - -#ifndef IMGUI_DISABLE - -#include - -namespace ImGui -{ - // ImGui::InputText() with std::string - // Because text input needs dynamic resizing, we need to setup a callback to grow the capacity - IMGUI_API bool InputText(const char* label, std::string* str, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = nullptr, void* user_data = nullptr); - IMGUI_API bool InputTextMultiline(const char* label, std::string* str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = nullptr, void* user_data = nullptr); - IMGUI_API bool InputTextWithHint(const char* label, const char* hint, std::string* str, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = nullptr, void* user_data = nullptr); -} - -#endif // #ifndef IMGUI_DISABLE diff --git a/include/imgui/imstb_rectpack.h b/include/imgui/imstb_rectpack.h deleted file mode 100644 index f6917e7..0000000 --- a/include/imgui/imstb_rectpack.h +++ /dev/null @@ -1,627 +0,0 @@ -// [DEAR IMGUI] -// This is a slightly modified version of stb_rect_pack.h 1.01. -// Grep for [DEAR IMGUI] to find the changes. -// -// stb_rect_pack.h - v1.01 - public domain - rectangle packing -// Sean Barrett 2014 -// -// Useful for e.g. packing rectangular textures into an atlas. -// Does not do rotation. -// -// Before #including, -// -// #define STB_RECT_PACK_IMPLEMENTATION -// -// in the file that you want to have the implementation. -// -// Not necessarily the awesomest packing method, but better than -// the totally naive one in stb_truetype (which is primarily what -// this is meant to replace). -// -// Has only had a few tests run, may have issues. -// -// More docs to come. -// -// No memory allocations; uses qsort() and assert() from stdlib. -// Can override those by defining STBRP_SORT and STBRP_ASSERT. -// -// This library currently uses the Skyline Bottom-Left algorithm. -// -// Please note: better rectangle packers are welcome! Please -// implement them to the same API, but with a different init -// function. -// -// Credits -// -// Library -// Sean Barrett -// Minor features -// Martins Mozeiko -// github:IntellectualKitty -// -// Bugfixes / warning fixes -// Jeremy Jaussaud -// Fabian Giesen -// -// Version history: -// -// 1.01 (2021-07-11) always use large rect mode, expose STBRP__MAXVAL in public section -// 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles -// 0.99 (2019-02-07) warning fixes -// 0.11 (2017-03-03) return packing success/fail result -// 0.10 (2016-10-25) remove cast-away-const to avoid warnings -// 0.09 (2016-08-27) fix compiler warnings -// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0) -// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0) -// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort -// 0.05: added STBRP_ASSERT to allow replacing assert -// 0.04: fixed minor bug in STBRP_LARGE_RECTS support -// 0.01: initial release -// -// LICENSE -// -// See end of file for license information. - -////////////////////////////////////////////////////////////////////////////// -// -// INCLUDE SECTION -// - -#ifndef STB_INCLUDE_STB_RECT_PACK_H -#define STB_INCLUDE_STB_RECT_PACK_H - -#define STB_RECT_PACK_VERSION 1 - -#ifdef STBRP_STATIC -#define STBRP_DEF static -#else -#define STBRP_DEF extern -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct stbrp_context stbrp_context; -typedef struct stbrp_node stbrp_node; -typedef struct stbrp_rect stbrp_rect; - -typedef int stbrp_coord; - -#define STBRP__MAXVAL 0x7fffffff -// Mostly for internal use, but this is the maximum supported coordinate value. - -STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects); -// Assign packed locations to rectangles. The rectangles are of type -// 'stbrp_rect' defined below, stored in the array 'rects', and there -// are 'num_rects' many of them. -// -// Rectangles which are successfully packed have the 'was_packed' flag -// set to a non-zero value and 'x' and 'y' store the minimum location -// on each axis (i.e. bottom-left in cartesian coordinates, top-left -// if you imagine y increasing downwards). Rectangles which do not fit -// have the 'was_packed' flag set to 0. -// -// You should not try to access the 'rects' array from another thread -// while this function is running, as the function temporarily reorders -// the array while it executes. -// -// To pack into another rectangle, you need to call stbrp_init_target -// again. To continue packing into the same rectangle, you can call -// this function again. Calling this multiple times with multiple rect -// arrays will probably produce worse packing results than calling it -// a single time with the full rectangle array, but the option is -// available. -// -// The function returns 1 if all of the rectangles were successfully -// packed and 0 otherwise. - -struct stbrp_rect -{ - // reserved for your use: - int id; - - // input: - stbrp_coord w, h; - - // output: - stbrp_coord x, y; - int was_packed; // non-zero if valid packing - -}; // 16 bytes, nominally - - -STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes); -// Initialize a rectangle packer to: -// pack a rectangle that is 'width' by 'height' in dimensions -// using temporary storage provided by the array 'nodes', which is 'num_nodes' long -// -// You must call this function every time you start packing into a new target. -// -// There is no "shutdown" function. The 'nodes' memory must stay valid for -// the following stbrp_pack_rects() call (or calls), but can be freed after -// the call (or calls) finish. -// -// Note: to guarantee best results, either: -// 1. make sure 'num_nodes' >= 'width' -// or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1' -// -// If you don't do either of the above things, widths will be quantized to multiples -// of small integers to guarantee the algorithm doesn't run out of temporary storage. -// -// If you do #2, then the non-quantized algorithm will be used, but the algorithm -// may run out of temporary storage and be unable to pack some rectangles. - -STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem); -// Optionally call this function after init but before doing any packing to -// change the handling of the out-of-temp-memory scenario, described above. -// If you call init again, this will be reset to the default (false). - - -STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic); -// Optionally select which packing heuristic the library should use. Different -// heuristics will produce better/worse results for different data sets. -// If you call init again, this will be reset to the default. - -enum -{ - STBRP_HEURISTIC_Skyline_default=0, - STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default, - STBRP_HEURISTIC_Skyline_BF_sortHeight -}; - - -////////////////////////////////////////////////////////////////////////////// -// -// the details of the following structures don't matter to you, but they must -// be visible so you can handle the memory allocations for them - -struct stbrp_node -{ - stbrp_coord x,y; - stbrp_node *next; -}; - -struct stbrp_context -{ - int width; - int height; - int align; - int init_mode; - int heuristic; - int num_nodes; - stbrp_node *active_head; - stbrp_node *free_head; - stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2' -}; - -#ifdef __cplusplus -} -#endif - -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// IMPLEMENTATION SECTION -// - -#ifdef STB_RECT_PACK_IMPLEMENTATION -#ifndef STBRP_SORT -#include -#define STBRP_SORT qsort -#endif - -#ifndef STBRP_ASSERT -#include -#define STBRP_ASSERT assert -#endif - -#ifdef _MSC_VER -#define STBRP__NOTUSED(v) (void)(v) -#define STBRP__CDECL __cdecl -#else -#define STBRP__NOTUSED(v) (void)sizeof(v) -#define STBRP__CDECL -#endif - -enum -{ - STBRP__INIT_skyline = 1 -}; - -STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic) -{ - switch (context->init_mode) { - case STBRP__INIT_skyline: - STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight); - context->heuristic = heuristic; - break; - default: - STBRP_ASSERT(0); - } -} - -STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem) -{ - if (allow_out_of_mem) - // if it's ok to run out of memory, then don't bother aligning them; - // this gives better packing, but may fail due to OOM (even though - // the rectangles easily fit). @TODO a smarter approach would be to only - // quantize once we've hit OOM, then we could get rid of this parameter. - context->align = 1; - else { - // if it's not ok to run out of memory, then quantize the widths - // so that num_nodes is always enough nodes. - // - // I.e. num_nodes * align >= width - // align >= width / num_nodes - // align = ceil(width/num_nodes) - - context->align = (context->width + context->num_nodes-1) / context->num_nodes; - } -} - -STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes) -{ - int i; - - for (i=0; i < num_nodes-1; ++i) - nodes[i].next = &nodes[i+1]; - nodes[i].next = NULL; - context->init_mode = STBRP__INIT_skyline; - context->heuristic = STBRP_HEURISTIC_Skyline_default; - context->free_head = &nodes[0]; - context->active_head = &context->extra[0]; - context->width = width; - context->height = height; - context->num_nodes = num_nodes; - stbrp_setup_allow_out_of_mem(context, 0); - - // node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly) - context->extra[0].x = 0; - context->extra[0].y = 0; - context->extra[0].next = &context->extra[1]; - context->extra[1].x = (stbrp_coord) width; - context->extra[1].y = (1<<30); - context->extra[1].next = NULL; -} - -// find minimum y position if it starts at x1 -static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste) -{ - stbrp_node *node = first; - int x1 = x0 + width; - int min_y, visited_width, waste_area; - - STBRP__NOTUSED(c); - - STBRP_ASSERT(first->x <= x0); - - #if 0 - // skip in case we're past the node - while (node->next->x <= x0) - ++node; - #else - STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency - #endif - - STBRP_ASSERT(node->x <= x0); - - min_y = 0; - waste_area = 0; - visited_width = 0; - while (node->x < x1) { - if (node->y > min_y) { - // raise min_y higher. - // we've accounted for all waste up to min_y, - // but we'll now add more waste for everything we've visted - waste_area += visited_width * (node->y - min_y); - min_y = node->y; - // the first time through, visited_width might be reduced - if (node->x < x0) - visited_width += node->next->x - x0; - else - visited_width += node->next->x - node->x; - } else { - // add waste area - int under_width = node->next->x - node->x; - if (under_width + visited_width > width) - under_width = width - visited_width; - waste_area += under_width * (min_y - node->y); - visited_width += under_width; - } - node = node->next; - } - - *pwaste = waste_area; - return min_y; -} - -typedef struct -{ - int x,y; - stbrp_node **prev_link; -} stbrp__findresult; - -static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height) -{ - int best_waste = (1<<30), best_x, best_y = (1 << 30); - stbrp__findresult fr; - stbrp_node **prev, *node, *tail, **best = NULL; - - // align to multiple of c->align - width = (width + c->align - 1); - width -= width % c->align; - STBRP_ASSERT(width % c->align == 0); - - // if it can't possibly fit, bail immediately - if (width > c->width || height > c->height) { - fr.prev_link = NULL; - fr.x = fr.y = 0; - return fr; - } - - node = c->active_head; - prev = &c->active_head; - while (node->x + width <= c->width) { - int y,waste; - y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste); - if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL - // bottom left - if (y < best_y) { - best_y = y; - best = prev; - } - } else { - // best-fit - if (y + height <= c->height) { - // can only use it if it first vertically - if (y < best_y || (y == best_y && waste < best_waste)) { - best_y = y; - best_waste = waste; - best = prev; - } - } - } - prev = &node->next; - node = node->next; - } - - best_x = (best == NULL) ? 0 : (*best)->x; - - // if doing best-fit (BF), we also have to try aligning right edge to each node position - // - // e.g, if fitting - // - // ____________________ - // |____________________| - // - // into - // - // | | - // | ____________| - // |____________| - // - // then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned - // - // This makes BF take about 2x the time - - if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) { - tail = c->active_head; - node = c->active_head; - prev = &c->active_head; - // find first node that's admissible - while (tail->x < width) - tail = tail->next; - while (tail) { - int xpos = tail->x - width; - int y,waste; - STBRP_ASSERT(xpos >= 0); - // find the left position that matches this - while (node->next->x <= xpos) { - prev = &node->next; - node = node->next; - } - STBRP_ASSERT(node->next->x > xpos && node->x <= xpos); - y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste); - if (y + height <= c->height) { - if (y <= best_y) { - if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) { - best_x = xpos; - //STBRP_ASSERT(y <= best_y); [DEAR IMGUI] - best_y = y; - best_waste = waste; - best = prev; - } - } - } - tail = tail->next; - } - } - - fr.prev_link = best; - fr.x = best_x; - fr.y = best_y; - return fr; -} - -static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height) -{ - // find best position according to heuristic - stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height); - stbrp_node *node, *cur; - - // bail if: - // 1. it failed - // 2. the best node doesn't fit (we don't always check this) - // 3. we're out of memory - if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) { - res.prev_link = NULL; - return res; - } - - // on success, create new node - node = context->free_head; - node->x = (stbrp_coord) res.x; - node->y = (stbrp_coord) (res.y + height); - - context->free_head = node->next; - - // insert the new node into the right starting point, and - // let 'cur' point to the remaining nodes needing to be - // stiched back in - - cur = *res.prev_link; - if (cur->x < res.x) { - // preserve the existing one, so start testing with the next one - stbrp_node *next = cur->next; - cur->next = node; - cur = next; - } else { - *res.prev_link = node; - } - - // from here, traverse cur and free the nodes, until we get to one - // that shouldn't be freed - while (cur->next && cur->next->x <= res.x + width) { - stbrp_node *next = cur->next; - // move the current node to the free list - cur->next = context->free_head; - context->free_head = cur; - cur = next; - } - - // stitch the list back in - node->next = cur; - - if (cur->x < res.x + width) - cur->x = (stbrp_coord) (res.x + width); - -#ifdef _DEBUG - cur = context->active_head; - while (cur->x < context->width) { - STBRP_ASSERT(cur->x < cur->next->x); - cur = cur->next; - } - STBRP_ASSERT(cur->next == NULL); - - { - int count=0; - cur = context->active_head; - while (cur) { - cur = cur->next; - ++count; - } - cur = context->free_head; - while (cur) { - cur = cur->next; - ++count; - } - STBRP_ASSERT(count == context->num_nodes+2); - } -#endif - - return res; -} - -static int STBRP__CDECL rect_height_compare(const void *a, const void *b) -{ - const stbrp_rect *p = (const stbrp_rect *) a; - const stbrp_rect *q = (const stbrp_rect *) b; - if (p->h > q->h) - return -1; - if (p->h < q->h) - return 1; - return (p->w > q->w) ? -1 : (p->w < q->w); -} - -static int STBRP__CDECL rect_original_order(const void *a, const void *b) -{ - const stbrp_rect *p = (const stbrp_rect *) a; - const stbrp_rect *q = (const stbrp_rect *) b; - return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed); -} - -STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects) -{ - int i, all_rects_packed = 1; - - // we use the 'was_packed' field internally to allow sorting/unsorting - for (i=0; i < num_rects; ++i) { - rects[i].was_packed = i; - } - - // sort according to heuristic - STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare); - - for (i=0; i < num_rects; ++i) { - if (rects[i].w == 0 || rects[i].h == 0) { - rects[i].x = rects[i].y = 0; // empty rect needs no space - } else { - stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h); - if (fr.prev_link) { - rects[i].x = (stbrp_coord) fr.x; - rects[i].y = (stbrp_coord) fr.y; - } else { - rects[i].x = rects[i].y = STBRP__MAXVAL; - } - } - } - - // unsort - STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order); - - // set was_packed flags and all_rects_packed status - for (i=0; i < num_rects; ++i) { - rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL); - if (!rects[i].was_packed) - all_rects_packed = 0; - } - - // return the all_rects_packed status - return all_rects_packed; -} -#endif - -/* ------------------------------------------------------------------------------- -This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------- -ALTERNATIVE A - MIT License -Copyright (c) 2017 Sean Barrett -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. ------------------------------------------------------------------------------- -ALTERNATIVE B - Public Domain (www.unlicense.org) -This is free and unencumbered software released into the public domain. -Anyone is free to copy, modify, publish, use, compile, sell, or distribute this -software, either in source code form or as a compiled binary, for any purpose, -commercial or non-commercial, and by any means. -In jurisdictions that recognize copyright laws, the author or authors of this -software dedicate any and all copyright interest in the software to the public -domain. We make this dedication for the benefit of the public at large and to -the detriment of our heirs and successors. We intend this dedication to be an -overt act of relinquishment in perpetuity of all present and future rights to -this software under copyright law. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- -*/ diff --git a/include/imgui/imstb_textedit.h b/include/imgui/imstb_textedit.h deleted file mode 100644 index 33eef70..0000000 --- a/include/imgui/imstb_textedit.h +++ /dev/null @@ -1,1488 +0,0 @@ -// [DEAR IMGUI] -// This is a slightly modified version of stb_textedit.h 1.14. -// Those changes would need to be pushed into nothings/stb: -// - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321) -// - Fix in stb_textedit_find_charpos to handle last line (see https://github.com/ocornut/imgui/issues/6000 + #6783) -// - Added name to struct or it may be forward declared in our code. -// - Added UTF-8 support (see https://github.com/nothings/stb/issues/188 + https://github.com/ocornut/imgui/pull/7925) -// Grep for [DEAR IMGUI] to find the changes. -// - Also renamed macros used or defined outside of IMSTB_TEXTEDIT_IMPLEMENTATION block from STB_TEXTEDIT_* to IMSTB_TEXTEDIT_* - -// stb_textedit.h - v1.14 - public domain - Sean Barrett -// Development of this library was sponsored by RAD Game Tools -// -// This C header file implements the guts of a multi-line text-editing -// widget; you implement display, word-wrapping, and low-level string -// insertion/deletion, and stb_textedit will map user inputs into -// insertions & deletions, plus updates to the cursor position, -// selection state, and undo state. -// -// It is intended for use in games and other systems that need to build -// their own custom widgets and which do not have heavy text-editing -// requirements (this library is not recommended for use for editing large -// texts, as its performance does not scale and it has limited undo). -// -// Non-trivial behaviors are modelled after Windows text controls. -// -// -// LICENSE -// -// See end of file for license information. -// -// -// DEPENDENCIES -// -// Uses the C runtime function 'memmove', which you can override -// by defining IMSTB_TEXTEDIT_memmove before the implementation. -// Uses no other functions. Performs no runtime allocations. -// -// -// VERSION HISTORY -// -// 1.14 (2021-07-11) page up/down, various fixes -// 1.13 (2019-02-07) fix bug in undo size management -// 1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash -// 1.11 (2017-03-03) fix HOME on last line, dragging off single-line textfield -// 1.10 (2016-10-25) suppress warnings about casting away const with -Wcast-qual -// 1.9 (2016-08-27) customizable move-by-word -// 1.8 (2016-04-02) better keyboard handling when mouse button is down -// 1.7 (2015-09-13) change y range handling in case baseline is non-0 -// 1.6 (2015-04-15) allow STB_TEXTEDIT_memmove -// 1.5 (2014-09-10) add support for secondary keys for OS X -// 1.4 (2014-08-17) fix signed/unsigned warnings -// 1.3 (2014-06-19) fix mouse clicking to round to nearest char boundary -// 1.2 (2014-05-27) fix some RAD types that had crept into the new code -// 1.1 (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE ) -// 1.0 (2012-07-26) improve documentation, initial public release -// 0.3 (2012-02-24) bugfixes, single-line mode; insert mode -// 0.2 (2011-11-28) fixes to undo/redo -// 0.1 (2010-07-08) initial version -// -// ADDITIONAL CONTRIBUTORS -// -// Ulf Winklemann: move-by-word in 1.1 -// Fabian Giesen: secondary key inputs in 1.5 -// Martins Mozeiko: STB_TEXTEDIT_memmove in 1.6 -// Louis Schnellbach: page up/down in 1.14 -// -// Bugfixes: -// Scott Graham -// Daniel Keller -// Omar Cornut -// Dan Thompson -// -// USAGE -// -// This file behaves differently depending on what symbols you define -// before including it. -// -// -// Header-file mode: -// -// If you do not define STB_TEXTEDIT_IMPLEMENTATION before including this, -// it will operate in "header file" mode. In this mode, it declares a -// single public symbol, STB_TexteditState, which encapsulates the current -// state of a text widget (except for the string, which you will store -// separately). -// -// To compile in this mode, you must define STB_TEXTEDIT_CHARTYPE to a -// primitive type that defines a single character (e.g. char, wchar_t, etc). -// -// To save space or increase undo-ability, you can optionally define the -// following things that are used by the undo system: -// -// STB_TEXTEDIT_POSITIONTYPE small int type encoding a valid cursor position -// STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow -// STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer -// -// If you don't define these, they are set to permissive types and -// moderate sizes. The undo system does no memory allocations, so -// it grows STB_TexteditState by the worst-case storage which is (in bytes): -// -// [4 + 3 * sizeof(STB_TEXTEDIT_POSITIONTYPE)] * STB_TEXTEDIT_UNDOSTATECOUNT -// + sizeof(STB_TEXTEDIT_CHARTYPE) * STB_TEXTEDIT_UNDOCHARCOUNT -// -// -// Implementation mode: -// -// If you define STB_TEXTEDIT_IMPLEMENTATION before including this, it -// will compile the implementation of the text edit widget, depending -// on a large number of symbols which must be defined before the include. -// -// The implementation is defined only as static functions. You will then -// need to provide your own APIs in the same file which will access the -// static functions. -// -// The basic concept is that you provide a "string" object which -// behaves like an array of characters. stb_textedit uses indices to -// refer to positions in the string, implicitly representing positions -// in the displayed textedit. This is true for both plain text and -// rich text; even with rich text stb_truetype interacts with your -// code as if there was an array of all the displayed characters. -// -// Symbols that must be the same in header-file and implementation mode: -// -// STB_TEXTEDIT_CHARTYPE the character type -// STB_TEXTEDIT_POSITIONTYPE small type that is a valid cursor position -// STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow -// STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer -// -// Symbols you must define for implementation mode: -// -// STB_TEXTEDIT_STRING the type of object representing a string being edited, -// typically this is a wrapper object with other data you need -// -// STB_TEXTEDIT_STRINGLEN(obj) the length of the string (ideally O(1)) -// STB_TEXTEDIT_LAYOUTROW(&r,obj,n) returns the results of laying out a line of characters -// starting from character #n (see discussion below) -// STB_TEXTEDIT_GETWIDTH(obj,n,i) returns the pixel delta from the xpos of the i'th character -// to the xpos of the i+1'th char for a line of characters -// starting at character #n (i.e. accounts for kerning -// with previous char) -// STB_TEXTEDIT_KEYTOTEXT(k) maps a keyboard input to an insertable character -// (return type is int, -1 means not valid to insert) -// (not supported if you want to use UTF-8, see below) -// STB_TEXTEDIT_GETCHAR(obj,i) returns the i'th character of obj, 0-based -// STB_TEXTEDIT_NEWLINE the character returned by _GETCHAR() we recognize -// as manually wordwrapping for end-of-line positioning -// -// STB_TEXTEDIT_DELETECHARS(obj,i,n) delete n characters starting at i -// STB_TEXTEDIT_INSERTCHARS(obj,i,c*,n) insert n characters at i (pointed to by STB_TEXTEDIT_CHARTYPE*) -// -// STB_TEXTEDIT_K_SHIFT a power of two that is or'd in to a keyboard input to represent the shift key -// -// STB_TEXTEDIT_K_LEFT keyboard input to move cursor left -// STB_TEXTEDIT_K_RIGHT keyboard input to move cursor right -// STB_TEXTEDIT_K_UP keyboard input to move cursor up -// STB_TEXTEDIT_K_DOWN keyboard input to move cursor down -// STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page -// STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page -// STB_TEXTEDIT_K_LINESTART keyboard input to move cursor to start of line // e.g. HOME -// STB_TEXTEDIT_K_LINEEND keyboard input to move cursor to end of line // e.g. END -// STB_TEXTEDIT_K_TEXTSTART keyboard input to move cursor to start of text // e.g. ctrl-HOME -// STB_TEXTEDIT_K_TEXTEND keyboard input to move cursor to end of text // e.g. ctrl-END -// STB_TEXTEDIT_K_DELETE keyboard input to delete selection or character under cursor -// STB_TEXTEDIT_K_BACKSPACE keyboard input to delete selection or character left of cursor -// STB_TEXTEDIT_K_UNDO keyboard input to perform undo -// STB_TEXTEDIT_K_REDO keyboard input to perform redo -// -// Optional: -// STB_TEXTEDIT_K_INSERT keyboard input to toggle insert mode -// STB_TEXTEDIT_IS_SPACE(ch) true if character is whitespace (e.g. 'isspace'), -// required for default WORDLEFT/WORDRIGHT handlers -// STB_TEXTEDIT_MOVEWORDLEFT(obj,i) custom handler for WORDLEFT, returns index to move cursor to -// STB_TEXTEDIT_MOVEWORDRIGHT(obj,i) custom handler for WORDRIGHT, returns index to move cursor to -// STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word // e.g. ctrl-LEFT -// STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word // e.g. ctrl-RIGHT -// STB_TEXTEDIT_K_LINESTART2 secondary keyboard input to move cursor to start of line -// STB_TEXTEDIT_K_LINEEND2 secondary keyboard input to move cursor to end of line -// STB_TEXTEDIT_K_TEXTSTART2 secondary keyboard input to move cursor to start of text -// STB_TEXTEDIT_K_TEXTEND2 secondary keyboard input to move cursor to end of text -// -// To support UTF-8: -// -// STB_TEXTEDIT_GETPREVCHARINDEX returns index of previous character -// STB_TEXTEDIT_GETNEXTCHARINDEX returns index of next character -// Do NOT define STB_TEXTEDIT_KEYTOTEXT. -// Instead, call stb_textedit_text() directly for text contents. -// -// Keyboard input must be encoded as a single integer value; e.g. a character code -// and some bitflags that represent shift states. to simplify the interface, SHIFT must -// be a bitflag, so we can test the shifted state of cursor movements to allow selection, -// i.e. (STB_TEXTEDIT_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow. -// -// You can encode other things, such as CONTROL or ALT, in additional bits, and -// then test for their presence in e.g. STB_TEXTEDIT_K_WORDLEFT. For example, -// my Windows implementations add an additional CONTROL bit, and an additional KEYDOWN -// bit. Then all of the STB_TEXTEDIT_K_ values bitwise-or in the KEYDOWN bit, -// and I pass both WM_KEYDOWN and WM_CHAR events to the "key" function in the -// API below. The control keys will only match WM_KEYDOWN events because of the -// keydown bit I add, and STB_TEXTEDIT_KEYTOTEXT only tests for the KEYDOWN -// bit so it only decodes WM_CHAR events. -// -// STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed -// row of characters assuming they start on the i'th character--the width and -// the height and the number of characters consumed. This allows this library -// to traverse the entire layout incrementally. You need to compute word-wrapping -// here. -// -// Each textfield keeps its own insert mode state, which is not how normal -// applications work. To keep an app-wide insert mode, update/copy the -// "insert_mode" field of STB_TexteditState before/after calling API functions. -// -// API -// -// void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line) -// -// void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) -// void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) -// int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) -// int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len) -// void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXEDIT_KEYTYPE key) -// void stb_textedit_text(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int text_len) -// -// Each of these functions potentially updates the string and updates the -// state. -// -// initialize_state: -// set the textedit state to a known good default state when initially -// constructing the textedit. -// -// click: -// call this with the mouse x,y on a mouse down; it will update the cursor -// and reset the selection start/end to the cursor point. the x,y must -// be relative to the text widget, with (0,0) being the top left. -// -// drag: -// call this with the mouse x,y on a mouse drag/up; it will update the -// cursor and the selection end point -// -// cut: -// call this to delete the current selection; returns true if there was -// one. you should FIRST copy the current selection to the system paste buffer. -// (To copy, just copy the current selection out of the string yourself.) -// -// paste: -// call this to paste text at the current cursor point or over the current -// selection if there is one. -// -// key: -// call this for keyboard inputs sent to the textfield. you can use it -// for "key down" events or for "translated" key events. if you need to -// do both (as in Win32), or distinguish Unicode characters from control -// inputs, set a high bit to distinguish the two; then you can define the -// various definitions like STB_TEXTEDIT_K_LEFT have the is-key-event bit -// set, and make STB_TEXTEDIT_KEYTOCHAR check that the is-key-event bit is -// clear. STB_TEXTEDIT_KEYTYPE defaults to int, but you can #define it to -// anything other type you want before including. -// if the STB_TEXTEDIT_KEYTOTEXT function is defined, selected keys are -// transformed into text and stb_textedit_text() is automatically called. -// -// text: (added 2025) -// call this to directly send text input the textfield, which is required -// for UTF-8 support, because stb_textedit_key() + STB_TEXTEDIT_KEYTOTEXT() -// cannot infer text length. -// -// -// When rendering, you can read the cursor position and selection state from -// the STB_TexteditState. -// -// -// Notes: -// -// This is designed to be usable in IMGUI, so it allows for the possibility of -// running in an IMGUI that has NOT cached the multi-line layout. For this -// reason, it provides an interface that is compatible with computing the -// layout incrementally--we try to make sure we make as few passes through -// as possible. (For example, to locate the mouse pointer in the text, we -// could define functions that return the X and Y positions of characters -// and binary search Y and then X, but if we're doing dynamic layout this -// will run the layout algorithm many times, so instead we manually search -// forward in one pass. Similar logic applies to e.g. up-arrow and -// down-arrow movement.) -// -// If it's run in a widget that *has* cached the layout, then this is less -// efficient, but it's not horrible on modern computers. But you wouldn't -// want to edit million-line files with it. - - -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//// -//// Header-file mode -//// -//// - -#ifndef INCLUDE_IMSTB_TEXTEDIT_H -#define INCLUDE_IMSTB_TEXTEDIT_H - -//////////////////////////////////////////////////////////////////////// -// -// STB_TexteditState -// -// Definition of STB_TexteditState which you should store -// per-textfield; it includes cursor position, selection state, -// and undo state. -// - -#ifndef IMSTB_TEXTEDIT_UNDOSTATECOUNT -#define IMSTB_TEXTEDIT_UNDOSTATECOUNT 99 -#endif -#ifndef IMSTB_TEXTEDIT_UNDOCHARCOUNT -#define IMSTB_TEXTEDIT_UNDOCHARCOUNT 999 -#endif -#ifndef IMSTB_TEXTEDIT_CHARTYPE -#define IMSTB_TEXTEDIT_CHARTYPE int -#endif -#ifndef IMSTB_TEXTEDIT_POSITIONTYPE -#define IMSTB_TEXTEDIT_POSITIONTYPE int -#endif - -typedef struct -{ - // private data - IMSTB_TEXTEDIT_POSITIONTYPE where; - IMSTB_TEXTEDIT_POSITIONTYPE insert_length; - IMSTB_TEXTEDIT_POSITIONTYPE delete_length; - int char_storage; -} StbUndoRecord; - -typedef struct -{ - // private data - StbUndoRecord undo_rec [IMSTB_TEXTEDIT_UNDOSTATECOUNT]; - IMSTB_TEXTEDIT_CHARTYPE undo_char[IMSTB_TEXTEDIT_UNDOCHARCOUNT]; - short undo_point, redo_point; - int undo_char_point, redo_char_point; -} StbUndoState; - -typedef struct STB_TexteditState -{ - ///////////////////// - // - // public data - // - - int cursor; - // position of the text cursor within the string - - int select_start; // selection start point - int select_end; - // selection start and end point in characters; if equal, no selection. - // note that start may be less than or greater than end (e.g. when - // dragging the mouse, start is where the initial click was, and you - // can drag in either direction) - - unsigned char insert_mode; - // each textfield keeps its own insert mode state. to keep an app-wide - // insert mode, copy this value in/out of the app state - - int row_count_per_page; - // page size in number of row. - // this value MUST be set to >0 for pageup or pagedown in multilines documents. - - ///////////////////// - // - // private data - // - unsigned char cursor_at_end_of_line; // not implemented yet - unsigned char initialized; - unsigned char has_preferred_x; - unsigned char single_line; - unsigned char padding1, padding2, padding3; - float preferred_x; // this determines where the cursor up/down tries to seek to along x - StbUndoState undostate; -} STB_TexteditState; - - -//////////////////////////////////////////////////////////////////////// -// -// StbTexteditRow -// -// Result of layout query, used by stb_textedit to determine where -// the text in each row is. - -// result of layout query -typedef struct -{ - float x0,x1; // starting x location, end x location (allows for align=right, etc) - float baseline_y_delta; // position of baseline relative to previous row's baseline - float ymin,ymax; // height of row above and below baseline - int num_chars; -} StbTexteditRow; -#endif //INCLUDE_IMSTB_TEXTEDIT_H - - -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//// -//// Implementation mode -//// -//// - - -// implementation isn't include-guarded, since it might have indirectly -// included just the "header" portion -#ifdef IMSTB_TEXTEDIT_IMPLEMENTATION - -#ifndef IMSTB_TEXTEDIT_memmove -#include -#define IMSTB_TEXTEDIT_memmove memmove -#endif - -// [DEAR IMGUI] -// Functions must be implemented for UTF8 support -// Code in this file that uses those functions is modified for [DEAR IMGUI] and deviates from the original stb_textedit. -// There is not necessarily a '[DEAR IMGUI]' at the usage sites. -#ifndef IMSTB_TEXTEDIT_GETPREVCHARINDEX -#define IMSTB_TEXTEDIT_GETPREVCHARINDEX(OBJ, IDX) ((IDX) - 1) -#endif -#ifndef IMSTB_TEXTEDIT_GETNEXTCHARINDEX -#define IMSTB_TEXTEDIT_GETNEXTCHARINDEX(OBJ, IDX) ((IDX) + 1) -#endif - -///////////////////////////////////////////////////////////////////////////// -// -// Mouse input handling -// - -// traverse the layout to locate the nearest character to a display position -static int stb_text_locate_coord(IMSTB_TEXTEDIT_STRING *str, float x, float y) -{ - StbTexteditRow r; - int n = STB_TEXTEDIT_STRINGLEN(str); - float base_y = 0, prev_x; - int i=0, k; - - r.x0 = r.x1 = 0; - r.ymin = r.ymax = 0; - r.num_chars = 0; - - // search rows to find one that straddles 'y' - while (i < n) { - STB_TEXTEDIT_LAYOUTROW(&r, str, i); - if (r.num_chars <= 0) - return n; - - if (i==0 && y < base_y + r.ymin) - return 0; - - if (y < base_y + r.ymax) - break; - - i += r.num_chars; - base_y += r.baseline_y_delta; - } - - // below all text, return 'after' last character - if (i >= n) - return n; - - // check if it's before the beginning of the line - if (x < r.x0) - return i; - - // check if it's before the end of the line - if (x < r.x1) { - // search characters in row for one that straddles 'x' - prev_x = r.x0; - for (k=0; k < r.num_chars; k = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, i + k) - i) { - float w = STB_TEXTEDIT_GETWIDTH(str, i, k); - if (x < prev_x+w) { - if (x < prev_x+w/2) - return k+i; - else - return IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, i + k); - } - prev_x += w; - } - // shouldn't happen, but if it does, fall through to end-of-line case - } - - // if the last character is a newline, return that. otherwise return 'after' the last character - if (STB_TEXTEDIT_GETCHAR(str, i+r.num_chars-1) == STB_TEXTEDIT_NEWLINE) - return i+r.num_chars-1; - else - return i+r.num_chars; -} - -// API click: on mouse down, move the cursor to the clicked location, and reset the selection -static void stb_textedit_click(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) -{ - // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse - // goes off the top or bottom of the text - if( state->single_line ) - { - StbTexteditRow r; - STB_TEXTEDIT_LAYOUTROW(&r, str, 0); - y = r.ymin; - } - - state->cursor = stb_text_locate_coord(str, x, y); - state->select_start = state->cursor; - state->select_end = state->cursor; - state->has_preferred_x = 0; -} - -// API drag: on mouse drag, move the cursor and selection endpoint to the clicked location -static void stb_textedit_drag(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) -{ - int p = 0; - - // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse - // goes off the top or bottom of the text - if( state->single_line ) - { - StbTexteditRow r; - STB_TEXTEDIT_LAYOUTROW(&r, str, 0); - y = r.ymin; - } - - if (state->select_start == state->select_end) - state->select_start = state->cursor; - - p = stb_text_locate_coord(str, x, y); - state->cursor = state->select_end = p; -} - -///////////////////////////////////////////////////////////////////////////// -// -// Keyboard input handling -// - -// forward declarations -static void stb_text_undo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state); -static void stb_text_redo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state); -static void stb_text_makeundo_delete(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length); -static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length); -static void stb_text_makeundo_replace(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length); - -typedef struct -{ - float x,y; // position of n'th character - float height; // height of line - int first_char, length; // first char of row, and length - int prev_first; // first char of previous row -} StbFindState; - -// find the x/y location of a character, and remember info about the previous row in -// case we get a move-up event (for page up, we'll have to rescan) -static void stb_textedit_find_charpos(StbFindState *find, IMSTB_TEXTEDIT_STRING *str, int n, int single_line) -{ - StbTexteditRow r; - int prev_start = 0; - int z = STB_TEXTEDIT_STRINGLEN(str); - int i=0, first; - - if (n == z && single_line) { - // special case if it's at the end (may not be needed?) - STB_TEXTEDIT_LAYOUTROW(&r, str, 0); - find->y = 0; - find->first_char = 0; - find->length = z; - find->height = r.ymax - r.ymin; - find->x = r.x1; - return; - } - - // search rows to find the one that straddles character n - find->y = 0; - - for(;;) { - STB_TEXTEDIT_LAYOUTROW(&r, str, i); - if (n < i + r.num_chars) - break; - if (i + r.num_chars == z && z > 0 && STB_TEXTEDIT_GETCHAR(str, z - 1) != STB_TEXTEDIT_NEWLINE) // [DEAR IMGUI] special handling for last line - break; // [DEAR IMGUI] - prev_start = i; - i += r.num_chars; - find->y += r.baseline_y_delta; - if (i == z) // [DEAR IMGUI] - { - r.num_chars = 0; // [DEAR IMGUI] - break; // [DEAR IMGUI] - } - } - - find->first_char = first = i; - find->length = r.num_chars; - find->height = r.ymax - r.ymin; - find->prev_first = prev_start; - - // now scan to find xpos - find->x = r.x0; - for (i=0; first+i < n; i = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, first + i) - first) - find->x += STB_TEXTEDIT_GETWIDTH(str, first, i); -} - -#define STB_TEXT_HAS_SELECTION(s) ((s)->select_start != (s)->select_end) - -// make the selection/cursor state valid if client altered the string -static void stb_textedit_clamp(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) -{ - int n = STB_TEXTEDIT_STRINGLEN(str); - if (STB_TEXT_HAS_SELECTION(state)) { - if (state->select_start > n) state->select_start = n; - if (state->select_end > n) state->select_end = n; - // if clamping forced them to be equal, move the cursor to match - if (state->select_start == state->select_end) - state->cursor = state->select_start; - } - if (state->cursor > n) state->cursor = n; -} - -// delete characters while updating undo -static void stb_textedit_delete(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int len) -{ - stb_text_makeundo_delete(str, state, where, len); - STB_TEXTEDIT_DELETECHARS(str, where, len); - state->has_preferred_x = 0; -} - -// delete the section -static void stb_textedit_delete_selection(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) -{ - stb_textedit_clamp(str, state); - if (STB_TEXT_HAS_SELECTION(state)) { - if (state->select_start < state->select_end) { - stb_textedit_delete(str, state, state->select_start, state->select_end - state->select_start); - state->select_end = state->cursor = state->select_start; - } else { - stb_textedit_delete(str, state, state->select_end, state->select_start - state->select_end); - state->select_start = state->cursor = state->select_end; - } - state->has_preferred_x = 0; - } -} - -// canoncialize the selection so start <= end -static void stb_textedit_sortselection(STB_TexteditState *state) -{ - if (state->select_end < state->select_start) { - int temp = state->select_end; - state->select_end = state->select_start; - state->select_start = temp; - } -} - -// move cursor to first character of selection -static void stb_textedit_move_to_first(STB_TexteditState *state) -{ - if (STB_TEXT_HAS_SELECTION(state)) { - stb_textedit_sortselection(state); - state->cursor = state->select_start; - state->select_end = state->select_start; - state->has_preferred_x = 0; - } -} - -// move cursor to last character of selection -static void stb_textedit_move_to_last(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) -{ - if (STB_TEXT_HAS_SELECTION(state)) { - stb_textedit_sortselection(state); - stb_textedit_clamp(str, state); - state->cursor = state->select_end; - state->select_start = state->select_end; - state->has_preferred_x = 0; - } -} - -#ifdef STB_TEXTEDIT_IS_SPACE -static int is_word_boundary( IMSTB_TEXTEDIT_STRING *str, int idx ) -{ - return idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str,idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str, idx) ) ) : 1; -} - -#ifndef STB_TEXTEDIT_MOVEWORDLEFT -static int stb_textedit_move_to_word_previous( IMSTB_TEXTEDIT_STRING *str, int c ) -{ - c = IMSTB_TEXTEDIT_GETPREVCHARINDEX( str, c ); // always move at least one character - while (c >= 0 && !is_word_boundary(str, c)) - c = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, c); - - if( c < 0 ) - c = 0; - - return c; -} -#define STB_TEXTEDIT_MOVEWORDLEFT stb_textedit_move_to_word_previous -#endif - -#ifndef STB_TEXTEDIT_MOVEWORDRIGHT -static int stb_textedit_move_to_word_next( IMSTB_TEXTEDIT_STRING *str, int c ) -{ - const int len = STB_TEXTEDIT_STRINGLEN(str); - c = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, c); // always move at least one character - while( c < len && !is_word_boundary( str, c ) ) - c = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, c); - - if( c > len ) - c = len; - - return c; -} -#define STB_TEXTEDIT_MOVEWORDRIGHT stb_textedit_move_to_word_next -#endif - -#endif - -// update selection and cursor to match each other -static void stb_textedit_prep_selection_at_cursor(STB_TexteditState *state) -{ - if (!STB_TEXT_HAS_SELECTION(state)) - state->select_start = state->select_end = state->cursor; - else - state->cursor = state->select_end; -} - -// API cut: delete selection -static int stb_textedit_cut(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) -{ - if (STB_TEXT_HAS_SELECTION(state)) { - stb_textedit_delete_selection(str,state); // implicitly clamps - state->has_preferred_x = 0; - return 1; - } - return 0; -} - -// API paste: replace existing selection with passed-in text -static int stb_textedit_paste_internal(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, IMSTB_TEXTEDIT_CHARTYPE *text, int len) -{ - // if there's a selection, the paste should delete it - stb_textedit_clamp(str, state); - stb_textedit_delete_selection(str,state); - // try to insert the characters - if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, len)) { - stb_text_makeundo_insert(state, state->cursor, len); - state->cursor += len; - state->has_preferred_x = 0; - return 1; - } - // note: paste failure will leave deleted selection, may be restored with an undo (see https://github.com/nothings/stb/issues/734 for details) - return 0; -} - -#ifndef STB_TEXTEDIT_KEYTYPE -#define STB_TEXTEDIT_KEYTYPE int -#endif - -// API key: process text input -// [DEAR IMGUI] Added stb_textedit_text(), extracted out and called by stb_textedit_key() for backward compatibility. -static void stb_textedit_text(IMSTB_TEXTEDIT_STRING* str, STB_TexteditState* state, const IMSTB_TEXTEDIT_CHARTYPE* text, int text_len) -{ - // can't add newline in single-line mode - if (text[0] == '\n' && state->single_line) - return; - - if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) { - stb_text_makeundo_replace(str, state, state->cursor, 1, 1); - STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1); - if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, text_len)) { - state->cursor += text_len; - state->has_preferred_x = 0; - } - } else { - stb_textedit_delete_selection(str, state); // implicitly clamps - if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, text_len)) { - stb_text_makeundo_insert(state, state->cursor, text_len); - state->cursor += text_len; - state->has_preferred_x = 0; - } - } -} - -// API key: process a keyboard input -static void stb_textedit_key(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key) -{ -retry: - switch (key) { - default: { -#ifdef STB_TEXTEDIT_KEYTOTEXT - // This is not suitable for UTF-8 support. - int c = STB_TEXTEDIT_KEYTOTEXT(key); - if (c > 0) { - IMSTB_TEXTEDIT_CHARTYPE ch = (IMSTB_TEXTEDIT_CHARTYPE)c; - stb_textedit_text(str, state, &ch, 1); - } -#endif - break; - } - -#ifdef STB_TEXTEDIT_K_INSERT - case STB_TEXTEDIT_K_INSERT: - state->insert_mode = !state->insert_mode; - break; -#endif - - case STB_TEXTEDIT_K_UNDO: - stb_text_undo(str, state); - state->has_preferred_x = 0; - break; - - case STB_TEXTEDIT_K_REDO: - stb_text_redo(str, state); - state->has_preferred_x = 0; - break; - - case STB_TEXTEDIT_K_LEFT: - // if currently there's a selection, move cursor to start of selection - if (STB_TEXT_HAS_SELECTION(state)) - stb_textedit_move_to_first(state); - else - if (state->cursor > 0) - state->cursor = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor); - state->has_preferred_x = 0; - break; - - case STB_TEXTEDIT_K_RIGHT: - // if currently there's a selection, move cursor to end of selection - if (STB_TEXT_HAS_SELECTION(state)) - stb_textedit_move_to_last(str, state); - else - state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); - stb_textedit_clamp(str, state); - state->has_preferred_x = 0; - break; - - case STB_TEXTEDIT_K_LEFT | STB_TEXTEDIT_K_SHIFT: - stb_textedit_clamp(str, state); - stb_textedit_prep_selection_at_cursor(state); - // move selection left - if (state->select_end > 0) - state->select_end = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->select_end); - state->cursor = state->select_end; - state->has_preferred_x = 0; - break; - -#ifdef STB_TEXTEDIT_MOVEWORDLEFT - case STB_TEXTEDIT_K_WORDLEFT: - if (STB_TEXT_HAS_SELECTION(state)) - stb_textedit_move_to_first(state); - else { - state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor); - stb_textedit_clamp( str, state ); - } - break; - - case STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT: - if( !STB_TEXT_HAS_SELECTION( state ) ) - stb_textedit_prep_selection_at_cursor(state); - - state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor); - state->select_end = state->cursor; - - stb_textedit_clamp( str, state ); - break; -#endif - -#ifdef STB_TEXTEDIT_MOVEWORDRIGHT - case STB_TEXTEDIT_K_WORDRIGHT: - if (STB_TEXT_HAS_SELECTION(state)) - stb_textedit_move_to_last(str, state); - else { - state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor); - stb_textedit_clamp( str, state ); - } - break; - - case STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT: - if( !STB_TEXT_HAS_SELECTION( state ) ) - stb_textedit_prep_selection_at_cursor(state); - - state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor); - state->select_end = state->cursor; - - stb_textedit_clamp( str, state ); - break; -#endif - - case STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT: - stb_textedit_prep_selection_at_cursor(state); - // move selection right - state->select_end = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->select_end); - stb_textedit_clamp(str, state); - state->cursor = state->select_end; - state->has_preferred_x = 0; - break; - - case STB_TEXTEDIT_K_DOWN: - case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT: - case STB_TEXTEDIT_K_PGDOWN: - case STB_TEXTEDIT_K_PGDOWN | STB_TEXTEDIT_K_SHIFT: { - StbFindState find; - StbTexteditRow row; - int i, j, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; - int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGDOWN; - int row_count = is_page ? state->row_count_per_page : 1; - - if (!is_page && state->single_line) { - // on windows, up&down in single-line behave like left&right - key = STB_TEXTEDIT_K_RIGHT | (key & STB_TEXTEDIT_K_SHIFT); - goto retry; - } - - if (sel) - stb_textedit_prep_selection_at_cursor(state); - else if (STB_TEXT_HAS_SELECTION(state)) - stb_textedit_move_to_last(str, state); - - // compute current position of cursor point - stb_textedit_clamp(str, state); - stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); - - for (j = 0; j < row_count; ++j) { - float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x; - int start = find.first_char + find.length; - - if (find.length == 0) - break; - - // [DEAR IMGUI] - // going down while being on the last line shouldn't bring us to that line end - if (STB_TEXTEDIT_GETCHAR(str, find.first_char + find.length - 1) != STB_TEXTEDIT_NEWLINE) - break; - - // now find character position down a row - state->cursor = start; - STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); - x = row.x0; - for (i=0; i < row.num_chars; ) { - float dx = STB_TEXTEDIT_GETWIDTH(str, start, i); - int next = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); - #ifdef IMSTB_TEXTEDIT_GETWIDTH_NEWLINE - if (dx == IMSTB_TEXTEDIT_GETWIDTH_NEWLINE) - break; - #endif - x += dx; - if (x > goal_x) - break; - i += next - state->cursor; - state->cursor = next; - } - stb_textedit_clamp(str, state); - - state->has_preferred_x = 1; - state->preferred_x = goal_x; - - if (sel) - state->select_end = state->cursor; - - // go to next line - find.first_char = find.first_char + find.length; - find.length = row.num_chars; - } - break; - } - - case STB_TEXTEDIT_K_UP: - case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT: - case STB_TEXTEDIT_K_PGUP: - case STB_TEXTEDIT_K_PGUP | STB_TEXTEDIT_K_SHIFT: { - StbFindState find; - StbTexteditRow row; - int i, j, prev_scan, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; - int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGUP; - int row_count = is_page ? state->row_count_per_page : 1; - - if (!is_page && state->single_line) { - // on windows, up&down become left&right - key = STB_TEXTEDIT_K_LEFT | (key & STB_TEXTEDIT_K_SHIFT); - goto retry; - } - - if (sel) - stb_textedit_prep_selection_at_cursor(state); - else if (STB_TEXT_HAS_SELECTION(state)) - stb_textedit_move_to_first(state); - - // compute current position of cursor point - stb_textedit_clamp(str, state); - stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); - - for (j = 0; j < row_count; ++j) { - float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x; - - // can only go up if there's a previous row - if (find.prev_first == find.first_char) - break; - - // now find character position up a row - state->cursor = find.prev_first; - STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); - x = row.x0; - for (i=0; i < row.num_chars; ) { - float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i); - int next = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); - #ifdef IMSTB_TEXTEDIT_GETWIDTH_NEWLINE - if (dx == IMSTB_TEXTEDIT_GETWIDTH_NEWLINE) - break; - #endif - x += dx; - if (x > goal_x) - break; - i += next - state->cursor; - state->cursor = next; - } - stb_textedit_clamp(str, state); - - state->has_preferred_x = 1; - state->preferred_x = goal_x; - - if (sel) - state->select_end = state->cursor; - - // go to previous line - // (we need to scan previous line the hard way. maybe we could expose this as a new API function?) - prev_scan = find.prev_first > 0 ? find.prev_first - 1 : 0; - while (prev_scan > 0) - { - int prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, prev_scan); - if (STB_TEXTEDIT_GETCHAR(str, prev) == STB_TEXTEDIT_NEWLINE) - break; - prev_scan = prev; - } - find.first_char = find.prev_first; - find.prev_first = prev_scan; - } - break; - } - - case STB_TEXTEDIT_K_DELETE: - case STB_TEXTEDIT_K_DELETE | STB_TEXTEDIT_K_SHIFT: - if (STB_TEXT_HAS_SELECTION(state)) - stb_textedit_delete_selection(str, state); - else { - int n = STB_TEXTEDIT_STRINGLEN(str); - if (state->cursor < n) - stb_textedit_delete(str, state, state->cursor, IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor) - state->cursor); - } - state->has_preferred_x = 0; - break; - - case STB_TEXTEDIT_K_BACKSPACE: - case STB_TEXTEDIT_K_BACKSPACE | STB_TEXTEDIT_K_SHIFT: - if (STB_TEXT_HAS_SELECTION(state)) - stb_textedit_delete_selection(str, state); - else { - stb_textedit_clamp(str, state); - if (state->cursor > 0) { - int prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor); - stb_textedit_delete(str, state, prev, state->cursor - prev); - state->cursor = prev; - } - } - state->has_preferred_x = 0; - break; - -#ifdef STB_TEXTEDIT_K_TEXTSTART2 - case STB_TEXTEDIT_K_TEXTSTART2: -#endif - case STB_TEXTEDIT_K_TEXTSTART: - state->cursor = state->select_start = state->select_end = 0; - state->has_preferred_x = 0; - break; - -#ifdef STB_TEXTEDIT_K_TEXTEND2 - case STB_TEXTEDIT_K_TEXTEND2: -#endif - case STB_TEXTEDIT_K_TEXTEND: - state->cursor = STB_TEXTEDIT_STRINGLEN(str); - state->select_start = state->select_end = 0; - state->has_preferred_x = 0; - break; - -#ifdef STB_TEXTEDIT_K_TEXTSTART2 - case STB_TEXTEDIT_K_TEXTSTART2 | STB_TEXTEDIT_K_SHIFT: -#endif - case STB_TEXTEDIT_K_TEXTSTART | STB_TEXTEDIT_K_SHIFT: - stb_textedit_prep_selection_at_cursor(state); - state->cursor = state->select_end = 0; - state->has_preferred_x = 0; - break; - -#ifdef STB_TEXTEDIT_K_TEXTEND2 - case STB_TEXTEDIT_K_TEXTEND2 | STB_TEXTEDIT_K_SHIFT: -#endif - case STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT: - stb_textedit_prep_selection_at_cursor(state); - state->cursor = state->select_end = STB_TEXTEDIT_STRINGLEN(str); - state->has_preferred_x = 0; - break; - - -#ifdef STB_TEXTEDIT_K_LINESTART2 - case STB_TEXTEDIT_K_LINESTART2: -#endif - case STB_TEXTEDIT_K_LINESTART: - stb_textedit_clamp(str, state); - stb_textedit_move_to_first(state); - if (state->single_line) - state->cursor = 0; - else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) - state->cursor = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor); - state->has_preferred_x = 0; - break; - -#ifdef STB_TEXTEDIT_K_LINEEND2 - case STB_TEXTEDIT_K_LINEEND2: -#endif - case STB_TEXTEDIT_K_LINEEND: { - int n = STB_TEXTEDIT_STRINGLEN(str); - stb_textedit_clamp(str, state); - stb_textedit_move_to_first(state); - if (state->single_line) - state->cursor = n; - else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) - state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); - state->has_preferred_x = 0; - break; - } - -#ifdef STB_TEXTEDIT_K_LINESTART2 - case STB_TEXTEDIT_K_LINESTART2 | STB_TEXTEDIT_K_SHIFT: -#endif - case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT: - stb_textedit_clamp(str, state); - stb_textedit_prep_selection_at_cursor(state); - if (state->single_line) - state->cursor = 0; - else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) - state->cursor = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor); - state->select_end = state->cursor; - state->has_preferred_x = 0; - break; - -#ifdef STB_TEXTEDIT_K_LINEEND2 - case STB_TEXTEDIT_K_LINEEND2 | STB_TEXTEDIT_K_SHIFT: -#endif - case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: { - int n = STB_TEXTEDIT_STRINGLEN(str); - stb_textedit_clamp(str, state); - stb_textedit_prep_selection_at_cursor(state); - if (state->single_line) - state->cursor = n; - else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) - state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); - state->select_end = state->cursor; - state->has_preferred_x = 0; - break; - } - } -} - -///////////////////////////////////////////////////////////////////////////// -// -// Undo processing -// -// @OPTIMIZE: the undo/redo buffer should be circular - -static void stb_textedit_flush_redo(StbUndoState *state) -{ - state->redo_point = IMSTB_TEXTEDIT_UNDOSTATECOUNT; - state->redo_char_point = IMSTB_TEXTEDIT_UNDOCHARCOUNT; -} - -// discard the oldest entry in the undo list -static void stb_textedit_discard_undo(StbUndoState *state) -{ - if (state->undo_point > 0) { - // if the 0th undo state has characters, clean those up - if (state->undo_rec[0].char_storage >= 0) { - int n = state->undo_rec[0].insert_length, i; - // delete n characters from all other records - state->undo_char_point -= n; - IMSTB_TEXTEDIT_memmove(state->undo_char, state->undo_char + n, (size_t) (state->undo_char_point*sizeof(IMSTB_TEXTEDIT_CHARTYPE))); - for (i=0; i < state->undo_point; ++i) - if (state->undo_rec[i].char_storage >= 0) - state->undo_rec[i].char_storage -= n; // @OPTIMIZE: get rid of char_storage and infer it - } - --state->undo_point; - IMSTB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) (state->undo_point*sizeof(state->undo_rec[0]))); - } -} - -// discard the oldest entry in the redo list--it's bad if this -// ever happens, but because undo & redo have to store the actual -// characters in different cases, the redo character buffer can -// fill up even though the undo buffer didn't -static void stb_textedit_discard_redo(StbUndoState *state) -{ - int k = IMSTB_TEXTEDIT_UNDOSTATECOUNT-1; - - if (state->redo_point <= k) { - // if the k'th undo state has characters, clean those up - if (state->undo_rec[k].char_storage >= 0) { - int n = state->undo_rec[k].insert_length, i; - // move the remaining redo character data to the end of the buffer - state->redo_char_point += n; - IMSTB_TEXTEDIT_memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((IMSTB_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point)*sizeof(IMSTB_TEXTEDIT_CHARTYPE))); - // adjust the position of all the other records to account for above memmove - for (i=state->redo_point; i < k; ++i) - if (state->undo_rec[i].char_storage >= 0) - state->undo_rec[i].char_storage += n; - } - // now move all the redo records towards the end of the buffer; the first one is at 'redo_point' - // [DEAR IMGUI] - size_t move_size = (size_t)((IMSTB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point - 1) * sizeof(state->undo_rec[0])); - const char* buf_begin = (char*)state->undo_rec; (void)buf_begin; - const char* buf_end = (char*)state->undo_rec + sizeof(state->undo_rec); (void)buf_end; - IM_ASSERT(((char*)(state->undo_rec + state->redo_point)) >= buf_begin); - IM_ASSERT(((char*)(state->undo_rec + state->redo_point + 1) + move_size) <= buf_end); - IMSTB_TEXTEDIT_memmove(state->undo_rec + state->redo_point+1, state->undo_rec + state->redo_point, move_size); - - // now move redo_point to point to the new one - ++state->redo_point; - } -} - -static StbUndoRecord *stb_text_create_undo_record(StbUndoState *state, int numchars) -{ - // any time we create a new undo record, we discard redo - stb_textedit_flush_redo(state); - - // if we have no free records, we have to make room, by sliding the - // existing records down - if (state->undo_point == IMSTB_TEXTEDIT_UNDOSTATECOUNT) - stb_textedit_discard_undo(state); - - // if the characters to store won't possibly fit in the buffer, we can't undo - if (numchars > IMSTB_TEXTEDIT_UNDOCHARCOUNT) { - state->undo_point = 0; - state->undo_char_point = 0; - return NULL; - } - - // if we don't have enough free characters in the buffer, we have to make room - while (state->undo_char_point + numchars > IMSTB_TEXTEDIT_UNDOCHARCOUNT) - stb_textedit_discard_undo(state); - - return &state->undo_rec[state->undo_point++]; -} - -static IMSTB_TEXTEDIT_CHARTYPE *stb_text_createundo(StbUndoState *state, int pos, int insert_len, int delete_len) -{ - StbUndoRecord *r = stb_text_create_undo_record(state, insert_len); - if (r == NULL) - return NULL; - - r->where = pos; - r->insert_length = (IMSTB_TEXTEDIT_POSITIONTYPE) insert_len; - r->delete_length = (IMSTB_TEXTEDIT_POSITIONTYPE) delete_len; - - if (insert_len == 0) { - r->char_storage = -1; - return NULL; - } else { - r->char_storage = state->undo_char_point; - state->undo_char_point += insert_len; - return &state->undo_char[r->char_storage]; - } -} - -static void stb_text_undo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) -{ - StbUndoState *s = &state->undostate; - StbUndoRecord u, *r; - if (s->undo_point == 0) - return; - - // we need to do two things: apply the undo record, and create a redo record - u = s->undo_rec[s->undo_point-1]; - r = &s->undo_rec[s->redo_point-1]; - r->char_storage = -1; - - r->insert_length = u.delete_length; - r->delete_length = u.insert_length; - r->where = u.where; - - if (u.delete_length) { - // if the undo record says to delete characters, then the redo record will - // need to re-insert the characters that get deleted, so we need to store - // them. - - // there are three cases: - // there's enough room to store the characters - // characters stored for *redoing* don't leave room for redo - // characters stored for *undoing* don't leave room for redo - // if the last is true, we have to bail - - if (s->undo_char_point + u.delete_length >= IMSTB_TEXTEDIT_UNDOCHARCOUNT) { - // the undo records take up too much character space; there's no space to store the redo characters - r->insert_length = 0; - } else { - int i; - - // there's definitely room to store the characters eventually - while (s->undo_char_point + u.delete_length > s->redo_char_point) { - // should never happen: - if (s->redo_point == IMSTB_TEXTEDIT_UNDOSTATECOUNT) - return; - // there's currently not enough room, so discard a redo record - stb_textedit_discard_redo(s); - } - r = &s->undo_rec[s->redo_point-1]; - - r->char_storage = s->redo_char_point - u.delete_length; - s->redo_char_point = s->redo_char_point - u.delete_length; - - // now save the characters - for (i=0; i < u.delete_length; ++i) - s->undo_char[r->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i); - } - - // now we can carry out the deletion - STB_TEXTEDIT_DELETECHARS(str, u.where, u.delete_length); - } - - // check type of recorded action: - if (u.insert_length) { - // easy case: was a deletion, so we need to insert n characters - STB_TEXTEDIT_INSERTCHARS(str, u.where, &s->undo_char[u.char_storage], u.insert_length); - s->undo_char_point -= u.insert_length; - } - - state->cursor = u.where + u.insert_length; - - s->undo_point--; - s->redo_point--; -} - -static void stb_text_redo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) -{ - StbUndoState *s = &state->undostate; - StbUndoRecord *u, r; - if (s->redo_point == IMSTB_TEXTEDIT_UNDOSTATECOUNT) - return; - - // we need to do two things: apply the redo record, and create an undo record - u = &s->undo_rec[s->undo_point]; - r = s->undo_rec[s->redo_point]; - - // we KNOW there must be room for the undo record, because the redo record - // was derived from an undo record - - u->delete_length = r.insert_length; - u->insert_length = r.delete_length; - u->where = r.where; - u->char_storage = -1; - - if (r.delete_length) { - // the redo record requires us to delete characters, so the undo record - // needs to store the characters - - if (s->undo_char_point + u->insert_length > s->redo_char_point) { - u->insert_length = 0; - u->delete_length = 0; - } else { - int i; - u->char_storage = s->undo_char_point; - s->undo_char_point = s->undo_char_point + u->insert_length; - - // now save the characters - for (i=0; i < u->insert_length; ++i) - s->undo_char[u->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u->where + i); - } - - STB_TEXTEDIT_DELETECHARS(str, r.where, r.delete_length); - } - - if (r.insert_length) { - // easy case: need to insert n characters - STB_TEXTEDIT_INSERTCHARS(str, r.where, &s->undo_char[r.char_storage], r.insert_length); - s->redo_char_point += r.insert_length; - } - - state->cursor = r.where + r.insert_length; - - s->undo_point++; - s->redo_point++; -} - -static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length) -{ - stb_text_createundo(&state->undostate, where, 0, length); -} - -static void stb_text_makeundo_delete(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length) -{ - int i; - IMSTB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, length, 0); - if (p) { - for (i=0; i < length; ++i) - p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); - } -} - -static void stb_text_makeundo_replace(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length) -{ - int i; - IMSTB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, old_length, new_length); - if (p) { - for (i=0; i < old_length; ++i) - p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); - } -} - -// reset the state to default -static void stb_textedit_clear_state(STB_TexteditState *state, int is_single_line) -{ - state->undostate.undo_point = 0; - state->undostate.undo_char_point = 0; - state->undostate.redo_point = IMSTB_TEXTEDIT_UNDOSTATECOUNT; - state->undostate.redo_char_point = IMSTB_TEXTEDIT_UNDOCHARCOUNT; - state->select_end = state->select_start = 0; - state->cursor = 0; - state->has_preferred_x = 0; - state->preferred_x = 0; - state->cursor_at_end_of_line = 0; - state->initialized = 1; - state->single_line = (unsigned char) is_single_line; - state->insert_mode = 0; - state->row_count_per_page = 0; -} - -// API initialize -static void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line) -{ - stb_textedit_clear_state(state, is_single_line); -} - -#if defined(__GNUC__) || defined(__clang__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wcast-qual" -#endif - -static int stb_textedit_paste(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, IMSTB_TEXTEDIT_CHARTYPE const *ctext, int len) -{ - return stb_textedit_paste_internal(str, state, (IMSTB_TEXTEDIT_CHARTYPE *) ctext, len); -} - -#if defined(__GNUC__) || defined(__clang__) -#pragma GCC diagnostic pop -#endif - -#endif//IMSTB_TEXTEDIT_IMPLEMENTATION - -/* ------------------------------------------------------------------------------- -This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------- -ALTERNATIVE A - MIT License -Copyright (c) 2017 Sean Barrett -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. ------------------------------------------------------------------------------- -ALTERNATIVE B - Public Domain (www.unlicense.org) -This is free and unencumbered software released into the public domain. -Anyone is free to copy, modify, publish, use, compile, sell, or distribute this -software, either in source code form or as a compiled binary, for any purpose, -commercial or non-commercial, and by any means. -In jurisdictions that recognize copyright laws, the author or authors of this -software dedicate any and all copyright interest in the software to the public -domain. We make this dedication for the benefit of the public at large and to -the detriment of our heirs and successors. We intend this dedication to be an -overt act of relinquishment in perpetuity of all present and future rights to -this software under copyright law. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- -*/ diff --git a/include/imgui/imstb_truetype.h b/include/imgui/imstb_truetype.h deleted file mode 100644 index cf33289..0000000 --- a/include/imgui/imstb_truetype.h +++ /dev/null @@ -1,5085 +0,0 @@ -// [DEAR IMGUI] -// This is a slightly modified version of stb_truetype.h 1.26. -// Mostly fixing for compiler and static analyzer warnings. -// Grep for [DEAR IMGUI] to find the changes. - -// stb_truetype.h - v1.26 - public domain -// authored from 2009-2021 by Sean Barrett / RAD Game Tools -// -// ======================================================================= -// -// NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES -// -// This library does no range checking of the offsets found in the file, -// meaning an attacker can use it to read arbitrary memory. -// -// ======================================================================= -// -// This library processes TrueType files: -// parse files -// extract glyph metrics -// extract glyph shapes -// render glyphs to one-channel bitmaps with antialiasing (box filter) -// render glyphs to one-channel SDF bitmaps (signed-distance field/function) -// -// Todo: -// non-MS cmaps -// crashproof on bad data -// hinting? (no longer patented) -// cleartype-style AA? -// optimize: use simple memory allocator for intermediates -// optimize: build edge-list directly from curves -// optimize: rasterize directly from curves? -// -// ADDITIONAL CONTRIBUTORS -// -// Mikko Mononen: compound shape support, more cmap formats -// Tor Andersson: kerning, subpixel rendering -// Dougall Johnson: OpenType / Type 2 font handling -// Daniel Ribeiro Maciel: basic GPOS-based kerning -// -// Misc other: -// Ryan Gordon -// Simon Glass -// github:IntellectualKitty -// Imanol Celaya -// Daniel Ribeiro Maciel -// -// Bug/warning reports/fixes: -// "Zer" on mollyrocket Fabian "ryg" Giesen github:NiLuJe -// Cass Everitt Martins Mozeiko github:aloucks -// stoiko (Haemimont Games) Cap Petschulat github:oyvindjam -// Brian Hook Omar Cornut github:vassvik -// Walter van Niftrik Ryan Griege -// David Gow Peter LaValle -// David Given Sergey Popov -// Ivan-Assen Ivanov Giumo X. Clanjor -// Anthony Pesch Higor Euripedes -// Johan Duparc Thomas Fields -// Hou Qiming Derek Vinyard -// Rob Loach Cort Stratton -// Kenney Phillis Jr. Brian Costabile -// Ken Voskuil (kaesve) -// -// VERSION HISTORY -// -// 1.26 (2021-08-28) fix broken rasterizer -// 1.25 (2021-07-11) many fixes -// 1.24 (2020-02-05) fix warning -// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) -// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined -// 1.21 (2019-02-25) fix warning -// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() -// 1.19 (2018-02-11) GPOS kerning, STBTT_fmod -// 1.18 (2018-01-29) add missing function -// 1.17 (2017-07-23) make more arguments const; doc fix -// 1.16 (2017-07-12) SDF support -// 1.15 (2017-03-03) make more arguments const -// 1.14 (2017-01-16) num-fonts-in-TTC function -// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts -// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual -// 1.11 (2016-04-02) fix unused-variable warning -// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef -// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly -// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges -// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; -// variant PackFontRanges to pack and render in separate phases; -// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); -// fixed an assert() bug in the new rasterizer -// replace assert() with STBTT_assert() in new rasterizer -// -// Full history can be found at the end of this file. -// -// LICENSE -// -// See end of file for license information. -// -// USAGE -// -// Include this file in whatever places need to refer to it. In ONE C/C++ -// file, write: -// #define STB_TRUETYPE_IMPLEMENTATION -// before the #include of this file. This expands out the actual -// implementation into that C/C++ file. -// -// To make the implementation private to the file that generates the implementation, -// #define STBTT_STATIC -// -// Simple 3D API (don't ship this, but it's fine for tools and quick start) -// stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture -// stbtt_GetBakedQuad() -- compute quad to draw for a given char -// -// Improved 3D API (more shippable): -// #include "stb_rect_pack.h" -- optional, but you really want it -// stbtt_PackBegin() -// stbtt_PackSetOversampling() -- for improved quality on small fonts -// stbtt_PackFontRanges() -- pack and renders -// stbtt_PackEnd() -// stbtt_GetPackedQuad() -// -// "Load" a font file from a memory buffer (you have to keep the buffer loaded) -// stbtt_InitFont() -// stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections -// stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections -// -// Render a unicode codepoint to a bitmap -// stbtt_GetCodepointBitmap() -- allocates and returns a bitmap -// stbtt_MakeCodepointBitmap() -- renders into bitmap you provide -// stbtt_GetCodepointBitmapBox() -- how big the bitmap must be -// -// Character advance/positioning -// stbtt_GetCodepointHMetrics() -// stbtt_GetFontVMetrics() -// stbtt_GetFontVMetricsOS2() -// stbtt_GetCodepointKernAdvance() -// -// Starting with version 1.06, the rasterizer was replaced with a new, -// faster and generally-more-precise rasterizer. The new rasterizer more -// accurately measures pixel coverage for anti-aliasing, except in the case -// where multiple shapes overlap, in which case it overestimates the AA pixel -// coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If -// this turns out to be a problem, you can re-enable the old rasterizer with -// #define STBTT_RASTERIZER_VERSION 1 -// which will incur about a 15% speed hit. -// -// ADDITIONAL DOCUMENTATION -// -// Immediately after this block comment are a series of sample programs. -// -// After the sample programs is the "header file" section. This section -// includes documentation for each API function. -// -// Some important concepts to understand to use this library: -// -// Codepoint -// Characters are defined by unicode codepoints, e.g. 65 is -// uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is -// the hiragana for "ma". -// -// Glyph -// A visual character shape (every codepoint is rendered as -// some glyph) -// -// Glyph index -// A font-specific integer ID representing a glyph -// -// Baseline -// Glyph shapes are defined relative to a baseline, which is the -// bottom of uppercase characters. Characters extend both above -// and below the baseline. -// -// Current Point -// As you draw text to the screen, you keep track of a "current point" -// which is the origin of each character. The current point's vertical -// position is the baseline. Even "baked fonts" use this model. -// -// Vertical Font Metrics -// The vertical qualities of the font, used to vertically position -// and space the characters. See docs for stbtt_GetFontVMetrics. -// -// Font Size in Pixels or Points -// The preferred interface for specifying font sizes in stb_truetype -// is to specify how tall the font's vertical extent should be in pixels. -// If that sounds good enough, skip the next paragraph. -// -// Most font APIs instead use "points", which are a common typographic -// measurement for describing font size, defined as 72 points per inch. -// stb_truetype provides a point API for compatibility. However, true -// "per inch" conventions don't make much sense on computer displays -// since different monitors have different number of pixels per -// inch. For example, Windows traditionally uses a convention that -// there are 96 pixels per inch, thus making 'inch' measurements have -// nothing to do with inches, and thus effectively defining a point to -// be 1.333 pixels. Additionally, the TrueType font data provides -// an explicit scale factor to scale a given font's glyphs to points, -// but the author has observed that this scale factor is often wrong -// for non-commercial fonts, thus making fonts scaled in points -// according to the TrueType spec incoherently sized in practice. -// -// DETAILED USAGE: -// -// Scale: -// Select how high you want the font to be, in points or pixels. -// Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute -// a scale factor SF that will be used by all other functions. -// -// Baseline: -// You need to select a y-coordinate that is the baseline of where -// your text will appear. Call GetFontBoundingBox to get the baseline-relative -// bounding box for all characters. SF*-y0 will be the distance in pixels -// that the worst-case character could extend above the baseline, so if -// you want the top edge of characters to appear at the top of the -// screen where y=0, then you would set the baseline to SF*-y0. -// -// Current point: -// Set the current point where the first character will appear. The -// first character could extend left of the current point; this is font -// dependent. You can either choose a current point that is the leftmost -// point and hope, or add some padding, or check the bounding box or -// left-side-bearing of the first character to be displayed and set -// the current point based on that. -// -// Displaying a character: -// Compute the bounding box of the character. It will contain signed values -// relative to . I.e. if it returns x0,y0,x1,y1, -// then the character should be displayed in the rectangle from -// to = 32 && *text < 128) { - stbtt_aligned_quad q; - stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9 - glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y0); - glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y0); - glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y1); - glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y1); - } - ++text; - } - glEnd(); -} -#endif -// -// -////////////////////////////////////////////////////////////////////////////// -// -// Complete program (this compiles): get a single bitmap, print as ASCII art -// -#if 0 -#include -#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation -#include "stb_truetype.h" - -char ttf_buffer[1<<25]; - -int main(int argc, char **argv) -{ - stbtt_fontinfo font; - unsigned char *bitmap; - int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20); - - fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); - - stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); - bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); - - for (j=0; j < h; ++j) { - for (i=0; i < w; ++i) - putchar(" .:ioVM@"[bitmap[j*w+i]>>5]); - putchar('\n'); - } - return 0; -} -#endif -// -// Output: -// -// .ii. -// @@@@@@. -// V@Mio@@o -// :i. V@V -// :oM@@M -// :@@@MM@M -// @@o o@M -// :@@. M@M -// @@@o@@@@ -// :M@@V:@@. -// -////////////////////////////////////////////////////////////////////////////// -// -// Complete program: print "Hello World!" banner, with bugs -// -#if 0 -char buffer[24<<20]; -unsigned char screen[20][79]; - -int main(int arg, char **argv) -{ - stbtt_fontinfo font; - int i,j,ascent,baseline,ch=0; - float scale, xpos=2; // leave a little padding in case the character extends left - char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness - - fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb")); - stbtt_InitFont(&font, buffer, 0); - - scale = stbtt_ScaleForPixelHeight(&font, 15); - stbtt_GetFontVMetrics(&font, &ascent,0,0); - baseline = (int) (ascent*scale); - - while (text[ch]) { - int advance,lsb,x0,y0,x1,y1; - float x_shift = xpos - (float) floor(xpos); - stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb); - stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1); - stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]); - // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong - // because this API is really for baking character bitmaps into textures. if you want to render - // a sequence of characters, you really need to render each bitmap to a temp buffer, then - // "alpha blend" that into the working buffer - xpos += (advance * scale); - if (text[ch+1]) - xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]); - ++ch; - } - - for (j=0; j < 20; ++j) { - for (i=0; i < 78; ++i) - putchar(" .:ioVM@"[screen[j][i]>>5]); - putchar('\n'); - } - - return 0; -} -#endif - - -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// -//// -//// INTEGRATION WITH YOUR CODEBASE -//// -//// The following sections allow you to supply alternate definitions -//// of C library functions used by stb_truetype, e.g. if you don't -//// link with the C runtime library. - -#ifdef STB_TRUETYPE_IMPLEMENTATION - // #define your own (u)stbtt_int8/16/32 before including to override this - #ifndef stbtt_uint8 - typedef unsigned char stbtt_uint8; - typedef signed char stbtt_int8; - typedef unsigned short stbtt_uint16; - typedef signed short stbtt_int16; - typedef unsigned int stbtt_uint32; - typedef signed int stbtt_int32; - #endif - - typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1]; - typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1]; - - // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h - #ifndef STBTT_ifloor - #include - #define STBTT_ifloor(x) ((int) floor(x)) - #define STBTT_iceil(x) ((int) ceil(x)) - #endif - - #ifndef STBTT_sqrt - #include - #define STBTT_sqrt(x) sqrt(x) - #define STBTT_pow(x,y) pow(x,y) - #endif - - #ifndef STBTT_fmod - #include - #define STBTT_fmod(x,y) fmod(x,y) - #endif - - #ifndef STBTT_cos - #include - #define STBTT_cos(x) cos(x) - #define STBTT_acos(x) acos(x) - #endif - - #ifndef STBTT_fabs - #include - #define STBTT_fabs(x) fabs(x) - #endif - - // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h - #ifndef STBTT_malloc - #include - #define STBTT_malloc(x,u) ((void)(u),malloc(x)) - #define STBTT_free(x,u) ((void)(u),free(x)) - #endif - - #ifndef STBTT_assert - #include - #define STBTT_assert(x) assert(x) - #endif - - #ifndef STBTT_strlen - #include - #define STBTT_strlen(x) strlen(x) - #endif - - #ifndef STBTT_memcpy - #include - #define STBTT_memcpy memcpy - #define STBTT_memset memset - #endif -#endif - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -//// -//// INTERFACE -//// -//// - -#ifndef __STB_INCLUDE_STB_TRUETYPE_H__ -#define __STB_INCLUDE_STB_TRUETYPE_H__ - -#ifdef STBTT_STATIC -#define STBTT_DEF static -#else -#define STBTT_DEF extern -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -// private structure -typedef struct -{ - unsigned char *data; - int cursor; - int size; -} stbtt__buf; - -////////////////////////////////////////////////////////////////////////////// -// -// TEXTURE BAKING API -// -// If you use this API, you only have to call two functions ever. -// - -typedef struct -{ - unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap - float xoff,yoff,xadvance; -} stbtt_bakedchar; - -STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) - float pixel_height, // height of font in pixels - unsigned char *pixels, int pw, int ph, // bitmap to be filled in - int first_char, int num_chars, // characters to bake - stbtt_bakedchar *chardata); // you allocate this, it's num_chars long -// if return is positive, the first unused row of the bitmap -// if return is negative, returns the negative of the number of characters that fit -// if return is 0, no characters fit and no rows were used -// This uses a very crappy packing. - -typedef struct -{ - float x0,y0,s0,t0; // top-left - float x1,y1,s1,t1; // bottom-right -} stbtt_aligned_quad; - -STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above - int char_index, // character to display - float *xpos, float *ypos, // pointers to current position in screen pixel space - stbtt_aligned_quad *q, // output: quad to draw - int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier -// Call GetBakedQuad with char_index = 'character - first_char', and it -// creates the quad you need to draw and advances the current position. -// -// The coordinate system used assumes y increases downwards. -// -// Characters will extend both above and below the current position; -// see discussion of "BASELINE" above. -// -// It's inefficient; you might want to c&p it and optimize it. - -STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap); -// Query the font vertical metrics without having to create a font first. - - -////////////////////////////////////////////////////////////////////////////// -// -// NEW TEXTURE BAKING API -// -// This provides options for packing multiple fonts into one atlas, not -// perfectly but better than nothing. - -typedef struct -{ - unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap - float xoff,yoff,xadvance; - float xoff2,yoff2; -} stbtt_packedchar; - -typedef struct stbtt_pack_context stbtt_pack_context; -typedef struct stbtt_fontinfo stbtt_fontinfo; -#ifndef STB_RECT_PACK_VERSION -typedef struct stbrp_rect stbrp_rect; -#endif - -STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context); -// Initializes a packing context stored in the passed-in stbtt_pack_context. -// Future calls using this context will pack characters into the bitmap passed -// in here: a 1-channel bitmap that is width * height. stride_in_bytes is -// the distance from one row to the next (or 0 to mean they are packed tightly -// together). "padding" is the amount of padding to leave between each -// character (normally you want '1' for bitmaps you'll use as textures with -// bilinear filtering). -// -// Returns 0 on failure, 1 on success. - -STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc); -// Cleans up the packing context and frees all memory. - -#define STBTT_POINT_SIZE(x) (-(x)) - -STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, - int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range); -// Creates character bitmaps from the font_index'th font found in fontdata (use -// font_index=0 if you don't know what that is). It creates num_chars_in_range -// bitmaps for characters with unicode values starting at first_unicode_char_in_range -// and increasing. Data for how to render them is stored in chardata_for_range; -// pass these to stbtt_GetPackedQuad to get back renderable quads. -// -// font_size is the full height of the character from ascender to descender, -// as computed by stbtt_ScaleForPixelHeight. To use a point size as computed -// by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE() -// and pass that result as 'font_size': -// ..., 20 , ... // font max minus min y is 20 pixels tall -// ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall - -typedef struct -{ - float font_size; - int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint - int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints - int num_chars; - stbtt_packedchar *chardata_for_range; // output - unsigned char h_oversample, v_oversample; // don't set these, they're used internally -} stbtt_pack_range; - -STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges); -// Creates character bitmaps from multiple ranges of characters stored in -// ranges. This will usually create a better-packed bitmap than multiple -// calls to stbtt_PackFontRange. Note that you can call this multiple -// times within a single PackBegin/PackEnd. - -STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample); -// Oversampling a font increases the quality by allowing higher-quality subpixel -// positioning, and is especially valuable at smaller text sizes. -// -// This function sets the amount of oversampling for all following calls to -// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given -// pack context. The default (no oversampling) is achieved by h_oversample=1 -// and v_oversample=1. The total number of pixels required is -// h_oversample*v_oversample larger than the default; for example, 2x2 -// oversampling requires 4x the storage of 1x1. For best results, render -// oversampled textures with bilinear filtering. Look at the readme in -// stb/tests/oversample for information about oversampled fonts -// -// To use with PackFontRangesGather etc., you must set it before calls -// call to PackFontRangesGatherRects. - -STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip); -// If skip != 0, this tells stb_truetype to skip any codepoints for which -// there is no corresponding glyph. If skip=0, which is the default, then -// codepoints without a glyph received the font's "missing character" glyph, -// typically an empty box by convention. - -STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above - int char_index, // character to display - float *xpos, float *ypos, // pointers to current position in screen pixel space - stbtt_aligned_quad *q, // output: quad to draw - int align_to_integer); - -STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); -STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects); -STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); -// Calling these functions in sequence is roughly equivalent to calling -// stbtt_PackFontRanges(). If you more control over the packing of multiple -// fonts, or if you want to pack custom data into a font texture, take a look -// at the source to of stbtt_PackFontRanges() and create a custom version -// using these functions, e.g. call GatherRects multiple times, -// building up a single array of rects, then call PackRects once, -// then call RenderIntoRects repeatedly. This may result in a -// better packing than calling PackFontRanges multiple times -// (or it may not). - -// this is an opaque structure that you shouldn't mess with which holds -// all the context needed from PackBegin to PackEnd. -struct stbtt_pack_context { - void *user_allocator_context; - void *pack_info; - int width; - int height; - int stride_in_bytes; - int padding; - int skip_missing; - unsigned int h_oversample, v_oversample; - unsigned char *pixels; - void *nodes; -}; - -////////////////////////////////////////////////////////////////////////////// -// -// FONT LOADING -// -// - -STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data); -// This function will determine the number of fonts in a font file. TrueType -// collection (.ttc) files may contain multiple fonts, while TrueType font -// (.ttf) files only contain one font. The number of fonts can be used for -// indexing with the previous function where the index is between zero and one -// less than the total fonts. If an error occurs, -1 is returned. - -STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); -// Each .ttf/.ttc file may have more than one font. Each font has a sequential -// index number starting from 0. Call this function to get the font offset for -// a given index; it returns -1 if the index is out of range. A regular .ttf -// file will only define one font and it always be at offset 0, so it will -// return '0' for index 0, and -1 for all other indices. - -// The following structure is defined publicly so you can declare one on -// the stack or as a global or etc, but you should treat it as opaque. -struct stbtt_fontinfo -{ - void * userdata; - unsigned char * data; // pointer to .ttf file - int fontstart; // offset of start of font - - int numGlyphs; // number of glyphs, needed for range checking - - int loca,head,glyf,hhea,hmtx,kern,gpos,svg; // table locations as offset from start of .ttf - int index_map; // a cmap mapping for our chosen character encoding - int indexToLocFormat; // format needed to map from glyph index to glyph - - stbtt__buf cff; // cff font data - stbtt__buf charstrings; // the charstring index - stbtt__buf gsubrs; // global charstring subroutines index - stbtt__buf subrs; // private charstring subroutines index - stbtt__buf fontdicts; // array of font dicts - stbtt__buf fdselect; // map from glyph to fontdict -}; - -STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset); -// Given an offset into the file that defines a font, this function builds -// the necessary cached info for the rest of the system. You must allocate -// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't -// need to do anything special to free it, because the contents are pure -// value data with no additional data structures. Returns 0 on failure. - - -////////////////////////////////////////////////////////////////////////////// -// -// CHARACTER TO GLYPH-INDEX CONVERSIOn - -STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); -// If you're going to perform multiple operations on the same character -// and you want a speed-up, call this function with the character you're -// going to process, then use glyph-based functions instead of the -// codepoint-based functions. -// Returns 0 if the character codepoint is not defined in the font. - - -////////////////////////////////////////////////////////////////////////////// -// -// CHARACTER PROPERTIES -// - -STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels); -// computes a scale factor to produce a font whose "height" is 'pixels' tall. -// Height is measured as the distance from the highest ascender to the lowest -// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics -// and computing: -// scale = pixels / (ascent - descent) -// so if you prefer to measure height by the ascent only, use a similar calculation. - -STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); -// computes a scale factor to produce a font whose EM size is mapped to -// 'pixels' tall. This is probably what traditional APIs compute, but -// I'm not positive. - -STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap); -// ascent is the coordinate above the baseline the font extends; descent -// is the coordinate below the baseline the font extends (i.e. it is typically negative) -// lineGap is the spacing between one row's descent and the next row's ascent... -// so you should advance the vertical position by "*ascent - *descent + *lineGap" -// these are expressed in unscaled coordinates, so you must multiply by -// the scale factor for a given size - -STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap); -// analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2 -// table (specific to MS/Windows TTF files). -// -// Returns 1 on success (table present), 0 on failure. - -STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); -// the bounding box around all possible characters - -STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); -// leftSideBearing is the offset from the current horizontal position to the left edge of the character -// advanceWidth is the offset from the current horizontal position to the next horizontal position -// these are expressed in unscaled coordinates - -STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2); -// an additional amount to add to the 'advance' value between ch1 and ch2 - -STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1); -// Gets the bounding box of the visible part of the glyph, in unscaled coordinates - -STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); -STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); -STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); -// as above, but takes one or more glyph indices for greater efficiency - -typedef struct stbtt_kerningentry -{ - int glyph1; // use stbtt_FindGlyphIndex - int glyph2; - int advance; -} stbtt_kerningentry; - -STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info); -STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length); -// Retrieves a complete list of all of the kerning pairs provided by the font -// stbtt_GetKerningTable never writes more than table_length entries and returns how many entries it did write. -// The table will be sorted by (a.glyph1 == b.glyph1)?(a.glyph2 < b.glyph2):(a.glyph1 < b.glyph1) - -////////////////////////////////////////////////////////////////////////////// -// -// GLYPH SHAPES (you probably don't need these, but they have to go before -// the bitmaps for C declaration-order reasons) -// - -#ifndef STBTT_vmove // you can predefine these to use different values (but why?) - enum { - STBTT_vmove=1, - STBTT_vline, - STBTT_vcurve, - STBTT_vcubic - }; -#endif - -#ifndef stbtt_vertex // you can predefine this to use different values - // (we share this with other code at RAD) - #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file - typedef struct - { - stbtt_vertex_type x,y,cx,cy,cx1,cy1; - unsigned char type,padding; - } stbtt_vertex; -#endif - -STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index); -// returns non-zero if nothing is drawn for this glyph - -STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices); -STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices); -// returns # of vertices and fills *vertices with the pointer to them -// these are expressed in "unscaled" coordinates -// -// The shape is a series of contours. Each one starts with -// a STBTT_moveto, then consists of a series of mixed -// STBTT_lineto and STBTT_curveto segments. A lineto -// draws a line from previous endpoint to its x,y; a curveto -// draws a quadratic bezier from previous endpoint to -// its x,y, using cx,cy as the bezier control point. - -STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices); -// frees the data allocated above - -STBTT_DEF unsigned char *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl); -STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg); -STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg); -// fills svg with the character's SVG data. -// returns data size or 0 if SVG not found. - -////////////////////////////////////////////////////////////////////////////// -// -// BITMAP RENDERING -// - -STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata); -// frees the bitmap allocated below - -STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff); -// allocates a large-enough single-channel 8bpp bitmap and renders the -// specified character/glyph at the specified scale into it, with -// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque). -// *width & *height are filled out with the width & height of the bitmap, -// which is stored left-to-right, top-to-bottom. -// -// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap - -STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff); -// the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel -// shift for the character - -STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint); -// the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap -// in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap -// is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the -// width and height and positioning info for it first. - -STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint); -// same as stbtt_MakeCodepointBitmap, but you can specify a subpixel -// shift for the character - -STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint); -// same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering -// is performed (see stbtt_PackSetOversampling) - -STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); -// get the bbox of the bitmap centered around the glyph origin; so the -// bitmap width is ix1-ix0, height is iy1-iy0, and location to place -// the bitmap top left is (leftSideBearing*scale,iy0). -// (Note that the bitmap uses y-increases-down, but the shape uses -// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.) - -STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); -// same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel -// shift for the character - -// the following functions are equivalent to the above functions, but operate -// on glyph indices instead of Unicode codepoints (for efficiency) -STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff); -STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff); -STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph); -STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph); -STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph); -STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); -STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); - - -// @TODO: don't expose this structure -typedef struct -{ - int w,h,stride; - unsigned char *pixels; -} stbtt__bitmap; - -// rasterize a shape with quadratic beziers into a bitmap -STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into - float flatness_in_pixels, // allowable error of curve in pixels - stbtt_vertex *vertices, // array of vertices defining shape - int num_verts, // number of vertices in above array - float scale_x, float scale_y, // scale applied to input vertices - float shift_x, float shift_y, // translation applied to input vertices - int x_off, int y_off, // another translation applied to input - int invert, // if non-zero, vertically flip shape - void *userdata); // context for to STBTT_MALLOC - -////////////////////////////////////////////////////////////////////////////// -// -// Signed Distance Function (or Field) rendering - -STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata); -// frees the SDF bitmap allocated below - -STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); -STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); -// These functions compute a discretized SDF field for a single character, suitable for storing -// in a single-channel texture, sampling with bilinear filtering, and testing against -// larger than some threshold to produce scalable fonts. -// info -- the font -// scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap -// glyph/codepoint -- the character to generate the SDF for -// padding -- extra "pixels" around the character which are filled with the distance to the character (not 0), -// which allows effects like bit outlines -// onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character) -// pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale) -// if positive, > onedge_value is inside; if negative, < onedge_value is inside -// width,height -- output height & width of the SDF bitmap (including padding) -// xoff,yoff -- output origin of the character -// return value -- a 2D array of bytes 0..255, width*height in size -// -// pixel_dist_scale & onedge_value are a scale & bias that allows you to make -// optimal use of the limited 0..255 for your application, trading off precision -// and special effects. SDF values outside the range 0..255 are clamped to 0..255. -// -// Example: -// scale = stbtt_ScaleForPixelHeight(22) -// padding = 5 -// onedge_value = 180 -// pixel_dist_scale = 180/5.0 = 36.0 -// -// This will create an SDF bitmap in which the character is about 22 pixels -// high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled -// shape, sample the SDF at each pixel and fill the pixel if the SDF value -// is greater than or equal to 180/255. (You'll actually want to antialias, -// which is beyond the scope of this example.) Additionally, you can compute -// offset outlines (e.g. to stroke the character border inside & outside, -// or only outside). For example, to fill outside the character up to 3 SDF -// pixels, you would compare against (180-36.0*3)/255 = 72/255. The above -// choice of variables maps a range from 5 pixels outside the shape to -// 2 pixels inside the shape to 0..255; this is intended primarily for apply -// outside effects only (the interior range is needed to allow proper -// antialiasing of the font at *smaller* sizes) -// -// The function computes the SDF analytically at each SDF pixel, not by e.g. -// building a higher-res bitmap and approximating it. In theory the quality -// should be as high as possible for an SDF of this size & representation, but -// unclear if this is true in practice (perhaps building a higher-res bitmap -// and computing from that can allow drop-out prevention). -// -// The algorithm has not been optimized at all, so expect it to be slow -// if computing lots of characters or very large sizes. - - - -////////////////////////////////////////////////////////////////////////////// -// -// Finding the right font... -// -// You should really just solve this offline, keep your own tables -// of what font is what, and don't try to get it out of the .ttf file. -// That's because getting it out of the .ttf file is really hard, because -// the names in the file can appear in many possible encodings, in many -// possible languages, and e.g. if you need a case-insensitive comparison, -// the details of that depend on the encoding & language in a complex way -// (actually underspecified in truetype, but also gigantic). -// -// But you can use the provided functions in two possible ways: -// stbtt_FindMatchingFont() will use *case-sensitive* comparisons on -// unicode-encoded names to try to find the font you want; -// you can run this before calling stbtt_InitFont() -// -// stbtt_GetFontNameString() lets you get any of the various strings -// from the file yourself and do your own comparisons on them. -// You have to have called stbtt_InitFont() first. - - -STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags); -// returns the offset (not index) of the font that matches, or -1 if none -// if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold". -// if you use any other flag, use a font name like "Arial"; this checks -// the 'macStyle' header field; i don't know if fonts set this consistently -#define STBTT_MACSTYLE_DONTCARE 0 -#define STBTT_MACSTYLE_BOLD 1 -#define STBTT_MACSTYLE_ITALIC 2 -#define STBTT_MACSTYLE_UNDERSCORE 4 -#define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0 - -STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2); -// returns 1/0 whether the first string interpreted as utf8 is identical to -// the second string interpreted as big-endian utf16... useful for strings from next func - -STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID); -// returns the string (which may be big-endian double byte, e.g. for unicode) -// and puts the length in bytes in *length. -// -// some of the values for the IDs are below; for more see the truetype spec: -// http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html -// http://www.microsoft.com/typography/otspec/name.htm - -enum { // platformID - STBTT_PLATFORM_ID_UNICODE =0, - STBTT_PLATFORM_ID_MAC =1, - STBTT_PLATFORM_ID_ISO =2, - STBTT_PLATFORM_ID_MICROSOFT =3 -}; - -enum { // encodingID for STBTT_PLATFORM_ID_UNICODE - STBTT_UNICODE_EID_UNICODE_1_0 =0, - STBTT_UNICODE_EID_UNICODE_1_1 =1, - STBTT_UNICODE_EID_ISO_10646 =2, - STBTT_UNICODE_EID_UNICODE_2_0_BMP=3, - STBTT_UNICODE_EID_UNICODE_2_0_FULL=4 -}; - -enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT - STBTT_MS_EID_SYMBOL =0, - STBTT_MS_EID_UNICODE_BMP =1, - STBTT_MS_EID_SHIFTJIS =2, - STBTT_MS_EID_UNICODE_FULL =10 -}; - -enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes - STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4, - STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5, - STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6, - STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7 -}; - -enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID... - // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs - STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410, - STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411, - STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412, - STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419, - STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409, - STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D -}; - -enum { // languageID for STBTT_PLATFORM_ID_MAC - STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11, - STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23, - STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32, - STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 , - STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 , - STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33, - STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19 -}; - -#ifdef __cplusplus -} -#endif - -#endif // __STB_INCLUDE_STB_TRUETYPE_H__ - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -//// -//// IMPLEMENTATION -//// -//// - -#ifdef STB_TRUETYPE_IMPLEMENTATION - -#ifndef STBTT_MAX_OVERSAMPLE -#define STBTT_MAX_OVERSAMPLE 8 -#endif - -#if STBTT_MAX_OVERSAMPLE > 255 -#error "STBTT_MAX_OVERSAMPLE cannot be > 255" -#endif - -typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1]; - -#ifndef STBTT_RASTERIZER_VERSION -#define STBTT_RASTERIZER_VERSION 2 -#endif - -#ifdef _MSC_VER -#define STBTT__NOTUSED(v) (void)(v) -#else -#define STBTT__NOTUSED(v) (void)sizeof(v) -#endif - -////////////////////////////////////////////////////////////////////////// -// -// stbtt__buf helpers to parse data from file -// - -static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b) -{ - if (b->cursor >= b->size) - return 0; - return b->data[b->cursor++]; -} - -static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b) -{ - if (b->cursor >= b->size) - return 0; - return b->data[b->cursor]; -} - -static void stbtt__buf_seek(stbtt__buf *b, int o) -{ - STBTT_assert(!(o > b->size || o < 0)); - b->cursor = (o > b->size || o < 0) ? b->size : o; -} - -static void stbtt__buf_skip(stbtt__buf *b, int o) -{ - stbtt__buf_seek(b, b->cursor + o); -} - -static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n) -{ - stbtt_uint32 v = 0; - int i; - STBTT_assert(n >= 1 && n <= 4); - for (i = 0; i < n; i++) - v = (v << 8) | stbtt__buf_get8(b); - return v; -} - -static stbtt__buf stbtt__new_buf(const void *p, size_t size) -{ - stbtt__buf r; - STBTT_assert(size < 0x40000000); - r.data = (stbtt_uint8*) p; - r.size = (int) size; - r.cursor = 0; - return r; -} - -#define stbtt__buf_get16(b) stbtt__buf_get((b), 2) -#define stbtt__buf_get32(b) stbtt__buf_get((b), 4) - -static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s) -{ - stbtt__buf r = stbtt__new_buf(NULL, 0); - if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r; - r.data = b->data + o; - r.size = s; - return r; -} - -static stbtt__buf stbtt__cff_get_index(stbtt__buf *b) -{ - int count, start, offsize; - start = b->cursor; - count = stbtt__buf_get16(b); - if (count) { - offsize = stbtt__buf_get8(b); - STBTT_assert(offsize >= 1 && offsize <= 4); - stbtt__buf_skip(b, offsize * count); - stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1); - } - return stbtt__buf_range(b, start, b->cursor - start); -} - -static stbtt_uint32 stbtt__cff_int(stbtt__buf *b) -{ - int b0 = stbtt__buf_get8(b); - if (b0 >= 32 && b0 <= 246) return b0 - 139; - else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108; - else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108; - else if (b0 == 28) return stbtt__buf_get16(b); - else if (b0 == 29) return stbtt__buf_get32(b); - STBTT_assert(0); - return 0; -} - -static void stbtt__cff_skip_operand(stbtt__buf *b) { - int v, b0 = stbtt__buf_peek8(b); - STBTT_assert(b0 >= 28); - if (b0 == 30) { - stbtt__buf_skip(b, 1); - while (b->cursor < b->size) { - v = stbtt__buf_get8(b); - if ((v & 0xF) == 0xF || (v >> 4) == 0xF) - break; - } - } else { - stbtt__cff_int(b); - } -} - -static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key) -{ - stbtt__buf_seek(b, 0); - while (b->cursor < b->size) { - int start = b->cursor, end, op; - while (stbtt__buf_peek8(b) >= 28) - stbtt__cff_skip_operand(b); - end = b->cursor; - op = stbtt__buf_get8(b); - if (op == 12) op = stbtt__buf_get8(b) | 0x100; - if (op == key) return stbtt__buf_range(b, start, end-start); - } - return stbtt__buf_range(b, 0, 0); -} - -static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out) -{ - int i; - stbtt__buf operands = stbtt__dict_get(b, key); - for (i = 0; i < outcount && operands.cursor < operands.size; i++) - out[i] = stbtt__cff_int(&operands); -} - -static int stbtt__cff_index_count(stbtt__buf *b) -{ - stbtt__buf_seek(b, 0); - return stbtt__buf_get16(b); -} - -static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i) -{ - int count, offsize, start, end; - stbtt__buf_seek(&b, 0); - count = stbtt__buf_get16(&b); - offsize = stbtt__buf_get8(&b); - STBTT_assert(i >= 0 && i < count); - STBTT_assert(offsize >= 1 && offsize <= 4); - stbtt__buf_skip(&b, i*offsize); - start = stbtt__buf_get(&b, offsize); - end = stbtt__buf_get(&b, offsize); - return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start); -} - -////////////////////////////////////////////////////////////////////////// -// -// accessors to parse data from file -// - -// on platforms that don't allow misaligned reads, if we want to allow -// truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE - -#define ttBYTE(p) (* (stbtt_uint8 *) (p)) -#define ttCHAR(p) (* (stbtt_int8 *) (p)) -#define ttFixed(p) ttLONG(p) - -static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } -static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } -static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } -static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } - -#define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)) -#define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3]) - -static int stbtt__isfont(stbtt_uint8 *font) -{ - // check the version number - if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1 - if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this! - if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF - if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0 - if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts - return 0; -} - -// @OPTIMIZE: binary search -static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag) -{ - stbtt_int32 num_tables = ttUSHORT(data+fontstart+4); - stbtt_uint32 tabledir = fontstart + 12; - stbtt_int32 i; - for (i=0; i < num_tables; ++i) { - stbtt_uint32 loc = tabledir + 16*i; - if (stbtt_tag(data+loc+0, tag)) - return ttULONG(data+loc+8); - } - return 0; -} - -static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index) -{ - // if it's just a font, there's only one valid index - if (stbtt__isfont(font_collection)) - return index == 0 ? 0 : -1; - - // check if it's a TTC - if (stbtt_tag(font_collection, "ttcf")) { - // version 1? - if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { - stbtt_int32 n = ttLONG(font_collection+8); - if (index >= n) - return -1; - return ttULONG(font_collection+12+index*4); - } - } - return -1; -} - -static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection) -{ - // if it's just a font, there's only one valid font - if (stbtt__isfont(font_collection)) - return 1; - - // check if it's a TTC - if (stbtt_tag(font_collection, "ttcf")) { - // version 1? - if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { - return ttLONG(font_collection+8); - } - } - return 0; -} - -static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict) -{ - stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 }; - stbtt__buf pdict; - stbtt__dict_get_ints(&fontdict, 18, 2, private_loc); - if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0); - pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]); - stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff); - if (!subrsoff) return stbtt__new_buf(NULL, 0); - stbtt__buf_seek(&cff, private_loc[1]+subrsoff); - return stbtt__cff_get_index(&cff); -} - -// since most people won't use this, find this table the first time it's needed -static int stbtt__get_svg(stbtt_fontinfo *info) -{ - stbtt_uint32 t; - if (info->svg < 0) { - t = stbtt__find_table(info->data, info->fontstart, "SVG "); - if (t) { - stbtt_uint32 offset = ttULONG(info->data + t + 2); - info->svg = t + offset; - } else { - info->svg = 0; - } - } - return info->svg; -} - -static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart) -{ - stbtt_uint32 cmap, t; - stbtt_int32 i,numTables; - - info->data = data; - info->fontstart = fontstart; - info->cff = stbtt__new_buf(NULL, 0); - - cmap = stbtt__find_table(data, fontstart, "cmap"); // required - info->loca = stbtt__find_table(data, fontstart, "loca"); // required - info->head = stbtt__find_table(data, fontstart, "head"); // required - info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required - info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required - info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required - info->kern = stbtt__find_table(data, fontstart, "kern"); // not required - info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required - - if (!cmap || !info->head || !info->hhea || !info->hmtx) - return 0; - if (info->glyf) { - // required for truetype - if (!info->loca) return 0; - } else { - // initialization for CFF / Type2 fonts (OTF) - stbtt__buf b, topdict, topdictidx; - stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0; - stbtt_uint32 cff; - - cff = stbtt__find_table(data, fontstart, "CFF "); - if (!cff) return 0; - - info->fontdicts = stbtt__new_buf(NULL, 0); - info->fdselect = stbtt__new_buf(NULL, 0); - - // @TODO this should use size from table (not 512MB) - info->cff = stbtt__new_buf(data+cff, 512*1024*1024); - b = info->cff; - - // read the header - stbtt__buf_skip(&b, 2); - stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize - - // @TODO the name INDEX could list multiple fonts, - // but we just use the first one. - stbtt__cff_get_index(&b); // name INDEX - topdictidx = stbtt__cff_get_index(&b); - topdict = stbtt__cff_index_get(topdictidx, 0); - stbtt__cff_get_index(&b); // string INDEX - info->gsubrs = stbtt__cff_get_index(&b); - - stbtt__dict_get_ints(&topdict, 17, 1, &charstrings); - stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype); - stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff); - stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff); - info->subrs = stbtt__get_subrs(b, topdict); - - // we only support Type 2 charstrings - if (cstype != 2) return 0; - if (charstrings == 0) return 0; - - if (fdarrayoff) { - // looks like a CID font - if (!fdselectoff) return 0; - stbtt__buf_seek(&b, fdarrayoff); - info->fontdicts = stbtt__cff_get_index(&b); - info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff); - } - - stbtt__buf_seek(&b, charstrings); - info->charstrings = stbtt__cff_get_index(&b); - } - - t = stbtt__find_table(data, fontstart, "maxp"); - if (t) - info->numGlyphs = ttUSHORT(data+t+4); - else - info->numGlyphs = 0xffff; - - info->svg = -1; - - // find a cmap encoding table we understand *now* to avoid searching - // later. (todo: could make this installable) - // the same regardless of glyph. - numTables = ttUSHORT(data + cmap + 2); - info->index_map = 0; - for (i=0; i < numTables; ++i) { - stbtt_uint32 encoding_record = cmap + 4 + 8 * i; - // find an encoding we understand: - switch(ttUSHORT(data+encoding_record)) { - case STBTT_PLATFORM_ID_MICROSOFT: - switch (ttUSHORT(data+encoding_record+2)) { - case STBTT_MS_EID_UNICODE_BMP: - case STBTT_MS_EID_UNICODE_FULL: - // MS/Unicode - info->index_map = cmap + ttULONG(data+encoding_record+4); - break; - } - break; - case STBTT_PLATFORM_ID_UNICODE: - // Mac/iOS has these - // all the encodingIDs are unicode, so we don't bother to check it - info->index_map = cmap + ttULONG(data+encoding_record+4); - break; - } - } - if (info->index_map == 0) - return 0; - - info->indexToLocFormat = ttUSHORT(data+info->head + 50); - return 1; -} - -STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint) -{ - stbtt_uint8 *data = info->data; - stbtt_uint32 index_map = info->index_map; - - stbtt_uint16 format = ttUSHORT(data + index_map + 0); - if (format == 0) { // apple byte encoding - stbtt_int32 bytes = ttUSHORT(data + index_map + 2); - if (unicode_codepoint < bytes-6) - return ttBYTE(data + index_map + 6 + unicode_codepoint); - return 0; - } else if (format == 6) { - stbtt_uint32 first = ttUSHORT(data + index_map + 6); - stbtt_uint32 count = ttUSHORT(data + index_map + 8); - if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count) - return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2); - return 0; - } else if (format == 2) { - STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean - return 0; - } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges - stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1; - stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1; - stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10); - stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1; - - // do a binary search of the segments - stbtt_uint32 endCount = index_map + 14; - stbtt_uint32 search = endCount; - - if (unicode_codepoint > 0xffff) - return 0; - - // they lie from endCount .. endCount + segCount - // but searchRange is the nearest power of two, so... - if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2)) - search += rangeShift*2; - - // now decrement to bias correctly to find smallest - search -= 2; - while (entrySelector) { - stbtt_uint16 end; - searchRange >>= 1; - end = ttUSHORT(data + search + searchRange*2); - if (unicode_codepoint > end) - search += searchRange*2; - --entrySelector; - } - search += 2; - - { - stbtt_uint16 offset, start, last; - stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1); - - start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); - last = ttUSHORT(data + endCount + 2*item); - if (unicode_codepoint < start || unicode_codepoint > last) - return 0; - - offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); - if (offset == 0) - return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); - - return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); - } - } else if (format == 12 || format == 13) { - stbtt_uint32 ngroups = ttULONG(data+index_map+12); - stbtt_int32 low,high; - low = 0; high = (stbtt_int32)ngroups; - // Binary search the right group. - while (low < high) { - stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high - stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12); - stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4); - if ((stbtt_uint32) unicode_codepoint < start_char) - high = mid; - else if ((stbtt_uint32) unicode_codepoint > end_char) - low = mid+1; - else { - stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8); - if (format == 12) - return start_glyph + unicode_codepoint-start_char; - else // format == 13 - return start_glyph; - } - } - return 0; // not found - } - // @TODO - STBTT_assert(0); - return 0; -} - -STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices) -{ - return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices); -} - -static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy) -{ - v->type = type; - v->x = (stbtt_int16) x; - v->y = (stbtt_int16) y; - v->cx = (stbtt_int16) cx; - v->cy = (stbtt_int16) cy; -} - -static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index) -{ - int g1,g2; - - STBTT_assert(!info->cff.size); - - if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range - if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format - - if (info->indexToLocFormat == 0) { - g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2; - g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2; - } else { - g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4); - g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4); - } - - return g1==g2 ? -1 : g1; // if length is 0, return -1 -} - -static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); - -STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) -{ - if (info->cff.size) { - stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); - } else { - int g = stbtt__GetGlyfOffset(info, glyph_index); - if (g < 0) return 0; - - if (x0) *x0 = ttSHORT(info->data + g + 2); - if (y0) *y0 = ttSHORT(info->data + g + 4); - if (x1) *x1 = ttSHORT(info->data + g + 6); - if (y1) *y1 = ttSHORT(info->data + g + 8); - } - return 1; -} - -STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1) -{ - return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1); -} - -STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index) -{ - stbtt_int16 numberOfContours; - int g; - if (info->cff.size) - return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0; - g = stbtt__GetGlyfOffset(info, glyph_index); - if (g < 0) return 1; - numberOfContours = ttSHORT(info->data + g); - return numberOfContours == 0; -} - -static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off, - stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy) -{ - if (start_off) { - if (was_off) - stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy); - stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy); - } else { - if (was_off) - stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy); - else - stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0); - } - return num_vertices; -} - -static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) -{ - stbtt_int16 numberOfContours; - stbtt_uint8 *endPtsOfContours; - stbtt_uint8 *data = info->data; - stbtt_vertex *vertices=0; - int num_vertices=0; - int g = stbtt__GetGlyfOffset(info, glyph_index); - - *pvertices = NULL; - - if (g < 0) return 0; - - numberOfContours = ttSHORT(data + g); - - if (numberOfContours > 0) { - stbtt_uint8 flags=0,flagcount; - stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0; - stbtt_int32 x,y,cx,cy,sx,sy, scx,scy; - stbtt_uint8 *points; - endPtsOfContours = (data + g + 10); - ins = ttUSHORT(data + g + 10 + numberOfContours * 2); - points = data + g + 10 + numberOfContours * 2 + 2 + ins; - - n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2); - - m = n + 2*numberOfContours; // a loose bound on how many vertices we might need - vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata); - if (vertices == 0) - return 0; - - next_move = 0; - flagcount=0; - - // in first pass, we load uninterpreted data into the allocated array - // above, shifted to the end of the array so we won't overwrite it when - // we create our final data starting from the front - - off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated - - // first load flags - - for (i=0; i < n; ++i) { - if (flagcount == 0) { - flags = *points++; - if (flags & 8) - flagcount = *points++; - } else - --flagcount; - vertices[off+i].type = flags; - } - - // now load x coordinates - x=0; - for (i=0; i < n; ++i) { - flags = vertices[off+i].type; - if (flags & 2) { - stbtt_int16 dx = *points++; - x += (flags & 16) ? dx : -dx; // ??? - } else { - if (!(flags & 16)) { - x = x + (stbtt_int16) (points[0]*256 + points[1]); - points += 2; - } - } - vertices[off+i].x = (stbtt_int16) x; - } - - // now load y coordinates - y=0; - for (i=0; i < n; ++i) { - flags = vertices[off+i].type; - if (flags & 4) { - stbtt_int16 dy = *points++; - y += (flags & 32) ? dy : -dy; // ??? - } else { - if (!(flags & 32)) { - y = y + (stbtt_int16) (points[0]*256 + points[1]); - points += 2; - } - } - vertices[off+i].y = (stbtt_int16) y; - } - - // now convert them to our format - num_vertices=0; - sx = sy = cx = cy = scx = scy = 0; - for (i=0; i < n; ++i) { - flags = vertices[off+i].type; - x = (stbtt_int16) vertices[off+i].x; - y = (stbtt_int16) vertices[off+i].y; - - if (next_move == i) { - if (i != 0) - num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); - - // now start the new one - start_off = !(flags & 1); - if (start_off) { - // if we start off with an off-curve point, then when we need to find a point on the curve - // where we can start, and we need to save some state for when we wraparound. - scx = x; - scy = y; - if (!(vertices[off+i+1].type & 1)) { - // next point is also a curve point, so interpolate an on-point curve - sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1; - sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1; - } else { - // otherwise just use the next point as our start point - sx = (stbtt_int32) vertices[off+i+1].x; - sy = (stbtt_int32) vertices[off+i+1].y; - ++i; // we're using point i+1 as the starting point, so skip it - } - } else { - sx = x; - sy = y; - } - stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0); - was_off = 0; - next_move = 1 + ttUSHORT(endPtsOfContours+j*2); - ++j; - } else { - if (!(flags & 1)) { // if it's a curve - if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint - stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy); - cx = x; - cy = y; - was_off = 1; - } else { - if (was_off) - stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy); - else - stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0); - was_off = 0; - } - } - } - num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); - } else if (numberOfContours < 0) { - // Compound shapes. - int more = 1; - stbtt_uint8 *comp = data + g + 10; - num_vertices = 0; - vertices = 0; - while (more) { - stbtt_uint16 flags, gidx; - int comp_num_verts = 0, i; - stbtt_vertex *comp_verts = 0, *tmp = 0; - float mtx[6] = {1,0,0,1,0,0}, m, n; - - flags = ttSHORT(comp); comp+=2; - gidx = ttSHORT(comp); comp+=2; - - if (flags & 2) { // XY values - if (flags & 1) { // shorts - mtx[4] = ttSHORT(comp); comp+=2; - mtx[5] = ttSHORT(comp); comp+=2; - } else { - mtx[4] = ttCHAR(comp); comp+=1; - mtx[5] = ttCHAR(comp); comp+=1; - } - } - else { - // @TODO handle matching point - STBTT_assert(0); - } - if (flags & (1<<3)) { // WE_HAVE_A_SCALE - mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; - mtx[1] = mtx[2] = 0; - } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE - mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; - mtx[1] = mtx[2] = 0; - mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; - } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO - mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; - mtx[1] = ttSHORT(comp)/16384.0f; comp+=2; - mtx[2] = ttSHORT(comp)/16384.0f; comp+=2; - mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; - } - - // Find transformation scales. - m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]); - n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]); - - // Get indexed glyph. - comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts); - if (comp_num_verts > 0) { - // Transform vertices. - for (i = 0; i < comp_num_verts; ++i) { - stbtt_vertex* v = &comp_verts[i]; - stbtt_vertex_type x,y; - x=v->x; y=v->y; - v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); - v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); - x=v->cx; y=v->cy; - v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); - v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); - } - // Append vertices. - tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata); - if (!tmp) { - if (vertices) STBTT_free(vertices, info->userdata); - if (comp_verts) STBTT_free(comp_verts, info->userdata); - return 0; - } - if (num_vertices > 0 && vertices) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex)); - STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex)); - if (vertices) STBTT_free(vertices, info->userdata); - vertices = tmp; - STBTT_free(comp_verts, info->userdata); - num_vertices += comp_num_verts; - } - // More components ? - more = flags & (1<<5); - } - } else { - // numberOfCounters == 0, do nothing - } - - *pvertices = vertices; - return num_vertices; -} - -typedef struct -{ - int bounds; - int started; - float first_x, first_y; - float x, y; - stbtt_int32 min_x, max_x, min_y, max_y; - - stbtt_vertex *pvertices; - int num_vertices; -} stbtt__csctx; - -#define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0} - -static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y) -{ - if (x > c->max_x || !c->started) c->max_x = x; - if (y > c->max_y || !c->started) c->max_y = y; - if (x < c->min_x || !c->started) c->min_x = x; - if (y < c->min_y || !c->started) c->min_y = y; - c->started = 1; -} - -static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1) -{ - if (c->bounds) { - stbtt__track_vertex(c, x, y); - if (type == STBTT_vcubic) { - stbtt__track_vertex(c, cx, cy); - stbtt__track_vertex(c, cx1, cy1); - } - } else { - stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy); - c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1; - c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1; - } - c->num_vertices++; -} - -static void stbtt__csctx_close_shape(stbtt__csctx *ctx) -{ - if (ctx->first_x != ctx->x || ctx->first_y != ctx->y) - stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0); -} - -static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy) -{ - stbtt__csctx_close_shape(ctx); - ctx->first_x = ctx->x = ctx->x + dx; - ctx->first_y = ctx->y = ctx->y + dy; - stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); -} - -static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy) -{ - ctx->x += dx; - ctx->y += dy; - stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); -} - -static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) -{ - float cx1 = ctx->x + dx1; - float cy1 = ctx->y + dy1; - float cx2 = cx1 + dx2; - float cy2 = cy1 + dy2; - ctx->x = cx2 + dx3; - ctx->y = cy2 + dy3; - stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2); -} - -static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n) -{ - int count = stbtt__cff_index_count(&idx); - int bias = 107; - if (count >= 33900) - bias = 32768; - else if (count >= 1240) - bias = 1131; - n += bias; - if (n < 0 || n >= count) - return stbtt__new_buf(NULL, 0); - return stbtt__cff_index_get(idx, n); -} - -static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index) -{ - stbtt__buf fdselect = info->fdselect; - int nranges, start, end, v, fmt, fdselector = -1, i; - - stbtt__buf_seek(&fdselect, 0); - fmt = stbtt__buf_get8(&fdselect); - if (fmt == 0) { - // untested - stbtt__buf_skip(&fdselect, glyph_index); - fdselector = stbtt__buf_get8(&fdselect); - } else if (fmt == 3) { - nranges = stbtt__buf_get16(&fdselect); - start = stbtt__buf_get16(&fdselect); - for (i = 0; i < nranges; i++) { - v = stbtt__buf_get8(&fdselect); - end = stbtt__buf_get16(&fdselect); - if (glyph_index >= start && glyph_index < end) { - fdselector = v; - break; - } - start = end; - } - } - if (fdselector == -1) return stbtt__new_buf(NULL, 0); // [DEAR IMGUI] fixed, see #6007 and nothings/stb#1422 - return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector)); -} - -static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c) -{ - int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0; - int has_subrs = 0, clear_stack; - float s[48]; - stbtt__buf subr_stack[10], subrs = info->subrs, b; - float f; - -#define STBTT__CSERR(s) (0) - - // this currently ignores the initial width value, which isn't needed if we have hmtx - b = stbtt__cff_index_get(info->charstrings, glyph_index); - while (b.cursor < b.size) { - i = 0; - clear_stack = 1; - b0 = stbtt__buf_get8(&b); - switch (b0) { - // @TODO implement hinting - case 0x13: // hintmask - case 0x14: // cntrmask - if (in_header) - maskbits += (sp / 2); // implicit "vstem" - in_header = 0; - stbtt__buf_skip(&b, (maskbits + 7) / 8); - break; - - case 0x01: // hstem - case 0x03: // vstem - case 0x12: // hstemhm - case 0x17: // vstemhm - maskbits += (sp / 2); - break; - - case 0x15: // rmoveto - in_header = 0; - if (sp < 2) return STBTT__CSERR("rmoveto stack"); - stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]); - break; - case 0x04: // vmoveto - in_header = 0; - if (sp < 1) return STBTT__CSERR("vmoveto stack"); - stbtt__csctx_rmove_to(c, 0, s[sp-1]); - break; - case 0x16: // hmoveto - in_header = 0; - if (sp < 1) return STBTT__CSERR("hmoveto stack"); - stbtt__csctx_rmove_to(c, s[sp-1], 0); - break; - - case 0x05: // rlineto - if (sp < 2) return STBTT__CSERR("rlineto stack"); - for (; i + 1 < sp; i += 2) - stbtt__csctx_rline_to(c, s[i], s[i+1]); - break; - - // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical - // starting from a different place. - - case 0x07: // vlineto - if (sp < 1) return STBTT__CSERR("vlineto stack"); - goto vlineto; - case 0x06: // hlineto - if (sp < 1) return STBTT__CSERR("hlineto stack"); - for (;;) { - if (i >= sp) break; - stbtt__csctx_rline_to(c, s[i], 0); - i++; - vlineto: - if (i >= sp) break; - stbtt__csctx_rline_to(c, 0, s[i]); - i++; - } - break; - - case 0x1F: // hvcurveto - if (sp < 4) return STBTT__CSERR("hvcurveto stack"); - goto hvcurveto; - case 0x1E: // vhcurveto - if (sp < 4) return STBTT__CSERR("vhcurveto stack"); - for (;;) { - if (i + 3 >= sp) break; - stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f); - i += 4; - hvcurveto: - if (i + 3 >= sp) break; - stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]); - i += 4; - } - break; - - case 0x08: // rrcurveto - if (sp < 6) return STBTT__CSERR("rcurveline stack"); - for (; i + 5 < sp; i += 6) - stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); - break; - - case 0x18: // rcurveline - if (sp < 8) return STBTT__CSERR("rcurveline stack"); - for (; i + 5 < sp - 2; i += 6) - stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); - if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack"); - stbtt__csctx_rline_to(c, s[i], s[i+1]); - break; - - case 0x19: // rlinecurve - if (sp < 8) return STBTT__CSERR("rlinecurve stack"); - for (; i + 1 < sp - 6; i += 2) - stbtt__csctx_rline_to(c, s[i], s[i+1]); - if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack"); - stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); - break; - - case 0x1A: // vvcurveto - case 0x1B: // hhcurveto - if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack"); - f = 0.0; - if (sp & 1) { f = s[i]; i++; } - for (; i + 3 < sp; i += 4) { - if (b0 == 0x1B) - stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0); - else - stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]); - f = 0.0; - } - break; - - case 0x0A: // callsubr - if (!has_subrs) { - if (info->fdselect.size) - subrs = stbtt__cid_get_glyph_subrs(info, glyph_index); - has_subrs = 1; - } - // FALLTHROUGH - case 0x1D: // callgsubr - if (sp < 1) return STBTT__CSERR("call(g|)subr stack"); - v = (int) s[--sp]; - if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit"); - subr_stack[subr_stack_height++] = b; - b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v); - if (b.size == 0) return STBTT__CSERR("subr not found"); - b.cursor = 0; - clear_stack = 0; - break; - - case 0x0B: // return - if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr"); - b = subr_stack[--subr_stack_height]; - clear_stack = 0; - break; - - case 0x0E: // endchar - stbtt__csctx_close_shape(c); - return 1; - - case 0x0C: { // two-byte escape - float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6; - float dx, dy; - int b1 = stbtt__buf_get8(&b); - switch (b1) { - // @TODO These "flex" implementations ignore the flex-depth and resolution, - // and always draw beziers. - case 0x22: // hflex - if (sp < 7) return STBTT__CSERR("hflex stack"); - dx1 = s[0]; - dx2 = s[1]; - dy2 = s[2]; - dx3 = s[3]; - dx4 = s[4]; - dx5 = s[5]; - dx6 = s[6]; - stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0); - stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0); - break; - - case 0x23: // flex - if (sp < 13) return STBTT__CSERR("flex stack"); - dx1 = s[0]; - dy1 = s[1]; - dx2 = s[2]; - dy2 = s[3]; - dx3 = s[4]; - dy3 = s[5]; - dx4 = s[6]; - dy4 = s[7]; - dx5 = s[8]; - dy5 = s[9]; - dx6 = s[10]; - dy6 = s[11]; - //fd is s[12] - stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); - stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); - break; - - case 0x24: // hflex1 - if (sp < 9) return STBTT__CSERR("hflex1 stack"); - dx1 = s[0]; - dy1 = s[1]; - dx2 = s[2]; - dy2 = s[3]; - dx3 = s[4]; - dx4 = s[5]; - dx5 = s[6]; - dy5 = s[7]; - dx6 = s[8]; - stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0); - stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5)); - break; - - case 0x25: // flex1 - if (sp < 11) return STBTT__CSERR("flex1 stack"); - dx1 = s[0]; - dy1 = s[1]; - dx2 = s[2]; - dy2 = s[3]; - dx3 = s[4]; - dy3 = s[5]; - dx4 = s[6]; - dy4 = s[7]; - dx5 = s[8]; - dy5 = s[9]; - dx6 = dy6 = s[10]; - dx = dx1+dx2+dx3+dx4+dx5; - dy = dy1+dy2+dy3+dy4+dy5; - if (STBTT_fabs(dx) > STBTT_fabs(dy)) - dy6 = -dy; - else - dx6 = -dx; - stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); - stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); - break; - - default: - return STBTT__CSERR("unimplemented"); - } - } break; - - default: - if (b0 != 255 && b0 != 28 && b0 < 32) - return STBTT__CSERR("reserved operator"); - - // push immediate - if (b0 == 255) { - f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000; - } else { - stbtt__buf_skip(&b, -1); - f = (float)(stbtt_int16)stbtt__cff_int(&b); - } - if (sp >= 48) return STBTT__CSERR("push stack overflow"); - s[sp++] = f; - clear_stack = 0; - break; - } - if (clear_stack) sp = 0; - } - return STBTT__CSERR("no endchar"); - -#undef STBTT__CSERR -} - -static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) -{ - // runs the charstring twice, once to count and once to output (to avoid realloc) - stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1); - stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0); - if (stbtt__run_charstring(info, glyph_index, &count_ctx)) { - *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata); - output_ctx.pvertices = *pvertices; - if (stbtt__run_charstring(info, glyph_index, &output_ctx)) { - STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices); - return output_ctx.num_vertices; - } - } - *pvertices = NULL; - return 0; -} - -static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) -{ - stbtt__csctx c = STBTT__CSCTX_INIT(1); - int r = stbtt__run_charstring(info, glyph_index, &c); - if (x0) *x0 = r ? c.min_x : 0; - if (y0) *y0 = r ? c.min_y : 0; - if (x1) *x1 = r ? c.max_x : 0; - if (y1) *y1 = r ? c.max_y : 0; - return r ? c.num_vertices : 0; -} - -STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) -{ - if (!info->cff.size) - return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices); - else - return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices); -} - -STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing) -{ - stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34); - if (glyph_index < numOfLongHorMetrics) { - if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index); - if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2); - } else { - if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1)); - if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics)); - } -} - -STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info) -{ - stbtt_uint8 *data = info->data + info->kern; - - // we only look at the first table. it must be 'horizontal' and format 0. - if (!info->kern) - return 0; - if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 - return 0; - if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format - return 0; - - return ttUSHORT(data+10); -} - -STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length) -{ - stbtt_uint8 *data = info->data + info->kern; - int k, length; - - // we only look at the first table. it must be 'horizontal' and format 0. - if (!info->kern) - return 0; - if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 - return 0; - if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format - return 0; - - length = ttUSHORT(data+10); - if (table_length < length) - length = table_length; - - for (k = 0; k < length; k++) - { - table[k].glyph1 = ttUSHORT(data+18+(k*6)); - table[k].glyph2 = ttUSHORT(data+20+(k*6)); - table[k].advance = ttSHORT(data+22+(k*6)); - } - - return length; -} - -static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) -{ - stbtt_uint8 *data = info->data + info->kern; - stbtt_uint32 needle, straw; - int l, r, m; - - // we only look at the first table. it must be 'horizontal' and format 0. - if (!info->kern) - return 0; - if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 - return 0; - if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format - return 0; - - l = 0; - r = ttUSHORT(data+10) - 1; - needle = glyph1 << 16 | glyph2; - while (l <= r) { - m = (l + r) >> 1; - straw = ttULONG(data+18+(m*6)); // note: unaligned read - if (needle < straw) - r = m - 1; - else if (needle > straw) - l = m + 1; - else - return ttSHORT(data+22+(m*6)); - } - return 0; -} - -static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph) -{ - stbtt_uint16 coverageFormat = ttUSHORT(coverageTable); - switch (coverageFormat) { - case 1: { - stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2); - - // Binary search. - stbtt_int32 l=0, r=glyphCount-1, m; - int straw, needle=glyph; - while (l <= r) { - stbtt_uint8 *glyphArray = coverageTable + 4; - stbtt_uint16 glyphID; - m = (l + r) >> 1; - glyphID = ttUSHORT(glyphArray + 2 * m); - straw = glyphID; - if (needle < straw) - r = m - 1; - else if (needle > straw) - l = m + 1; - else { - return m; - } - } - break; - } - - case 2: { - stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2); - stbtt_uint8 *rangeArray = coverageTable + 4; - - // Binary search. - stbtt_int32 l=0, r=rangeCount-1, m; - int strawStart, strawEnd, needle=glyph; - while (l <= r) { - stbtt_uint8 *rangeRecord; - m = (l + r) >> 1; - rangeRecord = rangeArray + 6 * m; - strawStart = ttUSHORT(rangeRecord); - strawEnd = ttUSHORT(rangeRecord + 2); - if (needle < strawStart) - r = m - 1; - else if (needle > strawEnd) - l = m + 1; - else { - stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4); - return startCoverageIndex + glyph - strawStart; - } - } - break; - } - - default: return -1; // unsupported - } - - return -1; -} - -static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph) -{ - stbtt_uint16 classDefFormat = ttUSHORT(classDefTable); - switch (classDefFormat) - { - case 1: { - stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2); - stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4); - stbtt_uint8 *classDef1ValueArray = classDefTable + 6; - - if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount) - return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID)); - break; - } - - case 2: { - stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2); - stbtt_uint8 *classRangeRecords = classDefTable + 4; - - // Binary search. - stbtt_int32 l=0, r=classRangeCount-1, m; - int strawStart, strawEnd, needle=glyph; - while (l <= r) { - stbtt_uint8 *classRangeRecord; - m = (l + r) >> 1; - classRangeRecord = classRangeRecords + 6 * m; - strawStart = ttUSHORT(classRangeRecord); - strawEnd = ttUSHORT(classRangeRecord + 2); - if (needle < strawStart) - r = m - 1; - else if (needle > strawEnd) - l = m + 1; - else - return (stbtt_int32)ttUSHORT(classRangeRecord + 4); - } - break; - } - - default: - return -1; // Unsupported definition type, return an error. - } - - // "All glyphs not assigned to a class fall into class 0". (OpenType spec) - return 0; -} - -// Define to STBTT_assert(x) if you want to break on unimplemented formats. -#define STBTT_GPOS_TODO_assert(x) - -static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) -{ - stbtt_uint16 lookupListOffset; - stbtt_uint8 *lookupList; - stbtt_uint16 lookupCount; - stbtt_uint8 *data; - stbtt_int32 i, sti; - - if (!info->gpos) return 0; - - data = info->data + info->gpos; - - if (ttUSHORT(data+0) != 1) return 0; // Major version 1 - if (ttUSHORT(data+2) != 0) return 0; // Minor version 0 - - lookupListOffset = ttUSHORT(data+8); - lookupList = data + lookupListOffset; - lookupCount = ttUSHORT(lookupList); - - for (i=0; i= pairSetCount) return 0; - - needle=glyph2; - r=pairValueCount-1; - l=0; - - // Binary search. - while (l <= r) { - stbtt_uint16 secondGlyph; - stbtt_uint8 *pairValue; - m = (l + r) >> 1; - pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m; - secondGlyph = ttUSHORT(pairValue); - straw = secondGlyph; - if (needle < straw) - r = m - 1; - else if (needle > straw) - l = m + 1; - else { - stbtt_int16 xAdvance = ttSHORT(pairValue + 2); - return xAdvance; - } - } - } else - return 0; - break; - } - - case 2: { - stbtt_uint16 valueFormat1 = ttUSHORT(table + 4); - stbtt_uint16 valueFormat2 = ttUSHORT(table + 6); - if (valueFormat1 == 4 && valueFormat2 == 0) { // Support more formats? - stbtt_uint16 classDef1Offset = ttUSHORT(table + 8); - stbtt_uint16 classDef2Offset = ttUSHORT(table + 10); - int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1); - int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2); - - stbtt_uint16 class1Count = ttUSHORT(table + 12); - stbtt_uint16 class2Count = ttUSHORT(table + 14); - stbtt_uint8 *class1Records, *class2Records; - stbtt_int16 xAdvance; - - if (glyph1class < 0 || glyph1class >= class1Count) return 0; // malformed - if (glyph2class < 0 || glyph2class >= class2Count) return 0; // malformed - - class1Records = table + 16; - class2Records = class1Records + 2 * (glyph1class * class2Count); - xAdvance = ttSHORT(class2Records + 2 * glyph2class); - return xAdvance; - } else - return 0; - break; - } - - default: - return 0; // Unsupported position format - } - } - } - - return 0; -} - -STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2) -{ - int xAdvance = 0; - - if (info->gpos) - xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2); - else if (info->kern) - xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2); - - return xAdvance; -} - -STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2) -{ - if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs - return 0; - return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2)); -} - -STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing) -{ - stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing); -} - -STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap) -{ - if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4); - if (descent) *descent = ttSHORT(info->data+info->hhea + 6); - if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8); -} - -STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap) -{ - int tab = stbtt__find_table(info->data, info->fontstart, "OS/2"); - if (!tab) - return 0; - if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68); - if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70); - if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72); - return 1; -} - -STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1) -{ - *x0 = ttSHORT(info->data + info->head + 36); - *y0 = ttSHORT(info->data + info->head + 38); - *x1 = ttSHORT(info->data + info->head + 40); - *y1 = ttSHORT(info->data + info->head + 42); -} - -STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) -{ - int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); - return (float) height / fheight; -} - -STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) -{ - int unitsPerEm = ttUSHORT(info->data + info->head + 18); - return pixels / unitsPerEm; -} - -STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v) -{ - STBTT_free(v, info->userdata); -} - -STBTT_DEF stbtt_uint8 *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl) -{ - int i; - stbtt_uint8 *data = info->data; - stbtt_uint8 *svg_doc_list = data + stbtt__get_svg((stbtt_fontinfo *) info); - - int numEntries = ttUSHORT(svg_doc_list); - stbtt_uint8 *svg_docs = svg_doc_list + 2; - - for(i=0; i= ttUSHORT(svg_doc)) && (gl <= ttUSHORT(svg_doc + 2))) - return svg_doc; - } - return 0; -} - -STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg) -{ - stbtt_uint8 *data = info->data; - stbtt_uint8 *svg_doc; - - if (info->svg == 0) - return 0; - - svg_doc = stbtt_FindSVGDoc(info, gl); - if (svg_doc != NULL) { - *svg = (char *) data + info->svg + ttULONG(svg_doc + 4); - return ttULONG(svg_doc + 8); - } else { - return 0; - } -} - -STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg) -{ - return stbtt_GetGlyphSVG(info, stbtt_FindGlyphIndex(info, unicode_codepoint), svg); -} - -////////////////////////////////////////////////////////////////////////////// -// -// antialiasing software rasterizer -// - -STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) -{ - int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning - if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) { - // e.g. space character - if (ix0) *ix0 = 0; - if (iy0) *iy0 = 0; - if (ix1) *ix1 = 0; - if (iy1) *iy1 = 0; - } else { - // move to integral bboxes (treating pixels as little squares, what pixels get touched)? - if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x); - if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y); - if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x); - if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y); - } -} - -STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) -{ - stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1); -} - -STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) -{ - stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1); -} - -STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) -{ - stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1); -} - -////////////////////////////////////////////////////////////////////////////// -// -// Rasterizer - -typedef struct stbtt__hheap_chunk -{ - struct stbtt__hheap_chunk *next; -} stbtt__hheap_chunk; - -typedef struct stbtt__hheap -{ - struct stbtt__hheap_chunk *head; - void *first_free; - int num_remaining_in_head_chunk; -} stbtt__hheap; - -static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata) -{ - if (hh->first_free) { - void *p = hh->first_free; - hh->first_free = * (void **) p; - return p; - } else { - if (hh->num_remaining_in_head_chunk == 0) { - int count = (size < 32 ? 2000 : size < 128 ? 800 : 100); - stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata); - if (c == NULL) - return NULL; - c->next = hh->head; - hh->head = c; - hh->num_remaining_in_head_chunk = count; - } - --hh->num_remaining_in_head_chunk; - return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk; - } -} - -static void stbtt__hheap_free(stbtt__hheap *hh, void *p) -{ - *(void **) p = hh->first_free; - hh->first_free = p; -} - -static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata) -{ - stbtt__hheap_chunk *c = hh->head; - while (c) { - stbtt__hheap_chunk *n = c->next; - STBTT_free(c, userdata); - c = n; - } -} - -typedef struct stbtt__edge { - float x0,y0, x1,y1; - int invert; -} stbtt__edge; - - -typedef struct stbtt__active_edge -{ - struct stbtt__active_edge *next; - #if STBTT_RASTERIZER_VERSION==1 - int x,dx; - float ey; - int direction; - #elif STBTT_RASTERIZER_VERSION==2 - float fx,fdx,fdy; - float direction; - float sy; - float ey; - #else - #error "Unrecognized value of STBTT_RASTERIZER_VERSION" - #endif -} stbtt__active_edge; - -#if STBTT_RASTERIZER_VERSION == 1 -#define STBTT_FIXSHIFT 10 -#define STBTT_FIX (1 << STBTT_FIXSHIFT) -#define STBTT_FIXMASK (STBTT_FIX-1) - -static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) -{ - stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); - float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); - STBTT_assert(z != NULL); - if (!z) return z; - - // round dx down to avoid overshooting - if (dxdy < 0) - z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy); - else - z->dx = STBTT_ifloor(STBTT_FIX * dxdy); - - z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount - z->x -= off_x * STBTT_FIX; - - z->ey = e->y1; - z->next = 0; - z->direction = e->invert ? 1 : -1; - return z; -} -#elif STBTT_RASTERIZER_VERSION == 2 -static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) -{ - stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); - float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); - STBTT_assert(z != NULL); - //STBTT_assert(e->y0 <= start_point); - if (!z) return z; - z->fdx = dxdy; - z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f; - z->fx = e->x0 + dxdy * (start_point - e->y0); - z->fx -= off_x; - z->direction = e->invert ? 1.0f : -1.0f; - z->sy = e->y0; - z->ey = e->y1; - z->next = 0; - return z; -} -#else -#error "Unrecognized value of STBTT_RASTERIZER_VERSION" -#endif - -#if STBTT_RASTERIZER_VERSION == 1 -// note: this routine clips fills that extend off the edges... ideally this -// wouldn't happen, but it could happen if the truetype glyph bounding boxes -// are wrong, or if the user supplies a too-small bitmap -static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight) -{ - // non-zero winding fill - int x0=0, w=0; - - while (e) { - if (w == 0) { - // if we're currently at zero, we need to record the edge start point - x0 = e->x; w += e->direction; - } else { - int x1 = e->x; w += e->direction; - // if we went to zero, we need to draw - if (w == 0) { - int i = x0 >> STBTT_FIXSHIFT; - int j = x1 >> STBTT_FIXSHIFT; - - if (i < len && j >= 0) { - if (i == j) { - // x0,x1 are the same pixel, so compute combined coverage - scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT); - } else { - if (i >= 0) // add antialiasing for x0 - scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT); - else - i = -1; // clip - - if (j < len) // add antialiasing for x1 - scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT); - else - j = len; // clip - - for (++i; i < j; ++i) // fill pixels between x0 and x1 - scanline[i] = scanline[i] + (stbtt_uint8) max_weight; - } - } - } - } - - e = e->next; - } -} - -static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) -{ - stbtt__hheap hh = { 0, 0, 0 }; - stbtt__active_edge *active = NULL; - int y,j=0; - int max_weight = (255 / vsubsample); // weight per vertical scanline - int s; // vertical subsample index - unsigned char scanline_data[512], *scanline; - - if (result->w > 512) - scanline = (unsigned char *) STBTT_malloc(result->w, userdata); - else - scanline = scanline_data; - - y = off_y * vsubsample; - e[n].y0 = (off_y + result->h) * (float) vsubsample + 1; - - while (j < result->h) { - STBTT_memset(scanline, 0, result->w); - for (s=0; s < vsubsample; ++s) { - // find center of pixel for this scanline - float scan_y = y + 0.5f; - stbtt__active_edge **step = &active; - - // update all active edges; - // remove all active edges that terminate before the center of this scanline - while (*step) { - stbtt__active_edge * z = *step; - if (z->ey <= scan_y) { - *step = z->next; // delete from list - STBTT_assert(z->direction); - z->direction = 0; - stbtt__hheap_free(&hh, z); - } else { - z->x += z->dx; // advance to position for current scanline - step = &((*step)->next); // advance through list - } - } - - // resort the list if needed - for(;;) { - int changed=0; - step = &active; - while (*step && (*step)->next) { - if ((*step)->x > (*step)->next->x) { - stbtt__active_edge *t = *step; - stbtt__active_edge *q = t->next; - - t->next = q->next; - q->next = t; - *step = q; - changed = 1; - } - step = &(*step)->next; - } - if (!changed) break; - } - - // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline - while (e->y0 <= scan_y) { - if (e->y1 > scan_y) { - stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata); - if (z != NULL) { - // find insertion point - if (active == NULL) - active = z; - else if (z->x < active->x) { - // insert at front - z->next = active; - active = z; - } else { - // find thing to insert AFTER - stbtt__active_edge *p = active; - while (p->next && p->next->x < z->x) - p = p->next; - // at this point, p->next->x is NOT < z->x - z->next = p->next; - p->next = z; - } - } - } - ++e; - } - - // now process all active edges in XOR fashion - if (active) - stbtt__fill_active_edges(scanline, result->w, active, max_weight); - - ++y; - } - STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w); - ++j; - } - - stbtt__hheap_cleanup(&hh, userdata); - - if (scanline != scanline_data) - STBTT_free(scanline, userdata); -} - -#elif STBTT_RASTERIZER_VERSION == 2 - -// the edge passed in here does not cross the vertical line at x or the vertical line at x+1 -// (i.e. it has already been clipped to those) -static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1) -{ - if (y0 == y1) return; - STBTT_assert(y0 < y1); - STBTT_assert(e->sy <= e->ey); - if (y0 > e->ey) return; - if (y1 < e->sy) return; - if (y0 < e->sy) { - x0 += (x1-x0) * (e->sy - y0) / (y1-y0); - y0 = e->sy; - } - if (y1 > e->ey) { - x1 += (x1-x0) * (e->ey - y1) / (y1-y0); - y1 = e->ey; - } - - if (x0 == x) - STBTT_assert(x1 <= x+1); - else if (x0 == x+1) - STBTT_assert(x1 >= x); - else if (x0 <= x) - STBTT_assert(x1 <= x); - else if (x0 >= x+1) - STBTT_assert(x1 >= x+1); - else - STBTT_assert(x1 >= x && x1 <= x+1); - - if (x0 <= x && x1 <= x) - scanline[x] += e->direction * (y1-y0); - else if (x0 >= x+1 && x1 >= x+1) - ; - else { - STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1); - scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position - } -} - -static float stbtt__sized_trapezoid_area(float height, float top_width, float bottom_width) -{ - STBTT_assert(top_width >= 0); - STBTT_assert(bottom_width >= 0); - return (top_width + bottom_width) / 2.0f * height; -} - -static float stbtt__position_trapezoid_area(float height, float tx0, float tx1, float bx0, float bx1) -{ - return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0); -} - -static float stbtt__sized_triangle_area(float height, float width) -{ - return height * width / 2; -} - -static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top) -{ - float y_bottom = y_top+1; - - while (e) { - // brute force every pixel - - // compute intersection points with top & bottom - STBTT_assert(e->ey >= y_top); - - if (e->fdx == 0) { - float x0 = e->fx; - if (x0 < len) { - if (x0 >= 0) { - stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom); - stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom); - } else { - stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom); - } - } - } else { - float x0 = e->fx; - float dx = e->fdx; - float xb = x0 + dx; - float x_top, x_bottom; - float sy0,sy1; - float dy = e->fdy; - STBTT_assert(e->sy <= y_bottom && e->ey >= y_top); - - // compute endpoints of line segment clipped to this scanline (if the - // line segment starts on this scanline. x0 is the intersection of the - // line with y_top, but that may be off the line segment. - if (e->sy > y_top) { - x_top = x0 + dx * (e->sy - y_top); - sy0 = e->sy; - } else { - x_top = x0; - sy0 = y_top; - } - if (e->ey < y_bottom) { - x_bottom = x0 + dx * (e->ey - y_top); - sy1 = e->ey; - } else { - x_bottom = xb; - sy1 = y_bottom; - } - - if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) { - // from here on, we don't have to range check x values - - if ((int) x_top == (int) x_bottom) { - float height; - // simple case, only spans one pixel - int x = (int) x_top; - height = (sy1 - sy0) * e->direction; - STBTT_assert(x >= 0 && x < len); - scanline[x] += stbtt__position_trapezoid_area(height, x_top, x+1.0f, x_bottom, x+1.0f); - scanline_fill[x] += height; // everything right of this pixel is filled - } else { - int x,x1,x2; - float y_crossing, y_final, step, sign, area; - // covers 2+ pixels - if (x_top > x_bottom) { - // flip scanline vertically; signed area is the same - float t; - sy0 = y_bottom - (sy0 - y_top); - sy1 = y_bottom - (sy1 - y_top); - t = sy0, sy0 = sy1, sy1 = t; - t = x_bottom, x_bottom = x_top, x_top = t; - dx = -dx; - dy = -dy; - t = x0, x0 = xb, xb = t; - } - STBTT_assert(dy >= 0); - STBTT_assert(dx >= 0); - - x1 = (int) x_top; - x2 = (int) x_bottom; - // compute intersection with y axis at x1+1 - y_crossing = y_top + dy * (x1+1 - x0); - - // compute intersection with y axis at x2 - y_final = y_top + dy * (x2 - x0); - - // x1 x_top x2 x_bottom - // y_top +------|-----+------------+------------+--------|---+------------+ - // | | | | | | - // | | | | | | - // sy0 | Txxxxx|............|............|............|............| - // y_crossing | *xxxxx.......|............|............|............| - // | | xxxxx..|............|............|............| - // | | /- xx*xxxx........|............|............| - // | | dy < | xxxxxx..|............|............| - // y_final | | \- | xx*xxx.........|............| - // sy1 | | | | xxxxxB...|............| - // | | | | | | - // | | | | | | - // y_bottom +------------+------------+------------+------------+------------+ - // - // goal is to measure the area covered by '.' in each pixel - - // if x2 is right at the right edge of x1, y_crossing can blow up, github #1057 - // @TODO: maybe test against sy1 rather than y_bottom? - if (y_crossing > y_bottom) - y_crossing = y_bottom; - - sign = e->direction; - - // area of the rectangle covered from sy0..y_crossing - area = sign * (y_crossing-sy0); - - // area of the triangle (x_top,sy0), (x1+1,sy0), (x1+1,y_crossing) - scanline[x1] += stbtt__sized_triangle_area(area, x1+1 - x_top); - - // check if final y_crossing is blown up; no test case for this - if (y_final > y_bottom) { - int denom = (x2 - (x1+1)); - y_final = y_bottom; - if (denom != 0) { // [DEAR IMGUI] Avoid div by zero (https://github.com/nothings/stb/issues/1316) - dy = (y_final - y_crossing ) / denom; // if denom=0, y_final = y_crossing, so y_final <= y_bottom - } - } - - // in second pixel, area covered by line segment found in first pixel - // is always a rectangle 1 wide * the height of that line segment; this - // is exactly what the variable 'area' stores. it also gets a contribution - // from the line segment within it. the THIRD pixel will get the first - // pixel's rectangle contribution, the second pixel's rectangle contribution, - // and its own contribution. the 'own contribution' is the same in every pixel except - // the leftmost and rightmost, a trapezoid that slides down in each pixel. - // the second pixel's contribution to the third pixel will be the - // rectangle 1 wide times the height change in the second pixel, which is dy. - - step = sign * dy * 1; // dy is dy/dx, change in y for every 1 change in x, - // which multiplied by 1-pixel-width is how much pixel area changes for each step in x - // so the area advances by 'step' every time - - for (x = x1+1; x < x2; ++x) { - scanline[x] += area + step/2; // area of trapezoid is 1*step/2 - area += step; - } - STBTT_assert(STBTT_fabs(area) <= 1.01f); // accumulated error from area += step unless we round step down - STBTT_assert(sy1 > y_final-0.01f); - - // area covered in the last pixel is the rectangle from all the pixels to the left, - // plus the trapezoid filled by the line segment in this pixel all the way to the right edge - scanline[x2] += area + sign * stbtt__position_trapezoid_area(sy1-y_final, (float) x2, x2+1.0f, x_bottom, x2+1.0f); - - // the rest of the line is filled based on the total height of the line segment in this pixel - scanline_fill[x2] += sign * (sy1-sy0); - } - } else { - // if edge goes outside of box we're drawing, we require - // clipping logic. since this does not match the intended use - // of this library, we use a different, very slow brute - // force implementation - // note though that this does happen some of the time because - // x_top and x_bottom can be extrapolated at the top & bottom of - // the shape and actually lie outside the bounding box - int x; - for (x=0; x < len; ++x) { - // cases: - // - // there can be up to two intersections with the pixel. any intersection - // with left or right edges can be handled by splitting into two (or three) - // regions. intersections with top & bottom do not necessitate case-wise logic. - // - // the old way of doing this found the intersections with the left & right edges, - // then used some simple logic to produce up to three segments in sorted order - // from top-to-bottom. however, this had a problem: if an x edge was epsilon - // across the x border, then the corresponding y position might not be distinct - // from the other y segment, and it might ignored as an empty segment. to avoid - // that, we need to explicitly produce segments based on x positions. - - // rename variables to clearly-defined pairs - float y0 = y_top; - float x1 = (float) (x); - float x2 = (float) (x+1); - float x3 = xb; - float y3 = y_bottom; - - // x = e->x + e->dx * (y-y_top) - // (y-y_top) = (x - e->x) / e->dx - // y = (x - e->x) / e->dx + y_top - float y1 = (x - x0) / dx + y_top; - float y2 = (x+1 - x0) / dx + y_top; - - if (x0 < x1 && x3 > x2) { // three segments descending down-right - stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); - stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2); - stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); - } else if (x3 < x1 && x0 > x2) { // three segments descending down-left - stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); - stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1); - stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); - } else if (x0 < x1 && x3 > x1) { // two segments across x, down-right - stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); - stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); - } else if (x3 < x1 && x0 > x1) { // two segments across x, down-left - stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); - stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); - } else if (x0 < x2 && x3 > x2) { // two segments across x+1, down-right - stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); - stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); - } else if (x3 < x2 && x0 > x2) { // two segments across x+1, down-left - stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); - stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); - } else { // one segment - stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3); - } - } - } - } - e = e->next; - } -} - -// directly AA rasterize edges w/o supersampling -static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) -{ - stbtt__hheap hh = { 0, 0, 0 }; - stbtt__active_edge *active = NULL; - int y,j=0, i; - float scanline_data[129], *scanline, *scanline2; - - STBTT__NOTUSED(vsubsample); - - if (result->w > 64) - scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata); - else - scanline = scanline_data; - - scanline2 = scanline + result->w; - - y = off_y; - e[n].y0 = (float) (off_y + result->h) + 1; - - while (j < result->h) { - // find center of pixel for this scanline - float scan_y_top = y + 0.0f; - float scan_y_bottom = y + 1.0f; - stbtt__active_edge **step = &active; - - STBTT_memset(scanline , 0, result->w*sizeof(scanline[0])); - STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0])); - - // update all active edges; - // remove all active edges that terminate before the top of this scanline - while (*step) { - stbtt__active_edge * z = *step; - if (z->ey <= scan_y_top) { - *step = z->next; // delete from list - STBTT_assert(z->direction); - z->direction = 0; - stbtt__hheap_free(&hh, z); - } else { - step = &((*step)->next); // advance through list - } - } - - // insert all edges that start before the bottom of this scanline - while (e->y0 <= scan_y_bottom) { - if (e->y0 != e->y1) { - stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata); - if (z != NULL) { - if (j == 0 && off_y != 0) { - if (z->ey < scan_y_top) { - // this can happen due to subpixel positioning and some kind of fp rounding error i think - z->ey = scan_y_top; - } - } - STBTT_assert(z->ey >= scan_y_top); // if we get really unlucky a tiny bit of an edge can be out of bounds - // insert at front - z->next = active; - active = z; - } - } - ++e; - } - - // now process all active edges - if (active) - stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top); - - { - float sum = 0; - for (i=0; i < result->w; ++i) { - float k; - int m; - sum += scanline2[i]; - k = scanline[i] + sum; - k = (float) STBTT_fabs(k)*255 + 0.5f; - m = (int) k; - if (m > 255) m = 255; - result->pixels[j*result->stride + i] = (unsigned char) m; - } - } - // advance all the edges - step = &active; - while (*step) { - stbtt__active_edge *z = *step; - z->fx += z->fdx; // advance to position for current scanline - step = &((*step)->next); // advance through list - } - - ++y; - ++j; - } - - stbtt__hheap_cleanup(&hh, userdata); - - if (scanline != scanline_data) - STBTT_free(scanline, userdata); -} -#else -#error "Unrecognized value of STBTT_RASTERIZER_VERSION" -#endif - -#define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0) - -static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n) -{ - int i,j; - for (i=1; i < n; ++i) { - stbtt__edge t = p[i], *a = &t; - j = i; - while (j > 0) { - stbtt__edge *b = &p[j-1]; - int c = STBTT__COMPARE(a,b); - if (!c) break; - p[j] = p[j-1]; - --j; - } - if (i != j) - p[j] = t; - } -} - -static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n) -{ - /* threshold for transitioning to insertion sort */ - while (n > 12) { - stbtt__edge t; - int c01,c12,c,m,i,j; - - /* compute median of three */ - m = n >> 1; - c01 = STBTT__COMPARE(&p[0],&p[m]); - c12 = STBTT__COMPARE(&p[m],&p[n-1]); - /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ - if (c01 != c12) { - /* otherwise, we'll need to swap something else to middle */ - int z; - c = STBTT__COMPARE(&p[0],&p[n-1]); - /* 0>mid && midn => n; 0 0 */ - /* 0n: 0>n => 0; 0 n */ - z = (c == c12) ? 0 : n-1; - t = p[z]; - p[z] = p[m]; - p[m] = t; - } - /* now p[m] is the median-of-three */ - /* swap it to the beginning so it won't move around */ - t = p[0]; - p[0] = p[m]; - p[m] = t; - - /* partition loop */ - i=1; - j=n-1; - for(;;) { - /* handling of equality is crucial here */ - /* for sentinels & efficiency with duplicates */ - for (;;++i) { - if (!STBTT__COMPARE(&p[i], &p[0])) break; - } - for (;;--j) { - if (!STBTT__COMPARE(&p[0], &p[j])) break; - } - /* make sure we haven't crossed */ - if (i >= j) break; - t = p[i]; - p[i] = p[j]; - p[j] = t; - - ++i; - --j; - } - /* recurse on smaller side, iterate on larger */ - if (j < (n-i)) { - stbtt__sort_edges_quicksort(p,j); - p = p+i; - n = n-i; - } else { - stbtt__sort_edges_quicksort(p+i, n-i); - n = j; - } - } -} - -static void stbtt__sort_edges(stbtt__edge *p, int n) -{ - stbtt__sort_edges_quicksort(p, n); - stbtt__sort_edges_ins_sort(p, n); -} - -typedef struct -{ - float x,y; -} stbtt__point; - -static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata) -{ - float y_scale_inv = invert ? -scale_y : scale_y; - stbtt__edge *e; - int n,i,j,k,m; -#if STBTT_RASTERIZER_VERSION == 1 - int vsubsample = result->h < 8 ? 15 : 5; -#elif STBTT_RASTERIZER_VERSION == 2 - int vsubsample = 1; -#else - #error "Unrecognized value of STBTT_RASTERIZER_VERSION" -#endif - // vsubsample should divide 255 evenly; otherwise we won't reach full opacity - - // now we have to blow out the windings into explicit edge lists - n = 0; - for (i=0; i < windings; ++i) - n += wcount[i]; - - e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel - if (e == 0) return; - n = 0; - - m=0; - for (i=0; i < windings; ++i) { - stbtt__point *p = pts + m; - m += wcount[i]; - j = wcount[i]-1; - for (k=0; k < wcount[i]; j=k++) { - int a=k,b=j; - // skip the edge if horizontal - if (p[j].y == p[k].y) - continue; - // add edge from j to k to the list - e[n].invert = 0; - if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) { - e[n].invert = 1; - a=j,b=k; - } - e[n].x0 = p[a].x * scale_x + shift_x; - e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample; - e[n].x1 = p[b].x * scale_x + shift_x; - e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample; - ++n; - } - } - - // now sort the edges by their highest point (should snap to integer, and then by x) - //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); - stbtt__sort_edges(e, n); - - // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule - stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata); - - STBTT_free(e, userdata); -} - -static void stbtt__add_point(stbtt__point *points, int n, float x, float y) -{ - if (!points) return; // during first pass, it's unallocated - points[n].x = x; - points[n].y = y; -} - -// tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching -static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n) -{ - // midpoint - float mx = (x0 + 2*x1 + x2)/4; - float my = (y0 + 2*y1 + y2)/4; - // versus directly drawn line - float dx = (x0+x2)/2 - mx; - float dy = (y0+y2)/2 - my; - if (n > 16) // 65536 segments on one curve better be enough! - return 1; - if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA - stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1); - stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1); - } else { - stbtt__add_point(points, *num_points,x2,y2); - *num_points = *num_points+1; - } - return 1; -} - -static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n) -{ - // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough - float dx0 = x1-x0; - float dy0 = y1-y0; - float dx1 = x2-x1; - float dy1 = y2-y1; - float dx2 = x3-x2; - float dy2 = y3-y2; - float dx = x3-x0; - float dy = y3-y0; - float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2)); - float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy); - float flatness_squared = longlen*longlen-shortlen*shortlen; - - if (n > 16) // 65536 segments on one curve better be enough! - return; - - if (flatness_squared > objspace_flatness_squared) { - float x01 = (x0+x1)/2; - float y01 = (y0+y1)/2; - float x12 = (x1+x2)/2; - float y12 = (y1+y2)/2; - float x23 = (x2+x3)/2; - float y23 = (y2+y3)/2; - - float xa = (x01+x12)/2; - float ya = (y01+y12)/2; - float xb = (x12+x23)/2; - float yb = (y12+y23)/2; - - float mx = (xa+xb)/2; - float my = (ya+yb)/2; - - stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1); - stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1); - } else { - stbtt__add_point(points, *num_points,x3,y3); - *num_points = *num_points+1; - } -} - -// returns number of contours -static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata) -{ - stbtt__point *points=0; - int num_points=0; - - float objspace_flatness_squared = objspace_flatness * objspace_flatness; - int i,n=0,start=0, pass; - - // count how many "moves" there are to get the contour count - for (i=0; i < num_verts; ++i) - if (vertices[i].type == STBTT_vmove) - ++n; - - *num_contours = n; - if (n == 0) return 0; - - *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata); - - if (*contour_lengths == 0) { - *num_contours = 0; - return 0; - } - - // make two passes through the points so we don't need to realloc - for (pass=0; pass < 2; ++pass) { - float x=0,y=0; - if (pass == 1) { - points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata); - if (points == NULL) goto error; - } - num_points = 0; - n= -1; - for (i=0; i < num_verts; ++i) { - switch (vertices[i].type) { - case STBTT_vmove: - // start the next contour - if (n >= 0) - (*contour_lengths)[n] = num_points - start; - ++n; - start = num_points; - - x = vertices[i].x, y = vertices[i].y; - stbtt__add_point(points, num_points++, x,y); - break; - case STBTT_vline: - x = vertices[i].x, y = vertices[i].y; - stbtt__add_point(points, num_points++, x, y); - break; - case STBTT_vcurve: - stbtt__tesselate_curve(points, &num_points, x,y, - vertices[i].cx, vertices[i].cy, - vertices[i].x, vertices[i].y, - objspace_flatness_squared, 0); - x = vertices[i].x, y = vertices[i].y; - break; - case STBTT_vcubic: - stbtt__tesselate_cubic(points, &num_points, x,y, - vertices[i].cx, vertices[i].cy, - vertices[i].cx1, vertices[i].cy1, - vertices[i].x, vertices[i].y, - objspace_flatness_squared, 0); - x = vertices[i].x, y = vertices[i].y; - break; - } - } - (*contour_lengths)[n] = num_points - start; - } - - return points; -error: - STBTT_free(points, userdata); - STBTT_free(*contour_lengths, userdata); - *contour_lengths = 0; - *num_contours = 0; - return NULL; -} - -STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata) -{ - float scale = scale_x > scale_y ? scale_y : scale_x; - int winding_count = 0; - int *winding_lengths = NULL; - stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata); - if (windings) { - stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata); - STBTT_free(winding_lengths, userdata); - STBTT_free(windings, userdata); - } -} - -STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata) -{ - STBTT_free(bitmap, userdata); -} - -STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff) -{ - int ix0,iy0,ix1,iy1; - stbtt__bitmap gbm; - stbtt_vertex *vertices; - int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); - - if (scale_x == 0) scale_x = scale_y; - if (scale_y == 0) { - if (scale_x == 0) { - STBTT_free(vertices, info->userdata); - return NULL; - } - scale_y = scale_x; - } - - stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1); - - // now we get the size - gbm.w = (ix1 - ix0); - gbm.h = (iy1 - iy0); - gbm.pixels = NULL; // in case we error - - if (width ) *width = gbm.w; - if (height) *height = gbm.h; - if (xoff ) *xoff = ix0; - if (yoff ) *yoff = iy0; - - if (gbm.w && gbm.h) { - gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata); - if (gbm.pixels) { - gbm.stride = gbm.w; - - stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata); - } - } - STBTT_free(vertices, info->userdata); - return gbm.pixels; -} - -STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff) -{ - return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff); -} - -STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph) -{ - int ix0,iy0; - stbtt_vertex *vertices; - int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); - stbtt__bitmap gbm; - - stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0); - gbm.pixels = output; - gbm.w = out_w; - gbm.h = out_h; - gbm.stride = out_stride; - - if (gbm.w && gbm.h) - stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata); - - STBTT_free(vertices, info->userdata); -} - -STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph) -{ - stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph); -} - -STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff) -{ - return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff); -} - -STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint) -{ - stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint)); -} - -STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint) -{ - stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint)); -} - -STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff) -{ - return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff); -} - -STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint) -{ - stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint); -} - -////////////////////////////////////////////////////////////////////////////// -// -// bitmap baking -// -// This is SUPER-CRAPPY packing to keep source code small - -static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) - float pixel_height, // height of font in pixels - unsigned char *pixels, int pw, int ph, // bitmap to be filled in - int first_char, int num_chars, // characters to bake - stbtt_bakedchar *chardata) -{ - float scale; - int x,y,bottom_y, i; - stbtt_fontinfo f; - f.userdata = NULL; - if (!stbtt_InitFont(&f, data, offset)) - return -1; - STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels - x=y=1; - bottom_y = 1; - - scale = stbtt_ScaleForPixelHeight(&f, pixel_height); - - for (i=0; i < num_chars; ++i) { - int advance, lsb, x0,y0,x1,y1,gw,gh; - int g = stbtt_FindGlyphIndex(&f, first_char + i); - stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb); - stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1); - gw = x1-x0; - gh = y1-y0; - if (x + gw + 1 >= pw) - y = bottom_y, x = 1; // advance to next row - if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row - return -i; - STBTT_assert(x+gw < pw); - STBTT_assert(y+gh < ph); - stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g); - chardata[i].x0 = (stbtt_int16) x; - chardata[i].y0 = (stbtt_int16) y; - chardata[i].x1 = (stbtt_int16) (x + gw); - chardata[i].y1 = (stbtt_int16) (y + gh); - chardata[i].xadvance = scale * advance; - chardata[i].xoff = (float) x0; - chardata[i].yoff = (float) y0; - x = x + gw + 1; - if (y+gh+1 > bottom_y) - bottom_y = y+gh+1; - } - return bottom_y; -} - -STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule) -{ - float d3d_bias = opengl_fillrule ? 0 : -0.5f; - float ipw = 1.0f / pw, iph = 1.0f / ph; - const stbtt_bakedchar *b = chardata + char_index; - int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f); - int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f); - - q->x0 = round_x + d3d_bias; - q->y0 = round_y + d3d_bias; - q->x1 = round_x + b->x1 - b->x0 + d3d_bias; - q->y1 = round_y + b->y1 - b->y0 + d3d_bias; - - q->s0 = b->x0 * ipw; - q->t0 = b->y0 * iph; - q->s1 = b->x1 * ipw; - q->t1 = b->y1 * iph; - - *xpos += b->xadvance; -} - -////////////////////////////////////////////////////////////////////////////// -// -// rectangle packing replacement routines if you don't have stb_rect_pack.h -// - -#ifndef STB_RECT_PACK_VERSION - -typedef int stbrp_coord; - -//////////////////////////////////////////////////////////////////////////////////// -// // -// // -// COMPILER WARNING ?!?!? // -// // -// // -// if you get a compile warning due to these symbols being defined more than // -// once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" // -// // -//////////////////////////////////////////////////////////////////////////////////// - -typedef struct -{ - int width,height; - int x,y,bottom_y; -} stbrp_context; - -typedef struct -{ - unsigned char x; -} stbrp_node; - -struct stbrp_rect -{ - stbrp_coord x,y; - int id,w,h,was_packed; -}; - -static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes) -{ - con->width = pw; - con->height = ph; - con->x = 0; - con->y = 0; - con->bottom_y = 0; - STBTT__NOTUSED(nodes); - STBTT__NOTUSED(num_nodes); -} - -static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects) -{ - int i; - for (i=0; i < num_rects; ++i) { - if (con->x + rects[i].w > con->width) { - con->x = 0; - con->y = con->bottom_y; - } - if (con->y + rects[i].h > con->height) - break; - rects[i].x = con->x; - rects[i].y = con->y; - rects[i].was_packed = 1; - con->x += rects[i].w; - if (con->y + rects[i].h > con->bottom_y) - con->bottom_y = con->y + rects[i].h; - } - for ( ; i < num_rects; ++i) - rects[i].was_packed = 0; -} -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// bitmap baking -// -// This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If -// stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy. - -STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context) -{ - stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context); - int num_nodes = pw - padding; - stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context); - - if (context == NULL || nodes == NULL) { - if (context != NULL) STBTT_free(context, alloc_context); - if (nodes != NULL) STBTT_free(nodes , alloc_context); - return 0; - } - - spc->user_allocator_context = alloc_context; - spc->width = pw; - spc->height = ph; - spc->pixels = pixels; - spc->pack_info = context; - spc->nodes = nodes; - spc->padding = padding; - spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw; - spc->h_oversample = 1; - spc->v_oversample = 1; - spc->skip_missing = 0; - - stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes); - - if (pixels) - STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels - - return 1; -} - -STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc) -{ - STBTT_free(spc->nodes , spc->user_allocator_context); - STBTT_free(spc->pack_info, spc->user_allocator_context); -} - -STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample) -{ - STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE); - STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE); - if (h_oversample <= STBTT_MAX_OVERSAMPLE) - spc->h_oversample = h_oversample; - if (v_oversample <= STBTT_MAX_OVERSAMPLE) - spc->v_oversample = v_oversample; -} - -STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip) -{ - spc->skip_missing = skip; -} - -#define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1) - -static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) -{ - unsigned char buffer[STBTT_MAX_OVERSAMPLE]; - int safe_w = w - kernel_width; - int j; - STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze - for (j=0; j < h; ++j) { - int i; - unsigned int total; - STBTT_memset(buffer, 0, kernel_width); - - total = 0; - - // make kernel_width a constant in common cases so compiler can optimize out the divide - switch (kernel_width) { - case 2: - for (i=0; i <= safe_w; ++i) { - total += pixels[i] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; - pixels[i] = (unsigned char) (total / 2); - } - break; - case 3: - for (i=0; i <= safe_w; ++i) { - total += pixels[i] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; - pixels[i] = (unsigned char) (total / 3); - } - break; - case 4: - for (i=0; i <= safe_w; ++i) { - total += pixels[i] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; - pixels[i] = (unsigned char) (total / 4); - } - break; - case 5: - for (i=0; i <= safe_w; ++i) { - total += pixels[i] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; - pixels[i] = (unsigned char) (total / 5); - } - break; - default: - for (i=0; i <= safe_w; ++i) { - total += pixels[i] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; - pixels[i] = (unsigned char) (total / kernel_width); - } - break; - } - - for (; i < w; ++i) { - STBTT_assert(pixels[i] == 0); - total -= buffer[i & STBTT__OVER_MASK]; - pixels[i] = (unsigned char) (total / kernel_width); - } - - pixels += stride_in_bytes; - } -} - -static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) -{ - unsigned char buffer[STBTT_MAX_OVERSAMPLE]; - int safe_h = h - kernel_width; - int j; - STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze - for (j=0; j < w; ++j) { - int i; - unsigned int total; - STBTT_memset(buffer, 0, kernel_width); - - total = 0; - - // make kernel_width a constant in common cases so compiler can optimize out the divide - switch (kernel_width) { - case 2: - for (i=0; i <= safe_h; ++i) { - total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; - pixels[i*stride_in_bytes] = (unsigned char) (total / 2); - } - break; - case 3: - for (i=0; i <= safe_h; ++i) { - total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; - pixels[i*stride_in_bytes] = (unsigned char) (total / 3); - } - break; - case 4: - for (i=0; i <= safe_h; ++i) { - total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; - pixels[i*stride_in_bytes] = (unsigned char) (total / 4); - } - break; - case 5: - for (i=0; i <= safe_h; ++i) { - total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; - pixels[i*stride_in_bytes] = (unsigned char) (total / 5); - } - break; - default: - for (i=0; i <= safe_h; ++i) { - total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; - pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); - } - break; - } - - for (; i < h; ++i) { - STBTT_assert(pixels[i*stride_in_bytes] == 0); - total -= buffer[i & STBTT__OVER_MASK]; - pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); - } - - pixels += 1; - } -} - -static float stbtt__oversample_shift(int oversample) -{ - if (!oversample) - return 0.0f; - - // The prefilter is a box filter of width "oversample", - // which shifts phase by (oversample - 1)/2 pixels in - // oversampled space. We want to shift in the opposite - // direction to counter this. - return (float)-(oversample - 1) / (2.0f * (float)oversample); -} - -// rects array must be big enough to accommodate all characters in the given ranges -STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) -{ - int i,j,k; - int missing_glyph_added = 0; - - k=0; - for (i=0; i < num_ranges; ++i) { - float fh = ranges[i].font_size; - float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); - ranges[i].h_oversample = (unsigned char) spc->h_oversample; - ranges[i].v_oversample = (unsigned char) spc->v_oversample; - for (j=0; j < ranges[i].num_chars; ++j) { - int x0,y0,x1,y1; - int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; - int glyph = stbtt_FindGlyphIndex(info, codepoint); - if (glyph == 0 && (spc->skip_missing || missing_glyph_added)) { - rects[k].w = rects[k].h = 0; - } else { - stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, - scale * spc->h_oversample, - scale * spc->v_oversample, - 0,0, - &x0,&y0,&x1,&y1); - rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1); - rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1); - if (glyph == 0) - missing_glyph_added = 1; - } - ++k; - } - } - - return k; -} - -STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph) -{ - stbtt_MakeGlyphBitmapSubpixel(info, - output, - out_w - (prefilter_x - 1), - out_h - (prefilter_y - 1), - out_stride, - scale_x, - scale_y, - shift_x, - shift_y, - glyph); - - if (prefilter_x > 1) - stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x); - - if (prefilter_y > 1) - stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y); - - *sub_x = stbtt__oversample_shift(prefilter_x); - *sub_y = stbtt__oversample_shift(prefilter_y); -} - -// rects array must be big enough to accommodate all characters in the given ranges -STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) -{ - int i,j,k, missing_glyph = -1, return_value = 1; - - // save current values - int old_h_over = spc->h_oversample; - int old_v_over = spc->v_oversample; - - k = 0; - for (i=0; i < num_ranges; ++i) { - float fh = ranges[i].font_size; - float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); - float recip_h,recip_v,sub_x,sub_y; - spc->h_oversample = ranges[i].h_oversample; - spc->v_oversample = ranges[i].v_oversample; - recip_h = 1.0f / spc->h_oversample; - recip_v = 1.0f / spc->v_oversample; - sub_x = stbtt__oversample_shift(spc->h_oversample); - sub_y = stbtt__oversample_shift(spc->v_oversample); - for (j=0; j < ranges[i].num_chars; ++j) { - stbrp_rect *r = &rects[k]; - if (r->was_packed && r->w != 0 && r->h != 0) { - stbtt_packedchar *bc = &ranges[i].chardata_for_range[j]; - int advance, lsb, x0,y0,x1,y1; - int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; - int glyph = stbtt_FindGlyphIndex(info, codepoint); - stbrp_coord pad = (stbrp_coord) spc->padding; - - // pad on left and top - r->x += pad; - r->y += pad; - r->w -= pad; - r->h -= pad; - stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb); - stbtt_GetGlyphBitmapBox(info, glyph, - scale * spc->h_oversample, - scale * spc->v_oversample, - &x0,&y0,&x1,&y1); - stbtt_MakeGlyphBitmapSubpixel(info, - spc->pixels + r->x + r->y*spc->stride_in_bytes, - r->w - spc->h_oversample+1, - r->h - spc->v_oversample+1, - spc->stride_in_bytes, - scale * spc->h_oversample, - scale * spc->v_oversample, - 0,0, - glyph); - - if (spc->h_oversample > 1) - stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, - r->w, r->h, spc->stride_in_bytes, - spc->h_oversample); - - if (spc->v_oversample > 1) - stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, - r->w, r->h, spc->stride_in_bytes, - spc->v_oversample); - - bc->x0 = (stbtt_int16) r->x; - bc->y0 = (stbtt_int16) r->y; - bc->x1 = (stbtt_int16) (r->x + r->w); - bc->y1 = (stbtt_int16) (r->y + r->h); - bc->xadvance = scale * advance; - bc->xoff = (float) x0 * recip_h + sub_x; - bc->yoff = (float) y0 * recip_v + sub_y; - bc->xoff2 = (x0 + r->w) * recip_h + sub_x; - bc->yoff2 = (y0 + r->h) * recip_v + sub_y; - - if (glyph == 0) - missing_glyph = j; - } else if (spc->skip_missing) { - return_value = 0; - } else if (r->was_packed && r->w == 0 && r->h == 0 && missing_glyph >= 0) { - ranges[i].chardata_for_range[j] = ranges[i].chardata_for_range[missing_glyph]; - } else { - return_value = 0; // if any fail, report failure - } - - ++k; - } - } - - // restore original values - spc->h_oversample = old_h_over; - spc->v_oversample = old_v_over; - - return return_value; -} - -STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects) -{ - stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects); -} - -STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges) -{ - stbtt_fontinfo info; - int i, j, n, return_value; // [DEAR IMGUI] removed = 1; - //stbrp_context *context = (stbrp_context *) spc->pack_info; - stbrp_rect *rects; - - // flag all characters as NOT packed - for (i=0; i < num_ranges; ++i) - for (j=0; j < ranges[i].num_chars; ++j) - ranges[i].chardata_for_range[j].x0 = - ranges[i].chardata_for_range[j].y0 = - ranges[i].chardata_for_range[j].x1 = - ranges[i].chardata_for_range[j].y1 = 0; - - n = 0; - for (i=0; i < num_ranges; ++i) - n += ranges[i].num_chars; - - rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context); - if (rects == NULL) - return 0; - - info.userdata = spc->user_allocator_context; - stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index)); - - n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects); - - stbtt_PackFontRangesPackRects(spc, rects, n); - - return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects); - - STBTT_free(rects, spc->user_allocator_context); - return return_value; -} - -STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, - int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range) -{ - stbtt_pack_range range; - range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range; - range.array_of_unicode_codepoints = NULL; - range.num_chars = num_chars_in_range; - range.chardata_for_range = chardata_for_range; - range.font_size = font_size; - return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1); -} - -STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap) -{ - int i_ascent, i_descent, i_lineGap; - float scale; - stbtt_fontinfo info; - stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index)); - scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size); - stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap); - *ascent = (float) i_ascent * scale; - *descent = (float) i_descent * scale; - *lineGap = (float) i_lineGap * scale; -} - -STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer) -{ - float ipw = 1.0f / pw, iph = 1.0f / ph; - const stbtt_packedchar *b = chardata + char_index; - - if (align_to_integer) { - float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f); - float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f); - q->x0 = x; - q->y0 = y; - q->x1 = x + b->xoff2 - b->xoff; - q->y1 = y + b->yoff2 - b->yoff; - } else { - q->x0 = *xpos + b->xoff; - q->y0 = *ypos + b->yoff; - q->x1 = *xpos + b->xoff2; - q->y1 = *ypos + b->yoff2; - } - - q->s0 = b->x0 * ipw; - q->t0 = b->y0 * iph; - q->s1 = b->x1 * ipw; - q->t1 = b->y1 * iph; - - *xpos += b->xadvance; -} - -////////////////////////////////////////////////////////////////////////////// -// -// sdf computation -// - -#define STBTT_min(a,b) ((a) < (b) ? (a) : (b)) -#define STBTT_max(a,b) ((a) < (b) ? (b) : (a)) - -static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2]) -{ - float q0perp = q0[1]*ray[0] - q0[0]*ray[1]; - float q1perp = q1[1]*ray[0] - q1[0]*ray[1]; - float q2perp = q2[1]*ray[0] - q2[0]*ray[1]; - float roperp = orig[1]*ray[0] - orig[0]*ray[1]; - - float a = q0perp - 2*q1perp + q2perp; - float b = q1perp - q0perp; - float c = q0perp - roperp; - - float s0 = 0., s1 = 0.; - int num_s = 0; - - if (a != 0.0) { - float discr = b*b - a*c; - if (discr > 0.0) { - float rcpna = -1 / a; - float d = (float) STBTT_sqrt(discr); - s0 = (b+d) * rcpna; - s1 = (b-d) * rcpna; - if (s0 >= 0.0 && s0 <= 1.0) - num_s = 1; - if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) { - if (num_s == 0) s0 = s1; - ++num_s; - } - } - } else { - // 2*b*s + c = 0 - // s = -c / (2*b) - s0 = c / (-2 * b); - if (s0 >= 0.0 && s0 <= 1.0) - num_s = 1; - } - - if (num_s == 0) - return 0; - else { - float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]); - float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2; - - float q0d = q0[0]*rayn_x + q0[1]*rayn_y; - float q1d = q1[0]*rayn_x + q1[1]*rayn_y; - float q2d = q2[0]*rayn_x + q2[1]*rayn_y; - float rod = orig[0]*rayn_x + orig[1]*rayn_y; - - float q10d = q1d - q0d; - float q20d = q2d - q0d; - float q0rd = q0d - rod; - - hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d; - hits[0][1] = a*s0+b; - - if (num_s > 1) { - hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d; - hits[1][1] = a*s1+b; - return 2; - } else { - return 1; - } - } -} - -static int equal(float *a, float *b) -{ - return (a[0] == b[0] && a[1] == b[1]); -} - -static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts) -{ - int i; - float orig[2], ray[2] = { 1, 0 }; - float y_frac; - int winding = 0; - - // make sure y never passes through a vertex of the shape - y_frac = (float) STBTT_fmod(y, 1.0f); - if (y_frac < 0.01f) - y += 0.01f; - else if (y_frac > 0.99f) - y -= 0.01f; - - orig[0] = x; - orig[1] = y; - - // test a ray from (-infinity,y) to (x,y) - for (i=0; i < nverts; ++i) { - if (verts[i].type == STBTT_vline) { - int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y; - int x1 = (int) verts[i ].x, y1 = (int) verts[i ].y; - if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { - float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; - if (x_inter < x) - winding += (y0 < y1) ? 1 : -1; - } - } - if (verts[i].type == STBTT_vcurve) { - int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ; - int x1 = (int) verts[i ].cx, y1 = (int) verts[i ].cy; - int x2 = (int) verts[i ].x , y2 = (int) verts[i ].y ; - int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2)); - int by = STBTT_max(y0,STBTT_max(y1,y2)); - if (y > ay && y < by && x > ax) { - float q0[2],q1[2],q2[2]; - float hits[2][2]; - q0[0] = (float)x0; - q0[1] = (float)y0; - q1[0] = (float)x1; - q1[1] = (float)y1; - q2[0] = (float)x2; - q2[1] = (float)y2; - if (equal(q0,q1) || equal(q1,q2)) { - x0 = (int)verts[i-1].x; //-V1048 - y0 = (int)verts[i-1].y; //-V1048 - x1 = (int)verts[i ].x; - y1 = (int)verts[i ].y; - if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { - float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; - if (x_inter < x) - winding += (y0 < y1) ? 1 : -1; - } - } else { - int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits); - if (num_hits >= 1) - if (hits[0][0] < 0) - winding += (hits[0][1] < 0 ? -1 : 1); - if (num_hits >= 2) - if (hits[1][0] < 0) - winding += (hits[1][1] < 0 ? -1 : 1); - } - } - } - } - return winding; -} - -static float stbtt__cuberoot( float x ) -{ - if (x<0) - return -(float) STBTT_pow(-x,1.0f/3.0f); - else - return (float) STBTT_pow( x,1.0f/3.0f); -} - -// x^3 + a*x^2 + b*x + c = 0 -static int stbtt__solve_cubic(float a, float b, float c, float* r) -{ - float s = -a / 3; - float p = b - a*a / 3; - float q = a * (2*a*a - 9*b) / 27 + c; - float p3 = p*p*p; - float d = q*q + 4*p3 / 27; - if (d >= 0) { - float z = (float) STBTT_sqrt(d); - float u = (-q + z) / 2; - float v = (-q - z) / 2; - u = stbtt__cuberoot(u); - v = stbtt__cuberoot(v); - r[0] = s + u + v; - return 1; - } else { - float u = (float) STBTT_sqrt(-p/3); - float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative - float m = (float) STBTT_cos(v); - float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f; - r[0] = s + u * 2 * m; - r[1] = s - u * (m + n); - r[2] = s - u * (m - n); - - //STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe? - //STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f); - //STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f); - return 3; - } -} - -STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) -{ - float scale_x = scale, scale_y = scale; - int ix0,iy0,ix1,iy1; - int w,h; - unsigned char *data; - - if (scale == 0) return NULL; - - stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1); - - // if empty, return NULL - if (ix0 == ix1 || iy0 == iy1) - return NULL; - - ix0 -= padding; - iy0 -= padding; - ix1 += padding; - iy1 += padding; - - w = (ix1 - ix0); - h = (iy1 - iy0); - - if (width ) *width = w; - if (height) *height = h; - if (xoff ) *xoff = ix0; - if (yoff ) *yoff = iy0; - - // invert for y-downwards bitmaps - scale_y = -scale_y; - - { - int x,y,i,j; - float *precompute; - stbtt_vertex *verts; - int num_verts = stbtt_GetGlyphShape(info, glyph, &verts); - data = (unsigned char *) STBTT_malloc(w * h, info->userdata); - precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata); - - for (i=0,j=num_verts-1; i < num_verts; j=i++) { - if (verts[i].type == STBTT_vline) { - float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; - float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y; - float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)); - precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist; - } else if (verts[i].type == STBTT_vcurve) { - float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y; - float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y; - float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y; - float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; - float len2 = bx*bx + by*by; - if (len2 != 0.0f) - precompute[i] = 1.0f / (bx*bx + by*by); - else - precompute[i] = 0.0f; - } else - precompute[i] = 0.0f; - } - - for (y=iy0; y < iy1; ++y) { - for (x=ix0; x < ix1; ++x) { - float val; - float min_dist = 999999.0f; - float sx = (float) x + 0.5f; - float sy = (float) y + 0.5f; - float x_gspace = (sx / scale_x); - float y_gspace = (sy / scale_y); - - int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path - - for (i=0; i < num_verts; ++i) { - float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; - - if (verts[i].type == STBTT_vline && precompute[i] != 0.0f) { - float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y; - - float dist,dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); - if (dist2 < min_dist*min_dist) - min_dist = (float) STBTT_sqrt(dist2); - - // coarse culling against bbox - //if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist && - // sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist) - dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i]; - STBTT_assert(i != 0); - if (dist < min_dist) { - // check position along line - // x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0) - // minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy) - float dx = x1-x0, dy = y1-y0; - float px = x0-sx, py = y0-sy; - // minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy - // derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve - float t = -(px*dx + py*dy) / (dx*dx + dy*dy); - if (t >= 0.0f && t <= 1.0f) - min_dist = dist; - } - } else if (verts[i].type == STBTT_vcurve) { - float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y; - float x1 = verts[i ].cx*scale_x, y1 = verts[i ].cy*scale_y; - float box_x0 = STBTT_min(STBTT_min(x0,x1),x2); - float box_y0 = STBTT_min(STBTT_min(y0,y1),y2); - float box_x1 = STBTT_max(STBTT_max(x0,x1),x2); - float box_y1 = STBTT_max(STBTT_max(y0,y1),y2); - // coarse culling against bbox to avoid computing cubic unnecessarily - if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) { - int num=0; - float ax = x1-x0, ay = y1-y0; - float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; - float mx = x0 - sx, my = y0 - sy; - float res[3] = {0.f,0.f,0.f}; - float px,py,t,it,dist2; - float a_inv = precompute[i]; - if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula - float a = 3*(ax*bx + ay*by); - float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by); - float c = mx*ax+my*ay; - if (a == 0.0) { // if a is 0, it's linear - if (b != 0.0) { - res[num++] = -c/b; - } - } else { - float discriminant = b*b - 4*a*c; - if (discriminant < 0) - num = 0; - else { - float root = (float) STBTT_sqrt(discriminant); - res[0] = (-b - root)/(2*a); - res[1] = (-b + root)/(2*a); - num = 2; // don't bother distinguishing 1-solution case, as code below will still work - } - } - } else { - float b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point - float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv; - float d = (mx*ax+my*ay) * a_inv; - num = stbtt__solve_cubic(b, c, d, res); - } - dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); - if (dist2 < min_dist*min_dist) - min_dist = (float) STBTT_sqrt(dist2); - - if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) { - t = res[0], it = 1.0f - t; - px = it*it*x0 + 2*t*it*x1 + t*t*x2; - py = it*it*y0 + 2*t*it*y1 + t*t*y2; - dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); - if (dist2 < min_dist * min_dist) - min_dist = (float) STBTT_sqrt(dist2); - } - if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) { - t = res[1], it = 1.0f - t; - px = it*it*x0 + 2*t*it*x1 + t*t*x2; - py = it*it*y0 + 2*t*it*y1 + t*t*y2; - dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); - if (dist2 < min_dist * min_dist) - min_dist = (float) STBTT_sqrt(dist2); - } - if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) { - t = res[2], it = 1.0f - t; - px = it*it*x0 + 2*t*it*x1 + t*t*x2; - py = it*it*y0 + 2*t*it*y1 + t*t*y2; - dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); - if (dist2 < min_dist * min_dist) - min_dist = (float) STBTT_sqrt(dist2); - } - } - } - } - if (winding == 0) - min_dist = -min_dist; // if outside the shape, value is negative - val = onedge_value + pixel_dist_scale * min_dist; - if (val < 0) - val = 0; - else if (val > 255) - val = 255; - data[(y-iy0)*w+(x-ix0)] = (unsigned char) val; - } - } - STBTT_free(precompute, info->userdata); - STBTT_free(verts, info->userdata); - } - return data; -} - -STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) -{ - return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff); -} - -STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata) -{ - STBTT_free(bitmap, userdata); -} - -////////////////////////////////////////////////////////////////////////////// -// -// font name matching -- recommended not to use this -// - -// check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string -static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2) -{ - stbtt_int32 i=0; - - // convert utf16 to utf8 and compare the results while converting - while (len2) { - stbtt_uint16 ch = s2[0]*256 + s2[1]; - if (ch < 0x80) { - if (i >= len1) return -1; - if (s1[i++] != ch) return -1; - } else if (ch < 0x800) { - if (i+1 >= len1) return -1; - if (s1[i++] != 0xc0 + (ch >> 6)) return -1; - if (s1[i++] != 0x80 + (ch & 0x3f)) return -1; - } else if (ch >= 0xd800 && ch < 0xdc00) { - stbtt_uint32 c; - stbtt_uint16 ch2 = s2[2]*256 + s2[3]; - if (i+3 >= len1) return -1; - c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; - if (s1[i++] != 0xf0 + (c >> 18)) return -1; - if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1; - if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1; - if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1; - s2 += 2; // plus another 2 below - len2 -= 2; - } else if (ch >= 0xdc00 && ch < 0xe000) { - return -1; - } else { - if (i+2 >= len1) return -1; - if (s1[i++] != 0xe0 + (ch >> 12)) return -1; - if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1; - if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1; - } - s2 += 2; - len2 -= 2; - } - return i; -} - -static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2) -{ - return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2); -} - -// returns results in whatever encoding you request... but note that 2-byte encodings -// will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare -STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID) -{ - stbtt_int32 i,count,stringOffset; - stbtt_uint8 *fc = font->data; - stbtt_uint32 offset = font->fontstart; - stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); - if (!nm) return NULL; - - count = ttUSHORT(fc+nm+2); - stringOffset = nm + ttUSHORT(fc+nm+4); - for (i=0; i < count; ++i) { - stbtt_uint32 loc = nm + 6 + 12 * i; - if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2) - && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) { - *length = ttUSHORT(fc+loc+8); - return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10)); - } - } - return NULL; -} - -static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id) -{ - stbtt_int32 i; - stbtt_int32 count = ttUSHORT(fc+nm+2); - stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4); - - for (i=0; i < count; ++i) { - stbtt_uint32 loc = nm + 6 + 12 * i; - stbtt_int32 id = ttUSHORT(fc+loc+6); - if (id == target_id) { - // find the encoding - stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4); - - // is this a Unicode encoding? - if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) { - stbtt_int32 slen = ttUSHORT(fc+loc+8); - stbtt_int32 off = ttUSHORT(fc+loc+10); - - // check if there's a prefix match - stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen); - if (matchlen >= 0) { - // check for target_id+1 immediately following, with same encoding & language - if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) { - slen = ttUSHORT(fc+loc+12+8); - off = ttUSHORT(fc+loc+12+10); - if (slen == 0) { - if (matchlen == nlen) - return 1; - } else if (matchlen < nlen && name[matchlen] == ' ') { - ++matchlen; - if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen)) - return 1; - } - } else { - // if nothing immediately following - if (matchlen == nlen) - return 1; - } - } - } - - // @TODO handle other encodings - } - } - return 0; -} - -static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags) -{ - stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name); - stbtt_uint32 nm,hd; - if (!stbtt__isfont(fc+offset)) return 0; - - // check italics/bold/underline flags in macStyle... - if (flags) { - hd = stbtt__find_table(fc, offset, "head"); - if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0; - } - - nm = stbtt__find_table(fc, offset, "name"); - if (!nm) return 0; - - if (flags) { - // if we checked the macStyle flags, then just check the family and ignore the subfamily - if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1; - if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1; - if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; - } else { - if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1; - if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1; - if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; - } - - return 0; -} - -static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags) -{ - stbtt_int32 i; - for (i=0;;++i) { - stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i); - if (off < 0) return off; - if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags)) - return off; - } -} - -#if defined(__GNUC__) || defined(__clang__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wcast-qual" -#endif - -STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, - float pixel_height, unsigned char *pixels, int pw, int ph, - int first_char, int num_chars, stbtt_bakedchar *chardata) -{ - return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata); -} - -STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index) -{ - return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index); -} - -STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data) -{ - return stbtt_GetNumberOfFonts_internal((unsigned char *) data); -} - -STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset) -{ - return stbtt_InitFont_internal(info, (unsigned char *) data, offset); -} - -STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags) -{ - return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags); -} - -STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) -{ - return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2); -} - -#if defined(__GNUC__) || defined(__clang__) -#pragma GCC diagnostic pop -#endif - -#endif // STB_TRUETYPE_IMPLEMENTATION - - -// FULL VERSION HISTORY -// -// 1.25 (2021-07-11) many fixes -// 1.24 (2020-02-05) fix warning -// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) -// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined -// 1.21 (2019-02-25) fix warning -// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() -// 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod -// 1.18 (2018-01-29) add missing function -// 1.17 (2017-07-23) make more arguments const; doc fix -// 1.16 (2017-07-12) SDF support -// 1.15 (2017-03-03) make more arguments const -// 1.14 (2017-01-16) num-fonts-in-TTC function -// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts -// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual -// 1.11 (2016-04-02) fix unused-variable warning -// 1.10 (2016-04-02) allow user-defined fabs() replacement -// fix memory leak if fontsize=0.0 -// fix warning from duplicate typedef -// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges -// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges -// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; -// allow PackFontRanges to pack and render in separate phases; -// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); -// fixed an assert() bug in the new rasterizer -// replace assert() with STBTT_assert() in new rasterizer -// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine) -// also more precise AA rasterizer, except if shapes overlap -// remove need for STBTT_sort -// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC -// 1.04 (2015-04-15) typo in example -// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes -// 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++ -// 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match -// non-oversampled; STBTT_POINT_SIZE for packed case only -// 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling -// 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg) -// 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID -// 0.8b (2014-07-07) fix a warning -// 0.8 (2014-05-25) fix a few more warnings -// 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back -// 0.6c (2012-07-24) improve documentation -// 0.6b (2012-07-20) fix a few more warnings -// 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels, -// stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty -// 0.5 (2011-12-09) bugfixes: -// subpixel glyph renderer computed wrong bounding box -// first vertex of shape can be off-curve (FreeSans) -// 0.4b (2011-12-03) fixed an error in the font baking example -// 0.4 (2011-12-01) kerning, subpixel rendering (tor) -// bugfixes for: -// codepoint-to-glyph conversion using table fmt=12 -// codepoint-to-glyph conversion using table fmt=4 -// stbtt_GetBakedQuad with non-square texture (Zer) -// updated Hello World! sample to use kerning and subpixel -// fixed some warnings -// 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM) -// userdata, malloc-from-userdata, non-zero fill (stb) -// 0.2 (2009-03-11) Fix unsigned/signed char warnings -// 0.1 (2009-03-09) First public release -// - -/* ------------------------------------------------------------------------------- -This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------- -ALTERNATIVE A - MIT License -Copyright (c) 2017 Sean Barrett -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. ------------------------------------------------------------------------------- -ALTERNATIVE B - Public Domain (www.unlicense.org) -This is free and unencumbered software released into the public domain. -Anyone is free to copy, modify, publish, use, compile, sell, or distribute this -software, either in source code form or as a compiled binary, for any purpose, -commercial or non-commercial, and by any means. -In jurisdictions that recognize copyright laws, the author or authors of this -software dedicate any and all copyright interest in the software to the public -domain. We make this dedication for the benefit of the public at large and to -the detriment of our heirs and successors. We intend this dedication to be an -overt act of relinquishment in perpetuity of all present and future rights to -this software under copyright law. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- -*/ diff --git a/include/imgui/rlImGui.h b/include/imgui/rlImGui.h deleted file mode 100644 index 92d2e2c..0000000 --- a/include/imgui/rlImGui.h +++ /dev/null @@ -1,195 +0,0 @@ -/********************************************************************************************** -* -* raylibExtras * Utilities and Shared Components for Raylib -* -* rlImGui * basic ImGui integration -* -* LICENSE: ZLIB -* -* Copyright (c) 2024 Jeffery Myers -* -* Permission is hereby granted, free of charge, to any person obtaining a copy -* of this software and associated documentation files (the "Software"), to deal -* in the Software without restriction, including without limitation the rights -* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -* copies of the Software, and to permit persons to whom the Software is -* furnished to do so, subject to the following conditions: -* -* The above copyright notice and this permission notice shall be included in all -* copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -* SOFTWARE. -* -**********************************************************************************************/ - -#pragma once - -#include "raylib.h" - -// Function specifiers in case library is build/used as a shared library -// NOTE: Microsoft specifiers to tell compiler that symbols are imported/exported from a .dll -// NOTE: visibility("default") attribute makes symbols "visible" when compiled with -fvisibility=hidden -#if defined(_WIN32) -#if defined(__TINYC__) -#define __declspec(x) __attribute__((x)) -#endif -#if defined(BUILD_LIBTYPE_SHARED) -#define RLIMGUIAPI __declspec(dllexport) // We are building the library as a Win32 shared library (.dll) -#elif defined(USE_LIBTYPE_SHARED) -#define RLIMGUIAPI __declspec(dllimport) // We are using the library as a Win32 shared library (.dll) -#endif -#else -#if defined(BUILD_LIBTYPE_SHARED) -#define RLIMGUIAPI __attribute__((visibility("default"))) // We are building as a Unix shared library (.so/.dylib) -#endif -#endif - -#ifndef RLIMGUIAPI -#define RLIMGUIAPI // Functions defined as 'extern' by default (implicit specifiers) -#endif - -#ifndef NO_FONT_AWESOME -#include "extras/IconsFontAwesome6.h" -#ifndef FONT_AWESOME_ICON_SIZE -#define FONT_AWESOME_ICON_SIZE 11 -#endif -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -// High level API. This API is designed in the style of raylib and meant to work with reaylib code. -// It will manage it's own ImGui context and call common ImGui functions (like NewFrame and Render) for you -// for a lower level API that matches the other ImGui platforms, please see imgui_impl_raylib.h - -/// -/// Sets up ImGui, loads fonts and themes -/// Calls ImGui_ImplRaylib_Init and sets the theme. Will install Font awesome by default -/// -/// when true(default) the dark theme is used, when false the light theme is used -RLIMGUIAPI void rlImGuiSetup(bool darkTheme); - -/// -/// Starts a new ImGui Frame -/// Calls ImGui_ImplRaylib_NewFrame, ImGui_ImplRaylib_ProcessEvents, and ImGui::NewFrame together -/// -RLIMGUIAPI void rlImGuiBegin(void); - -/// -/// Ends an ImGui frame and submits all ImGui drawing to raylib for processing. -/// Calls ImGui:Render, an d ImGui_ImplRaylib_RenderDrawData to draw to the current raylib render target -/// -RLIMGUIAPI void rlImGuiEnd(void); - -/// -/// Cleanup ImGui and unload font atlas -/// Calls ImGui_ImplRaylib_Shutdown -/// -RLIMGUIAPI void rlImGuiShutdown(void); - -// Advanced StartupAPI - -/// -/// Custom initialization. Not needed if you call rlImGuiSetup. Only needed if you want to add custom setup code. -/// must be followed by rlImGuiEndInitImGui -/// Called by ImGui_ImplRaylib_Init, and does the first part of setup, before fonts are rendered -/// -RLIMGUIAPI void rlImGuiBeginInitImGui(void); - -/// -/// End Custom initialization. Not needed if you call rlImGuiSetup. Only needed if you want to add custom setup code. -/// must be proceeded by rlImGuiBeginInitImGui -/// Called by ImGui_ImplRaylib_Init and does the second part of setup, and renders fonts. -/// -RLIMGUIAPI void rlImGuiEndInitImGui(void); - -// Advanced Update API - -/// -/// Starts a new ImGui Frame with a specified delta time -/// -/// delta time, any value < 0 will use raylib GetFrameTime -RLIMGUIAPI void rlImGuiBeginDelta(float deltaTime); - -// ImGui Image API extensions -// Purely for convenience in working with raylib textures as images. -// If you want to call ImGui image functions directly, simply pass them the pointer to the texture. - -/// -/// Draw a texture as an image in an ImGui Context -/// Uses the current ImGui Cursor position and the full texture size. -/// -/// The raylib texture to draw -RLIMGUIAPI void rlImGuiImage(const Texture *image); - -/// -/// Draw a texture as an image in an ImGui Context at a specific size -/// Uses the current ImGui Cursor position and the specified width and height -/// The image will be scaled up or down to fit as needed -/// -/// The raylib texture to draw -/// The width of the drawn image -/// The height of the drawn image -RLIMGUIAPI void rlImGuiImageSize(const Texture *image, int width, int height); - -/// -/// Draw a texture as an image in an ImGui Context at a specific size -/// Uses the current ImGui Cursor position and the specified size -/// The image will be scaled up or down to fit as needed -/// -/// The raylib texture to draw -/// The size of drawn image -RLIMGUIAPI void rlImGuiImageSizeV(const Texture* image, Vector2 size); - -/// -/// Draw a portion texture as an image in an ImGui Context at a defined size -/// Uses the current ImGui Cursor position and the specified size -/// The image will be scaled up or down to fit as needed -/// -/// The raylib texture to draw -/// The width of the drawn image -/// The height of the drawn image -/// The portion of the texture to draw as an image. Negative values for the width and height will flip the image -RLIMGUIAPI void rlImGuiImageRect(const Texture* image, int destWidth, int destHeight, Rectangle sourceRect); - -/// -/// Draws a render texture as an image an ImGui Context, automatically flipping the Y axis so it will show correctly on screen -/// -/// The render texture to draw -RLIMGUIAPI void rlImGuiImageRenderTexture(const RenderTexture* image); - -/// -/// Draws a render texture as an image an ImGui Context, automatically flipping the Y axis so it will show correctly on screen -/// Fits the render texture to the available content area -/// -/// The render texture to draw -/// When true the image will be centered in the content area -RLIMGUIAPI void rlImGuiImageRenderTextureFit(const RenderTexture* image, bool center); - -/// -/// Draws a texture as an image button in an ImGui context. Uses the current ImGui cursor position and the full size of the texture -/// -/// The display name and ImGui ID for the button -/// The texture to draw -/// True if the button was clicked -bool rlImGuiImageButton(const char* name, const Texture* image); - -/// -/// Draws a texture as an image button in an ImGui context. Uses the current ImGui cursor position and the specified size. -/// -/// The display name and ImGui ID for the button -/// The texture to draw -/// The size of the button -/// True if the button was clicked -RLIMGUIAPI bool rlImGuiImageButtonSize(const char* name, const Texture* image, Vector2 size); - -#ifdef __cplusplus -} -#endif diff --git a/include/imgui/rlImGuiColors.h b/include/imgui/rlImGuiColors.h deleted file mode 100644 index 2240683..0000000 --- a/include/imgui/rlImGuiColors.h +++ /dev/null @@ -1,47 +0,0 @@ -/********************************************************************************************** -* -* raylibExtras * Utilities and Shared Components for Raylib -* -* rlImGui * basic ImGui integration -* -* LICENSE: ZLIB -* -* Copyright (c) 2024 Jeffery Myers -* -* Permission is hereby granted, free of charge, to any person obtaining a copy -* of this software and associated documentation files (the "Software"), to deal -* in the Software without restriction, including without limitation the rights -* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -* copies of the Software, and to permit persons to whom the Software is -* furnished to do so, subject to the following conditions: -* -* The above copyright notice and this permission notice shall be included in all -* copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -* SOFTWARE. -* -**********************************************************************************************/ - -#pragma once - -#include "raylib.h" -#include "imgui.h" - -namespace rlImGuiColors -{ - inline ImVec4 Convert(::Color color) - { - return ImVec4(color.r / 255.0f, color.g / 255.0f, color.b / 255.0f, color.a / 255.0f); - } - - inline ::Color Convert(ImVec4 color) - { - return ::Color{ (unsigned char)(color.x * 255.0f), (unsigned char)(color.y * 255.0f), (unsigned char)(color.z * 255.0f), (unsigned char)(color.w * 255.0f) }; - } -} diff --git a/include/interactable.hpp b/include/interactable.hpp deleted file mode 100644 index d762b55..0000000 --- a/include/interactable.hpp +++ /dev/null @@ -1,106 +0,0 @@ -#ifndef _RPGPP_INTERACTABLE_H -#define _RPGPP_INTERACTABLE_H - -#include "gamedata.hpp" -#include -#include -#include -#include -#include -#include - -/** Enum for interactable types */ -enum InteractableType { - INT_BLANK, - INT_TWO, - INT_WARPER -}; - -#define INTTYPE_MAX (3) - -/** Defines an object that is interactable in-game by a player's action */ -class Interactable { -private: - /** Whether this Interactable is valid */ - bool valid; - /** The type of this Interactable */ - InteractableType type; - /** The position of this Interactable in terms of tiles */ - Vector2 tilePos; - /** Tile size in pixels */ - int tileSize; - /** The absolute position of this Interactable in the world scene */ - Vector2 absolutePos; - /** The Rectangle of this Interactable */ - Rectangle rect; -protected: - /** Interactable properties. */ - std::map props; - /** Array for descriptive names of interactable types */ - static std::array interactableTypeNames; -public: - /** Empty constructor */ - Interactable(); - /** Construct from the type, tile position and size */ - Interactable(InteractableType type, Vector2 tilePos, int tileSize); - /** Get the array containing names of the Interactable names */ - static std::array& getTypeNames(); - /** Whether this Interactable is valid */ - bool isValid() const; - virtual ~Interactable(); - /** Get the Rectangle of this Interactable */ - Rectangle getRect() const; - /** Get this Interactable's type */ - InteractableType getType() const; - /** Get the World position of this Interactable */ - Vector2 getWorldPos() const; - /** Invoke the virtual interact method. Each Interactable has its own interact method. - * Shall be invoked when the player interacts with the Interactable */ - virtual void interact(); - /** Set a property of this interactable. */ - void setProp(std::string key, std::string value); -}; - -struct DiagInt { - std::string dialogueSource; -}; - -struct WarperInt { - std::string targetRoom; -}; - -class IntBaseWrapper { -public: - InteractableType type; - Vector2 pos; - bool onTouch = false; - IntBaseWrapper(); - virtual ~IntBaseWrapper(); - virtual void interact(); - void setOnTouch(bool val) { onTouch = val; }; -}; - -/** Templated class for Interactable types */ -template -class IntBase : public IntBaseWrapper { -private: - /** The data */ - T data; -public: - /** Constructor, which takes the position and the type enum. */ - IntBase(Vector2 pos, InteractableType type) { this->pos = pos; this->type = type; }; - /** Constructor, which takes the data itself. */ - IntBase(T value) { data = value; }; - /** Data setter. */ - void set(T data) { this->data = data; }; - /** Data getter. */ - T get() { return data; }; - /** The interact method. */ - void interact(); -}; - -std::unique_ptr make_inter_item(Vector2 pos, InteractableType type); -void inter_apply_vec(IntBaseWrapper* inter, std::vector props); -void inter_apply_bin(IntBaseWrapper* inter, const InteractableBin &bin); - -#endif diff --git a/include/interactablesContainer.hpp b/include/interactablesContainer.hpp deleted file mode 100644 index 148cc95..0000000 --- a/include/interactablesContainer.hpp +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef _RPGPP_INTERACTABLESCONTAINER_H -#define _RPGPP_INTERACTABLESCONTAINER_H - -#include "interactable.hpp" -#include "gamedata.hpp" -#include -#include -#include -using json = nlohmann::json; - -/** Container of Interactables that is to be used by a [Room](Room.md) */ -class InteractablesContainer { -private: - /** The vector, containing all Interactables */ - std::vector> vec; - std::vector> test; -public: - /** Empty constructor */ - InteractablesContainer(); - /** Add a new Interactable with tile position and type */ - void add(int x, int y, InteractableType type); - /** Get an Interactable by its tile position */ - IntBaseWrapper* getInt(int x, int y) const; - /** Remove an Interactable by its tile position */ - void removeInteractable(int x, int y); - /** Change the Interactable's type at the specified tile position */ - void setInteractableType(int x, int y, InteractableType type); - /** Get the vector that contains all Interactables */ - std::vector getList() const; - /** Add interactables from binary structures. */ - void addBinVector(const std::vector &bin); - /** Add interactables from a Room json object. Must contain 'interactables' - * and 'interactables_props' keys. */ - void addJsonData(json roomJson); - - template - void add(int x, int y, InteractableType type); -}; - -#endif diff --git a/include/interfaceService.hpp b/include/interfaceService.hpp deleted file mode 100644 index 1a3f62d..0000000 --- a/include/interfaceService.hpp +++ /dev/null @@ -1,41 +0,0 @@ -#ifndef _RPGPP_INTERFACESERVICE_H -#define _RPGPP_INTERFACESERVICE_H - -#include -#include -#include -#include -#include "dialogueBalloon.hpp" -#include "interfaceView.hpp" - -/** The InterfaceService acts for the User Interface (UI). */ -class InterfaceService { -private: - /** The loaded font that will be used for the User Interface. */ - Font font; - bool fpsVisible; - /** Texture for UI components. */ - Texture uiTexture; - /** Component for in-game dialogue. */ - DialogueBalloon dialogue; - /** Available UI Views. */ - std::unique_ptr> views; -public: - /** Empty constructor. */ - InterfaceService(); - ~InterfaceService(); - /** Get the font used for the game's UI. */ - Font getFont() const; - /** Get the texture, used for UI nine-patch components. */ - Texture getTexture() const; - /** Open the dialogue with a Dialogue structure */ - void showDialogue(const Dialogue &dialogue); - /** Update routine. */ - void update(); - /** Draw routine. */ - void draw(); - /** Unload routine. */ - void unload() const; -}; - -#endif diff --git a/include/interfaceView.hpp b/include/interfaceView.hpp deleted file mode 100644 index 7b165ba..0000000 --- a/include/interfaceView.hpp +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef _RPGPP_INTERFACEVIEW_H -#define _RPGPP_INTERFACEVIEW_H - -#include "uiElement.hpp" -#include -#include -#include - -class InterfaceView { -private: - Rectangle rect; - std::vector> elements; -public: - InterfaceView(); - InterfaceView(Rectangle rect); - void addElement(UIElement* element); - void update() const; - void draw(); -}; - -#endif diff --git a/include/luajit/buildvm.h b/include/luajit/buildvm.h deleted file mode 100644 index a56eefd..0000000 --- a/include/luajit/buildvm.h +++ /dev/null @@ -1,105 +0,0 @@ -/* -** LuaJIT VM builder. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _BUILDVM_H -#define _BUILDVM_H - -#include -#include -#include -#include -#include - -#include "lj_def.h" -#include "lj_arch.h" - -/* Hardcoded limits. Increase as needed. */ -#define BUILD_MAX_RELOC 200 /* Max. number of relocations. */ -#define BUILD_MAX_FOLD 4096 /* Max. number of fold rules. */ - -/* Prefix for scanned library definitions. */ -#define LIBDEF_PREFIX "LJLIB_" - -/* Prefix for scanned fold definitions. */ -#define FOLDDEF_PREFIX "LJFOLD" - -/* Prefixes for generated labels. */ -#define LABEL_PREFIX "lj_" -#define LABEL_PREFIX_BC LABEL_PREFIX "BC_" -#define LABEL_PREFIX_FF LABEL_PREFIX "ff_" -#define LABEL_PREFIX_CF LABEL_PREFIX "cf_" -#define LABEL_PREFIX_FFH LABEL_PREFIX "ffh_" -#define LABEL_PREFIX_LIBCF LABEL_PREFIX "lib_cf_" -#define LABEL_PREFIX_LIBINIT LABEL_PREFIX "lib_init_" - -/* Forward declaration. */ -struct dasm_State; - -/* Build modes. */ -#define BUILDDEF(_) \ - _(elfasm) _(coffasm) _(machasm) _(peobj) _(raw) \ - _(bcdef) _(ffdef) _(libdef) _(recdef) _(vmdef) \ - _(folddef) - -typedef enum { -#define BUILDENUM(name) BUILD_##name, -BUILDDEF(BUILDENUM) -#undef BUILDENUM - BUILD__MAX -} BuildMode; - -/* Code relocation. */ -typedef struct BuildReloc { - int32_t ofs; - int sym; - int type; -} BuildReloc; - -typedef struct BuildSym { - const char *name; - int32_t ofs; -} BuildSym; - -/* Build context structure. */ -typedef struct BuildCtx { - /* DynASM state pointer. Should be first member. */ - struct dasm_State *D; - /* Parsed command line. */ - BuildMode mode; - FILE *fp; - const char *outname; - char **args; - /* Code and symbols generated by DynASM. */ - uint8_t *code; - size_t codesz; - int npc, nglob, nsym, nreloc, nrelocsym; - void **glob; - BuildSym *sym; - const char **relocsym; - int32_t *bc_ofs; - const char *beginsym; - /* Strings generated by DynASM. */ - const char *const *globnames; - const char *const *extnames; - const char *dasm_ident; - const char *dasm_arch; - /* Relocations. */ - BuildReloc reloc[BUILD_MAX_RELOC]; -} BuildCtx; - -extern void owrite(BuildCtx *ctx, const void *ptr, size_t sz); -extern void emit_asm(BuildCtx *ctx); -extern void emit_peobj(BuildCtx *ctx); -extern void emit_lib(BuildCtx *ctx); -extern void emit_fold(BuildCtx *ctx); - -extern const char *const bc_names[]; -extern const char *const ir_names[]; -extern const char *const irt_names[]; -extern const char *const irfpm_names[]; -extern const char *const irfield_names[]; -extern const char *const ircall_names[]; - -#endif diff --git a/include/luajit/buildvm_libbc.h b/include/luajit/buildvm_libbc.h deleted file mode 100644 index 276463b..0000000 --- a/include/luajit/buildvm_libbc.h +++ /dev/null @@ -1,81 +0,0 @@ -/* This is a generated file. DO NOT EDIT! */ - -static const int libbc_endian = 0; - -static const uint8_t libbc_code[] = { -#if LJ_FR2 -/* math.deg */ 0,1,2,0,0,1,2,BC_MULVN,1,0,0,BC_RET1,1,2,0,241,135,158,166,3, -220,203,178,130,4, -/* math.rad */ 0,1,2,0,0,1,2,BC_MULVN,1,0,0,BC_RET1,1,2,0,243,244,148,165,20, -198,190,199,252,3, -/* string.len */ 0,1,2,0,0,0,3,BC_ISTYPE,0,5,0,BC_LEN,1,0,0,BC_RET1,1,2,0, -/* table.foreachi */ 0,2,10,0,0,0,15,BC_ISTYPE,0,12,0,BC_ISTYPE,1,9,0, -BC_KSHORT,2,1,0,BC_LEN,3,0,0,BC_KSHORT,4,1,0,BC_FORI,2,8,128,BC_MOV,6,1,0, -BC_MOV,8,5,0,BC_TGETR,9,5,0,BC_CALL,6,3,2,BC_ISEQP,6,0,0,BC_JMP,7,1,128, -BC_RET1,6,2,0,BC_FORL,2,248,127,BC_RET0,0,1,0, -/* table.foreach */ 0,2,11,0,0,1,16,BC_ISTYPE,0,12,0,BC_ISTYPE,1,9,0,BC_KPRI, -2,0,0,BC_MOV,3,0,0,BC_KNUM,4,0,0,BC_JMP,5,7,128,BC_MOV,7,1,0,BC_MOV,9,5,0, -BC_MOV,10,6,0,BC_CALL,7,3,2,BC_ISEQP,7,0,0,BC_JMP,8,1,128,BC_RET1,7,2,0, -BC_ITERN,5,3,3,BC_ITERL,5,247,127,BC_RET0,0,1,0,1,255,255,249,255,15, -/* table.getn */ 0,1,2,0,0,0,3,BC_ISTYPE,0,12,0,BC_LEN,1,0,0,BC_RET1,1,2,0, -/* table.remove */ 0,2,10,0,0,2,30,BC_ISTYPE,0,12,0,BC_LEN,2,0,0,BC_ISNEP,1,0, -0,BC_JMP,3,7,128,BC_ISEQN,2,0,0,BC_JMP,3,23,128,BC_TGETR,3,2,0,BC_KPRI,4,0,0, -BC_TSETR,4,2,0,BC_RET1,3,2,0,BC_JMP,3,18,128,BC_ISTYPE,1,14,0,BC_KSHORT,3,1,0, -BC_ISGT,3,1,0,BC_JMP,3,14,128,BC_ISGT,1,2,0,BC_JMP,3,12,128,BC_TGETR,3,1,0, -BC_ADDVN,4,1,1,BC_MOV,5,2,0,BC_KSHORT,6,1,0,BC_FORI,4,4,128,BC_SUBVN,8,1,7, -BC_TGETR,9,7,0,BC_TSETR,9,8,0,BC_FORL,4,252,127,BC_KPRI,4,0,0,BC_TSETR,4,2,0, -BC_RET1,3,2,0,BC_RET0,0,1,0,0,2, -/* table.move */ 0,5,12,0,0,0,35,BC_ISTYPE,0,12,0,BC_ISTYPE,1,14,0,BC_ISTYPE, -2,14,0,BC_ISTYPE,3,14,0,BC_ISNEP,4,0,0,BC_JMP,5,1,128,BC_MOV,4,0,0,BC_ISTYPE, -4,12,0,BC_ISGT,1,2,0,BC_JMP,5,24,128,BC_SUBVV,5,1,3,BC_ISLT,2,3,0,BC_JMP,6,4, -128,BC_ISLE,3,1,0,BC_JMP,6,2,128,BC_ISEQV,4,0,0,BC_JMP,6,9,128,BC_MOV,6,1,0, -BC_MOV,7,2,0,BC_KSHORT,8,1,0,BC_FORI,6,4,128,BC_ADDVV,10,5,9,BC_TGETR,11,9,0, -BC_TSETR,11,10,4,BC_FORL,6,252,127,BC_JMP,6,8,128,BC_MOV,6,2,0,BC_MOV,7,1,0, -BC_KSHORT,8,255,255,BC_FORI,6,4,128,BC_ADDVV,10,5,9,BC_TGETR,11,9,0,BC_TSETR, -11,10,4,BC_FORL,6,252,127,BC_RET1,4,2,0, -#else -/* math.deg */ 0,1,2,0,0,1,2,BC_MULVN,1,0,0,BC_RET1,1,2,0,241,135,158,166,3, -220,203,178,130,4, -/* math.rad */ 0,1,2,0,0,1,2,BC_MULVN,1,0,0,BC_RET1,1,2,0,243,244,148,165,20, -198,190,199,252,3, -/* string.len */ 0,1,2,0,0,0,3,BC_ISTYPE,0,5,0,BC_LEN,1,0,0,BC_RET1,1,2,0, -/* table.foreachi */ 0,2,9,0,0,0,15,BC_ISTYPE,0,12,0,BC_ISTYPE,1,9,0, -BC_KSHORT,2,1,0,BC_LEN,3,0,0,BC_KSHORT,4,1,0,BC_FORI,2,8,128,BC_MOV,6,1,0, -BC_MOV,7,5,0,BC_TGETR,8,5,0,BC_CALL,6,3,2,BC_ISEQP,6,0,0,BC_JMP,7,1,128, -BC_RET1,6,2,0,BC_FORL,2,248,127,BC_RET0,0,1,0, -/* table.foreach */ 0,2,10,0,0,1,16,BC_ISTYPE,0,12,0,BC_ISTYPE,1,9,0,BC_KPRI, -2,0,0,BC_MOV,3,0,0,BC_KNUM,4,0,0,BC_JMP,5,7,128,BC_MOV,7,1,0,BC_MOV,8,5,0, -BC_MOV,9,6,0,BC_CALL,7,3,2,BC_ISEQP,7,0,0,BC_JMP,8,1,128,BC_RET1,7,2,0, -BC_ITERN,5,3,3,BC_ITERL,5,247,127,BC_RET0,0,1,0,1,255,255,249,255,15, -/* table.getn */ 0,1,2,0,0,0,3,BC_ISTYPE,0,12,0,BC_LEN,1,0,0,BC_RET1,1,2,0, -/* table.remove */ 0,2,10,0,0,2,30,BC_ISTYPE,0,12,0,BC_LEN,2,0,0,BC_ISNEP,1,0, -0,BC_JMP,3,7,128,BC_ISEQN,2,0,0,BC_JMP,3,23,128,BC_TGETR,3,2,0,BC_KPRI,4,0,0, -BC_TSETR,4,2,0,BC_RET1,3,2,0,BC_JMP,3,18,128,BC_ISTYPE,1,14,0,BC_KSHORT,3,1,0, -BC_ISGT,3,1,0,BC_JMP,3,14,128,BC_ISGT,1,2,0,BC_JMP,3,12,128,BC_TGETR,3,1,0, -BC_ADDVN,4,1,1,BC_MOV,5,2,0,BC_KSHORT,6,1,0,BC_FORI,4,4,128,BC_SUBVN,8,1,7, -BC_TGETR,9,7,0,BC_TSETR,9,8,0,BC_FORL,4,252,127,BC_KPRI,4,0,0,BC_TSETR,4,2,0, -BC_RET1,3,2,0,BC_RET0,0,1,0,0,2, -/* table.move */ 0,5,12,0,0,0,35,BC_ISTYPE,0,12,0,BC_ISTYPE,1,14,0,BC_ISTYPE, -2,14,0,BC_ISTYPE,3,14,0,BC_ISNEP,4,0,0,BC_JMP,5,1,128,BC_MOV,4,0,0,BC_ISTYPE, -4,12,0,BC_ISGT,1,2,0,BC_JMP,5,24,128,BC_SUBVV,5,1,3,BC_ISLT,2,3,0,BC_JMP,6,4, -128,BC_ISLE,3,1,0,BC_JMP,6,2,128,BC_ISEQV,4,0,0,BC_JMP,6,9,128,BC_MOV,6,1,0, -BC_MOV,7,2,0,BC_KSHORT,8,1,0,BC_FORI,6,4,128,BC_ADDVV,10,5,9,BC_TGETR,11,9,0, -BC_TSETR,11,10,4,BC_FORL,6,252,127,BC_JMP,6,8,128,BC_MOV,6,2,0,BC_MOV,7,1,0, -BC_KSHORT,8,255,255,BC_FORI,6,4,128,BC_ADDVV,10,5,9,BC_TGETR,11,9,0,BC_TSETR, -11,10,4,BC_FORL,6,252,127,BC_RET1,4,2,0, -#endif -0 -}; - -static const struct { const char *name; int ofs; } libbc_map[] = { -{"math_deg",0}, -{"math_rad",25}, -{"string_len",50}, -{"table_foreachi",69}, -{"table_foreach",136}, -{"table_getn",213}, -{"table_remove",232}, -{"table_move",361}, -{NULL,508} -}; - diff --git a/include/luajit/lauxlib.h b/include/luajit/lauxlib.h deleted file mode 100644 index a44f027..0000000 --- a/include/luajit/lauxlib.h +++ /dev/null @@ -1,161 +0,0 @@ -/* -** $Id: lauxlib.h,v 1.88.1.1 2007/12/27 13:02:25 roberto Exp $ -** Auxiliary functions for building Lua libraries -** See Copyright Notice in lua.h -*/ - - -#ifndef lauxlib_h -#define lauxlib_h - - -#include -#include - -#include "lua.h" - - -/* extra error code for `luaL_load' */ -#define LUA_ERRFILE (LUA_ERRERR+1) - -typedef struct luaL_Reg { - const char *name; - lua_CFunction func; -} luaL_Reg; - -LUALIB_API void (luaL_openlib) (lua_State *L, const char *libname, - const luaL_Reg *l, int nup); -LUALIB_API void (luaL_register) (lua_State *L, const char *libname, - const luaL_Reg *l); -LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e); -LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e); -LUALIB_API int (luaL_typerror) (lua_State *L, int narg, const char *tname); -LUALIB_API int (luaL_argerror) (lua_State *L, int numarg, const char *extramsg); -LUALIB_API const char *(luaL_checklstring) (lua_State *L, int numArg, - size_t *l); -LUALIB_API const char *(luaL_optlstring) (lua_State *L, int numArg, - const char *def, size_t *l); -LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int numArg); -LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int nArg, lua_Number def); - -LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int numArg); -LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int nArg, - lua_Integer def); - -LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg); -LUALIB_API void (luaL_checktype) (lua_State *L, int narg, int t); -LUALIB_API void (luaL_checkany) (lua_State *L, int narg); - -LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname); -LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname); - -LUALIB_API void (luaL_where) (lua_State *L, int lvl); -LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...); - -LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def, - const char *const lst[]); - -/* pre-defined references */ -#define LUA_NOREF (-2) -#define LUA_REFNIL (-1) - -LUALIB_API int (luaL_ref) (lua_State *L, int t); -LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref); - -LUALIB_API int (luaL_loadfile) (lua_State *L, const char *filename); -LUALIB_API int (luaL_loadbuffer) (lua_State *L, const char *buff, size_t sz, - const char *name); -LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s); - -LUALIB_API lua_State *(luaL_newstate) (void); - - -LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p, - const char *r); - -LUALIB_API const char *(luaL_findtable) (lua_State *L, int idx, - const char *fname, int szhint); - -/* From Lua 5.2. */ -LUALIB_API int luaL_fileresult(lua_State *L, int stat, const char *fname); -LUALIB_API int luaL_execresult(lua_State *L, int stat); -LUALIB_API int (luaL_loadfilex) (lua_State *L, const char *filename, - const char *mode); -LUALIB_API int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz, - const char *name, const char *mode); -LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1, const char *msg, - int level); -LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup); -LUALIB_API void (luaL_pushmodule) (lua_State *L, const char *modname, - int sizehint); -LUALIB_API void *(luaL_testudata) (lua_State *L, int ud, const char *tname); -LUALIB_API void (luaL_setmetatable) (lua_State *L, const char *tname); - - -/* -** =============================================================== -** some useful macros -** =============================================================== -*/ - -#define luaL_argcheck(L, cond,numarg,extramsg) \ - ((void)((cond) || luaL_argerror(L, (numarg), (extramsg)))) -#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL)) -#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL)) -#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n))) -#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d))) -#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n))) -#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d))) - -#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i))) - -#define luaL_dofile(L, fn) \ - (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) - -#define luaL_dostring(L, s) \ - (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0)) - -#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n))) - -#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) - -/* From Lua 5.2. */ -#define luaL_newlibtable(L, l) \ - lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1) -#define luaL_newlib(L, l) (luaL_newlibtable(L, l), luaL_setfuncs(L, l, 0)) - -/* -** {====================================================== -** Generic Buffer manipulation -** ======================================================= -*/ - - - -typedef struct luaL_Buffer { - char *p; /* current position in buffer */ - int lvl; /* number of strings in the stack (level) */ - lua_State *L; - char buffer[LUAL_BUFFERSIZE]; -} luaL_Buffer; - -#define luaL_addchar(B,c) \ - ((void)((B)->p < ((B)->buffer+LUAL_BUFFERSIZE) || luaL_prepbuffer(B)), \ - (*(B)->p++ = (char)(c))) - -/* compatibility only */ -#define luaL_putchar(B,c) luaL_addchar(B,c) - -#define luaL_addsize(B,n) ((B)->p += (n)) - -LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B); -LUALIB_API char *(luaL_prepbuffer) (luaL_Buffer *B); -LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l); -LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s); -LUALIB_API void (luaL_addvalue) (luaL_Buffer *B); -LUALIB_API void (luaL_pushresult) (luaL_Buffer *B); - - -/* }====================================================== */ - -#endif diff --git a/include/luajit/lj_alloc.h b/include/luajit/lj_alloc.h deleted file mode 100644 index 669f50b..0000000 --- a/include/luajit/lj_alloc.h +++ /dev/null @@ -1,18 +0,0 @@ -/* -** Bundled memory allocator. -** Donated to the public domain. -*/ - -#ifndef _LJ_ALLOC_H -#define _LJ_ALLOC_H - -#include "lj_def.h" - -#ifndef LUAJIT_USE_SYSMALLOC -LJ_FUNC void *lj_alloc_create(PRNGState *rs); -LJ_FUNC void lj_alloc_setprng(void *msp, PRNGState *rs); -LJ_FUNC void lj_alloc_destroy(void *msp); -LJ_FUNC void *lj_alloc_f(void *msp, void *ptr, size_t osize, size_t nsize); -#endif - -#endif diff --git a/include/luajit/lj_arch.h b/include/luajit/lj_arch.h deleted file mode 100644 index 5f38806..0000000 --- a/include/luajit/lj_arch.h +++ /dev/null @@ -1,778 +0,0 @@ -/* -** Target architecture selection. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_ARCH_H -#define _LJ_ARCH_H - -#include "lua.h" - -/* -- Target definitions -------------------------------------------------- */ - -/* Target endianess. */ -#define LUAJIT_LE 0 -#define LUAJIT_BE 1 - -/* Target architectures. */ -#define LUAJIT_ARCH_X86 1 -#define LUAJIT_ARCH_x86 1 -#define LUAJIT_ARCH_X64 2 -#define LUAJIT_ARCH_x64 2 -#define LUAJIT_ARCH_ARM 3 -#define LUAJIT_ARCH_arm 3 -#define LUAJIT_ARCH_ARM64 4 -#define LUAJIT_ARCH_arm64 4 -#define LUAJIT_ARCH_PPC 5 -#define LUAJIT_ARCH_ppc 5 -#define LUAJIT_ARCH_MIPS 6 -#define LUAJIT_ARCH_mips 6 -#define LUAJIT_ARCH_MIPS32 6 -#define LUAJIT_ARCH_mips32 6 -#define LUAJIT_ARCH_MIPS64 7 -#define LUAJIT_ARCH_mips64 7 - -/* Target OS. */ -#define LUAJIT_OS_OTHER 0 -#define LUAJIT_OS_WINDOWS 1 -#define LUAJIT_OS_LINUX 2 -#define LUAJIT_OS_OSX 3 -#define LUAJIT_OS_BSD 4 -#define LUAJIT_OS_POSIX 5 - -/* Number mode. */ -#define LJ_NUMMODE_SINGLE 0 /* Single-number mode only. */ -#define LJ_NUMMODE_SINGLE_DUAL 1 /* Default to single-number mode. */ -#define LJ_NUMMODE_DUAL 2 /* Dual-number mode only. */ -#define LJ_NUMMODE_DUAL_SINGLE 3 /* Default to dual-number mode. */ - -/* -- Target detection ---------------------------------------------------- */ - -/* Select native target if no target defined. */ -#ifndef LUAJIT_TARGET - -#if defined(__i386) || defined(__i386__) || defined(_M_IX86) -#define LUAJIT_TARGET LUAJIT_ARCH_X86 -#elif defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64) -#define LUAJIT_TARGET LUAJIT_ARCH_X64 -#elif defined(__arm__) || defined(__arm) || defined(__ARM__) || defined(__ARM) -#define LUAJIT_TARGET LUAJIT_ARCH_ARM -#elif defined(__aarch64__) || defined(_M_ARM64) -#define LUAJIT_TARGET LUAJIT_ARCH_ARM64 -#elif defined(__ppc__) || defined(__ppc) || defined(__PPC__) || defined(__PPC) || defined(__powerpc__) || defined(__powerpc) || defined(__POWERPC__) || defined(__POWERPC) || defined(_M_PPC) -#define LUAJIT_TARGET LUAJIT_ARCH_PPC -#elif defined(__mips64__) || defined(__mips64) || defined(__MIPS64__) || defined(__MIPS64) -#define LUAJIT_TARGET LUAJIT_ARCH_MIPS64 -#elif defined(__mips__) || defined(__mips) || defined(__MIPS__) || defined(__MIPS) -#define LUAJIT_TARGET LUAJIT_ARCH_MIPS32 -#else -#error "Architecture not supported (in this version), see: https://luajit.org/status.html#architectures" -#endif - -#endif - -/* Select native OS if no target OS defined. */ -#ifndef LUAJIT_OS - -#if defined(_WIN32) && !defined(_XBOX_VER) -#define LUAJIT_OS LUAJIT_OS_WINDOWS -#elif defined(__linux__) -#define LUAJIT_OS LUAJIT_OS_LINUX -#elif defined(__MACH__) && defined(__APPLE__) -#include "TargetConditionals.h" -#define LUAJIT_OS LUAJIT_OS_OSX -#elif (defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \ - defined(__NetBSD__) || defined(__OpenBSD__) || \ - defined(__DragonFly__)) && !defined(__ORBIS__) && !defined(__PROSPERO__) -#define LUAJIT_OS LUAJIT_OS_BSD -#elif (defined(__sun__) && defined(__svr4__)) -#define LJ_TARGET_SOLARIS 1 -#define LUAJIT_OS LUAJIT_OS_POSIX -#elif defined(__HAIKU__) -#define LUAJIT_OS LUAJIT_OS_POSIX -#elif defined(__CYGWIN__) -#define LJ_TARGET_CYGWIN 1 -#define LUAJIT_OS LUAJIT_OS_POSIX -#elif defined(__QNX__) -#define LJ_TARGET_QNX 1 -#define LUAJIT_OS LUAJIT_OS_POSIX -#elif defined(__GNU__) -#define LJ_TARGET_HURD 1 -#define LUAJIT_OS LUAJIT_OS_POSIX -#else -#define LUAJIT_OS LUAJIT_OS_OTHER -#endif - -#endif - -/* Set target OS properties. */ -#if LUAJIT_OS == LUAJIT_OS_WINDOWS -#define LJ_OS_NAME "Windows" -#elif LUAJIT_OS == LUAJIT_OS_LINUX -#define LJ_OS_NAME "Linux" -#elif LUAJIT_OS == LUAJIT_OS_OSX -#define LJ_OS_NAME "OSX" -#elif LUAJIT_OS == LUAJIT_OS_BSD -#define LJ_OS_NAME "BSD" -#elif LUAJIT_OS == LUAJIT_OS_POSIX -#define LJ_OS_NAME "POSIX" -#else -#define LJ_OS_NAME "Other" -#endif - -#define LJ_TARGET_WINDOWS (LUAJIT_OS == LUAJIT_OS_WINDOWS) -#define LJ_TARGET_LINUX (LUAJIT_OS == LUAJIT_OS_LINUX) -#define LJ_TARGET_OSX (LUAJIT_OS == LUAJIT_OS_OSX) -#define LJ_TARGET_BSD (LUAJIT_OS == LUAJIT_OS_BSD) -#define LJ_TARGET_POSIX (LUAJIT_OS > LUAJIT_OS_WINDOWS) -#define LJ_TARGET_DLOPEN LJ_TARGET_POSIX - -#if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE -#define LJ_TARGET_IOS 1 -#else -#define LJ_TARGET_IOS 0 -#endif - -#ifdef __CELLOS_LV2__ -#define LJ_TARGET_PS3 1 -#define LJ_TARGET_CONSOLE 1 -#endif - -#ifdef __ORBIS__ -#define LJ_TARGET_PS4 1 -#define LJ_TARGET_CONSOLE 1 -#undef NULL -#define NULL ((void*)0) -#endif - -#ifdef __PROSPERO__ -#define LJ_TARGET_PS5 1 -#define LJ_TARGET_CONSOLE 1 -#undef NULL -#define NULL ((void*)0) -#endif - -#ifdef __psp2__ -#define LJ_TARGET_PSVITA 1 -#define LJ_TARGET_CONSOLE 1 -#endif - -#if _XBOX_VER >= 200 -#define LJ_TARGET_XBOX360 1 -#define LJ_TARGET_CONSOLE 1 -#endif - -#ifdef _DURANGO -#define LJ_TARGET_XBOXONE 1 -#define LJ_TARGET_CONSOLE 1 -#define LJ_TARGET_GC64 1 -#endif - -#ifdef __NX__ -#define LJ_TARGET_NX 1 -#define LJ_TARGET_CONSOLE 1 -#undef NULL -#define NULL ((void*)0) -#endif - -#ifdef _UWP -#define LJ_TARGET_UWP 1 -#if LUAJIT_TARGET == LUAJIT_ARCH_X64 -#define LJ_TARGET_GC64 1 -#endif -#endif - -/* -- Arch-specific settings ---------------------------------------------- */ - -/* Set target architecture properties. */ -#if LUAJIT_TARGET == LUAJIT_ARCH_X86 - -#define LJ_ARCH_NAME "x86" -#define LJ_ARCH_BITS 32 -#define LJ_ARCH_ENDIAN LUAJIT_LE -#define LJ_TARGET_X86 1 -#define LJ_TARGET_X86ORX64 1 -#define LJ_TARGET_EHRETREG 0 -#define LJ_TARGET_EHRAREG 8 -#define LJ_TARGET_MASKSHIFT 1 -#define LJ_TARGET_MASKROT 1 -#define LJ_TARGET_UNALIGNED 1 -#define LJ_ARCH_NUMMODE LJ_NUMMODE_SINGLE_DUAL - -#elif LUAJIT_TARGET == LUAJIT_ARCH_X64 - -#define LJ_ARCH_NAME "x64" -#define LJ_ARCH_BITS 64 -#define LJ_ARCH_ENDIAN LUAJIT_LE -#define LJ_TARGET_X64 1 -#define LJ_TARGET_X86ORX64 1 -#define LJ_TARGET_EHRETREG 0 -#define LJ_TARGET_EHRAREG 16 -#define LJ_TARGET_JUMPRANGE 31 /* +-2^31 = +-2GB */ -#define LJ_TARGET_MASKSHIFT 1 -#define LJ_TARGET_MASKROT 1 -#define LJ_TARGET_UNALIGNED 1 -#define LJ_ARCH_NUMMODE LJ_NUMMODE_SINGLE_DUAL -#ifndef LUAJIT_DISABLE_GC64 -#define LJ_TARGET_GC64 1 -#elif LJ_TARGET_OSX -#error "macOS requires GC64 -- don't disable it" -#endif - -#if !defined(LJ_ABI_BRANCH_TRACK) && (__CET__ & 1) && \ - LJ_TARGET_GC64 && defined(LUAJIT_ENABLE_CET_BR) -/* -** Control-Flow Enforcement Technique (CET) indirect branch tracking (IBT). -** This is not enabled by default because it causes a notable slowdown of -** the interpreter on all x64 CPUs, whether they have CET enabled or not. -** If your toolchain enables -fcf-protection=branch by default, you need -** to build with: make amalg XCFLAGS=-DLUAJIT_ENABLE_CET_BR -*/ -#define LJ_ABI_BRANCH_TRACK 1 -#endif - -#if !defined(LJ_ABI_SHADOW_STACK) && (__CET__ & 2) -/* -** Control-Flow Enforcement Technique (CET) shadow stack (CET-SS). -** It has no code overhead and doesn't cause any slowdowns when unused. -** It can also be unconditionally enabled since all code already follows -** a strict CALL to RET correspondence for performance reasons (all modern -** CPUs use a (non-enforcing) shadow stack for return branch prediction). -*/ -#define LJ_ABI_SHADOW_STACK 1 -#endif - -#elif LUAJIT_TARGET == LUAJIT_ARCH_ARM - -#define LJ_ARCH_NAME "arm" -#define LJ_ARCH_BITS 32 -#define LJ_ARCH_ENDIAN LUAJIT_LE -#if !defined(LJ_ARCH_HASFPU) && __SOFTFP__ -#define LJ_ARCH_HASFPU 0 -#endif -#if !defined(LJ_ABI_SOFTFP) && !__ARM_PCS_VFP -#define LJ_ABI_SOFTFP 1 -#endif -#define LJ_ABI_EABI 1 -#define LJ_TARGET_ARM 1 -#define LJ_TARGET_EHRETREG 0 -#define LJ_TARGET_EHRAREG 14 -#define LJ_TARGET_JUMPRANGE 25 /* +-2^25 = +-32MB */ -#define LJ_TARGET_MASKSHIFT 0 -#define LJ_TARGET_MASKROT 1 -#define LJ_TARGET_UNIFYROT 2 /* Want only IR_BROR. */ -#define LJ_ARCH_NUMMODE LJ_NUMMODE_DUAL - -#if __ARM_ARCH >= 8 || __ARM_ARCH_8__ || __ARM_ARCH_8A__ -#define LJ_ARCH_VERSION 80 -#elif __ARM_ARCH == 7 || __ARM_ARCH_7__ || __ARM_ARCH_7A__ || __ARM_ARCH_7R__ || __ARM_ARCH_7S__ || __ARM_ARCH_7VE__ -#define LJ_ARCH_VERSION 70 -#elif __ARM_ARCH_6T2__ -#define LJ_ARCH_VERSION 61 -#elif __ARM_ARCH == 6 || __ARM_ARCH_6__ || __ARM_ARCH_6J__ || __ARM_ARCH_6K__ || __ARM_ARCH_6Z__ || __ARM_ARCH_6ZK__ -#define LJ_ARCH_VERSION 60 -#else -#define LJ_ARCH_VERSION 50 -#endif - -#elif LUAJIT_TARGET == LUAJIT_ARCH_ARM64 - -#define LJ_ARCH_BITS 64 -#if defined(__AARCH64EB__) -#define LJ_ARCH_NAME "arm64be" -#define LJ_ARCH_ENDIAN LUAJIT_BE -#else -#define LJ_ARCH_NAME "arm64" -#define LJ_ARCH_ENDIAN LUAJIT_LE -#endif -#if !defined(LJ_ABI_PAUTH) && defined(__arm64e__) -#define LJ_ABI_PAUTH 1 -#endif -#if !defined(LJ_ABI_BRANCH_TRACK) && (__ARM_FEATURE_BTI_DEFAULT & 1) && \ - defined(LUAJIT_ENABLE_CET_BR) -/* See comments about LUAJIT_ENABLE_CET_BR above. */ -#define LJ_ABI_BRANCH_TRACK 1 -#endif -#define LJ_TARGET_ARM64 1 -#define LJ_TARGET_EHRETREG 0 -#define LJ_TARGET_EHRAREG 30 -#define LJ_TARGET_JUMPRANGE 27 /* +-2^27 = +-128MB */ -#define LJ_TARGET_MASKSHIFT 1 -#define LJ_TARGET_MASKROT 1 -#define LJ_TARGET_UNIFYROT 2 /* Want only IR_BROR. */ -#define LJ_TARGET_GC64 1 -#define LJ_PAGESIZE 16384 -#define LJ_ARCH_NUMMODE LJ_NUMMODE_DUAL - -#if __ARM_FEATURE_UNALIGNED -#define LJ_TARGET_UNALIGNED 1 -#endif - -#define LJ_ARCH_VERSION 80 - -#elif LUAJIT_TARGET == LUAJIT_ARCH_PPC - -#ifndef LJ_ARCH_ENDIAN -#if __BYTE_ORDER__ != __ORDER_BIG_ENDIAN__ -#define LJ_ARCH_ENDIAN LUAJIT_LE -#else -#define LJ_ARCH_ENDIAN LUAJIT_BE -#endif -#endif - -#if _LP64 -#define LJ_ARCH_BITS 64 -#if LJ_ARCH_ENDIAN == LUAJIT_LE -#define LJ_ARCH_NAME "ppc64le" -#else -#define LJ_ARCH_NAME "ppc64" -#endif -#else -#define LJ_ARCH_BITS 32 -#define LJ_ARCH_NAME "ppc" - -#if !defined(LJ_ARCH_HASFPU) -#if defined(_SOFT_FLOAT) || defined(_SOFT_DOUBLE) -#define LJ_ARCH_HASFPU 0 -#else -#define LJ_ARCH_HASFPU 1 -#endif -#endif - -#if !defined(LJ_ABI_SOFTFP) -#if defined(_SOFT_FLOAT) || defined(_SOFT_DOUBLE) -#define LJ_ABI_SOFTFP 1 -#else -#define LJ_ABI_SOFTFP 0 -#endif -#endif -#endif - -#if LJ_ABI_SOFTFP -#define LJ_ARCH_NUMMODE LJ_NUMMODE_DUAL -#else -#define LJ_ARCH_NUMMODE LJ_NUMMODE_DUAL_SINGLE -#endif - -#define LJ_TARGET_PPC 1 -#define LJ_TARGET_EHRETREG 3 -#define LJ_TARGET_EHRAREG 65 -#define LJ_TARGET_JUMPRANGE 25 /* +-2^25 = +-32MB */ -#define LJ_TARGET_MASKSHIFT 0 -#define LJ_TARGET_MASKROT 1 -#define LJ_TARGET_UNIFYROT 1 /* Want only IR_BROL. */ - -#if LJ_TARGET_CONSOLE -#define LJ_ARCH_PPC32ON64 1 -#define LJ_ARCH_NOFFI 1 -#elif LJ_ARCH_BITS == 64 -#error "No support for PPC64" -#undef LJ_TARGET_PPC -#endif - -#if _ARCH_PWR7 -#define LJ_ARCH_VERSION 70 -#elif _ARCH_PWR6 -#define LJ_ARCH_VERSION 60 -#elif _ARCH_PWR5X -#define LJ_ARCH_VERSION 51 -#elif _ARCH_PWR5 -#define LJ_ARCH_VERSION 50 -#elif _ARCH_PWR4 -#define LJ_ARCH_VERSION 40 -#else -#define LJ_ARCH_VERSION 0 -#endif -#if _ARCH_PPCSQ -#define LJ_ARCH_SQRT 1 -#endif -#if _ARCH_PWR5X -#define LJ_ARCH_ROUND 1 -#endif -#if __PPU__ -#define LJ_ARCH_CELL 1 -#endif -#if LJ_TARGET_XBOX360 -#define LJ_ARCH_XENON 1 -#endif - -#elif LUAJIT_TARGET == LUAJIT_ARCH_MIPS32 || LUAJIT_TARGET == LUAJIT_ARCH_MIPS64 - -#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) -#if __mips_isa_rev >= 6 -#define LJ_TARGET_MIPSR6 1 -#define LJ_TARGET_UNALIGNED 1 -#endif -#if LUAJIT_TARGET == LUAJIT_ARCH_MIPS32 -#if LJ_TARGET_MIPSR6 -#define LJ_ARCH_NAME "mips32r6el" -#else -#define LJ_ARCH_NAME "mipsel" -#endif -#else -#if LJ_TARGET_MIPSR6 -#define LJ_ARCH_NAME "mips64r6el" -#else -#define LJ_ARCH_NAME "mips64el" -#endif -#endif -#define LJ_ARCH_ENDIAN LUAJIT_LE -#else -#if LUAJIT_TARGET == LUAJIT_ARCH_MIPS32 -#if LJ_TARGET_MIPSR6 -#define LJ_ARCH_NAME "mips32r6" -#else -#define LJ_ARCH_NAME "mips" -#endif -#else -#if LJ_TARGET_MIPSR6 -#define LJ_ARCH_NAME "mips64r6" -#else -#define LJ_ARCH_NAME "mips64" -#endif -#endif -#define LJ_ARCH_ENDIAN LUAJIT_BE -#endif - -#if !defined(LJ_ARCH_HASFPU) -#ifdef __mips_soft_float -#define LJ_ARCH_HASFPU 0 -#else -#define LJ_ARCH_HASFPU 1 -#endif -#endif - -#if !defined(LJ_ABI_SOFTFP) -#ifdef __mips_soft_float -#define LJ_ABI_SOFTFP 1 -#else -#define LJ_ABI_SOFTFP 0 -#endif -#endif - -#if LUAJIT_TARGET == LUAJIT_ARCH_MIPS32 -#define LJ_ARCH_BITS 32 -#define LJ_TARGET_MIPS32 1 -#else -#define LJ_ARCH_BITS 64 -#define LJ_TARGET_MIPS64 1 -#define LJ_TARGET_GC64 1 -#endif -#define LJ_TARGET_MIPS 1 -#define LJ_TARGET_EHRETREG 4 -#define LJ_TARGET_EHRAREG 31 -#define LJ_TARGET_JUMPRANGE 28 /* 2^28 = 256MB-aligned region */ -#define LJ_TARGET_MASKSHIFT 1 -#define LJ_TARGET_MASKROT 1 -#define LJ_TARGET_UNIFYROT 2 /* Want only IR_BROR. */ -#define LJ_ARCH_NUMMODE LJ_NUMMODE_DUAL - -#if LJ_TARGET_MIPSR6 -#define LJ_ARCH_VERSION 60 -#elif _MIPS_ARCH_MIPS32R2 || _MIPS_ARCH_MIPS64R2 -#define LJ_ARCH_VERSION 20 -#else -#define LJ_ARCH_VERSION 10 -#endif - -#else -#error "No target architecture defined" -#endif - -/* -- Checks for requirements --------------------------------------------- */ - -/* Check for minimum required compiler versions. */ -#if defined(__GNUC__) -#if LJ_TARGET_X86 -#if (__GNUC__ < 3) || ((__GNUC__ == 3) && __GNUC_MINOR__ < 4) -#error "Need at least GCC 3.4 or newer" -#endif -#elif LJ_TARGET_X64 -#if __GNUC__ < 4 -#error "Need at least GCC 4.0 or newer" -#endif -#elif LJ_TARGET_ARM -#if (__GNUC__ < 4) || ((__GNUC__ == 4) && __GNUC_MINOR__ < 2) -#error "Need at least GCC 4.2 or newer" -#endif -#elif LJ_TARGET_ARM64 -#if __clang__ -#if ((__clang_major__ < 3) || ((__clang_major__ == 3) && __clang_minor__ < 5)) && !defined(__NX_TOOLCHAIN_MAJOR__) -#error "Need at least Clang 3.5 or newer" -#endif -#else -#if (__GNUC__ < 4) || ((__GNUC__ == 4) && __GNUC_MINOR__ < 8) -#error "Need at least GCC 4.8 or newer" -#endif -#endif -#elif !LJ_TARGET_PS3 -#if __clang__ -#if ((__clang_major__ < 3) || ((__clang_major__ == 3) && __clang_minor__ < 5)) -#error "Need at least Clang 3.5 or newer" -#endif -#else -#if (__GNUC__ < 4) || ((__GNUC__ == 4) && __GNUC_MINOR__ < 3) -#error "Need at least GCC 4.3 or newer" -#endif -#endif -#endif -#endif - -/* Check target-specific constraints. */ -#ifndef _BUILDVM_H -#if LJ_TARGET_X64 -#if __USING_SJLJ_EXCEPTIONS__ -#error "Need a C compiler with native exception handling on x64" -#endif -#elif LJ_TARGET_ARM -#if defined(__ARMEB__) -#error "No support for big-endian ARM" -#undef LJ_TARGET_ARM -#endif -#if __ARM_ARCH_6M__ || __ARM_ARCH_7M__ || __ARM_ARCH_7EM__ -#error "No support for Cortex-M CPUs" -#undef LJ_TARGET_ARM -#endif -#if !(__ARM_EABI__ || LJ_TARGET_IOS) -#error "Only ARM EABI or iOS 3.0+ ABI is supported" -#undef LJ_TARGET_ARM -#endif -#elif LJ_TARGET_ARM64 -#if defined(_ILP32) -#error "No support for ILP32 model on ARM64" -#undef LJ_TARGET_ARM64 -#endif -#elif LJ_TARGET_PPC -#if defined(_LITTLE_ENDIAN) && (!defined(_BYTE_ORDER) || (_BYTE_ORDER == _LITTLE_ENDIAN)) -#error "No support for little-endian PPC32" -#undef LJ_TARGET_PPC -#endif -#if defined(__NO_FPRS__) && !defined(_SOFT_FLOAT) -#error "No support for PPC/e500, use LuaJIT 2.0" -#undef LJ_TARGET_PPC -#endif -#elif LJ_TARGET_MIPS32 -#if !((defined(_MIPS_SIM_ABI32) && _MIPS_SIM == _MIPS_SIM_ABI32) || (defined(_ABIO32) && _MIPS_SIM == _ABIO32)) -#error "Only o32 ABI supported for MIPS32" -#undef LJ_TARGET_MIPS -#endif -#if LJ_TARGET_MIPSR6 -/* Not that useful, since most available r6 CPUs are 64 bit. */ -#error "No support for MIPS32R6" -#undef LJ_TARGET_MIPS -#endif -#elif LJ_TARGET_MIPS64 -#if !((defined(_MIPS_SIM_ABI64) && _MIPS_SIM == _MIPS_SIM_ABI64) || (defined(_ABI64) && _MIPS_SIM == _ABI64)) -/* MIPS32ON64 aka n32 ABI support might be desirable, but difficult. */ -#error "Only n64 ABI supported for MIPS64" -#undef LJ_TARGET_MIPS -#endif -#endif -#endif - -/* -- Derived defines ----------------------------------------------------- */ - -/* Enable or disable the dual-number mode for the VM. */ -#if (LJ_ARCH_NUMMODE == LJ_NUMMODE_SINGLE && LUAJIT_NUMMODE == 2) || \ - (LJ_ARCH_NUMMODE == LJ_NUMMODE_DUAL && LUAJIT_NUMMODE == 1) -#error "No support for this number mode on this architecture" -#endif -#if LJ_ARCH_NUMMODE == LJ_NUMMODE_DUAL || \ - (LJ_ARCH_NUMMODE == LJ_NUMMODE_DUAL_SINGLE && LUAJIT_NUMMODE != 1) || \ - (LJ_ARCH_NUMMODE == LJ_NUMMODE_SINGLE_DUAL && LUAJIT_NUMMODE == 2) -#define LJ_DUALNUM 1 -#else -#define LJ_DUALNUM 0 -#endif - -#if LJ_TARGET_IOS || LJ_TARGET_CONSOLE -/* Runtime code generation is restricted on iOS. Complain to Apple, not me. */ -/* Ditto for the consoles. Complain to Sony or MS, not me. */ -#ifndef LUAJIT_ENABLE_JIT -#define LJ_OS_NOJIT 1 -#endif -#endif - -/* 64 bit GC references. */ -#if LJ_TARGET_GC64 -#define LJ_GC64 1 -#else -#define LJ_GC64 0 -#endif - -/* 2-slot frame info. */ -#if LJ_GC64 -#define LJ_FR2 1 -#else -#define LJ_FR2 0 -#endif - -/* Disable or enable the JIT compiler. */ -#if defined(LUAJIT_DISABLE_JIT) || defined(LJ_ARCH_NOJIT) || defined(LJ_OS_NOJIT) -#define LJ_HASJIT 0 -#else -#define LJ_HASJIT 1 -#endif - -/* Disable or enable the FFI extension. */ -#if defined(LUAJIT_DISABLE_FFI) || defined(LJ_ARCH_NOFFI) -#define LJ_HASFFI 0 -#else -#define LJ_HASFFI 1 -#endif - -/* Disable or enable the string buffer extension. */ -#if defined(LUAJIT_DISABLE_BUFFER) -#define LJ_HASBUFFER 0 -#else -#define LJ_HASBUFFER 1 -#endif - -#if defined(LUAJIT_DISABLE_PROFILE) -#define LJ_HASPROFILE 0 -#elif LJ_TARGET_POSIX -#define LJ_HASPROFILE 1 -#define LJ_PROFILE_SIGPROF 1 -#elif LJ_TARGET_PS3 -#define LJ_HASPROFILE 1 -#define LJ_PROFILE_PTHREAD 1 -#elif LJ_TARGET_WINDOWS || LJ_TARGET_XBOX360 -#define LJ_HASPROFILE 1 -#define LJ_PROFILE_WTHREAD 1 -#else -#define LJ_HASPROFILE 0 -#endif - -#ifndef LJ_ARCH_HASFPU -#define LJ_ARCH_HASFPU 1 -#endif -#ifndef LJ_ABI_SOFTFP -#define LJ_ABI_SOFTFP 0 -#endif -#define LJ_SOFTFP (!LJ_ARCH_HASFPU) -#define LJ_SOFTFP32 (LJ_SOFTFP && LJ_32) - -#ifndef LJ_ABI_PAUTH -#define LJ_ABI_PAUTH 0 -#endif - -#if LJ_ARCH_ENDIAN == LUAJIT_BE -#define LJ_LE 0 -#define LJ_BE 1 -#define LJ_ENDIAN_SELECT(le, be) be -#define LJ_ENDIAN_LOHI(lo, hi) hi lo -#else -#define LJ_LE 1 -#define LJ_BE 0 -#define LJ_ENDIAN_SELECT(le, be) le -#define LJ_ENDIAN_LOHI(lo, hi) lo hi -#endif - -#if LJ_ARCH_BITS == 32 -#define LJ_32 1 -#define LJ_64 0 -#else -#define LJ_32 0 -#define LJ_64 1 -#endif - -#ifndef LJ_TARGET_UNALIGNED -#define LJ_TARGET_UNALIGNED 0 -#endif - -#ifndef LJ_PAGESIZE -#define LJ_PAGESIZE 4096 -#endif - -/* Various workarounds for embedded operating systems or weak C runtimes. */ -#if defined(__ANDROID__) || defined(__symbian__) || LJ_TARGET_XBOX360 || LJ_TARGET_WINDOWS -#define LUAJIT_NO_LOG2 -#endif -#if LJ_TARGET_CONSOLE || (LJ_TARGET_IOS && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0) -#define LJ_NO_SYSTEM 1 -#endif - -#if LJ_TARGET_WINDOWS || LJ_TARGET_CYGWIN -#define LJ_ABI_WIN 1 -#else -#define LJ_ABI_WIN 0 -#endif - -#if LJ_TARGET_WINDOWS -#if LJ_TARGET_UWP -#define LJ_WIN_VALLOC VirtualAllocFromApp -#define LJ_WIN_VPROTECT VirtualProtectFromApp -extern void *LJ_WIN_LOADLIBA(const char *path); -#else -#define LJ_WIN_VALLOC VirtualAlloc -#define LJ_WIN_VPROTECT VirtualProtect -#define LJ_WIN_LOADLIBA(path) LoadLibraryExA((path), NULL, 0) -#endif -#endif - -#if defined(LUAJIT_NO_UNWIND) || __GNU_COMPACT_EH__ || defined(__symbian__) || LJ_TARGET_IOS || LJ_TARGET_PS3 || LJ_TARGET_PS4 || LJ_TARGET_PS5 -#define LJ_NO_UNWIND 1 -#endif - -#if !LJ_NO_UNWIND && !defined(LUAJIT_UNWIND_INTERNAL) && (LJ_ABI_WIN || (defined(LUAJIT_UNWIND_EXTERNAL) && (defined(__GNUC__) || defined(__clang__)))) -#define LJ_UNWIND_EXT 1 -#else -#define LJ_UNWIND_EXT 0 -#endif - -#if LJ_UNWIND_EXT && LJ_HASJIT && !LJ_TARGET_ARM && !(LJ_ABI_WIN && LJ_TARGET_X86) -#define LJ_UNWIND_JIT 1 -#else -#define LJ_UNWIND_JIT 0 -#endif - -/* Compatibility with Lua 5.1 vs. 5.2. */ -#ifdef LUAJIT_ENABLE_LUA52COMPAT -#define LJ_52 1 -#else -#define LJ_52 0 -#endif - -/* -- VM security --------------------------------------------------------- */ - -/* Don't make any changes here. Instead build with: -** make "XCFLAGS=-DLUAJIT_SECURITY_flag=value" -** -** Important note to distro maintainers: DO NOT change the defaults for a -** regular distro build -- neither upwards, nor downwards! -** These build-time configurable security flags are intended for embedders -** who may have specific needs wrt. security vs. performance. -*/ - -/* Security defaults. */ -#ifndef LUAJIT_SECURITY_PRNG -/* PRNG init: 0 = fixed/insecure, 1 = secure from OS. */ -#define LUAJIT_SECURITY_PRNG 1 -#endif - -#ifndef LUAJIT_SECURITY_STRHASH -/* String hash: 0 = sparse only, 1 = sparse + dense. */ -#define LUAJIT_SECURITY_STRHASH 1 -#endif - -#ifndef LUAJIT_SECURITY_STRID -/* String IDs: 0 = linear, 1 = reseed < 255, 2 = reseed < 15, 3 = random. */ -#define LUAJIT_SECURITY_STRID 1 -#endif - -#ifndef LUAJIT_SECURITY_MCODE -/* Machine code page protection: 0 = insecure RWX, 1 = secure RW^X. */ -#define LUAJIT_SECURITY_MCODE 1 -#endif - -#define LJ_SECURITY_MODE \ - ( 0u \ - | ((LUAJIT_SECURITY_PRNG & 3) << 0) \ - | ((LUAJIT_SECURITY_STRHASH & 3) << 2) \ - | ((LUAJIT_SECURITY_STRID & 3) << 4) \ - | ((LUAJIT_SECURITY_MCODE & 3) << 6) \ - ) -#define LJ_SECURITY_MODESTRING \ - "\004prng\007strhash\005strid\005mcode" - -#endif diff --git a/include/luajit/lj_asm.h b/include/luajit/lj_asm.h deleted file mode 100644 index b793b10..0000000 --- a/include/luajit/lj_asm.h +++ /dev/null @@ -1,17 +0,0 @@ -/* -** IR assembler (SSA IR -> machine code). -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_ASM_H -#define _LJ_ASM_H - -#include "lj_jit.h" - -#if LJ_HASJIT -LJ_FUNC void lj_asm_trace(jit_State *J, GCtrace *T); -LJ_FUNC void lj_asm_patchexit(jit_State *J, GCtrace *T, ExitNo exitno, - MCode *target); -#endif - -#endif diff --git a/include/luajit/lj_asm_arm.h b/include/luajit/lj_asm_arm.h deleted file mode 100644 index 1ddd2b3..0000000 --- a/include/luajit/lj_asm_arm.h +++ /dev/null @@ -1,2345 +0,0 @@ -/* -** ARM IR assembler (SSA IR -> machine code). -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -/* -- Register allocator extensions --------------------------------------- */ - -/* Allocate a register with a hint. */ -static Reg ra_hintalloc(ASMState *as, IRRef ref, Reg hint, RegSet allow) -{ - Reg r = IR(ref)->r; - if (ra_noreg(r)) { - if (!ra_hashint(r) && !iscrossref(as, ref)) - ra_sethint(IR(ref)->r, hint); /* Propagate register hint. */ - r = ra_allocref(as, ref, allow); - } - ra_noweak(as, r); - return r; -} - -/* Allocate a scratch register pair. */ -static Reg ra_scratchpair(ASMState *as, RegSet allow) -{ - RegSet pick1 = as->freeset & allow; - RegSet pick2 = pick1 & (pick1 >> 1) & RSET_GPREVEN; - Reg r; - if (pick2) { - r = rset_picktop(pick2); - } else { - RegSet pick = pick1 & (allow >> 1) & RSET_GPREVEN; - if (pick) { - r = rset_picktop(pick); - ra_restore(as, regcost_ref(as->cost[r+1])); - } else { - pick = pick1 & (allow << 1) & RSET_GPRODD; - if (pick) { - r = ra_restore(as, regcost_ref(as->cost[rset_picktop(pick)-1])); - } else { - r = ra_evict(as, allow & (allow >> 1) & RSET_GPREVEN); - ra_restore(as, regcost_ref(as->cost[r+1])); - } - } - } - lj_assertA(rset_test(RSET_GPREVEN, r), "odd reg %d", r); - ra_modified(as, r); - ra_modified(as, r+1); - RA_DBGX((as, "scratchpair $r $r", r, r+1)); - return r; -} - -#if !LJ_SOFTFP -/* Allocate two source registers for three-operand instructions. */ -static Reg ra_alloc2(ASMState *as, IRIns *ir, RegSet allow) -{ - IRIns *irl = IR(ir->op1), *irr = IR(ir->op2); - Reg left = irl->r, right = irr->r; - if (ra_hasreg(left)) { - ra_noweak(as, left); - if (ra_noreg(right)) - right = ra_allocref(as, ir->op2, rset_exclude(allow, left)); - else - ra_noweak(as, right); - } else if (ra_hasreg(right)) { - ra_noweak(as, right); - left = ra_allocref(as, ir->op1, rset_exclude(allow, right)); - } else if (ra_hashint(right)) { - right = ra_allocref(as, ir->op2, allow); - left = ra_alloc1(as, ir->op1, rset_exclude(allow, right)); - } else { - left = ra_allocref(as, ir->op1, allow); - right = ra_alloc1(as, ir->op2, rset_exclude(allow, left)); - } - return left | (right << 8); -} -#endif - -/* -- Guard handling ------------------------------------------------------ */ - -/* Generate an exit stub group at the bottom of the reserved MCode memory. */ -static MCode *asm_exitstub_gen(ASMState *as, ExitNo group) -{ - ExitNo i; - int ind = 0; - MCode *target = (MCode *)(void *)lj_vm_exit_handler; - MCode *mxp = as->mcbot; - if (mxp + 6+EXITSTUBS_PER_GROUP >= as->mctop) - asm_mclimit(as); - if ((((target - mxp - 2) + 0x00800000u) >> 24) == 0) { - /* str lr, [sp]; bl ->vm_exit_handler; - ** .long DISPATCH_address, group. - */ - *mxp++ = ARMI_STR | ARMI_LS_P | ARMI_LS_U | ARMF_D(RID_LR) | ARMF_N(RID_SP); - *mxp = ARMI_BL | ((target - mxp - 2) & 0x00ffffffu); mxp++; - } else if ((as->flags & JIT_F_ARMV6T2)) { - /* - ** str lr, [sp]; movw/movt lr, vm_exit_handler; blx lr; - ** .long DISPATCH_address, group; - */ - *mxp++ = ARMI_STR | ARMI_LS_P | ARMI_LS_U | ARMF_D(RID_LR) | ARMF_N(RID_SP); - *mxp++ = emit_movw_k((uint32_t)target) | ARMF_D(RID_LR); - *mxp++ = emit_movt_k((uint32_t)target) | ARMF_D(RID_LR); - *mxp++ = ARMI_BLXr | ARMF_M(RID_LR); - ind = 2; - } else { - /* .long vm_exit_handler; - ** str lr, [sp]; ldr lr, [pc, #-16]; blx lr; - ** .long DISPATCH_address, group; - */ - *mxp++ = (MCode)target; - *mxp++ = ARMI_STR | ARMI_LS_P | ARMI_LS_U | ARMF_D(RID_LR) | ARMF_N(RID_SP); - *mxp++ = ARMI_LDRL | ARMF_D(RID_LR) | 16; - *mxp++ = ARMI_BLXr | ARMF_M(RID_LR); - ind = 1; - } - *mxp++ = (MCode)i32ptr(J2GG(as->J)->dispatch); /* DISPATCH address */ - *mxp++ = group*EXITSTUBS_PER_GROUP; - for (i = 0; i < EXITSTUBS_PER_GROUP; i++) - *mxp++ = ARMI_B | ((-6-ind-i) & 0x00ffffffu); - lj_mcode_sync(as->mcbot, mxp); - lj_mcode_commitbot(as->J, mxp); - as->mcbot = mxp; - as->mclim = as->mcbot + MCLIM_REDZONE; - return mxp - EXITSTUBS_PER_GROUP; -} - -/* Setup all needed exit stubs. */ -static void asm_exitstub_setup(ASMState *as, ExitNo nexits) -{ - ExitNo i; - if (nexits >= EXITSTUBS_PER_GROUP*LJ_MAX_EXITSTUBGR) - lj_trace_err(as->J, LJ_TRERR_SNAPOV); - for (i = 0; i < (nexits+EXITSTUBS_PER_GROUP-1)/EXITSTUBS_PER_GROUP; i++) - if (as->J->exitstubgroup[i] == NULL) - as->J->exitstubgroup[i] = asm_exitstub_gen(as, i); -} - -/* Emit conditional branch to exit for guard. */ -static void asm_guardcc(ASMState *as, ARMCC cc) -{ - MCode *target = exitstub_addr(as->J, as->snapno); - MCode *p = as->mcp; - if (LJ_UNLIKELY(p == as->invmcp)) { - as->loopinv = 1; - *p = ARMI_BL | ((target-p-2) & 0x00ffffffu); - emit_branch(as, ARMF_CC(ARMI_B, cc^1), p+1); - return; - } - emit_branch(as, ARMF_CC(ARMI_BL, cc), target); -} - -/* -- Operand fusion ------------------------------------------------------ */ - -/* Limit linear search to this distance. Avoids O(n^2) behavior. */ -#define CONFLICT_SEARCH_LIM 31 - -/* Check if there's no conflicting instruction between curins and ref. */ -static int noconflict(ASMState *as, IRRef ref, IROp conflict) -{ - IRIns *ir = as->ir; - IRRef i = as->curins; - if (i > ref + CONFLICT_SEARCH_LIM) - return 0; /* Give up, ref is too far away. */ - while (--i > ref) - if (ir[i].o == conflict) - return 0; /* Conflict found. */ - return 1; /* Ok, no conflict. */ -} - -/* Fuse the array base of colocated arrays. */ -static int32_t asm_fuseabase(ASMState *as, IRRef ref) -{ - IRIns *ir = IR(ref); - if (ir->o == IR_TNEW && ir->op1 <= LJ_MAX_COLOSIZE && - !neverfuse(as) && noconflict(as, ref, IR_NEWREF)) - return (int32_t)sizeof(GCtab); - return 0; -} - -/* Fuse array/hash/upvalue reference into register+offset operand. */ -static Reg asm_fuseahuref(ASMState *as, IRRef ref, int32_t *ofsp, RegSet allow, - int lim) -{ - IRIns *ir = IR(ref); - if (ra_noreg(ir->r)) { - if (ir->o == IR_AREF) { - if (mayfuse(as, ref)) { - if (irref_isk(ir->op2)) { - IRRef tab = IR(ir->op1)->op1; - int32_t ofs = asm_fuseabase(as, tab); - IRRef refa = ofs ? tab : ir->op1; - ofs += 8*IR(ir->op2)->i; - if (ofs > -lim && ofs < lim) { - *ofsp = ofs; - return ra_alloc1(as, refa, allow); - } - } - } - } else if (ir->o == IR_HREFK) { - if (mayfuse(as, ref)) { - int32_t ofs = (int32_t)(IR(ir->op2)->op2 * sizeof(Node)); - if (ofs < lim) { - *ofsp = ofs; - return ra_alloc1(as, ir->op1, allow); - } - } - } else if (ir->o == IR_UREFC) { - if (irref_isk(ir->op1)) { - GCfunc *fn = ir_kfunc(IR(ir->op1)); - int32_t ofs = i32ptr(&gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.tv); - *ofsp = (ofs & 255); /* Mask out less bits to allow LDRD. */ - return ra_allock(as, (ofs & ~255), allow); - } - } else if (ir->o == IR_TMPREF) { - *ofsp = 0; - return RID_SP; - } - } - *ofsp = 0; - return ra_alloc1(as, ref, allow); -} - -/* Fuse m operand into arithmetic/logic instructions. */ -static uint32_t asm_fuseopm(ASMState *as, ARMIns ai, IRRef ref, RegSet allow) -{ - IRIns *ir = IR(ref); - if (ra_hasreg(ir->r)) { - ra_noweak(as, ir->r); - return ARMF_M(ir->r); - } else if (irref_isk(ref)) { - uint32_t k = emit_isk12(ai, ir->i); - if (k) - return k; - } else if (mayfuse(as, ref)) { - if (ir->o >= IR_BSHL && ir->o <= IR_BROR) { - Reg m = ra_alloc1(as, ir->op1, allow); - ARMShift sh = ir->o == IR_BSHL ? ARMSH_LSL : - ir->o == IR_BSHR ? ARMSH_LSR : - ir->o == IR_BSAR ? ARMSH_ASR : ARMSH_ROR; - if (irref_isk(ir->op2)) { - return m | ARMF_SH(sh, (IR(ir->op2)->i & 31)); - } else { - Reg s = ra_alloc1(as, ir->op2, rset_exclude(allow, m)); - return m | ARMF_RSH(sh, s); - } - } else if (ir->o == IR_ADD && ir->op1 == ir->op2) { - Reg m = ra_alloc1(as, ir->op1, allow); - return m | ARMF_SH(ARMSH_LSL, 1); - } - } - return ra_allocref(as, ref, allow); -} - -/* Fuse shifts into loads/stores. Only bother with BSHL 2 => lsl #2. */ -static IRRef asm_fuselsl2(ASMState *as, IRRef ref) -{ - IRIns *ir = IR(ref); - if (ra_noreg(ir->r) && mayfuse(as, ref) && ir->o == IR_BSHL && - irref_isk(ir->op2) && IR(ir->op2)->i == 2) - return ir->op1; - return 0; /* No fusion. */ -} - -/* Fuse XLOAD/XSTORE reference into load/store operand. */ -static void asm_fusexref(ASMState *as, ARMIns ai, Reg rd, IRRef ref, - RegSet allow, int32_t ofs) -{ - IRIns *ir = IR(ref); - Reg base; - if (ra_noreg(ir->r) && canfuse(as, ir)) { - int32_t lim = (!LJ_SOFTFP && (ai & 0x08000000)) ? 1024 : - (ai & 0x04000000) ? 4096 : 256; - if (ir->o == IR_ADD) { - int32_t ofs2; - if (irref_isk(ir->op2) && - (ofs2 = ofs + IR(ir->op2)->i) > -lim && ofs2 < lim && - (!(!LJ_SOFTFP && (ai & 0x08000000)) || !(ofs2 & 3))) { - ofs = ofs2; - ref = ir->op1; - } else if (ofs == 0 && !(!LJ_SOFTFP && (ai & 0x08000000))) { - IRRef lref = ir->op1, rref = ir->op2; - Reg rn, rm; - if ((ai & 0x04000000)) { - IRRef sref = asm_fuselsl2(as, rref); - if (sref) { - rref = sref; - ai |= ARMF_SH(ARMSH_LSL, 2); - } else if ((sref = asm_fuselsl2(as, lref)) != 0) { - lref = rref; - rref = sref; - ai |= ARMF_SH(ARMSH_LSL, 2); - } - } - rn = ra_alloc1(as, lref, allow); - rm = ra_alloc1(as, rref, rset_exclude(allow, rn)); - if ((ai & 0x04000000)) ai |= ARMI_LS_R; - emit_dnm(as, ai|ARMI_LS_P|ARMI_LS_U, rd, rn, rm); - return; - } - } else if (ir->o == IR_STRREF && !(!LJ_SOFTFP && (ai & 0x08000000))) { - lj_assertA(ofs == 0, "bad usage"); - ofs = (int32_t)sizeof(GCstr); - if (irref_isk(ir->op2)) { - ofs += IR(ir->op2)->i; - ref = ir->op1; - } else if (irref_isk(ir->op1)) { - ofs += IR(ir->op1)->i; - ref = ir->op2; - } else { - /* NYI: Fuse ADD with constant. */ - Reg rn = ra_alloc1(as, ir->op1, allow); - uint32_t m = asm_fuseopm(as, 0, ir->op2, rset_exclude(allow, rn)); - if ((ai & 0x04000000)) - emit_lso(as, ai, rd, rd, ofs); - else - emit_lsox(as, ai, rd, rd, ofs); - emit_dn(as, ARMI_ADD^m, rd, rn); - return; - } - if (ofs <= -lim || ofs >= lim) { - Reg rn = ra_alloc1(as, ref, allow); - Reg rm = ra_allock(as, ofs, rset_exclude(allow, rn)); - if ((ai & 0x04000000)) ai |= ARMI_LS_R; - emit_dnm(as, ai|ARMI_LS_P|ARMI_LS_U, rd, rn, rm); - return; - } - } - } - base = ra_alloc1(as, ref, allow); -#if !LJ_SOFTFP - if ((ai & 0x08000000)) - emit_vlso(as, ai, rd, base, ofs); - else -#endif - if ((ai & 0x04000000)) - emit_lso(as, ai, rd, base, ofs); - else - emit_lsox(as, ai, rd, base, ofs); -} - -#if !LJ_SOFTFP -/* -** Fuse to multiply-add/sub instruction. -** VMLA rounds twice (UMA, not FMA) -- no need to check for JIT_F_OPT_FMA. -** VFMA needs VFPv4, which is uncommon on the remaining ARM32 targets. -*/ -static int asm_fusemadd(ASMState *as, IRIns *ir, ARMIns ai, ARMIns air) -{ - IRRef lref = ir->op1, rref = ir->op2; - IRIns *irm; - if (lref != rref && - ((mayfuse(as, lref) && (irm = IR(lref), irm->o == IR_MUL) && - ra_noreg(irm->r)) || - (mayfuse(as, rref) && (irm = IR(rref), irm->o == IR_MUL) && - (rref = lref, ai = air, ra_noreg(irm->r))))) { - Reg dest = ra_dest(as, ir, RSET_FPR); - Reg add = ra_hintalloc(as, rref, dest, RSET_FPR); - Reg right, left = ra_alloc2(as, irm, - rset_exclude(rset_exclude(RSET_FPR, dest), add)); - right = (left >> 8); left &= 255; - emit_dnm(as, ai, (dest & 15), (left & 15), (right & 15)); - if (dest != add) emit_dm(as, ARMI_VMOV_D, (dest & 15), (add & 15)); - return 1; - } - return 0; -} -#endif - -/* -- Calls --------------------------------------------------------------- */ - -/* Generate a call to a C function. */ -static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args) -{ - uint32_t n, nargs = CCI_XNARGS(ci); - int32_t ofs = 0; -#if LJ_SOFTFP - Reg gpr = REGARG_FIRSTGPR; -#else - Reg gpr, fpr = REGARG_FIRSTFPR, fprodd = 0; -#endif - if ((void *)ci->func) - emit_call(as, (void *)ci->func); -#if !LJ_SOFTFP - for (gpr = REGARG_FIRSTGPR; gpr <= REGARG_LASTGPR; gpr++) - as->cost[gpr] = REGCOST(~0u, ASMREF_L); - gpr = REGARG_FIRSTGPR; -#endif - for (n = 0; n < nargs; n++) { /* Setup args. */ - IRRef ref = args[n]; - IRIns *ir = IR(ref); -#if !LJ_SOFTFP - if (ref && irt_isfp(ir->t)) { - RegSet of = as->freeset; - Reg src; - if (!LJ_ABI_SOFTFP && !(ci->flags & CCI_VARARG)) { - if (irt_isnum(ir->t)) { - if (fpr <= REGARG_LASTFPR) { - ra_leftov(as, fpr, ref); - fpr++; - continue; - } - } else if (fprodd) { /* Ick. */ - src = ra_alloc1(as, ref, RSET_FPR); - emit_dm(as, ARMI_VMOV_S, (fprodd & 15), (src & 15) | 0x00400000); - fprodd = 0; - continue; - } else if (fpr <= REGARG_LASTFPR) { - ra_leftov(as, fpr, ref); - fprodd = fpr++; - continue; - } - /* Workaround to protect argument GPRs from being used for remat. */ - as->freeset &= ~RSET_RANGE(REGARG_FIRSTGPR, REGARG_LASTGPR+1); - src = ra_alloc1(as, ref, RSET_FPR); /* May alloc GPR to remat FPR. */ - as->freeset |= (of & RSET_RANGE(REGARG_FIRSTGPR, REGARG_LASTGPR+1)); - fprodd = 0; - goto stackfp; - } - /* Workaround to protect argument GPRs from being used for remat. */ - as->freeset &= ~RSET_RANGE(REGARG_FIRSTGPR, REGARG_LASTGPR+1); - src = ra_alloc1(as, ref, RSET_FPR); /* May alloc GPR to remat FPR. */ - as->freeset |= (of & RSET_RANGE(REGARG_FIRSTGPR, REGARG_LASTGPR+1)); - if (irt_isnum(ir->t)) gpr = (gpr+1) & ~1u; - if (gpr <= REGARG_LASTGPR) { - lj_assertA(rset_test(as->freeset, gpr), - "reg %d not free", gpr); /* Must have been evicted. */ - if (irt_isnum(ir->t)) { - lj_assertA(rset_test(as->freeset, gpr+1), - "reg %d not free", gpr+1); /* Ditto. */ - emit_dnm(as, ARMI_VMOV_RR_D, gpr, gpr+1, (src & 15)); - gpr += 2; - } else { - emit_dn(as, ARMI_VMOV_R_S, gpr, (src & 15)); - gpr++; - } - } else { - stackfp: - if (irt_isnum(ir->t)) ofs = (ofs + 4) & ~4; - emit_spstore(as, ir, src, ofs); - ofs += irt_isnum(ir->t) ? 8 : 4; - } - } else -#endif - { - if (gpr <= REGARG_LASTGPR) { - lj_assertA(rset_test(as->freeset, gpr), - "reg %d not free", gpr); /* Must have been evicted. */ - if (ref) ra_leftov(as, gpr, ref); - gpr++; - } else { - if (ref) { - Reg r = ra_alloc1(as, ref, RSET_GPR); - emit_spstore(as, ir, r, ofs); - } - ofs += 4; - } - } - } -} - -/* Setup result reg/sp for call. Evict scratch regs. */ -static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci) -{ - RegSet drop = RSET_SCRATCH; - int hiop = ((ir+1)->o == IR_HIOP && !irt_isnil((ir+1)->t)); - if (ra_hasreg(ir->r)) - rset_clear(drop, ir->r); /* Dest reg handled below. */ - if (hiop && ra_hasreg((ir+1)->r)) - rset_clear(drop, (ir+1)->r); /* Dest reg handled below. */ - ra_evictset(as, drop); /* Evictions must be performed first. */ - if (ra_used(ir)) { - lj_assertA(!irt_ispri(ir->t), "PRI dest"); - if (!LJ_SOFTFP && irt_isfp(ir->t)) { - if (LJ_ABI_SOFTFP || (ci->flags & (CCI_CASTU64|CCI_VARARG))) { - Reg dest = (ra_dest(as, ir, RSET_FPR) & 15); - if (irt_isnum(ir->t)) - emit_dnm(as, ARMI_VMOV_D_RR, RID_RETLO, RID_RETHI, dest); - else - emit_dn(as, ARMI_VMOV_S_R, RID_RET, dest); - } else { - ra_destreg(as, ir, RID_FPRET); - } - } else if (hiop) { - ra_destpair(as, ir); - } else { - ra_destreg(as, ir, RID_RET); - } - } - UNUSED(ci); -} - -static void asm_callx(ASMState *as, IRIns *ir) -{ - IRRef args[CCI_NARGS_MAX*2]; - CCallInfo ci; - IRRef func; - IRIns *irf; - ci.flags = asm_callx_flags(as, ir); - asm_collectargs(as, ir, &ci, args); - asm_setupresult(as, ir, &ci); - func = ir->op2; irf = IR(func); - if (irf->o == IR_CARG) { func = irf->op1; irf = IR(func); } - if (irref_isk(func)) { /* Call to constant address. */ - ci.func = (ASMFunction)(void *)(irf->i); - } else { /* Need a non-argument register for indirect calls. */ - Reg freg = ra_alloc1(as, func, RSET_RANGE(RID_R4, RID_R12+1)); - emit_m(as, ARMI_BLXr, freg); - ci.func = (ASMFunction)(void *)0; - } - asm_gencall(as, &ci, args); -} - -/* -- Returns ------------------------------------------------------------- */ - -/* Return to lower frame. Guard that it goes to the right spot. */ -static void asm_retf(ASMState *as, IRIns *ir) -{ - Reg base = ra_alloc1(as, REF_BASE, RSET_GPR); - void *pc = ir_kptr(IR(ir->op2)); - int32_t delta = 1+LJ_FR2+bc_a(*((const BCIns *)pc - 1)); - as->topslot -= (BCReg)delta; - if ((int32_t)as->topslot < 0) as->topslot = 0; - irt_setmark(IR(REF_BASE)->t); /* Children must not coalesce with BASE reg. */ - /* Need to force a spill on REF_BASE now to update the stack slot. */ - emit_lso(as, ARMI_STR, base, RID_SP, ra_spill(as, IR(REF_BASE))); - emit_setgl(as, base, jit_base); - emit_addptr(as, base, -8*delta); - asm_guardcc(as, CC_NE); - emit_nm(as, ARMI_CMP, RID_TMP, - ra_allock(as, i32ptr(pc), rset_exclude(RSET_GPR, base))); - emit_lso(as, ARMI_LDR, RID_TMP, base, -4); -} - -/* -- Buffer operations --------------------------------------------------- */ - -#if LJ_HASBUFFER -static void asm_bufhdr_write(ASMState *as, Reg sb) -{ - Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, sb)); - IRIns irgc; - int32_t addr = i32ptr((void *)&J2G(as->J)->cur_L); - irgc.ot = IRT(0, IRT_PGC); /* GC type. */ - emit_storeofs(as, &irgc, RID_TMP, sb, offsetof(SBuf, L)); - if ((as->flags & JIT_F_ARMV6T2)) { - emit_dnm(as, ARMI_BFI, RID_TMP, lj_fls(SBUF_MASK_FLAG), tmp); - } else { - emit_dnm(as, ARMI_ORR, RID_TMP, RID_TMP, tmp); - emit_dn(as, ARMI_AND|ARMI_K12|SBUF_MASK_FLAG, tmp, tmp); - } - emit_lso(as, ARMI_LDR, RID_TMP, - ra_allock(as, (addr & ~4095), - rset_exclude(rset_exclude(RSET_GPR, sb), tmp)), - (addr & 4095)); - emit_loadofs(as, &irgc, tmp, sb, offsetof(SBuf, L)); -} -#endif - -/* -- Type conversions ---------------------------------------------------- */ - -#if !LJ_SOFTFP -static void asm_tointg(ASMState *as, IRIns *ir, Reg left) -{ - Reg tmp = ra_scratch(as, rset_exclude(RSET_FPR, left)); - Reg dest = ra_dest(as, ir, RSET_GPR); - asm_guardcc(as, CC_NE); - emit_d(as, ARMI_VMRS, 0); - emit_dm(as, ARMI_VCMP_D, (tmp & 15), (left & 15)); - emit_dm(as, ARMI_VCVT_F64_S32, (tmp & 15), (tmp & 15)); - emit_dn(as, ARMI_VMOV_R_S, dest, (tmp & 15)); - emit_dm(as, ARMI_VCVT_S32_F64, (tmp & 15), (left & 15)); -} - -static void asm_tobit(ASMState *as, IRIns *ir) -{ - RegSet allow = RSET_FPR; - Reg left = ra_alloc1(as, ir->op1, allow); - Reg right = ra_alloc1(as, ir->op2, rset_clear(allow, left)); - Reg tmp = ra_scratch(as, rset_clear(allow, right)); - Reg dest = ra_dest(as, ir, RSET_GPR); - emit_dn(as, ARMI_VMOV_R_S, dest, (tmp & 15)); - emit_dnm(as, ARMI_VADD_D, (tmp & 15), (left & 15), (right & 15)); -} -#endif - -static void asm_conv(ASMState *as, IRIns *ir) -{ - IRType st = (IRType)(ir->op2 & IRCONV_SRCMASK); -#if !LJ_SOFTFP - int stfp = (st == IRT_NUM || st == IRT_FLOAT); -#endif - IRRef lref = ir->op1; - /* 64 bit integer conversions are handled by SPLIT. */ - lj_assertA(!irt_isint64(ir->t) && !(st == IRT_I64 || st == IRT_U64), - "IR %04d has unsplit 64 bit type", - (int)(ir - as->ir) - REF_BIAS); -#if LJ_SOFTFP - /* FP conversions are handled by SPLIT. */ - lj_assertA(!irt_isfp(ir->t) && !(st == IRT_NUM || st == IRT_FLOAT), - "IR %04d has FP type", - (int)(ir - as->ir) - REF_BIAS); - /* Can't check for same types: SPLIT uses CONV int.int + BXOR for sfp NEG. */ -#else - lj_assertA(irt_type(ir->t) != st, "inconsistent types for CONV"); - if (irt_isfp(ir->t)) { - Reg dest = ra_dest(as, ir, RSET_FPR); - if (stfp) { /* FP to FP conversion. */ - emit_dm(as, st == IRT_NUM ? ARMI_VCVT_F32_F64 : ARMI_VCVT_F64_F32, - (dest & 15), (ra_alloc1(as, lref, RSET_FPR) & 15)); - } else { /* Integer to FP conversion. */ - Reg left = ra_alloc1(as, lref, RSET_GPR); - ARMIns ai = irt_isfloat(ir->t) ? - (st == IRT_INT ? ARMI_VCVT_F32_S32 : ARMI_VCVT_F32_U32) : - (st == IRT_INT ? ARMI_VCVT_F64_S32 : ARMI_VCVT_F64_U32); - emit_dm(as, ai, (dest & 15), (dest & 15)); - emit_dn(as, ARMI_VMOV_S_R, left, (dest & 15)); - } - } else if (stfp) { /* FP to integer conversion. */ - if (irt_isguard(ir->t)) { - /* Checked conversions are only supported from number to int. */ - lj_assertA(irt_isint(ir->t) && st == IRT_NUM, - "bad type for checked CONV"); - asm_tointg(as, ir, ra_alloc1(as, lref, RSET_FPR)); - } else { - Reg left = ra_alloc1(as, lref, RSET_FPR); - Reg tmp = ra_scratch(as, rset_exclude(RSET_FPR, left)); - Reg dest = ra_dest(as, ir, RSET_GPR); - ARMIns ai; - lj_assertA(!irt_isu32(ir->t), "bad CONV u32.fp emitted"); - emit_dn(as, ARMI_VMOV_R_S, dest, (tmp & 15)); - ai = st == IRT_NUM ? ARMI_VCVT_S32_F64 : ARMI_VCVT_S32_F32; - emit_dm(as, ai, (tmp & 15), (left & 15)); - } - } else -#endif - { - Reg dest = ra_dest(as, ir, RSET_GPR); - if (st >= IRT_I8 && st <= IRT_U16) { /* Extend to 32 bit integer. */ - Reg left = ra_alloc1(as, lref, RSET_GPR); - lj_assertA(irt_isint(ir->t) || irt_isu32(ir->t), "bad type for CONV EXT"); - if ((as->flags & JIT_F_ARMV6)) { - ARMIns ai = st == IRT_I8 ? ARMI_SXTB : - st == IRT_U8 ? ARMI_UXTB : - st == IRT_I16 ? ARMI_SXTH : ARMI_UXTH; - emit_dm(as, ai, dest, left); - } else if (st == IRT_U8) { - emit_dn(as, ARMI_AND|ARMI_K12|255, dest, left); - } else { - uint32_t shift = st == IRT_I8 ? 24 : 16; - ARMShift sh = st == IRT_U16 ? ARMSH_LSR : ARMSH_ASR; - emit_dm(as, ARMI_MOV|ARMF_SH(sh, shift), dest, RID_TMP); - emit_dm(as, ARMI_MOV|ARMF_SH(ARMSH_LSL, shift), RID_TMP, left); - } - } else { /* Handle 32/32 bit no-op (cast). */ - ra_leftov(as, dest, lref); /* Do nothing, but may need to move regs. */ - } - } -} - -static void asm_strto(ASMState *as, IRIns *ir) -{ - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_strscan_num]; - IRRef args[2]; - Reg rlo = 0, rhi = 0, tmp; - int destused = ra_used(ir); - int32_t ofs = 0; - ra_evictset(as, RSET_SCRATCH); -#if LJ_SOFTFP - if (destused) { - if (ra_hasspill(ir->s) && ra_hasspill((ir+1)->s) && - (ir->s & 1) == 0 && ir->s + 1 == (ir+1)->s) { - int i; - for (i = 0; i < 2; i++) { - Reg r = (ir+i)->r; - if (ra_hasreg(r)) { - ra_free(as, r); - ra_modified(as, r); - emit_spload(as, ir+i, r, sps_scale((ir+i)->s)); - } - } - ofs = sps_scale(ir->s); - destused = 0; - } else { - rhi = ra_dest(as, ir+1, RSET_GPR); - rlo = ra_dest(as, ir, rset_exclude(RSET_GPR, rhi)); - } - } - asm_guardcc(as, CC_EQ); - if (destused) { - emit_lso(as, ARMI_LDR, rhi, RID_SP, 4); - emit_lso(as, ARMI_LDR, rlo, RID_SP, 0); - } -#else - UNUSED(rhi); - if (destused) { - if (ra_hasspill(ir->s)) { - ofs = sps_scale(ir->s); - destused = 0; - if (ra_hasreg(ir->r)) { - ra_free(as, ir->r); - ra_modified(as, ir->r); - emit_spload(as, ir, ir->r, ofs); - } - } else { - rlo = ra_dest(as, ir, RSET_FPR); - } - } - asm_guardcc(as, CC_EQ); - if (destused) - emit_vlso(as, ARMI_VLDR_D, rlo, RID_SP, 0); -#endif - emit_n(as, ARMI_CMP|ARMI_K12|0, RID_RET); /* Test return status. */ - args[0] = ir->op1; /* GCstr *str */ - args[1] = ASMREF_TMP1; /* TValue *n */ - asm_gencall(as, ci, args); - tmp = ra_releasetmp(as, ASMREF_TMP1); - if (ofs == 0) - emit_dm(as, ARMI_MOV, tmp, RID_SP); - else - emit_opk(as, ARMI_ADD, tmp, RID_SP, ofs, RSET_GPR); -} - -/* -- Memory references --------------------------------------------------- */ - -/* Get pointer to TValue. */ -static void asm_tvptr(ASMState *as, Reg dest, IRRef ref, MSize mode) -{ - if ((mode & IRTMPREF_IN1)) { - IRIns *ir = IR(ref); - if (irt_isnum(ir->t)) { - if ((mode & IRTMPREF_OUT1)) { -#if LJ_SOFTFP - lj_assertA(irref_isk(ref), "unsplit FP op"); - emit_dm(as, ARMI_MOV, dest, RID_SP); - emit_lso(as, ARMI_STR, - ra_allock(as, (int32_t)ir_knum(ir)->u32.lo, RSET_GPR), - RID_SP, 0); - emit_lso(as, ARMI_STR, - ra_allock(as, (int32_t)ir_knum(ir)->u32.hi, RSET_GPR), - RID_SP, 4); -#else - Reg src = ra_alloc1(as, ref, RSET_FPR); - emit_dm(as, ARMI_MOV, dest, RID_SP); - emit_vlso(as, ARMI_VSTR_D, src, RID_SP, 0); -#endif - } else if (irref_isk(ref)) { - /* Use the number constant itself as a TValue. */ - ra_allockreg(as, i32ptr(ir_knum(ir)), dest); - } else { -#if LJ_SOFTFP - lj_assertA(0, "unsplit FP op"); -#else - /* Otherwise force a spill and use the spill slot. */ - emit_opk(as, ARMI_ADD, dest, RID_SP, ra_spill(as, ir), RSET_GPR); -#endif - } - } else { - /* Otherwise use [sp] and [sp+4] to hold the TValue. - ** This assumes the following call has max. 4 args. - */ - Reg type; - emit_dm(as, ARMI_MOV, dest, RID_SP); - if (!irt_ispri(ir->t)) { - Reg src = ra_alloc1(as, ref, RSET_GPR); - emit_lso(as, ARMI_STR, src, RID_SP, 0); - } - if (LJ_SOFTFP && (ir+1)->o == IR_HIOP && !irt_isnil((ir+1)->t)) - type = ra_alloc1(as, ref+1, RSET_GPR); - else - type = ra_allock(as, irt_toitype(ir->t), RSET_GPR); - emit_lso(as, ARMI_STR, type, RID_SP, 4); - } - } else { - emit_dm(as, ARMI_MOV, dest, RID_SP); - } -} - -static void asm_aref(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg idx, base; - if (irref_isk(ir->op2)) { - IRRef tab = IR(ir->op1)->op1; - int32_t ofs = asm_fuseabase(as, tab); - IRRef refa = ofs ? tab : ir->op1; - uint32_t k = emit_isk12(ARMI_ADD, ofs + 8*IR(ir->op2)->i); - if (k) { - base = ra_alloc1(as, refa, RSET_GPR); - emit_dn(as, ARMI_ADD^k, dest, base); - return; - } - } - base = ra_alloc1(as, ir->op1, RSET_GPR); - idx = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, base)); - emit_dnm(as, ARMI_ADD|ARMF_SH(ARMSH_LSL, 3), dest, base, idx); -} - -/* Inlined hash lookup. Specialized for key type and for const keys. -** The equivalent C code is: -** Node *n = hashkey(t, key); -** do { -** if (lj_obj_equal(&n->key, key)) return &n->val; -** } while ((n = nextnode(n))); -** return niltv(L); -*/ -static void asm_href(ASMState *as, IRIns *ir, IROp merge) -{ - RegSet allow = RSET_GPR; - int destused = ra_used(ir); - Reg dest = ra_dest(as, ir, allow); - Reg tab = ra_alloc1(as, ir->op1, rset_clear(allow, dest)); - Reg key = 0, keyhi = 0, keynumhi = RID_NONE, tmp = RID_TMP; - IRRef refkey = ir->op2; - IRIns *irkey = IR(refkey); - IRType1 kt = irkey->t; - int32_t k = 0, khi = emit_isk12(ARMI_CMP, irt_toitype(kt)); - uint32_t khash; - MCLabel l_end, l_loop; - rset_clear(allow, tab); - if (!irref_isk(refkey) || irt_isstr(kt)) { -#if LJ_SOFTFP - key = ra_alloc1(as, refkey, allow); - rset_clear(allow, key); - if (irkey[1].o == IR_HIOP) { - if (ra_hasreg((irkey+1)->r)) { - keynumhi = (irkey+1)->r; - keyhi = RID_TMP; - ra_noweak(as, keynumhi); - } else { - keyhi = keynumhi = ra_allocref(as, refkey+1, allow); - } - rset_clear(allow, keynumhi); - khi = 0; - } -#else - if (irt_isnum(kt)) { - key = ra_scratch(as, allow); - rset_clear(allow, key); - keyhi = keynumhi = ra_scratch(as, allow); - rset_clear(allow, keyhi); - khi = 0; - } else { - key = ra_alloc1(as, refkey, allow); - rset_clear(allow, key); - } -#endif - } else if (irt_isnum(kt)) { - int32_t val = (int32_t)ir_knum(irkey)->u32.lo; - k = emit_isk12(ARMI_CMP, val); - if (!k) { - key = ra_allock(as, val, allow); - rset_clear(allow, key); - } - val = (int32_t)ir_knum(irkey)->u32.hi; - khi = emit_isk12(ARMI_CMP, val); - if (!khi) { - keyhi = ra_allock(as, val, allow); - rset_clear(allow, keyhi); - } - } else if (!irt_ispri(kt)) { - k = emit_isk12(ARMI_CMP, irkey->i); - if (!k) { - key = ra_alloc1(as, refkey, allow); - rset_clear(allow, key); - } - } - if (!irt_ispri(kt)) - tmp = ra_scratchpair(as, allow); - - /* Key not found in chain: jump to exit (if merged) or load niltv. */ - l_end = emit_label(as); - as->invmcp = NULL; - if (merge == IR_NE) - asm_guardcc(as, CC_AL); - else if (destused) - emit_loada(as, dest, niltvg(J2G(as->J))); - - /* Follow hash chain until the end. */ - l_loop = --as->mcp; - emit_n(as, ARMI_CMP|ARMI_K12|0, dest); - emit_lso(as, ARMI_LDR, dest, dest, (int32_t)offsetof(Node, next)); - - /* Type and value comparison. */ - if (merge == IR_EQ) - asm_guardcc(as, CC_EQ); - else - emit_branch(as, ARMF_CC(ARMI_B, CC_EQ), l_end); - if (!irt_ispri(kt)) { - emit_nm(as, ARMF_CC(ARMI_CMP, CC_EQ)^k, tmp, key); - emit_nm(as, ARMI_CMP^khi, tmp+1, keyhi); - emit_lsox(as, ARMI_LDRD, tmp, dest, (int32_t)offsetof(Node, key)); - } else { - emit_n(as, ARMI_CMP^khi, tmp); - emit_lso(as, ARMI_LDR, tmp, dest, (int32_t)offsetof(Node, key.it)); - } - *l_loop = ARMF_CC(ARMI_B, CC_NE) | ((as->mcp-l_loop-2) & 0x00ffffffu); - - /* Load main position relative to tab->node into dest. */ - khash = irref_isk(refkey) ? ir_khash(as, irkey) : 1; - if (khash == 0) { - emit_lso(as, ARMI_LDR, dest, tab, (int32_t)offsetof(GCtab, node)); - } else { - emit_dnm(as, ARMI_ADD|ARMF_SH(ARMSH_LSL, 3), dest, dest, tmp); - emit_dnm(as, ARMI_ADD|ARMF_SH(ARMSH_LSL, 1), tmp, tmp, tmp); - if (irt_isstr(kt)) { /* Fetch of str->sid is cheaper than ra_allock. */ - emit_dnm(as, ARMI_AND, tmp, tmp+1, RID_TMP); - emit_lso(as, ARMI_LDR, dest, tab, (int32_t)offsetof(GCtab, node)); - emit_lso(as, ARMI_LDR, tmp+1, key, (int32_t)offsetof(GCstr, sid)); - emit_lso(as, ARMI_LDR, RID_TMP, tab, (int32_t)offsetof(GCtab, hmask)); - } else if (irref_isk(refkey)) { - emit_opk(as, ARMI_AND, tmp, RID_TMP, (int32_t)khash, - rset_exclude(rset_exclude(RSET_GPR, tab), dest)); - emit_lso(as, ARMI_LDR, dest, tab, (int32_t)offsetof(GCtab, node)); - emit_lso(as, ARMI_LDR, RID_TMP, tab, (int32_t)offsetof(GCtab, hmask)); - } else { /* Must match with hash*() in lj_tab.c. */ - if (ra_hasreg(keynumhi)) { /* Canonicalize +-0.0 to 0.0. */ - if (keyhi == RID_TMP) - emit_dm(as, ARMF_CC(ARMI_MOV, CC_NE), keyhi, keynumhi); - emit_d(as, ARMF_CC(ARMI_MOV, CC_EQ)|ARMI_K12|0, keyhi); - } - emit_dnm(as, ARMI_AND, tmp, tmp, RID_TMP); - emit_dnm(as, ARMI_SUB|ARMF_SH(ARMSH_ROR, 32-HASH_ROT3), tmp, tmp, tmp+1); - emit_lso(as, ARMI_LDR, dest, tab, (int32_t)offsetof(GCtab, node)); - emit_dnm(as, ARMI_EOR|ARMF_SH(ARMSH_ROR, 32-((HASH_ROT2+HASH_ROT1)&31)), - tmp, tmp+1, tmp); - emit_lso(as, ARMI_LDR, RID_TMP, tab, (int32_t)offsetof(GCtab, hmask)); - emit_dnm(as, ARMI_SUB|ARMF_SH(ARMSH_ROR, 32-HASH_ROT1), tmp+1, tmp+1, tmp); - if (ra_hasreg(keynumhi)) { - emit_dnm(as, ARMI_EOR, tmp+1, tmp, key); - emit_dnm(as, ARMI_ORR|ARMI_S, RID_TMP, tmp, key); /* Test for +-0.0. */ - emit_dnm(as, ARMI_ADD, tmp, keynumhi, keynumhi); -#if !LJ_SOFTFP - emit_dnm(as, ARMI_VMOV_RR_D, key, keynumhi, - (ra_alloc1(as, refkey, RSET_FPR) & 15)); -#endif - } else { - emit_dnm(as, ARMI_EOR, tmp+1, tmp, key); - emit_opk(as, ARMI_ADD, tmp, key, (int32_t)HASH_BIAS, - rset_exclude(rset_exclude(RSET_GPR, tab), key)); - } - } - } -} - -static void asm_hrefk(ASMState *as, IRIns *ir) -{ - IRIns *kslot = IR(ir->op2); - IRIns *irkey = IR(kslot->op1); - int32_t ofs = (int32_t)(kslot->op2 * sizeof(Node)); - int32_t kofs = ofs + (int32_t)offsetof(Node, key); - Reg dest = (ra_used(ir) || ofs > 4095) ? ra_dest(as, ir, RSET_GPR) : RID_NONE; - Reg node = ra_alloc1(as, ir->op1, RSET_GPR); - Reg key = RID_NONE, type = RID_TMP, idx = node; - RegSet allow = rset_exclude(RSET_GPR, node); - lj_assertA(ofs % sizeof(Node) == 0, "unaligned HREFK slot"); - if (ofs > 4095) { - idx = dest; - rset_clear(allow, dest); - kofs = (int32_t)offsetof(Node, key); - } else if (ra_hasreg(dest)) { - emit_opk(as, ARMI_ADD, dest, node, ofs, allow); - } - asm_guardcc(as, CC_NE); - if (!irt_ispri(irkey->t)) { - RegSet even = (as->freeset & allow); - even = even & (even >> 1) & RSET_GPREVEN; - if (even) { - key = ra_scratch(as, even); - if (rset_test(as->freeset, key+1)) { - type = key+1; - ra_modified(as, type); - } - } else { - key = ra_scratch(as, allow); - } - rset_clear(allow, key); - } - rset_clear(allow, type); - if (irt_isnum(irkey->t)) { - emit_opk(as, ARMF_CC(ARMI_CMP, CC_EQ), 0, type, - (int32_t)ir_knum(irkey)->u32.hi, allow); - emit_opk(as, ARMI_CMP, 0, key, - (int32_t)ir_knum(irkey)->u32.lo, allow); - } else { - if (ra_hasreg(key)) - emit_opk(as, ARMF_CC(ARMI_CMP, CC_EQ), 0, key, irkey->i, allow); - emit_n(as, ARMI_CMN|ARMI_K12|-irt_toitype(irkey->t), type); - } - emit_lso(as, ARMI_LDR, type, idx, kofs+4); - if (ra_hasreg(key)) emit_lso(as, ARMI_LDR, key, idx, kofs); - if (ofs > 4095) - emit_opk(as, ARMI_ADD, dest, node, ofs, RSET_GPR); -} - -static void asm_uref(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - int guarded = (irt_t(ir->t) & (IRT_GUARD|IRT_TYPE)) == (IRT_GUARD|IRT_PGC); - if (irref_isk(ir->op1) && !guarded) { - GCfunc *fn = ir_kfunc(IR(ir->op1)); - MRef *v = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.v; - emit_lsptr(as, ARMI_LDR, dest, v); - } else { - if (guarded) { - asm_guardcc(as, ir->o == IR_UREFC ? CC_NE : CC_EQ); - emit_n(as, ARMI_CMP|ARMI_K12|1, RID_TMP); - } - if (ir->o == IR_UREFC) - emit_opk(as, ARMI_ADD, dest, dest, - (int32_t)offsetof(GCupval, tv), RSET_GPR); - else - emit_lso(as, ARMI_LDR, dest, dest, (int32_t)offsetof(GCupval, v)); - if (guarded) - emit_lso(as, ARMI_LDRB, RID_TMP, dest, - (int32_t)offsetof(GCupval, closed)); - if (irref_isk(ir->op1)) { - GCfunc *fn = ir_kfunc(IR(ir->op1)); - int32_t k = (int32_t)gcrefu(fn->l.uvptr[(ir->op2 >> 8)]); - emit_loadi(as, dest, k); - } else { - emit_lso(as, ARMI_LDR, dest, ra_alloc1(as, ir->op1, RSET_GPR), - (int32_t)offsetof(GCfuncL, uvptr) + 4*(int32_t)(ir->op2 >> 8)); - } - } -} - -static void asm_fref(ASMState *as, IRIns *ir) -{ - UNUSED(as); UNUSED(ir); - lj_assertA(!ra_used(ir), "unfused FREF"); -} - -static void asm_strref(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - IRRef ref = ir->op2, refk = ir->op1; - Reg r; - if (irref_isk(ref)) { - IRRef tmp = refk; refk = ref; ref = tmp; - } else if (!irref_isk(refk)) { - uint32_t k, m = ARMI_K12|sizeof(GCstr); - Reg right, left = ra_alloc1(as, ir->op1, RSET_GPR); - IRIns *irr = IR(ir->op2); - if (ra_hasreg(irr->r)) { - ra_noweak(as, irr->r); - right = irr->r; - } else if (mayfuse(as, irr->op2) && - irr->o == IR_ADD && irref_isk(irr->op2) && - (k = emit_isk12(ARMI_ADD, - (int32_t)sizeof(GCstr) + IR(irr->op2)->i))) { - m = k; - right = ra_alloc1(as, irr->op1, rset_exclude(RSET_GPR, left)); - } else { - right = ra_allocref(as, ir->op2, rset_exclude(RSET_GPR, left)); - } - emit_dn(as, ARMI_ADD^m, dest, dest); - emit_dnm(as, ARMI_ADD, dest, left, right); - return; - } - r = ra_alloc1(as, ref, RSET_GPR); - emit_opk(as, ARMI_ADD, dest, r, - sizeof(GCstr) + IR(refk)->i, rset_exclude(RSET_GPR, r)); -} - -/* -- Loads and stores ---------------------------------------------------- */ - -static ARMIns asm_fxloadins(ASMState *as, IRIns *ir) -{ - UNUSED(as); - switch (irt_type(ir->t)) { - case IRT_I8: return ARMI_LDRSB; - case IRT_U8: return ARMI_LDRB; - case IRT_I16: return ARMI_LDRSH; - case IRT_U16: return ARMI_LDRH; - case IRT_NUM: lj_assertA(!LJ_SOFTFP, "unsplit FP op"); return ARMI_VLDR_D; - case IRT_FLOAT: if (!LJ_SOFTFP) return ARMI_VLDR_S; /* fallthrough */ - default: return ARMI_LDR; - } -} - -static ARMIns asm_fxstoreins(ASMState *as, IRIns *ir) -{ - UNUSED(as); - switch (irt_type(ir->t)) { - case IRT_I8: case IRT_U8: return ARMI_STRB; - case IRT_I16: case IRT_U16: return ARMI_STRH; - case IRT_NUM: lj_assertA(!LJ_SOFTFP, "unsplit FP op"); return ARMI_VSTR_D; - case IRT_FLOAT: if (!LJ_SOFTFP) return ARMI_VSTR_S; /* fallthrough */ - default: return ARMI_STR; - } -} - -static void asm_fload(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - ARMIns ai = asm_fxloadins(as, ir); - Reg idx; - int32_t ofs; - if (ir->op1 == REF_NIL) { /* FLOAD from GG_State with offset. */ - idx = ra_allock(as, (int32_t)(ir->op2<<2) + (int32_t)J2GG(as->J), RSET_GPR); - ofs = 0; - } else { - idx = ra_alloc1(as, ir->op1, RSET_GPR); - if (ir->op2 == IRFL_TAB_ARRAY) { - ofs = asm_fuseabase(as, ir->op1); - if (ofs) { /* Turn the t->array load into an add for colocated arrays. */ - emit_dn(as, ARMI_ADD|ARMI_K12|ofs, dest, idx); - return; - } - } - ofs = field_ofs[ir->op2]; - } - if ((ai & 0x04000000)) - emit_lso(as, ai, dest, idx, ofs); - else - emit_lsox(as, ai, dest, idx, ofs); -} - -static void asm_fstore(ASMState *as, IRIns *ir) -{ - if (ir->r != RID_SINK) { - Reg src = ra_alloc1(as, ir->op2, RSET_GPR); - IRIns *irf = IR(ir->op1); - Reg idx = ra_alloc1(as, irf->op1, rset_exclude(RSET_GPR, src)); - int32_t ofs = field_ofs[irf->op2]; - ARMIns ai = asm_fxstoreins(as, ir); - if ((ai & 0x04000000)) - emit_lso(as, ai, src, idx, ofs); - else - emit_lsox(as, ai, src, idx, ofs); - } -} - -static void asm_xload(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, - (!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR); - lj_assertA(!(ir->op2 & IRXLOAD_UNALIGNED), "unaligned XLOAD"); - asm_fusexref(as, asm_fxloadins(as, ir), dest, ir->op1, RSET_GPR, 0); -} - -static void asm_xstore_(ASMState *as, IRIns *ir, int32_t ofs) -{ - if (ir->r != RID_SINK) { - Reg src = ra_alloc1(as, ir->op2, - (!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR); - asm_fusexref(as, asm_fxstoreins(as, ir), src, ir->op1, - rset_exclude(RSET_GPR, src), ofs); - } -} - -#define asm_xstore(as, ir) asm_xstore_(as, ir, 0) - -static void asm_ahuvload(ASMState *as, IRIns *ir) -{ - int hiop = (LJ_SOFTFP && (ir+1)->o == IR_HIOP); - IRType t = hiop ? IRT_NUM : irt_type(ir->t); - Reg dest = RID_NONE, type = RID_NONE, idx; - RegSet allow = RSET_GPR; - int32_t ofs = 0; - if (hiop && ra_used(ir+1)) { - type = ra_dest(as, ir+1, allow); - rset_clear(allow, type); - } - if (ra_used(ir)) { - lj_assertA((LJ_SOFTFP ? 0 : irt_isnum(ir->t)) || - irt_isint(ir->t) || irt_isaddr(ir->t), - "bad load type %d", irt_type(ir->t)); - dest = ra_dest(as, ir, (!LJ_SOFTFP && t == IRT_NUM) ? RSET_FPR : allow); - rset_clear(allow, dest); - } - idx = asm_fuseahuref(as, ir->op1, &ofs, allow, - (!LJ_SOFTFP && t == IRT_NUM) ? 1024 : 4096); - if (ir->o == IR_VLOAD) ofs += 8 * ir->op2; - if (!hiop || type == RID_NONE) { - rset_clear(allow, idx); - if (ofs < 256 && ra_hasreg(dest) && (dest & 1) == 0 && - rset_test((as->freeset & allow), dest+1)) { - type = dest+1; - ra_modified(as, type); - } else { - type = RID_TMP; - } - } - asm_guardcc(as, t == IRT_NUM ? CC_HS : CC_NE); - emit_n(as, ARMI_CMN|ARMI_K12|-irt_toitype_(t), type); - if (ra_hasreg(dest)) { -#if !LJ_SOFTFP - if (t == IRT_NUM) - emit_vlso(as, ARMI_VLDR_D, dest, idx, ofs); - else -#endif - emit_lso(as, ARMI_LDR, dest, idx, ofs); - } - emit_lso(as, ARMI_LDR, type, idx, ofs+4); -} - -static void asm_ahustore(ASMState *as, IRIns *ir) -{ - if (ir->r != RID_SINK) { - RegSet allow = RSET_GPR; - Reg idx, src = RID_NONE, type = RID_NONE; - int32_t ofs = 0; -#if !LJ_SOFTFP - if (irt_isnum(ir->t)) { - src = ra_alloc1(as, ir->op2, RSET_FPR); - idx = asm_fuseahuref(as, ir->op1, &ofs, allow, 1024); - emit_vlso(as, ARMI_VSTR_D, src, idx, ofs); - } else -#endif - { - int hiop = (LJ_SOFTFP && (ir+1)->o == IR_HIOP); - if (!irt_ispri(ir->t)) { - src = ra_alloc1(as, ir->op2, allow); - rset_clear(allow, src); - } - if (hiop) - type = ra_alloc1(as, (ir+1)->op2, allow); - else - type = ra_allock(as, (int32_t)irt_toitype(ir->t), allow); - idx = asm_fuseahuref(as, ir->op1, &ofs, rset_exclude(allow, type), 4096); - if (ra_hasreg(src)) emit_lso(as, ARMI_STR, src, idx, ofs); - emit_lso(as, ARMI_STR, type, idx, ofs+4); - } - } -} - -static void asm_sload(ASMState *as, IRIns *ir) -{ - int32_t ofs = 8*((int32_t)ir->op1-1) + ((ir->op2 & IRSLOAD_FRAME) ? 4 : 0); - int hiop = (LJ_SOFTFP && (ir+1)->o == IR_HIOP); - IRType t = hiop ? IRT_NUM : irt_type(ir->t); - Reg dest = RID_NONE, type = RID_NONE, base; - RegSet allow = RSET_GPR; - lj_assertA(!(ir->op2 & IRSLOAD_PARENT), - "bad parent SLOAD"); /* Handled by asm_head_side(). */ - lj_assertA(irt_isguard(ir->t) || !(ir->op2 & IRSLOAD_TYPECHECK), - "inconsistent SLOAD variant"); -#if LJ_SOFTFP - lj_assertA(!(ir->op2 & IRSLOAD_CONVERT), - "unsplit SLOAD convert"); /* Handled by LJ_SOFTFP SPLIT. */ - if (hiop && ra_used(ir+1)) { - type = ra_dest(as, ir+1, allow); - rset_clear(allow, type); - } -#else - if ((ir->op2 & IRSLOAD_CONVERT) && irt_isguard(ir->t) && t == IRT_INT) { - dest = ra_scratch(as, RSET_FPR); - asm_tointg(as, ir, dest); - t = IRT_NUM; /* Continue with a regular number type check. */ - } else -#endif - if (ra_used(ir)) { - Reg tmp = RID_NONE; - if ((ir->op2 & IRSLOAD_CONVERT)) - tmp = ra_scratch(as, t == IRT_INT ? RSET_FPR : RSET_GPR); - lj_assertA((LJ_SOFTFP ? 0 : irt_isnum(ir->t)) || - irt_isint(ir->t) || irt_isaddr(ir->t), - "bad SLOAD type %d", irt_type(ir->t)); - dest = ra_dest(as, ir, (!LJ_SOFTFP && t == IRT_NUM) ? RSET_FPR : allow); - rset_clear(allow, dest); - base = ra_alloc1(as, REF_BASE, allow); - if ((ir->op2 & IRSLOAD_CONVERT)) { - if (t == IRT_INT) { - emit_dn(as, ARMI_VMOV_R_S, dest, (tmp & 15)); - emit_dm(as, ARMI_VCVT_S32_F64, (tmp & 15), (tmp & 15)); - t = IRT_NUM; /* Check for original type. */ - } else { - emit_dm(as, ARMI_VCVT_F64_S32, (dest & 15), (dest & 15)); - emit_dn(as, ARMI_VMOV_S_R, tmp, (dest & 15)); - t = IRT_INT; /* Check for original type. */ - } - dest = tmp; - } - goto dotypecheck; - } - base = ra_alloc1(as, REF_BASE, allow); -dotypecheck: - rset_clear(allow, base); - if ((ir->op2 & IRSLOAD_TYPECHECK)) { - if (ra_noreg(type)) { - if (ofs < 256 && ra_hasreg(dest) && (dest & 1) == 0 && - rset_test((as->freeset & allow), dest+1)) { - type = dest+1; - ra_modified(as, type); - } else { - type = RID_TMP; - } - } - asm_guardcc(as, t == IRT_NUM ? CC_HS : CC_NE); - if ((ir->op2 & IRSLOAD_KEYINDEX)) { - emit_n(as, ARMI_CMN|ARMI_K12|1, type); - emit_dn(as, ARMI_EOR^emit_isk12(ARMI_EOR, ~LJ_KEYINDEX), type, type); - } else { - emit_n(as, ARMI_CMN|ARMI_K12|-irt_toitype_(t), type); - } - } - if (ra_hasreg(dest)) { -#if !LJ_SOFTFP - if (t == IRT_NUM) { - if (ofs < 1024) { - emit_vlso(as, ARMI_VLDR_D, dest, base, ofs); - } else { - if (ra_hasreg(type)) emit_lso(as, ARMI_LDR, type, base, ofs+4); - emit_vlso(as, ARMI_VLDR_D, dest, RID_TMP, 0); - emit_opk(as, ARMI_ADD, RID_TMP, base, ofs, allow); - return; - } - } else -#endif - emit_lso(as, ARMI_LDR, dest, base, ofs); - } - if (ra_hasreg(type)) emit_lso(as, ARMI_LDR, type, base, ofs+4); -} - -/* -- Allocations --------------------------------------------------------- */ - -#if LJ_HASFFI -static void asm_cnew(ASMState *as, IRIns *ir) -{ - CTState *cts = ctype_ctsG(J2G(as->J)); - CTypeID id = (CTypeID)IR(ir->op1)->i; - CTSize sz; - CTInfo info = lj_ctype_info(cts, id, &sz); - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_mem_newgco]; - IRRef args[4]; - RegSet allow = (RSET_GPR & ~RSET_SCRATCH); - RegSet drop = RSET_SCRATCH; - lj_assertA(sz != CTSIZE_INVALID || (ir->o == IR_CNEW && ir->op2 != REF_NIL), - "bad CNEW/CNEWI operands"); - - as->gcsteps++; - if (ra_hasreg(ir->r)) - rset_clear(drop, ir->r); /* Dest reg handled below. */ - ra_evictset(as, drop); - if (ra_used(ir)) - ra_destreg(as, ir, RID_RET); /* GCcdata * */ - - /* Initialize immutable cdata object. */ - if (ir->o == IR_CNEWI) { - int32_t ofs = sizeof(GCcdata); - lj_assertA(sz == 4 || sz == 8, "bad CNEWI size %d", sz); - if (sz == 8) { - ofs += 4; ir++; - lj_assertA(ir->o == IR_HIOP, "expected HIOP for CNEWI"); - } - for (;;) { - Reg r = ra_alloc1(as, ir->op2, allow); - emit_lso(as, ARMI_STR, r, RID_RET, ofs); - rset_clear(allow, r); - if (ofs == sizeof(GCcdata)) break; - ofs -= 4; ir--; - } - } else if (ir->op2 != REF_NIL) { /* Create VLA/VLS/aligned cdata. */ - ci = &lj_ir_callinfo[IRCALL_lj_cdata_newv]; - args[0] = ASMREF_L; /* lua_State *L */ - args[1] = ir->op1; /* CTypeID id */ - args[2] = ir->op2; /* CTSize sz */ - args[3] = ASMREF_TMP1; /* CTSize align */ - asm_gencall(as, ci, args); - emit_loadi(as, ra_releasetmp(as, ASMREF_TMP1), (int32_t)ctype_align(info)); - return; - } - - /* Initialize gct and ctypeid. lj_mem_newgco() already sets marked. */ - { - uint32_t k = emit_isk12(ARMI_MOV, id); - Reg r = k ? RID_R1 : ra_allock(as, id, allow); - emit_lso(as, ARMI_STRB, RID_TMP, RID_RET, offsetof(GCcdata, gct)); - emit_lsox(as, ARMI_STRH, r, RID_RET, offsetof(GCcdata, ctypeid)); - emit_d(as, ARMI_MOV|ARMI_K12|~LJ_TCDATA, RID_TMP); - if (k) emit_d(as, ARMI_MOV^k, RID_R1); - } - args[0] = ASMREF_L; /* lua_State *L */ - args[1] = ASMREF_TMP1; /* MSize size */ - asm_gencall(as, ci, args); - ra_allockreg(as, (int32_t)(sz+sizeof(GCcdata)), - ra_releasetmp(as, ASMREF_TMP1)); -} -#endif - -/* -- Write barriers ------------------------------------------------------ */ - -static void asm_tbar(ASMState *as, IRIns *ir) -{ - Reg tab = ra_alloc1(as, ir->op1, RSET_GPR); - Reg link = ra_scratch(as, rset_exclude(RSET_GPR, tab)); - Reg gr = ra_allock(as, i32ptr(J2G(as->J)), - rset_exclude(rset_exclude(RSET_GPR, tab), link)); - Reg mark = RID_TMP; - MCLabel l_end = emit_label(as); - emit_lso(as, ARMI_STR, link, tab, (int32_t)offsetof(GCtab, gclist)); - emit_lso(as, ARMI_STRB, mark, tab, (int32_t)offsetof(GCtab, marked)); - emit_lso(as, ARMI_STR, tab, gr, - (int32_t)offsetof(global_State, gc.grayagain)); - emit_dn(as, ARMI_BIC|ARMI_K12|LJ_GC_BLACK, mark, mark); - emit_lso(as, ARMI_LDR, link, gr, - (int32_t)offsetof(global_State, gc.grayagain)); - emit_branch(as, ARMF_CC(ARMI_B, CC_EQ), l_end); - emit_n(as, ARMI_TST|ARMI_K12|LJ_GC_BLACK, mark); - emit_lso(as, ARMI_LDRB, mark, tab, (int32_t)offsetof(GCtab, marked)); -} - -static void asm_obar(ASMState *as, IRIns *ir) -{ - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_barrieruv]; - IRRef args[2]; - MCLabel l_end; - Reg obj, val, tmp; - /* No need for other object barriers (yet). */ - lj_assertA(IR(ir->op1)->o == IR_UREFC, "bad OBAR type"); - ra_evictset(as, RSET_SCRATCH); - l_end = emit_label(as); - args[0] = ASMREF_TMP1; /* global_State *g */ - args[1] = ir->op1; /* TValue *tv */ - asm_gencall(as, ci, args); - if ((l_end[-1] >> 28) == CC_AL) - l_end[-1] = ARMF_CC(l_end[-1], CC_NE); - else - emit_branch(as, ARMF_CC(ARMI_B, CC_EQ), l_end); - ra_allockreg(as, i32ptr(J2G(as->J)), ra_releasetmp(as, ASMREF_TMP1)); - obj = IR(ir->op1)->r; - tmp = ra_scratch(as, rset_exclude(RSET_GPR, obj)); - emit_n(as, ARMF_CC(ARMI_TST, CC_NE)|ARMI_K12|LJ_GC_BLACK, tmp); - emit_n(as, ARMI_TST|ARMI_K12|LJ_GC_WHITES, RID_TMP); - val = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, obj)); - emit_lso(as, ARMI_LDRB, tmp, obj, - (int32_t)offsetof(GCupval, marked)-(int32_t)offsetof(GCupval, tv)); - emit_lso(as, ARMI_LDRB, RID_TMP, val, (int32_t)offsetof(GChead, marked)); -} - -/* -- Arithmetic and logic operations ------------------------------------- */ - -#if !LJ_SOFTFP -static void asm_fparith(ASMState *as, IRIns *ir, ARMIns ai) -{ - Reg dest = ra_dest(as, ir, RSET_FPR); - Reg right, left = ra_alloc2(as, ir, RSET_FPR); - right = (left >> 8); left &= 255; - emit_dnm(as, ai, (dest & 15), (left & 15), (right & 15)); -} - -static void asm_fpunary(ASMState *as, IRIns *ir, ARMIns ai) -{ - Reg dest = ra_dest(as, ir, RSET_FPR); - Reg left = ra_hintalloc(as, ir->op1, dest, RSET_FPR); - emit_dm(as, ai, (dest & 15), (left & 15)); -} - -static void asm_callround(ASMState *as, IRIns *ir, int id) -{ - /* The modified regs must match with the *.dasc implementation. */ - RegSet drop = RID2RSET(RID_R0)|RID2RSET(RID_R1)|RID2RSET(RID_R2)| - RID2RSET(RID_R3)|RID2RSET(RID_R12); - RegSet of; - Reg dest, src; - ra_evictset(as, drop); - dest = ra_dest(as, ir, RSET_FPR); - emit_dnm(as, ARMI_VMOV_D_RR, RID_RETLO, RID_RETHI, (dest & 15)); - emit_call(as, id == IRFPM_FLOOR ? (void *)lj_vm_floor_sf : - id == IRFPM_CEIL ? (void *)lj_vm_ceil_sf : - (void *)lj_vm_trunc_sf); - /* Workaround to protect argument GPRs from being used for remat. */ - of = as->freeset; - as->freeset &= ~RSET_RANGE(RID_R0, RID_R1+1); - as->cost[RID_R0] = as->cost[RID_R1] = REGCOST(~0u, ASMREF_L); - src = ra_alloc1(as, ir->op1, RSET_FPR); /* May alloc GPR to remat FPR. */ - as->freeset |= (of & RSET_RANGE(RID_R0, RID_R1+1)); - emit_dnm(as, ARMI_VMOV_RR_D, RID_R0, RID_R1, (src & 15)); -} - -static void asm_fpmath(ASMState *as, IRIns *ir) -{ - if (ir->op2 <= IRFPM_TRUNC) - asm_callround(as, ir, ir->op2); - else if (ir->op2 == IRFPM_SQRT) - asm_fpunary(as, ir, ARMI_VSQRT_D); - else - asm_callid(as, ir, IRCALL_lj_vm_floor + ir->op2); -} -#endif - -static int asm_swapops(ASMState *as, IRRef lref, IRRef rref) -{ - IRIns *ir; - if (irref_isk(rref)) - return 0; /* Don't swap constants to the left. */ - if (irref_isk(lref)) - return 1; /* But swap constants to the right. */ - ir = IR(rref); - if ((ir->o >= IR_BSHL && ir->o <= IR_BROR) || - (ir->o == IR_ADD && ir->op1 == ir->op2)) - return 0; /* Don't swap fusable operands to the left. */ - ir = IR(lref); - if ((ir->o >= IR_BSHL && ir->o <= IR_BROR) || - (ir->o == IR_ADD && ir->op1 == ir->op2)) - return 1; /* But swap fusable operands to the right. */ - return 0; /* Otherwise don't swap. */ -} - -static void asm_intop(ASMState *as, IRIns *ir, ARMIns ai) -{ - IRRef lref = ir->op1, rref = ir->op2; - Reg left, dest = ra_dest(as, ir, RSET_GPR); - uint32_t m; - if (asm_swapops(as, lref, rref)) { - IRRef tmp = lref; lref = rref; rref = tmp; - if ((ai & ~ARMI_S) == ARMI_SUB || (ai & ~ARMI_S) == ARMI_SBC) - ai ^= (ARMI_SUB^ARMI_RSB); - } - left = ra_hintalloc(as, lref, dest, RSET_GPR); - m = asm_fuseopm(as, ai, rref, rset_exclude(RSET_GPR, left)); - if (irt_isguard(ir->t)) { /* For IR_ADDOV etc. */ - asm_guardcc(as, CC_VS); - ai |= ARMI_S; - } - emit_dn(as, ai^m, dest, left); -} - -/* Try to drop cmp r, #0. */ -static ARMIns asm_drop_cmp0(ASMState *as, ARMIns ai) -{ - if (as->flagmcp == as->mcp) { - uint32_t cc = (as->mcp[1] >> 28); - as->flagmcp = NULL; - if (cc <= CC_NE) { - as->mcp++; - ai |= ARMI_S; - } else if (cc == CC_GE) { - *++as->mcp ^= ((CC_GE^CC_PL) << 28); - ai |= ARMI_S; - } else if (cc == CC_LT) { - *++as->mcp ^= ((CC_LT^CC_MI) << 28); - ai |= ARMI_S; - } /* else: other conds don't work in general. */ - } - return ai; -} - -static void asm_intop_s(ASMState *as, IRIns *ir, ARMIns ai) -{ - asm_intop(as, ir, asm_drop_cmp0(as, ai)); -} - -static void asm_intneg(ASMState *as, IRIns *ir, ARMIns ai) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); - emit_dn(as, ai|ARMI_K12|0, dest, left); -} - -/* NYI: use add/shift for MUL(OV) with constants. FOLD only does 2^k. */ -static void asm_intmul(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_alloc1(as, ir->op1, rset_exclude(RSET_GPR, dest)); - Reg right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); - Reg tmp = RID_NONE; - /* ARMv5 restriction: dest != left and dest_hi != left. */ - if (dest == left && left != right) { left = right; right = dest; } - if (irt_isguard(ir->t)) { /* IR_MULOV */ - if (!(as->flags & JIT_F_ARMV6) && dest == left) - tmp = left = ra_scratch(as, rset_exclude(RSET_GPR, left)); - asm_guardcc(as, CC_NE); - emit_nm(as, ARMI_TEQ|ARMF_SH(ARMSH_ASR, 31), RID_TMP, dest); - emit_dnm(as, ARMI_SMULL|ARMF_S(right), dest, RID_TMP, left); - } else { - if (!(as->flags & JIT_F_ARMV6) && dest == left) tmp = left = RID_TMP; - emit_nm(as, ARMI_MUL|ARMF_S(right), dest, left); - } - /* Only need this for the dest == left == right case. */ - if (ra_hasreg(tmp)) emit_dm(as, ARMI_MOV, tmp, right); -} - -static void asm_add(ASMState *as, IRIns *ir) -{ -#if !LJ_SOFTFP - if (irt_isnum(ir->t)) { - if (!asm_fusemadd(as, ir, ARMI_VMLA_D, ARMI_VMLA_D)) - asm_fparith(as, ir, ARMI_VADD_D); - return; - } -#endif - asm_intop_s(as, ir, ARMI_ADD); -} - -static void asm_sub(ASMState *as, IRIns *ir) -{ -#if !LJ_SOFTFP - if (irt_isnum(ir->t)) { - if (!asm_fusemadd(as, ir, ARMI_VNMLS_D, ARMI_VMLS_D)) - asm_fparith(as, ir, ARMI_VSUB_D); - return; - } -#endif - asm_intop_s(as, ir, ARMI_SUB); -} - -static void asm_mul(ASMState *as, IRIns *ir) -{ -#if !LJ_SOFTFP - if (irt_isnum(ir->t)) { - asm_fparith(as, ir, ARMI_VMUL_D); - return; - } -#endif - asm_intmul(as, ir); -} - -#define asm_addov(as, ir) asm_add(as, ir) -#define asm_subov(as, ir) asm_sub(as, ir) -#define asm_mulov(as, ir) asm_mul(as, ir) - -#if !LJ_SOFTFP -#define asm_fpdiv(as, ir) asm_fparith(as, ir, ARMI_VDIV_D) -#define asm_abs(as, ir) asm_fpunary(as, ir, ARMI_VABS_D) -#endif - -static void asm_neg(ASMState *as, IRIns *ir) -{ -#if !LJ_SOFTFP - if (irt_isnum(ir->t)) { - asm_fpunary(as, ir, ARMI_VNEG_D); - return; - } -#endif - asm_intneg(as, ir, ARMI_RSB); -} - -static void asm_bitop(ASMState *as, IRIns *ir, ARMIns ai) -{ - ai = asm_drop_cmp0(as, ai); - if (ir->op2 == 0) { - Reg dest = ra_dest(as, ir, RSET_GPR); - uint32_t m = asm_fuseopm(as, ai, ir->op1, RSET_GPR); - emit_d(as, ai^m, dest); - } else { - /* NYI: Turn BAND !k12 into uxtb, uxth or bfc or shl+shr. */ - asm_intop(as, ir, ai); - } -} - -#define asm_bnot(as, ir) asm_bitop(as, ir, ARMI_MVN) - -static void asm_bswap(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_alloc1(as, ir->op1, RSET_GPR); - if ((as->flags & JIT_F_ARMV6)) { - emit_dm(as, ARMI_REV, dest, left); - } else { - Reg tmp2 = dest; - if (tmp2 == left) - tmp2 = ra_scratch(as, rset_exclude(rset_exclude(RSET_GPR, dest), left)); - emit_dnm(as, ARMI_EOR|ARMF_SH(ARMSH_LSR, 8), dest, tmp2, RID_TMP); - emit_dm(as, ARMI_MOV|ARMF_SH(ARMSH_ROR, 8), tmp2, left); - emit_dn(as, ARMI_BIC|ARMI_K12|256*8|255, RID_TMP, RID_TMP); - emit_dnm(as, ARMI_EOR|ARMF_SH(ARMSH_ROR, 16), RID_TMP, left, left); - } -} - -#define asm_band(as, ir) asm_bitop(as, ir, ARMI_AND) -#define asm_bor(as, ir) asm_bitop(as, ir, ARMI_ORR) -#define asm_bxor(as, ir) asm_bitop(as, ir, ARMI_EOR) - -static void asm_bitshift(ASMState *as, IRIns *ir, ARMShift sh) -{ - if (irref_isk(ir->op2)) { /* Constant shifts. */ - /* NYI: Turn SHL+SHR or BAND+SHR into uxtb, uxth or ubfx. */ - /* NYI: Turn SHL+ASR into sxtb, sxth or sbfx. */ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_alloc1(as, ir->op1, RSET_GPR); - int32_t shift = (IR(ir->op2)->i & 31); - emit_dm(as, ARMI_MOV|ARMF_SH(sh, shift), dest, left); - } else { - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_alloc1(as, ir->op1, RSET_GPR); - Reg right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); - emit_dm(as, ARMI_MOV|ARMF_RSH(sh, right), dest, left); - } -} - -#define asm_bshl(as, ir) asm_bitshift(as, ir, ARMSH_LSL) -#define asm_bshr(as, ir) asm_bitshift(as, ir, ARMSH_LSR) -#define asm_bsar(as, ir) asm_bitshift(as, ir, ARMSH_ASR) -#define asm_bror(as, ir) asm_bitshift(as, ir, ARMSH_ROR) -#define asm_brol(as, ir) lj_assertA(0, "unexpected BROL") - -static void asm_intmin_max(ASMState *as, IRIns *ir, int cc) -{ - uint32_t kcmp = 0, kmov = 0; - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); - Reg right = 0; - if (irref_isk(ir->op2)) { - kcmp = emit_isk12(ARMI_CMP, IR(ir->op2)->i); - if (kcmp) kmov = emit_isk12(ARMI_MOV, IR(ir->op2)->i); - } - if (!kmov) { - kcmp = 0; - right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); - } - if (kmov || dest != right) { - emit_dm(as, ARMF_CC(ARMI_MOV, cc)^kmov, dest, right); - cc ^= 1; /* Must use opposite conditions for paired moves. */ - } else { - cc ^= (CC_LT^CC_GT); /* Otherwise may swap CC_LT <-> CC_GT. */ - } - if (dest != left) emit_dm(as, ARMF_CC(ARMI_MOV, cc), dest, left); - emit_nm(as, ARMI_CMP^kcmp, left, right); -} - -#if LJ_SOFTFP -static void asm_sfpmin_max(ASMState *as, IRIns *ir, int cc) -{ - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_softfp_cmp]; - RegSet drop = RSET_SCRATCH; - Reg r; - IRRef args[4]; - args[0] = ir->op1; args[1] = (ir+1)->op1; - args[2] = ir->op2; args[3] = (ir+1)->op2; - /* __aeabi_cdcmple preserves r0-r3. */ - if (ra_hasreg(ir->r)) rset_clear(drop, ir->r); - if (ra_hasreg((ir+1)->r)) rset_clear(drop, (ir+1)->r); - if (!rset_test(as->freeset, RID_R2) && - regcost_ref(as->cost[RID_R2]) == args[2]) rset_clear(drop, RID_R2); - if (!rset_test(as->freeset, RID_R3) && - regcost_ref(as->cost[RID_R3]) == args[3]) rset_clear(drop, RID_R3); - ra_evictset(as, drop); - ra_destpair(as, ir); - emit_dm(as, ARMF_CC(ARMI_MOV, cc), RID_RETHI, RID_R3); - emit_dm(as, ARMF_CC(ARMI_MOV, cc), RID_RETLO, RID_R2); - emit_call(as, (void *)ci->func); - for (r = RID_R0; r <= RID_R3; r++) - ra_leftov(as, r, args[r-RID_R0]); -} -#else -static void asm_fpmin_max(ASMState *as, IRIns *ir, int cc) -{ - Reg dest = (ra_dest(as, ir, RSET_FPR) & 15); - Reg right, left = ra_alloc2(as, ir, RSET_FPR); - right = ((left >> 8) & 15); left &= 15; - if (dest != left) emit_dm(as, ARMF_CC(ARMI_VMOV_D, cc^1), dest, left); - if (dest != right) emit_dm(as, ARMF_CC(ARMI_VMOV_D, cc), dest, right); - emit_d(as, ARMI_VMRS, 0); - emit_dm(as, ARMI_VCMP_D, left, right); -} -#endif - -static void asm_min_max(ASMState *as, IRIns *ir, int cc, int fcc) -{ -#if LJ_SOFTFP - UNUSED(fcc); -#else - if (irt_isnum(ir->t)) - asm_fpmin_max(as, ir, fcc); - else -#endif - asm_intmin_max(as, ir, cc); -} - -#define asm_min(as, ir) asm_min_max(as, ir, CC_GT, CC_PL) -#define asm_max(as, ir) asm_min_max(as, ir, CC_LT, CC_LE) - -/* -- Comparisons --------------------------------------------------------- */ - -/* Map of comparisons to flags. ORDER IR. */ -static const uint8_t asm_compmap[IR_ABC+1] = { - /* op FP swp int cc FP cc */ - /* LT */ CC_GE + (CC_HS << 4), - /* GE x */ CC_LT + (CC_HI << 4), - /* LE */ CC_GT + (CC_HI << 4), - /* GT x */ CC_LE + (CC_HS << 4), - /* ULT x */ CC_HS + (CC_LS << 4), - /* UGE */ CC_LO + (CC_LO << 4), - /* ULE x */ CC_HI + (CC_LO << 4), - /* UGT */ CC_LS + (CC_LS << 4), - /* EQ */ CC_NE + (CC_NE << 4), - /* NE */ CC_EQ + (CC_EQ << 4), - /* ABC */ CC_LS + (CC_LS << 4) /* Same as UGT. */ -}; - -#if LJ_SOFTFP -/* FP comparisons. */ -static void asm_sfpcomp(ASMState *as, IRIns *ir) -{ - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_softfp_cmp]; - RegSet drop = RSET_SCRATCH; - Reg r; - IRRef args[4]; - int swp = (((ir->o ^ (ir->o >> 2)) & ~(ir->o >> 3) & 1) << 1); - args[swp^0] = ir->op1; args[swp^1] = (ir+1)->op1; - args[swp^2] = ir->op2; args[swp^3] = (ir+1)->op2; - /* __aeabi_cdcmple preserves r0-r3. This helps to reduce spills. */ - for (r = RID_R0; r <= RID_R3; r++) - if (!rset_test(as->freeset, r) && - regcost_ref(as->cost[r]) == args[r-RID_R0]) rset_clear(drop, r); - ra_evictset(as, drop); - asm_guardcc(as, (asm_compmap[ir->o] >> 4)); - emit_call(as, (void *)ci->func); - for (r = RID_R0; r <= RID_R3; r++) - ra_leftov(as, r, args[r-RID_R0]); -} -#else -/* FP comparisons. */ -static void asm_fpcomp(ASMState *as, IRIns *ir) -{ - Reg left, right; - ARMIns ai; - int swp = ((ir->o ^ (ir->o >> 2)) & ~(ir->o >> 3) & 1); - if (!swp && irref_isk(ir->op2) && ir_knum(IR(ir->op2))->u64 == 0) { - left = (ra_alloc1(as, ir->op1, RSET_FPR) & 15); - right = 0; - ai = ARMI_VCMPZ_D; - } else { - left = ra_alloc2(as, ir, RSET_FPR); - if (swp) { - right = (left & 15); left = ((left >> 8) & 15); - } else { - right = ((left >> 8) & 15); left &= 15; - } - ai = ARMI_VCMP_D; - } - asm_guardcc(as, (asm_compmap[ir->o] >> 4)); - emit_d(as, ARMI_VMRS, 0); - emit_dm(as, ai, left, right); -} -#endif - -/* Integer comparisons. */ -static void asm_intcomp(ASMState *as, IRIns *ir) -{ - ARMCC cc = (asm_compmap[ir->o] & 15); - IRRef lref = ir->op1, rref = ir->op2; - Reg left; - uint32_t m; - int cmpprev0 = 0; - lj_assertA(irt_isint(ir->t) || irt_isu32(ir->t) || irt_isaddr(ir->t), - "bad comparison data type %d", irt_type(ir->t)); - if (asm_swapops(as, lref, rref)) { - Reg tmp = lref; lref = rref; rref = tmp; - if (cc >= CC_GE) cc ^= 7; /* LT <-> GT, LE <-> GE */ - else if (cc > CC_NE) cc ^= 11; /* LO <-> HI, LS <-> HS */ - } - if (irref_isk(rref) && IR(rref)->i == 0) { - IRIns *irl = IR(lref); - cmpprev0 = (irl+1 == ir); - /* Combine comp(BAND(left, right), 0) into tst left, right. */ - if (cmpprev0 && irl->o == IR_BAND && !ra_used(irl)) { - IRRef blref = irl->op1, brref = irl->op2; - uint32_t m2 = 0; - Reg bleft; - if (asm_swapops(as, blref, brref)) { - Reg tmp = blref; blref = brref; brref = tmp; - } - if (irref_isk(brref)) { - m2 = emit_isk12(ARMI_AND, IR(brref)->i); - if ((m2 & (ARMI_AND^ARMI_BIC))) - goto notst; /* Not beneficial if we miss a constant operand. */ - } - if (cc == CC_GE) cc = CC_PL; - else if (cc == CC_LT) cc = CC_MI; - else if (cc > CC_NE) goto notst; /* Other conds don't work with tst. */ - bleft = ra_alloc1(as, blref, RSET_GPR); - if (!m2) m2 = asm_fuseopm(as, 0, brref, rset_exclude(RSET_GPR, bleft)); - asm_guardcc(as, cc); - emit_n(as, ARMI_TST^m2, bleft); - return; - } - } -notst: - left = ra_alloc1(as, lref, RSET_GPR); - m = asm_fuseopm(as, ARMI_CMP, rref, rset_exclude(RSET_GPR, left)); - asm_guardcc(as, cc); - emit_n(as, ARMI_CMP^m, left); - /* Signed comparison with zero and referencing previous ins? */ - if (cmpprev0 && (cc <= CC_NE || cc >= CC_GE)) - as->flagmcp = as->mcp; /* Allow elimination of the compare. */ -} - -static void asm_comp(ASMState *as, IRIns *ir) -{ -#if !LJ_SOFTFP - if (irt_isnum(ir->t)) - asm_fpcomp(as, ir); - else -#endif - asm_intcomp(as, ir); -} - -#define asm_equal(as, ir) asm_comp(as, ir) - -#if LJ_HASFFI -/* 64 bit integer comparisons. */ -static void asm_int64comp(ASMState *as, IRIns *ir) -{ - int signedcomp = (ir->o <= IR_GT); - ARMCC cclo, cchi; - Reg leftlo, lefthi; - uint32_t mlo, mhi; - RegSet allow = RSET_GPR, oldfree; - - /* Always use unsigned comparison for loword. */ - cclo = asm_compmap[ir->o + (signedcomp ? 4 : 0)] & 15; - leftlo = ra_alloc1(as, ir->op1, allow); - oldfree = as->freeset; - mlo = asm_fuseopm(as, ARMI_CMP, ir->op2, rset_clear(allow, leftlo)); - allow &= ~(oldfree & ~as->freeset); /* Update for allocs of asm_fuseopm. */ - - /* Use signed or unsigned comparison for hiword. */ - cchi = asm_compmap[ir->o] & 15; - lefthi = ra_alloc1(as, (ir+1)->op1, allow); - mhi = asm_fuseopm(as, ARMI_CMP, (ir+1)->op2, rset_clear(allow, lefthi)); - - /* All register allocations must be performed _before_ this point. */ - if (signedcomp) { - MCLabel l_around = emit_label(as); - asm_guardcc(as, cclo); - emit_n(as, ARMI_CMP^mlo, leftlo); - emit_branch(as, ARMF_CC(ARMI_B, CC_NE), l_around); - if (cchi == CC_GE || cchi == CC_LE) cchi ^= 6; /* GE -> GT, LE -> LT */ - asm_guardcc(as, cchi); - } else { - asm_guardcc(as, cclo); - emit_n(as, ARMF_CC(ARMI_CMP, CC_EQ)^mlo, leftlo); - } - emit_n(as, ARMI_CMP^mhi, lefthi); -} -#endif - -/* -- Split register ops -------------------------------------------------- */ - -/* Hiword op of a split 32/32 bit op. Previous op is the loword op. */ -static void asm_hiop(ASMState *as, IRIns *ir) -{ - /* HIOP is marked as a store because it needs its own DCE logic. */ - int uselo = ra_used(ir-1), usehi = ra_used(ir); /* Loword/hiword used? */ - if (LJ_UNLIKELY(!(as->flags & JIT_F_OPT_DCE))) uselo = usehi = 1; -#if LJ_HASFFI || LJ_SOFTFP - if ((ir-1)->o <= IR_NE) { /* 64 bit integer or FP comparisons. ORDER IR. */ - as->curins--; /* Always skip the loword comparison. */ -#if LJ_SOFTFP - if (!irt_isint(ir->t)) { - asm_sfpcomp(as, ir-1); - return; - } -#endif -#if LJ_HASFFI - asm_int64comp(as, ir-1); -#endif - return; -#if LJ_SOFTFP - } else if ((ir-1)->o == IR_MIN || (ir-1)->o == IR_MAX) { - as->curins--; /* Always skip the loword min/max. */ - if (uselo || usehi) - asm_sfpmin_max(as, ir-1, (ir-1)->o == IR_MIN ? CC_HS : CC_LS); - return; -#elif LJ_HASFFI - } else if ((ir-1)->o == IR_CONV) { - as->curins--; /* Always skip the CONV. */ - if (usehi || uselo) - asm_conv64(as, ir); - return; -#endif - } else if ((ir-1)->o == IR_XSTORE) { - if ((ir-1)->r != RID_SINK) - asm_xstore_(as, ir, 4); - return; - } -#endif - if (!usehi) return; /* Skip unused hiword op for all remaining ops. */ - switch ((ir-1)->o) { -#if LJ_HASFFI - case IR_ADD: - as->curins--; - asm_intop(as, ir, ARMI_ADC); - asm_intop(as, ir-1, ARMI_ADD|ARMI_S); - break; - case IR_SUB: - as->curins--; - asm_intop(as, ir, ARMI_SBC); - asm_intop(as, ir-1, ARMI_SUB|ARMI_S); - break; - case IR_NEG: - as->curins--; - asm_intneg(as, ir, ARMI_RSC); - asm_intneg(as, ir-1, ARMI_RSB|ARMI_S); - break; - case IR_CNEWI: - /* Nothing to do here. Handled by lo op itself. */ - break; -#endif -#if LJ_SOFTFP - case IR_SLOAD: case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD: - case IR_STRTO: - if (!uselo) - ra_allocref(as, ir->op1, RSET_GPR); /* Mark lo op as used. */ - break; - case IR_ASTORE: case IR_HSTORE: case IR_USTORE: case IR_TOSTR: case IR_TMPREF: - /* Nothing to do here. Handled by lo op itself. */ - break; -#endif - case IR_CALLN: case IR_CALLL: case IR_CALLS: case IR_CALLXS: - if (!uselo) - ra_allocref(as, ir->op1, RID2RSET(RID_RETLO)); /* Mark lo op as used. */ - break; - default: lj_assertA(0, "bad HIOP for op %d", (ir-1)->o); break; - } -} - -/* -- Profiling ----------------------------------------------------------- */ - -static void asm_prof(ASMState *as, IRIns *ir) -{ - UNUSED(ir); - asm_guardcc(as, CC_NE); - emit_n(as, ARMI_TST|ARMI_K12|HOOK_PROFILE, RID_TMP); - emit_lsptr(as, ARMI_LDRB, RID_TMP, (void *)&J2G(as->J)->hookmask); -} - -/* -- Stack handling ------------------------------------------------------ */ - -/* Check Lua stack size for overflow. Use exit handler as fallback. */ -static void asm_stack_check(ASMState *as, BCReg topslot, - IRIns *irp, RegSet allow, ExitNo exitno) -{ - int savereg = 0; - Reg pbase; - uint32_t k; - if (irp) { - if (!ra_hasspill(irp->s)) { - pbase = irp->r; - lj_assertA(ra_hasreg(pbase), "base reg lost"); - } else if (allow) { - pbase = rset_pickbot(allow); - } else { - pbase = RID_RET; - savereg = 1; - } - } else { - pbase = RID_BASE; - } - emit_branch(as, ARMF_CC(ARMI_BL, CC_LS), exitstub_addr(as->J, exitno)); - if (savereg) - emit_lso(as, ARMI_LDR, RID_RET, RID_SP, 0); /* Restore temp. register. */ - k = emit_isk12(0, (int32_t)(8*topslot)); - lj_assertA(k, "slot offset %d does not fit in K12", 8*topslot); - emit_n(as, ARMI_CMP^k, RID_TMP); - emit_dnm(as, ARMI_SUB, RID_TMP, RID_TMP, pbase); - emit_lso(as, ARMI_LDR, RID_TMP, RID_TMP, - (int32_t)offsetof(lua_State, maxstack)); - if (irp) { /* Must not spill arbitrary registers in head of side trace. */ - int32_t i = i32ptr(&J2G(as->J)->cur_L); - if (ra_hasspill(irp->s)) - emit_lso(as, ARMI_LDR, pbase, RID_SP, sps_scale(irp->s)); - emit_lso(as, ARMI_LDR, RID_TMP, RID_TMP, (i & 4095)); - if (savereg) - emit_lso(as, ARMI_STR, RID_RET, RID_SP, 0); /* Save temp. register. */ - emit_loadi(as, RID_TMP, (i & ~4095)); - } else { - emit_getgl(as, RID_TMP, cur_L); - } -} - -/* Restore Lua stack from on-trace state. */ -static void asm_stack_restore(ASMState *as, SnapShot *snap) -{ - SnapEntry *map = &as->T->snapmap[snap->mapofs]; - SnapEntry *flinks = &as->T->snapmap[snap_nextofs(as->T, snap)-1]; - MSize n, nent = snap->nent; - int32_t bias = 0; - /* Store the value of all modified slots to the Lua stack. */ - for (n = 0; n < nent; n++) { - SnapEntry sn = map[n]; - BCReg s = snap_slot(sn); - int32_t ofs = 8*((int32_t)s-1) - bias; - IRRef ref = snap_ref(sn); - IRIns *ir = IR(ref); - if ((sn & SNAP_NORESTORE)) - continue; - if (irt_isnum(ir->t)) { -#if LJ_SOFTFP - RegSet odd = rset_exclude(RSET_GPRODD, RID_BASE); - Reg tmp; - /* LJ_SOFTFP: must be a number constant. */ - lj_assertA(irref_isk(ref), "unsplit FP op"); - tmp = ra_allock(as, (int32_t)ir_knum(ir)->u32.lo, - rset_exclude(RSET_GPREVEN, RID_BASE)); - emit_lso(as, ARMI_STR, tmp, RID_BASE, ofs); - if (rset_test(as->freeset, tmp+1)) odd = RID2RSET(tmp+1); - tmp = ra_allock(as, (int32_t)ir_knum(ir)->u32.hi, odd); - emit_lso(as, ARMI_STR, tmp, RID_BASE, ofs+4); -#else - Reg src = ra_alloc1(as, ref, RSET_FPR); - if (LJ_UNLIKELY(ofs < -1020 || ofs > 1020)) { - int32_t adj = ofs & 0xffffff00; /* K12-friendly. */ - bias += adj; - ofs -= adj; - emit_addptr(as, RID_BASE, -adj); - } - emit_vlso(as, ARMI_VSTR_D, src, RID_BASE, ofs); -#endif - } else { - RegSet odd = rset_exclude(RSET_GPRODD, RID_BASE); - Reg type; - lj_assertA(irt_ispri(ir->t) || irt_isaddr(ir->t) || irt_isinteger(ir->t), - "restore of IR type %d", irt_type(ir->t)); - if (!irt_ispri(ir->t)) { - Reg src = ra_alloc1(as, ref, rset_exclude(RSET_GPREVEN, RID_BASE)); - emit_lso(as, ARMI_STR, src, RID_BASE, ofs); - if (rset_test(as->freeset, src+1)) odd = RID2RSET(src+1); - } - if ((sn & (SNAP_CONT|SNAP_FRAME))) { - if (s == 0) continue; /* Do not overwrite link to previous frame. */ - type = ra_allock(as, (int32_t)(*flinks--), odd); -#if LJ_SOFTFP - } else if ((sn & SNAP_SOFTFPNUM)) { - type = ra_alloc1(as, ref+1, rset_exclude(RSET_GPRODD, RID_BASE)); -#endif - } else if ((sn & SNAP_KEYINDEX)) { - type = ra_allock(as, (int32_t)LJ_KEYINDEX, odd); - } else { - type = ra_allock(as, (int32_t)irt_toitype(ir->t), odd); - } - emit_lso(as, ARMI_STR, type, RID_BASE, ofs+4); - } - checkmclim(as); - } - emit_addptr(as, RID_BASE, bias); - lj_assertA(map + nent == flinks, "inconsistent frames in snapshot"); -} - -/* -- GC handling --------------------------------------------------------- */ - -/* Marker to prevent patching the GC check exit. */ -#define ARM_NOPATCH_GC_CHECK (ARMI_BIC|ARMI_K12) - -/* Check GC threshold and do one or more GC steps. */ -static void asm_gc_check(ASMState *as) -{ - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_step_jit]; - IRRef args[2]; - MCLabel l_end; - Reg tmp1, tmp2; - ra_evictset(as, RSET_SCRATCH); - l_end = emit_label(as); - /* Exit trace if in GCSatomic or GCSfinalize. Avoids syncing GC objects. */ - asm_guardcc(as, CC_NE); /* Assumes asm_snap_prep() already done. */ - *--as->mcp = ARM_NOPATCH_GC_CHECK; - emit_n(as, ARMI_CMP|ARMI_K12|0, RID_RET); - args[0] = ASMREF_TMP1; /* global_State *g */ - args[1] = ASMREF_TMP2; /* MSize steps */ - asm_gencall(as, ci, args); - tmp1 = ra_releasetmp(as, ASMREF_TMP1); - tmp2 = ra_releasetmp(as, ASMREF_TMP2); - emit_loadi(as, tmp2, as->gcsteps); - /* Jump around GC step if GC total < GC threshold. */ - emit_branch(as, ARMF_CC(ARMI_B, CC_LS), l_end); - emit_nm(as, ARMI_CMP, RID_TMP, tmp2); - emit_lso(as, ARMI_LDR, tmp2, tmp1, - (int32_t)offsetof(global_State, gc.threshold)); - emit_lso(as, ARMI_LDR, RID_TMP, tmp1, - (int32_t)offsetof(global_State, gc.total)); - ra_allockreg(as, i32ptr(J2G(as->J)), tmp1); - as->gcsteps = 0; - checkmclim(as); -} - -/* -- Loop handling ------------------------------------------------------- */ - -/* Fixup the loop branch. */ -static void asm_loop_fixup(ASMState *as) -{ - MCode *p = as->mctop; - MCode *target = as->mcp; - if (as->loopinv) { /* Inverted loop branch? */ - /* asm_guardcc already inverted the bcc and patched the final bl. */ - p[-2] |= ((uint32_t)(target-p) & 0x00ffffffu); - } else { - p[-1] = ARMI_B | ((uint32_t)((target-p)-1) & 0x00ffffffu); - } -} - -/* Fixup the tail of the loop. */ -static void asm_loop_tail_fixup(ASMState *as) -{ - UNUSED(as); /* Nothing to do. */ -} - -/* -- Head of trace ------------------------------------------------------- */ - -/* Reload L register from g->cur_L. */ -static void asm_head_lreg(ASMState *as) -{ - IRIns *ir = IR(ASMREF_L); - if (ra_used(ir)) { - Reg r = ra_dest(as, ir, RSET_GPR); - emit_getgl(as, r, cur_L); - ra_evictk(as); - } -} - -/* Coalesce BASE register for a root trace. */ -static void asm_head_root_base(ASMState *as) -{ - IRIns *ir; - asm_head_lreg(as); - ir = IR(REF_BASE); - if (ra_hasreg(ir->r) && (rset_test(as->modset, ir->r) || irt_ismarked(ir->t))) - ra_spill(as, ir); - ra_destreg(as, ir, RID_BASE); -} - -/* Coalesce BASE register for a side trace. */ -static Reg asm_head_side_base(ASMState *as, IRIns *irp) -{ - IRIns *ir; - asm_head_lreg(as); - ir = IR(REF_BASE); - if (ra_hasreg(ir->r) && (rset_test(as->modset, ir->r) || irt_ismarked(ir->t))) - ra_spill(as, ir); - if (ra_hasspill(irp->s)) { - return ra_dest(as, ir, RSET_GPR); - } else { - Reg r = irp->r; - lj_assertA(ra_hasreg(r), "base reg lost"); - if (r != ir->r && !rset_test(as->freeset, r)) - ra_restore(as, regcost_ref(as->cost[r])); - ra_destreg(as, ir, r); - return r; - } -} - -/* -- Tail of trace ------------------------------------------------------- */ - -/* Fixup the tail code. */ -static void asm_tail_fixup(ASMState *as, TraceNo lnk) -{ - MCode *target = lnk ? traceref(as->J, lnk)->mcode : (MCode *)(void *)lj_vm_exit_interp; - MCode *mcp = as->mctail; - int32_t spadj = as->T->spadjust; - if (spadj) { /* Emit stack adjustment. */ - uint32_t k = emit_isk12(ARMI_ADD, spadj); - lj_assertA(k, "stack adjustment %d does not fit in K12", spadj); - *mcp++ = (ARMI_ADD^k) | ARMF_D(RID_SP) | ARMF_N(RID_SP); - } - if ((((target - mcp - 2) + 0x00800000u) >> 24) == 0) { - *mcp = ARMI_B | ((target - mcp - 2) & 0x00ffffffu); mcp++; - } else if ((as->flags & JIT_F_ARMV6T2)) { - *mcp++ = emit_movw_k((uint32_t)target) | ARMF_D(RID_LR); - *mcp++ = emit_movt_k((uint32_t)target) | ARMF_D(RID_LR); - *mcp++ = ARMI_BX | ARMF_M(RID_LR); - } else { - *mcp++ = ARMI_LDRL | ARMI_LS_U | ARMF_D(RID_LR) | 0; - *mcp++ = ARMI_BX | ARMF_M(RID_LR); - *mcp++ = (MCode)target; - } - while (as->mctop > mcp) *--as->mctop = ARMI_NOP; -} - -/* Prepare tail of code. */ -static void asm_tail_prep(ASMState *as, TraceNo lnk) -{ - MCode *p = as->mctop - 1; /* Leave room for exit branch. */ - if (as->loopref) { - as->invmcp = as->mcp = p; - } else { - if (!lnk) { - MCode *target = (MCode *)(void *)lj_vm_exit_interp; - if ((((target - p - 2) + 0x00800000u) >> 24) || - (((target - p - 1) + 0x00800000u) >> 24)) p -= 2; - } - p--; /* Leave room for stack pointer adjustment. */ - as->mcp = p; - as->invmcp = NULL; - } - *p = 0; /* Prevent load/store merging. */ - as->mctail = p; -} - -/* -- Trace setup --------------------------------------------------------- */ - -/* Ensure there are enough stack slots for call arguments. */ -static Reg asm_setup_call_slots(ASMState *as, IRIns *ir, const CCallInfo *ci) -{ - IRRef args[CCI_NARGS_MAX*2]; - uint32_t i, nargs = CCI_XNARGS(ci); - int nslots = 0, ngpr = REGARG_NUMGPR, nfpr = REGARG_NUMFPR, fprodd = 0; - asm_collectargs(as, ir, ci, args); - for (i = 0; i < nargs; i++) { - if (!LJ_SOFTFP && args[i] && irt_isfp(IR(args[i])->t)) { - if (!LJ_ABI_SOFTFP && !(ci->flags & CCI_VARARG)) { - if (irt_isnum(IR(args[i])->t)) { - if (nfpr > 0) nfpr--; - else fprodd = 0, nslots = (nslots + 3) & ~1; - } else { - if (fprodd) fprodd--; - else if (nfpr > 0) fprodd = 1, nfpr--; - else nslots++; - } - } else if (irt_isnum(IR(args[i])->t)) { - ngpr &= ~1; - if (ngpr > 0) ngpr -= 2; else nslots += 2; - } else { - if (ngpr > 0) ngpr--; else nslots++; - } - } else { - if (ngpr > 0) ngpr--; else nslots++; - } - } - if (nslots > as->evenspill) /* Leave room for args in stack slots. */ - as->evenspill = nslots; - return REGSP_HINT(irt_isfp(ir->t) ? RID_FPRET : RID_RET); -} - -static void asm_setup_target(ASMState *as) -{ - /* May need extra exit for asm_stack_check on side traces. */ - asm_exitstub_setup(as, as->T->nsnap + (as->parent ? 1 : 0)); -} - -/* -- Trace patching ------------------------------------------------------ */ - -/* Patch exit jumps of existing machine code to a new target. */ -void lj_asm_patchexit(jit_State *J, GCtrace *T, ExitNo exitno, MCode *target) -{ - MCode *p = T->mcode; - MCode *pe = (MCode *)((char *)p + T->szmcode); - MCode *cstart = NULL, *cend = p; - MCode *mcarea = lj_mcode_patch(J, p, 0); - MCode *px = exitstub_addr(J, exitno) - 2; - for (; p < pe; p++) { - /* Look for bl_cc exitstub, replace with b_cc target. */ - uint32_t ins = *p; - if ((ins & 0x0f000000u) == 0x0b000000u && ins < 0xf0000000u && - ((ins ^ (px-p)) & 0x00ffffffu) == 0 && - p[-1] != ARM_NOPATCH_GC_CHECK) { - *p = (ins & 0xfe000000u) | (((target-p)-2) & 0x00ffffffu); - cend = p+1; - if (!cstart) cstart = p; - } - } - lj_assertJ(cstart != NULL, "exit stub %d not found", exitno); - lj_mcode_sync(cstart, cend); - lj_mcode_patch(J, mcarea, 1); -} - diff --git a/include/luajit/lj_asm_arm64.h b/include/luajit/lj_asm_arm64.h deleted file mode 100644 index 507fc08..0000000 --- a/include/luajit/lj_asm_arm64.h +++ /dev/null @@ -1,2100 +0,0 @@ -/* -** ARM64 IR assembler (SSA IR -> machine code). -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -** -** Contributed by Djordje Kovacevic and Stefan Pejic from RT-RK.com. -** Sponsored by Cisco Systems, Inc. -*/ - -/* -- Register allocator extensions --------------------------------------- */ - -/* Allocate a register with a hint. */ -static Reg ra_hintalloc(ASMState *as, IRRef ref, Reg hint, RegSet allow) -{ - Reg r = IR(ref)->r; - if (ra_noreg(r)) { - if (!ra_hashint(r) && !iscrossref(as, ref)) - ra_sethint(IR(ref)->r, hint); /* Propagate register hint. */ - r = ra_allocref(as, ref, allow); - } - ra_noweak(as, r); - return r; -} - -/* Allocate two source registers for three-operand instructions. */ -static Reg ra_alloc2(ASMState *as, IRIns *ir, RegSet allow) -{ - IRIns *irl = IR(ir->op1), *irr = IR(ir->op2); - Reg left = irl->r, right = irr->r; - if (ra_hasreg(left)) { - ra_noweak(as, left); - if (ra_noreg(right)) - right = ra_allocref(as, ir->op2, rset_exclude(allow, left)); - else - ra_noweak(as, right); - } else if (ra_hasreg(right)) { - ra_noweak(as, right); - left = ra_allocref(as, ir->op1, rset_exclude(allow, right)); - } else if (ra_hashint(right)) { - right = ra_allocref(as, ir->op2, allow); - left = ra_alloc1(as, ir->op1, rset_exclude(allow, right)); - } else { - left = ra_allocref(as, ir->op1, allow); - right = ra_alloc1(as, ir->op2, rset_exclude(allow, left)); - } - return left | (right << 8); -} - -/* -- Guard handling ------------------------------------------------------ */ - -/* Setup all needed exit stubs. */ -static void asm_exitstub_setup(ASMState *as, ExitNo nexits) -{ - ExitNo i; - int ind; - MCode *target = (MCode *)(void *)lj_vm_exit_handler; - MCode *mxp = as->mctop; - if (mxp - (nexits + 4 + MCLIM_REDZONE) < as->mclim) - asm_mclimit(as); - ind = !A64F_S_OK(target - (mxp - nexits - 2), 26); - /* !ind: 1: str lr,[sp]; bl ->vm_exit_handler; movz w0,traceno; - ** ind: 1: str lr,[sp]; ldr lr, [gl, K64_VXH]; blr lr; movz w0,traceno; - ** bl <1; bl <1; ... - */ - for (i = nexits-1; (int32_t)i >= 0; i--) - *--mxp = A64I_LE(A64I_BL | A64F_S26(-3-ind-i)); - as->mcexit = mxp; - *--mxp = A64I_LE(A64I_MOVZw | A64F_U16(as->T->traceno)); - if (ind) { - *--mxp = A64I_LE(A64I_BLR_AUTH | A64F_N(RID_LR)); - *--mxp = A64I_LE(A64I_LDRx | A64F_D(RID_LR) | A64F_N(RID_GL) | A64F_U12(glofs(as, &as->J->k64[LJ_K64_VM_EXIT_HANDLER]) >> 3)); - } else { - mxp--; - *mxp = A64I_LE(A64I_BL | A64F_S26(target-mxp)); - } - *--mxp = A64I_LE(A64I_STRx | A64F_D(RID_LR) | A64F_N(RID_SP)); - as->mctop = mxp; -} - -static MCode *asm_exitstub_addr(ASMState *as, ExitNo exitno) -{ - /* Keep this in-sync with exitstub_trace_addr(). */ - return as->mcexit + exitno; -} - -/* Emit conditional branch to exit for guard. */ -static void asm_guardcc(ASMState *as, A64CC cc) -{ - MCode *target = asm_exitstub_addr(as, as->snapno); - MCode *p = as->mcp; - if (LJ_UNLIKELY(p == as->invmcp)) { - as->loopinv = 1; - *p = A64I_B | A64F_S26(target-p); - emit_cond_branch(as, cc^1, p-1); - return; - } - emit_cond_branch(as, cc, target); -} - -/* Emit test and branch instruction to exit for guard, if in range. */ -static int asm_guardtnb(ASMState *as, A64Ins ai, Reg r, uint32_t bit) -{ - MCode *target = asm_exitstub_addr(as, as->snapno); - MCode *p = as->mcp; - ptrdiff_t delta = target - p; - if (LJ_UNLIKELY(p == as->invmcp)) { - if (as->orignins > 1023) return 0; /* Delta might end up too large. */ - as->loopinv = 1; - *p = A64I_B | A64F_S26(delta); - ai ^= 0x01000000u; - target = p-1; - } else if (LJ_UNLIKELY(delta >= 0x1fff)) { - return 0; - } - emit_tnb(as, ai, r, bit, target); - return 1; -} - -/* Emit compare and branch instruction to exit for guard. */ -static void asm_guardcnb(ASMState *as, A64Ins ai, Reg r) -{ - MCode *target = asm_exitstub_addr(as, as->snapno); - MCode *p = as->mcp; - if (LJ_UNLIKELY(p == as->invmcp)) { - as->loopinv = 1; - *p = A64I_B | A64F_S26(target-p); - emit_cnb(as, ai^0x01000000u, r, p-1); - return; - } - emit_cnb(as, ai, r, target); -} - -/* -- Operand fusion ------------------------------------------------------ */ - -/* Limit linear search to this distance. Avoids O(n^2) behavior. */ -#define CONFLICT_SEARCH_LIM 31 - -static int asm_isk32(ASMState *as, IRRef ref, int32_t *k) -{ - if (irref_isk(ref)) { - IRIns *ir = IR(ref); - if (ir->o == IR_KNULL || !irt_is64(ir->t)) { - *k = ir->i; - return 1; - } else if (checki32((int64_t)ir_k64(ir)->u64)) { - *k = (int32_t)ir_k64(ir)->u64; - return 1; - } - } - return 0; -} - -/* Check if there's no conflicting instruction between curins and ref. */ -static int noconflict(ASMState *as, IRRef ref, IROp conflict) -{ - IRIns *ir = as->ir; - IRRef i = as->curins; - if (i > ref + CONFLICT_SEARCH_LIM) - return 0; /* Give up, ref is too far away. */ - while (--i > ref) - if (ir[i].o == conflict) - return 0; /* Conflict found. */ - return 1; /* Ok, no conflict. */ -} - -/* Fuse the array base of colocated arrays. */ -static int32_t asm_fuseabase(ASMState *as, IRRef ref) -{ - IRIns *ir = IR(ref); - if (ir->o == IR_TNEW && ir->op1 <= LJ_MAX_COLOSIZE && - !neverfuse(as) && noconflict(as, ref, IR_NEWREF)) - return (int32_t)sizeof(GCtab); - return 0; -} - -#define FUSE_REG 0x40000000 - -/* Fuse array/hash/upvalue reference into register+offset operand. */ -static Reg asm_fuseahuref(ASMState *as, IRRef ref, int32_t *ofsp, RegSet allow, - A64Ins ins) -{ - IRIns *ir = IR(ref); - if (ra_noreg(ir->r)) { - if (ir->o == IR_AREF) { - if (mayfuse(as, ref)) { - if (irref_isk(ir->op2)) { - IRRef tab = IR(ir->op1)->op1; - int32_t ofs = asm_fuseabase(as, tab); - IRRef refa = ofs ? tab : ir->op1; - ofs += 8*IR(ir->op2)->i; - if (emit_checkofs(ins, ofs)) { - *ofsp = ofs; - return ra_alloc1(as, refa, allow); - } - } else { - Reg base = ra_alloc1(as, ir->op1, allow); - *ofsp = FUSE_REG|ra_alloc1(as, ir->op2, rset_exclude(allow, base)); - return base; - } - } - } else if (ir->o == IR_HREFK) { - if (mayfuse(as, ref)) { - int32_t ofs = (int32_t)(IR(ir->op2)->op2 * sizeof(Node)); - if (emit_checkofs(ins, ofs)) { - *ofsp = ofs; - return ra_alloc1(as, ir->op1, allow); - } - } - } else if (ir->o == IR_UREFC) { - if (irref_isk(ir->op1)) { - GCfunc *fn = ir_kfunc(IR(ir->op1)); - GCupval *uv = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv; - int64_t ofs = glofs(as, &uv->tv); - if (emit_checkofs(ins, ofs)) { - *ofsp = (int32_t)ofs; - return RID_GL; - } - } - } else if (ir->o == IR_TMPREF) { - *ofsp = (int32_t)glofs(as, &J2G(as->J)->tmptv); - return RID_GL; - } - } - *ofsp = 0; - return ra_alloc1(as, ref, allow); -} - -/* Fuse m operand into arithmetic/logic instructions. */ -static uint32_t asm_fuseopm(ASMState *as, A64Ins ai, IRRef ref, RegSet allow) -{ - IRIns *ir = IR(ref); - int logical = (ai & 0x1f000000) == 0x0a000000; - if (ra_hasreg(ir->r)) { - ra_noweak(as, ir->r); - return A64F_M(ir->r); - } else if (irref_isk(ref)) { - int64_t k = get_k64val(as, ref); - uint32_t m = logical ? emit_isk13(k, irt_is64(ir->t)) : - emit_isk12(irt_is64(ir->t) ? k : (int32_t)k); - if (m) - return m; - } else if (mayfuse(as, ref)) { - if ((ir->o >= IR_BSHL && ir->o <= IR_BSAR && irref_isk(ir->op2)) || - (ir->o == IR_ADD && ir->op1 == ir->op2)) { - A64Shift sh = ir->o == IR_BSHR ? A64SH_LSR : - ir->o == IR_BSAR ? A64SH_ASR : A64SH_LSL; - int shift = ir->o == IR_ADD ? 1 : - (IR(ir->op2)->i & (irt_is64(ir->t) ? 63 : 31)); - IRIns *irl = IR(ir->op1); - if (sh == A64SH_LSL && - irl->o == IR_CONV && !logical && - irl->op2 == ((IRT_I64<op1, allow); - return A64F_M(m) | A64F_EXSH(A64EX_SXTW, shift); - } else { - Reg m = ra_alloc1(as, ir->op1, allow); - return A64F_M(m) | A64F_SH(sh, shift); - } - } else if (ir->o == IR_BROR && logical && irref_isk(ir->op2)) { - Reg m = ra_alloc1(as, ir->op1, allow); - int shift = (IR(ir->op2)->i & (irt_is64(ir->t) ? 63 : 31)); - return A64F_M(m) | A64F_SH(A64SH_ROR, shift); - } else if (ir->o == IR_CONV && !logical && - ir->op2 == ((IRT_I64<op1, allow); - return A64F_M(m) | A64F_EX(A64EX_SXTW); - } - } - return A64F_M(ra_allocref(as, ref, allow)); -} - -/* Fuse XLOAD/XSTORE reference into load/store operand. */ -static void asm_fusexref(ASMState *as, A64Ins ai, Reg rd, IRRef ref, - RegSet allow) -{ - IRIns *ir = IR(ref); - Reg base; - int32_t ofs = 0; - if (ra_noreg(ir->r) && canfuse(as, ir)) { - if (ir->o == IR_ADD) { - if (asm_isk32(as, ir->op2, &ofs) && emit_checkofs(ai, ofs)) { - ref = ir->op1; - } else { - Reg rn, rm; - IRRef lref = ir->op1, rref = ir->op2; - IRIns *irl = IR(lref); - if (mayfuse(as, irl->op1)) { - unsigned int shift = 4; - if (irl->o == IR_BSHL && irref_isk(irl->op2)) { - shift = (IR(irl->op2)->i & 63); - } else if (irl->o == IR_ADD && irl->op1 == irl->op2) { - shift = 1; - } - if ((ai >> 30) == shift) { - lref = irl->op1; - irl = IR(lref); - ai |= A64I_LS_SH; - } - } - if (irl->o == IR_CONV && - irl->op2 == ((IRT_I64<op1; - ai |= A64I_LS_SXTWx; - } else { - ai |= A64I_LS_LSLx; - } - rm = ra_alloc1(as, lref, allow); - rn = ra_alloc1(as, rref, rset_exclude(allow, rm)); - emit_dnm(as, (ai^A64I_LS_R), (rd & 31), rn, rm); - return; - } - } else if (ir->o == IR_STRREF) { - if (asm_isk32(as, ir->op2, &ofs)) { - ref = ir->op1; - } else if (asm_isk32(as, ir->op1, &ofs)) { - ref = ir->op2; - } else { - Reg refk = irref_isk(ir->op1) ? ir->op1 : ir->op2; - Reg refv = irref_isk(ir->op1) ? ir->op2 : ir->op1; - Reg rn = ra_alloc1(as, refv, allow); - IRIns *irr = IR(refk); - uint32_t m; - if (irr+1 == ir && !ra_used(irr) && - irr->o == IR_ADD && irref_isk(irr->op2)) { - ofs = sizeof(GCstr) + IR(irr->op2)->i; - if (emit_checkofs(ai, ofs)) { - Reg rm = ra_alloc1(as, irr->op1, rset_exclude(allow, rn)); - m = A64F_M(rm) | A64F_EX(A64EX_SXTW); - goto skipopm; - } - } - m = asm_fuseopm(as, 0, refk, rset_exclude(allow, rn)); - ofs = sizeof(GCstr); - skipopm: - emit_lso(as, ai, rd, rd, ofs); - emit_dn(as, A64I_ADDx^m, rd, rn); - return; - } - ofs += sizeof(GCstr); - if (!emit_checkofs(ai, ofs)) { - Reg rn = ra_alloc1(as, ref, allow); - Reg rm = ra_allock(as, ofs, rset_exclude(allow, rn)); - emit_dnm(as, (ai^A64I_LS_R)|A64I_LS_UXTWx, rd, rn, rm); - return; - } - } - } - base = ra_alloc1(as, ref, allow); - emit_lso(as, ai, (rd & 31), base, ofs); -} - -/* Fuse FP multiply-add/sub. */ -static int asm_fusemadd(ASMState *as, IRIns *ir, A64Ins ai, A64Ins air) -{ - IRRef lref = ir->op1, rref = ir->op2; - IRIns *irm; - if ((as->flags & JIT_F_OPT_FMA) && - lref != rref && - ((mayfuse(as, lref) && (irm = IR(lref), irm->o == IR_MUL) && - ra_noreg(irm->r)) || - (mayfuse(as, rref) && (irm = IR(rref), irm->o == IR_MUL) && - (rref = lref, ai = air, ra_noreg(irm->r))))) { - Reg dest = ra_dest(as, ir, RSET_FPR); - Reg add = ra_hintalloc(as, rref, dest, RSET_FPR); - Reg left = ra_alloc2(as, irm, - rset_exclude(rset_exclude(RSET_FPR, dest), add)); - Reg right = (left >> 8); left &= 255; - emit_dnma(as, ai, (dest & 31), (left & 31), (right & 31), (add & 31)); - return 1; - } - return 0; -} - -/* Fuse BAND + BSHL/BSHR into UBFM. */ -static int asm_fuseandshift(ASMState *as, IRIns *ir) -{ - IRIns *irl = IR(ir->op1); - lj_assertA(ir->o == IR_BAND, "bad usage"); - if (canfuse(as, irl) && irref_isk(ir->op2)) { - uint64_t mask = get_k64val(as, ir->op2); - if (irref_isk(irl->op2) && (irl->o == IR_BSHR || irl->o == IR_BSHL)) { - int32_t shmask = irt_is64(irl->t) ? 63 : 31; - int32_t shift = (IR(irl->op2)->i & shmask); - int32_t imms = shift; - if (irl->o == IR_BSHL) { - mask >>= shift; - shift = (shmask-shift+1) & shmask; - imms = 0; - } - if (mask && !((mask+1) & mask)) { /* Contiguous 1-bits at the bottom. */ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_alloc1(as, irl->op1, RSET_GPR); - A64Ins ai = shmask == 63 ? A64I_UBFMx : A64I_UBFMw; - imms += 63 - emit_clz64(mask); - if (imms > shmask) imms = shmask; - emit_dn(as, ai | A64F_IMMS(imms) | A64F_IMMR(shift), dest, left); - return 1; - } - } - } - return 0; -} - -/* Fuse BOR(BSHL, BSHR) into EXTR/ROR. */ -static int asm_fuseorshift(ASMState *as, IRIns *ir) -{ - IRIns *irl = IR(ir->op1), *irr = IR(ir->op2); - lj_assertA(ir->o == IR_BOR, "bad usage"); - if (canfuse(as, irl) && canfuse(as, irr) && - ((irl->o == IR_BSHR && irr->o == IR_BSHL) || - (irl->o == IR_BSHL && irr->o == IR_BSHR))) { - if (irref_isk(irl->op2) && irref_isk(irr->op2)) { - IRRef lref = irl->op1, rref = irr->op1; - uint32_t lshift = IR(irl->op2)->i, rshift = IR(irr->op2)->i; - if (irl->o == IR_BSHR) { /* BSHR needs to be the right operand. */ - uint32_t tmp2; - IRRef tmp1 = lref; lref = rref; rref = tmp1; - tmp2 = lshift; lshift = rshift; rshift = tmp2; - } - if (rshift + lshift == (irt_is64(ir->t) ? 64 : 32)) { - A64Ins ai = irt_is64(ir->t) ? A64I_EXTRx : A64I_EXTRw; - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_alloc1(as, lref, RSET_GPR); - Reg right = ra_alloc1(as, rref, rset_exclude(RSET_GPR, left)); - emit_dnm(as, ai | A64F_IMMS(rshift), dest, left, right); - return 1; - } - } - } - return 0; -} - -/* -- Calls --------------------------------------------------------------- */ - -/* Generate a call to a C function. */ -static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args) -{ - uint32_t n, nargs = CCI_XNARGS(ci); - int32_t spofs = 0, spalign = LJ_HASFFI && LJ_TARGET_OSX ? 0 : 7; - Reg gpr, fpr = REGARG_FIRSTFPR; - if (ci->func) - emit_call(as, ci->func); - for (gpr = REGARG_FIRSTGPR; gpr <= REGARG_LASTGPR; gpr++) - as->cost[gpr] = REGCOST(~0u, ASMREF_L); - gpr = REGARG_FIRSTGPR; -#if LJ_HASFFI && LJ_ABI_WIN - if ((ci->flags & CCI_VARARG)) { - fpr = REGARG_LASTFPR+1; - } -#endif - for (n = 0; n < nargs; n++) { /* Setup args. */ - IRRef ref = args[n]; - IRIns *ir = IR(ref); - if (ref) { - if (irt_isfp(ir->t)) { - if (fpr <= REGARG_LASTFPR) { - lj_assertA(rset_test(as->freeset, fpr), - "reg %d not free", fpr); /* Must have been evicted. */ - ra_leftov(as, fpr, ref); - fpr++; -#if LJ_HASFFI && LJ_ABI_WIN - } else if ((ci->flags & CCI_VARARG) && (gpr <= REGARG_LASTGPR)) { - Reg rf = ra_alloc1(as, ref, RSET_FPR); - emit_dn(as, A64I_FMOV_R_D, gpr++, rf & 31); -#endif - } else { - Reg r = ra_alloc1(as, ref, RSET_FPR); - int32_t al = spalign; -#if LJ_HASFFI && LJ_TARGET_OSX - al |= irt_isnum(ir->t) ? 7 : 3; -#endif - spofs = (spofs + al) & ~al; - if (LJ_BE && al >= 7 && !irt_isnum(ir->t)) spofs += 4, al -= 4; - emit_spstore(as, ir, r, spofs); - spofs += al + 1; - } - } else { - if (gpr <= REGARG_LASTGPR) { - lj_assertA(rset_test(as->freeset, gpr), - "reg %d not free", gpr); /* Must have been evicted. */ - ra_leftov(as, gpr, ref); - gpr++; - } else { - Reg r = ra_alloc1(as, ref, RSET_GPR); - int32_t al = spalign; -#if LJ_HASFFI && LJ_TARGET_OSX - al |= irt_size(ir->t) - 1; -#endif - spofs = (spofs + al) & ~al; - if (al >= 3) { - if (LJ_BE && al >= 7 && !irt_is64(ir->t)) spofs += 4, al -= 4; - emit_spstore(as, ir, r, spofs); - } else { - lj_assertA(al == 0 || al == 1, "size %d unexpected", al + 1); - emit_lso(as, al ? A64I_STRH : A64I_STRB, r, RID_SP, spofs); - } - spofs += al + 1; - } - } -#if LJ_HASFFI && LJ_TARGET_OSX - } else { /* Marker for start of varargs. */ - gpr = REGARG_LASTGPR+1; - fpr = REGARG_LASTFPR+1; - spalign = 7; -#endif - } - } -} - -/* Setup result reg/sp for call. Evict scratch regs. */ -static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci) -{ - RegSet drop = RSET_SCRATCH; - int hiop = ((ir+1)->o == IR_HIOP && !irt_isnil((ir+1)->t)); - if (ra_hasreg(ir->r)) - rset_clear(drop, ir->r); /* Dest reg handled below. */ - if (hiop && ra_hasreg((ir+1)->r)) - rset_clear(drop, (ir+1)->r); /* Dest reg handled below. */ - ra_evictset(as, drop); /* Evictions must be performed first. */ - if (ra_used(ir)) { - lj_assertA(!irt_ispri(ir->t), "PRI dest"); - if (irt_isfp(ir->t)) { - if (ci->flags & CCI_CASTU64) { - Reg dest = ra_dest(as, ir, RSET_FPR) & 31; - emit_dn(as, irt_isnum(ir->t) ? A64I_FMOV_D_R : A64I_FMOV_S_R, - dest, RID_RET); - } else { - ra_destreg(as, ir, RID_FPRET); - } - } else if (hiop) { - ra_destpair(as, ir); - } else { - ra_destreg(as, ir, RID_RET); - } - } - UNUSED(ci); -} - -static void asm_callx(ASMState *as, IRIns *ir) -{ - IRRef args[CCI_NARGS_MAX*2]; - CCallInfo ci; - IRRef func; - IRIns *irf; - ci.flags = asm_callx_flags(as, ir); - asm_collectargs(as, ir, &ci, args); - asm_setupresult(as, ir, &ci); - func = ir->op2; irf = IR(func); - if (irf->o == IR_CARG) { func = irf->op1; irf = IR(func); } - if (irref_isk(func)) { /* Call to constant address. */ - ci.func = (ASMFunction)(ir_k64(irf)->u64); - } else { /* Need a non-argument register for indirect calls. */ - Reg freg = ra_alloc1(as, func, RSET_RANGE(RID_X8, RID_MAX_GPR)-RSET_FIXED); - emit_n(as, A64I_BLR_AUTH, freg); - ci.func = (ASMFunction)(void *)0; - } - asm_gencall(as, &ci, args); -} - -/* -- Returns ------------------------------------------------------------- */ - -/* Return to lower frame. Guard that it goes to the right spot. */ -static void asm_retf(ASMState *as, IRIns *ir) -{ - Reg base = ra_alloc1(as, REF_BASE, RSET_GPR); - void *pc = ir_kptr(IR(ir->op2)); - int32_t delta = 1+LJ_FR2+bc_a(*((const BCIns *)pc - 1)); - as->topslot -= (BCReg)delta; - if ((int32_t)as->topslot < 0) as->topslot = 0; - irt_setmark(IR(REF_BASE)->t); /* Children must not coalesce with BASE reg. */ - emit_setgl(as, base, jit_base); - emit_addptr(as, base, -8*delta); - asm_guardcc(as, CC_NE); - emit_nm(as, A64I_CMPx, RID_TMP, - ra_allock(as, i64ptr(pc), rset_exclude(RSET_GPR, base))); - emit_lso(as, A64I_LDRx, RID_TMP, base, -8); -} - -/* -- Buffer operations --------------------------------------------------- */ - -#if LJ_HASBUFFER -static void asm_bufhdr_write(ASMState *as, Reg sb) -{ - Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, sb)); - IRIns irgc; - irgc.ot = IRT(0, IRT_PGC); /* GC type. */ - emit_storeofs(as, &irgc, RID_TMP, sb, offsetof(SBuf, L)); - emit_dn(as, A64I_BFMx | A64F_IMMS(lj_fls(SBUF_MASK_FLAG)) | A64F_IMMR(0), RID_TMP, tmp); - emit_getgl(as, RID_TMP, cur_L); - emit_loadofs(as, &irgc, tmp, sb, offsetof(SBuf, L)); -} -#endif - -/* -- Type conversions ---------------------------------------------------- */ - -static void asm_tointg(ASMState *as, IRIns *ir, Reg left) -{ - Reg tmp = ra_scratch(as, rset_exclude(RSET_FPR, left)); - Reg dest = ra_dest(as, ir, RSET_GPR); - asm_guardcc(as, CC_NE); - emit_nm(as, A64I_FCMPd, (tmp & 31), (left & 31)); - emit_dn(as, A64I_FCVT_F64_S32, (tmp & 31), dest); - emit_dn(as, A64I_FCVT_S32_F64, dest, (left & 31)); -} - -static void asm_tobit(ASMState *as, IRIns *ir) -{ - RegSet allow = RSET_FPR; - Reg left = ra_alloc1(as, ir->op1, allow); - Reg right = ra_alloc1(as, ir->op2, rset_clear(allow, left)); - Reg tmp = ra_scratch(as, rset_clear(allow, right)); - Reg dest = ra_dest(as, ir, RSET_GPR); - emit_dn(as, A64I_FMOV_R_S, dest, (tmp & 31)); - emit_dnm(as, A64I_FADDd, (tmp & 31), (left & 31), (right & 31)); -} - -static void asm_conv(ASMState *as, IRIns *ir) -{ - IRType st = (IRType)(ir->op2 & IRCONV_SRCMASK); - int st64 = (st == IRT_I64 || st == IRT_U64 || st == IRT_P64); - int stfp = (st == IRT_NUM || st == IRT_FLOAT); - IRRef lref = ir->op1; - lj_assertA(irt_type(ir->t) != st, "inconsistent types for CONV"); - if (irt_isfp(ir->t)) { - Reg dest = ra_dest(as, ir, RSET_FPR); - if (stfp) { /* FP to FP conversion. */ - emit_dn(as, st == IRT_NUM ? A64I_FCVT_F32_F64 : A64I_FCVT_F64_F32, - (dest & 31), (ra_alloc1(as, lref, RSET_FPR) & 31)); - } else { /* Integer to FP conversion. */ - Reg left = ra_alloc1(as, lref, RSET_GPR); - A64Ins ai = irt_isfloat(ir->t) ? - (((IRT_IS64 >> st) & 1) ? - (st == IRT_I64 ? A64I_FCVT_F32_S64 : A64I_FCVT_F32_U64) : - (st == IRT_INT ? A64I_FCVT_F32_S32 : A64I_FCVT_F32_U32)) : - (((IRT_IS64 >> st) & 1) ? - (st == IRT_I64 ? A64I_FCVT_F64_S64 : A64I_FCVT_F64_U64) : - (st == IRT_INT ? A64I_FCVT_F64_S32 : A64I_FCVT_F64_U32)); - emit_dn(as, ai, (dest & 31), left); - } - } else if (stfp) { /* FP to integer conversion. */ - if (irt_isguard(ir->t)) { - /* Checked conversions are only supported from number to int. */ - lj_assertA(irt_isint(ir->t) && st == IRT_NUM, - "bad type for checked CONV"); - asm_tointg(as, ir, ra_alloc1(as, lref, RSET_FPR)); - } else { - Reg left = ra_alloc1(as, lref, RSET_FPR); - Reg dest = ra_dest(as, ir, RSET_GPR); - lj_assertA(!irt_isu32(ir->t), "bad CONV u32.fp emitted"); - if (irt_isu64(ir->t)) { - emit_dnm(as, A64I_CSELx | A64F_CC(CC_VC), dest, dest, RID_TMP); - emit_n(as, (A64I_CMNx^A64I_K12) | A64F_U12(1), dest); - emit_dn(as, st == IRT_NUM ? A64I_FCVT_U64_F64 : A64I_FCVT_U64_F32, RID_TMP, (left & 31)); - emit_dn(as, st == IRT_NUM ? A64I_FCVT_S64_F64 : A64I_FCVT_S64_F32, dest, (left & 31)); - } else { - A64Ins ai = irt_is64(ir->t) ? - (st == IRT_NUM ? A64I_FCVT_S64_F64 : A64I_FCVT_S64_F32) : - (st == IRT_NUM ? A64I_FCVT_S32_F64 : A64I_FCVT_S32_F32); - emit_dn(as, ai, dest, (left & 31)); - } - } - } else if (st >= IRT_I8 && st <= IRT_U16) { /* Extend to 32 bit integer. */ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_alloc1(as, lref, RSET_GPR); - A64Ins ai = st == IRT_I8 ? A64I_SXTBw : - st == IRT_U8 ? A64I_UXTBw : - st == IRT_I16 ? A64I_SXTHw : A64I_UXTHw; - lj_assertA(irt_isint(ir->t) || irt_isu32(ir->t), "bad type for CONV EXT"); - emit_dn(as, ai, dest, left); - } else { - Reg dest = ra_dest(as, ir, RSET_GPR); - if (irt_is64(ir->t)) { - if (st64 || !(ir->op2 & IRCONV_SEXT)) { - /* 64/64 bit no-op (cast) or 32 to 64 bit zero extension. */ - ra_leftov(as, dest, lref); /* Do nothing, but may need to move regs. */ - } else { /* 32 to 64 bit sign extension. */ - Reg left = ra_alloc1(as, lref, RSET_GPR); - emit_dn(as, A64I_SXTW, dest, left); - } - } else { - if (st64 && !(ir->op2 & IRCONV_NONE)) { - /* This is either a 32 bit reg/reg mov which zeroes the hiword - ** or a load of the loword from a 64 bit address. - */ - Reg left = ra_alloc1(as, lref, RSET_GPR); - emit_dm(as, A64I_MOVw, dest, left); - } else { /* 32/32 bit no-op (cast). */ - ra_leftov(as, dest, lref); /* Do nothing, but may need to move regs. */ - } - } - } -} - -static void asm_strto(ASMState *as, IRIns *ir) -{ - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_strscan_num]; - IRRef args[2]; - Reg tmp; - int32_t ofs = 0; - ra_evictset(as, RSET_SCRATCH); - if (ra_used(ir)) { - if (ra_hasspill(ir->s)) { - ofs = sps_scale(ir->s); - if (ra_hasreg(ir->r)) { - ra_free(as, ir->r); - ra_modified(as, ir->r); - emit_spload(as, ir, ir->r, ofs); - } - } else { - Reg dest = ra_dest(as, ir, RSET_FPR); - emit_lso(as, A64I_LDRd, (dest & 31), RID_SP, 0); - } - } - asm_guardcnb(as, A64I_CBZ, RID_RET); - args[0] = ir->op1; /* GCstr *str */ - args[1] = ASMREF_TMP1; /* TValue *n */ - asm_gencall(as, ci, args); - tmp = ra_releasetmp(as, ASMREF_TMP1); - emit_opk(as, A64I_ADDx, tmp, RID_SP, ofs, RSET_GPR); -} - -/* -- Memory references --------------------------------------------------- */ - -/* Store tagged value for ref at base+ofs. */ -static void asm_tvstore64(ASMState *as, Reg base, int32_t ofs, IRRef ref) -{ - RegSet allow = rset_exclude(RSET_GPR, base); - IRIns *ir = IR(ref); - lj_assertA(irt_ispri(ir->t) || irt_isaddr(ir->t) || irt_isinteger(ir->t), - "store of IR type %d", irt_type(ir->t)); - if (irref_isk(ref)) { - TValue k; - lj_ir_kvalue(as->J->L, &k, ir); - emit_lso(as, A64I_STRx, ra_allock(as, k.u64, allow), base, ofs); - } else { - Reg src = ra_alloc1(as, ref, allow); - rset_clear(allow, src); - if (irt_isinteger(ir->t)) { - Reg type = ra_allock(as, (int64_t)irt_toitype(ir->t) << 47, allow); - emit_lso(as, A64I_STRx, RID_TMP, base, ofs); - emit_dnm(as, A64I_ADDx | A64F_EX(A64EX_UXTW), RID_TMP, type, src); - } else { - Reg type = ra_allock(as, (int32_t)irt_toitype(ir->t), allow); - emit_lso(as, A64I_STRx, RID_TMP, base, ofs); - emit_dnm(as, A64I_ADDx | A64F_SH(A64SH_LSL, 47), RID_TMP, src, type); - } - } -} - -/* Get pointer to TValue. */ -static void asm_tvptr(ASMState *as, Reg dest, IRRef ref, MSize mode) -{ - if ((mode & IRTMPREF_IN1)) { - IRIns *ir = IR(ref); - if (irt_isnum(ir->t)) { - if (irref_isk(ref) && !(mode & IRTMPREF_OUT1)) { - /* Use the number constant itself as a TValue. */ - ra_allockreg(as, i64ptr(ir_knum(ir)), dest); - return; - } - emit_lso(as, A64I_STRd, (ra_alloc1(as, ref, RSET_FPR) & 31), dest, 0); - } else { - asm_tvstore64(as, dest, 0, ref); - } - } - /* g->tmptv holds the TValue(s). */ - emit_dn(as, A64I_ADDx^emit_isk12(glofs(as, &J2G(as->J)->tmptv)), dest, RID_GL); -} - -static void asm_aref(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg idx, base; - if (irref_isk(ir->op2)) { - IRRef tab = IR(ir->op1)->op1; - int32_t ofs = asm_fuseabase(as, tab); - IRRef refa = ofs ? tab : ir->op1; - uint32_t k = emit_isk12(ofs + 8*IR(ir->op2)->i); - if (k) { - base = ra_alloc1(as, refa, RSET_GPR); - emit_dn(as, A64I_ADDx^k, dest, base); - return; - } - } - base = ra_alloc1(as, ir->op1, RSET_GPR); - idx = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, base)); - emit_dnm(as, A64I_ADDx | A64F_EXSH(A64EX_UXTW, 3), dest, base, idx); -} - -/* Inlined hash lookup. Specialized for key type and for const keys. -** The equivalent C code is: -** Node *n = hashkey(t, key); -** do { -** if (lj_obj_equal(&n->key, key)) return &n->val; -** } while ((n = nextnode(n))); -** return niltv(L); -*/ -static void asm_href(ASMState *as, IRIns *ir, IROp merge) -{ - RegSet allow = RSET_GPR; - int destused = ra_used(ir); - Reg dest = ra_dest(as, ir, allow); - Reg tab = ra_alloc1(as, ir->op1, rset_clear(allow, dest)); - Reg tmp = RID_TMP, type = RID_NONE, key = RID_NONE, tkey; - IRRef refkey = ir->op2; - IRIns *irkey = IR(refkey); - int isk = irref_isk(refkey); - IRType1 kt = irkey->t; - uint32_t k = 0; - uint32_t khash; - MCLabel l_end, l_loop; - rset_clear(allow, tab); - - /* Allocate register for tkey outside of the loop. */ - if (isk) { - int64_t kk; - if (irt_isaddr(kt)) { - kk = ((int64_t)irt_toitype(kt) << 47) | irkey[1].tv.u64; - } else if (irt_isnum(kt)) { - kk = (int64_t)ir_knum(irkey)->u64; - /* Assumes -0.0 is already canonicalized to +0.0. */ - } else { - lj_assertA(irt_ispri(kt) && !irt_isnil(kt), "bad HREF key type"); - kk = ~((int64_t)~irt_toitype(kt) << 47); - } - k = emit_isk12(kk); - tkey = k ? 0 : ra_allock(as, kk, allow); - } else { - tkey = ra_scratch(as, allow); - } - - /* Key not found in chain: jump to exit (if merged) or load niltv. */ - l_end = emit_label(as); - as->invmcp = NULL; - if (merge == IR_NE) { - asm_guardcc(as, CC_AL); - } else if (destused) { - uint32_t k12 = emit_isk12(offsetof(global_State, nilnode.val)); - lj_assertA(k12 != 0, "Cannot k12 encode niltv(L)"); - emit_dn(as, A64I_ADDx^k12, dest, RID_GL); - } - - /* Follow hash chain until the end. */ - l_loop = --as->mcp; - if (destused) - emit_lso(as, A64I_LDRx, dest, dest, offsetof(Node, next)); - - /* Type and value comparison. */ - if (merge == IR_EQ) - asm_guardcc(as, CC_EQ); - else - emit_cond_branch(as, CC_EQ, l_end); - emit_nm(as, A64I_CMPx^k, tmp, tkey); - if (!destused) - emit_lso(as, A64I_LDRx, dest, dest, offsetof(Node, next)); - emit_lso(as, A64I_LDRx, tmp, dest, offsetof(Node, key)); - *l_loop = A64I_X | A64I_CBNZ | A64F_S19(as->mcp - l_loop) | dest; - - /* Construct tkey as canonicalized or tagged key. */ - if (!isk) { - if (irt_isnum(kt)) { - key = ra_alloc1(as, refkey, RSET_FPR); - emit_dnm(as, A64I_CSELx | A64F_CC(CC_EQ), tkey, RID_ZERO, tkey); - /* A64I_FMOV_R_D from key to tkey done below. */ - } else { - lj_assertA(irt_isaddr(kt), "bad HREF key type"); - key = ra_alloc1(as, refkey, allow); - type = ra_allock(as, irt_toitype(kt) << 15, rset_clear(allow, key)); - emit_dnm(as, A64I_ADDx | A64F_SH(A64SH_LSL, 32), tkey, key, type); - } - } - - /* Load main position relative to tab->node into dest. */ - khash = isk ? ir_khash(as, irkey) : 1; - if (khash == 0) { - emit_lso(as, A64I_LDRx, dest, tab, offsetof(GCtab, node)); - } else { - emit_dnm(as, A64I_ADDx | A64F_SH(A64SH_LSL, 3), dest, tmp, dest); - emit_dnm(as, A64I_ADDx | A64F_SH(A64SH_LSL, 1), dest, dest, dest); - emit_lso(as, A64I_LDRx, tmp, tab, offsetof(GCtab, node)); - if (isk) { - Reg tmphash = ra_allock(as, khash, allow); - emit_dnm(as, A64I_ANDw, dest, dest, tmphash); - emit_lso(as, A64I_LDRw, dest, tab, offsetof(GCtab, hmask)); - } else if (irt_isstr(kt)) { - emit_dnm(as, A64I_ANDw, dest, dest, tmp); - emit_lso(as, A64I_LDRw, tmp, key, offsetof(GCstr, sid)); - emit_lso(as, A64I_LDRw, dest, tab, offsetof(GCtab, hmask)); - } else { /* Must match with hash*() in lj_tab.c. */ - emit_dnm(as, A64I_ANDw, dest, dest, tmp); - emit_lso(as, A64I_LDRw, tmp, tab, offsetof(GCtab, hmask)); - emit_dnm(as, A64I_SUBw, dest, dest, tmp); - emit_dnm(as, A64I_EXTRw | (A64F_IMMS(32-HASH_ROT3)), tmp, tmp, tmp); - emit_dnm(as, A64I_EORw | A64F_SH(A64SH_ROR, 32-HASH_ROT2), dest, tmp, dest); - emit_dnm(as, A64I_SUBw, tmp, tmp, dest); - emit_dnm(as, A64I_EXTRw | (A64F_IMMS(32-HASH_ROT1)), dest, dest, dest); - if (irt_isnum(kt)) { - emit_dnm(as, A64I_EORw, tmp, tkey, dest); - emit_dnm(as, A64I_ADDw, dest, dest, dest); - emit_dn(as, A64I_LSRx | A64F_IMMR(32)|A64F_IMMS(32), dest, tkey); - emit_nm(as, A64I_FCMPZd, (key & 31), 0); - emit_dn(as, A64I_FMOV_R_D, tkey, (key & 31)); - } else { - emit_dnm(as, A64I_EORw, tmp, key, dest); - emit_dnm(as, A64I_EORx | A64F_SH(A64SH_LSR, 32), dest, type, key); - } - } - } -} - -static void asm_hrefk(ASMState *as, IRIns *ir) -{ - IRIns *kslot = IR(ir->op2); - IRIns *irkey = IR(kslot->op1); - int32_t ofs = (int32_t)(kslot->op2 * sizeof(Node)); - int32_t kofs = ofs + (int32_t)offsetof(Node, key); - int bigofs = !emit_checkofs(A64I_LDRx, kofs); - Reg dest = (ra_used(ir) || bigofs) ? ra_dest(as, ir, RSET_GPR) : RID_NONE; - Reg node = ra_alloc1(as, ir->op1, RSET_GPR); - Reg idx = node; - RegSet allow = rset_exclude(RSET_GPR, node); - uint64_t k; - lj_assertA(ofs % sizeof(Node) == 0, "unaligned HREFK slot"); - if (bigofs) { - idx = dest; - rset_clear(allow, dest); - kofs = (int32_t)offsetof(Node, key); - } else if (ra_hasreg(dest)) { - emit_opk(as, A64I_ADDx, dest, node, ofs, allow); - } - asm_guardcc(as, CC_NE); - if (irt_ispri(irkey->t)) { - k = ~((int64_t)~irt_toitype(irkey->t) << 47); - } else if (irt_isnum(irkey->t)) { - k = ir_knum(irkey)->u64; - } else { - k = ((uint64_t)irt_toitype(irkey->t) << 47) | (uint64_t)ir_kgc(irkey); - } - emit_nm(as, A64I_CMPx, RID_TMP, ra_allock(as, k, allow)); - emit_lso(as, A64I_LDRx, RID_TMP, idx, kofs); - if (bigofs) - emit_opk(as, A64I_ADDx, dest, node, ofs, rset_exclude(RSET_GPR, node)); -} - -static void asm_uref(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - int guarded = (irt_t(ir->t) & (IRT_GUARD|IRT_TYPE)) == (IRT_GUARD|IRT_PGC); - if (irref_isk(ir->op1) && !guarded) { - GCfunc *fn = ir_kfunc(IR(ir->op1)); - MRef *v = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.v; - emit_lsptr(as, A64I_LDRx, dest, v); - } else { - if (guarded) - asm_guardcnb(as, ir->o == IR_UREFC ? A64I_CBZ : A64I_CBNZ, RID_TMP); - if (ir->o == IR_UREFC) - emit_opk(as, A64I_ADDx, dest, dest, - (int32_t)offsetof(GCupval, tv), RSET_GPR); - else - emit_lso(as, A64I_LDRx, dest, dest, (int32_t)offsetof(GCupval, v)); - if (guarded) - emit_lso(as, A64I_LDRB, RID_TMP, dest, - (int32_t)offsetof(GCupval, closed)); - if (irref_isk(ir->op1)) { - GCfunc *fn = ir_kfunc(IR(ir->op1)); - uint64_t k = gcrefu(fn->l.uvptr[(ir->op2 >> 8)]); - emit_loadu64(as, dest, k); - } else { - emit_lso(as, A64I_LDRx, dest, ra_alloc1(as, ir->op1, RSET_GPR), - (int32_t)offsetof(GCfuncL, uvptr) + 8*(int32_t)(ir->op2 >> 8)); - } - } -} - -static void asm_fref(ASMState *as, IRIns *ir) -{ - UNUSED(as); UNUSED(ir); - lj_assertA(!ra_used(ir), "unfused FREF"); -} - -static void asm_strref(ASMState *as, IRIns *ir) -{ - RegSet allow = RSET_GPR; - Reg dest = ra_dest(as, ir, allow); - Reg base = ra_alloc1(as, ir->op1, allow); - IRIns *irr = IR(ir->op2); - int32_t ofs = sizeof(GCstr); - uint32_t m; - rset_clear(allow, base); - if (irref_isk(ir->op2) && (m = emit_isk12(ofs + irr->i))) { - emit_dn(as, A64I_ADDx^m, dest, base); - } else { - emit_dn(as, (A64I_ADDx^A64I_K12) | A64F_U12(ofs), dest, dest); - emit_dnm(as, A64I_ADDx, dest, base, ra_alloc1(as, ir->op2, allow)); - } -} - -/* -- Loads and stores ---------------------------------------------------- */ - -static A64Ins asm_fxloadins(IRIns *ir) -{ - switch (irt_type(ir->t)) { - case IRT_I8: return A64I_LDRB ^ A64I_LS_S; - case IRT_U8: return A64I_LDRB; - case IRT_I16: return A64I_LDRH ^ A64I_LS_S; - case IRT_U16: return A64I_LDRH; - case IRT_NUM: return A64I_LDRd; - case IRT_FLOAT: return A64I_LDRs; - default: return irt_is64(ir->t) ? A64I_LDRx : A64I_LDRw; - } -} - -static A64Ins asm_fxstoreins(IRIns *ir) -{ - switch (irt_type(ir->t)) { - case IRT_I8: case IRT_U8: return A64I_STRB; - case IRT_I16: case IRT_U16: return A64I_STRH; - case IRT_NUM: return A64I_STRd; - case IRT_FLOAT: return A64I_STRs; - default: return irt_is64(ir->t) ? A64I_STRx : A64I_STRw; - } -} - -static void asm_fload(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg idx; - A64Ins ai = asm_fxloadins(ir); - int32_t ofs; - if (ir->op1 == REF_NIL) { /* FLOAD from GG_State with offset. */ - idx = RID_GL; - ofs = (ir->op2 << 2) - GG_OFS(g); - } else { - idx = ra_alloc1(as, ir->op1, RSET_GPR); - if (ir->op2 == IRFL_TAB_ARRAY) { - ofs = asm_fuseabase(as, ir->op1); - if (ofs) { /* Turn the t->array load into an add for colocated arrays. */ - emit_dn(as, (A64I_ADDx^A64I_K12) | A64F_U12(ofs), dest, idx); - return; - } - } - ofs = field_ofs[ir->op2]; - } - emit_lso(as, ai, (dest & 31), idx, ofs); -} - -static void asm_fstore(ASMState *as, IRIns *ir) -{ - if (ir->r != RID_SINK) { - Reg src = ra_alloc1(as, ir->op2, RSET_GPR); - IRIns *irf = IR(ir->op1); - Reg idx = ra_alloc1(as, irf->op1, rset_exclude(RSET_GPR, src)); - int32_t ofs = field_ofs[irf->op2]; - emit_lso(as, asm_fxstoreins(ir), (src & 31), idx, ofs); - } -} - -static void asm_xload(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR); - lj_assertA(LJ_TARGET_UNALIGNED || !(ir->op2 & IRXLOAD_UNALIGNED), - "unaligned XLOAD"); - asm_fusexref(as, asm_fxloadins(ir), dest, ir->op1, RSET_GPR); -} - -static void asm_xstore(ASMState *as, IRIns *ir) -{ - if (ir->r != RID_SINK) { - Reg src = ra_alloc1(as, ir->op2, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR); - asm_fusexref(as, asm_fxstoreins(ir), src, ir->op1, - rset_exclude(RSET_GPR, src)); - } -} - -static void asm_ahuvload(ASMState *as, IRIns *ir) -{ - Reg idx, tmp; - int32_t ofs = 0; - RegSet gpr = RSET_GPR, allow = irt_isnum(ir->t) ? RSET_FPR : RSET_GPR; - lj_assertA(irt_isnum(ir->t) || irt_ispri(ir->t) || irt_isaddr(ir->t) || - irt_isint(ir->t), - "bad load type %d", irt_type(ir->t)); - if (ra_used(ir)) { - Reg dest = ra_dest(as, ir, allow); - tmp = irt_isnum(ir->t) ? ra_scratch(as, rset_clear(gpr, dest)) : dest; - if (irt_isaddr(ir->t)) { - emit_dn(as, A64I_ANDx^emit_isk13(LJ_GCVMASK, 1), dest, dest); - } else if (irt_isnum(ir->t)) { - emit_dn(as, A64I_FMOV_D_R, (dest & 31), tmp); - } else if (irt_isint(ir->t)) { - emit_dm(as, A64I_MOVw, dest, dest); - } - } else { - tmp = ra_scratch(as, gpr); - } - idx = asm_fuseahuref(as, ir->op1, &ofs, rset_clear(gpr, tmp), A64I_LDRx); - rset_clear(gpr, idx); - if (ofs & FUSE_REG) rset_clear(gpr, ofs & 31); - if (ir->o == IR_VLOAD) ofs += 8 * ir->op2; - /* Always do the type check, even if the load result is unused. */ - asm_guardcc(as, irt_isnum(ir->t) ? CC_LS : CC_NE); - if (irt_type(ir->t) >= IRT_NUM) { - lj_assertA(irt_isinteger(ir->t) || irt_isnum(ir->t), - "bad load type %d", irt_type(ir->t)); - emit_nm(as, A64I_CMPx | A64F_SH(A64SH_LSR, 32), - ra_allock(as, LJ_TISNUM << 15, gpr), tmp); - } else if (irt_isaddr(ir->t)) { - emit_n(as, (A64I_CMNx^A64I_K12) | A64F_U12(-irt_toitype(ir->t)), RID_TMP); - emit_dn(as, A64I_ASRx | A64F_IMMR(47), RID_TMP, tmp); - } else if (irt_isnil(ir->t)) { - emit_n(as, (A64I_CMNx^A64I_K12) | A64F_U12(1), tmp); - } else { - emit_nm(as, A64I_CMPx | A64F_SH(A64SH_LSR, 32), - ra_allock(as, (irt_toitype(ir->t) << 15) | 0x7fff, gpr), tmp); - } - if (ofs & FUSE_REG) - emit_dnm(as, (A64I_LDRx^A64I_LS_R)|A64I_LS_UXTWx|A64I_LS_SH, tmp, idx, (ofs & 31)); - else - emit_lso(as, A64I_LDRx, tmp, idx, ofs); -} - -static void asm_ahustore(ASMState *as, IRIns *ir) -{ - if (ir->r != RID_SINK) { - RegSet allow = RSET_GPR; - Reg idx, src = RID_NONE, tmp = RID_TMP, type = RID_NONE; - int32_t ofs = 0; - if (irt_isnum(ir->t)) { - src = ra_alloc1(as, ir->op2, RSET_FPR); - idx = asm_fuseahuref(as, ir->op1, &ofs, allow, A64I_STRd); - if (ofs & FUSE_REG) - emit_dnm(as, (A64I_STRd^A64I_LS_R)|A64I_LS_UXTWx|A64I_LS_SH, (src & 31), idx, (ofs &31)); - else - emit_lso(as, A64I_STRd, (src & 31), idx, ofs); - } else { - if (!irt_ispri(ir->t)) { - src = ra_alloc1(as, ir->op2, allow); - rset_clear(allow, src); - if (irt_isinteger(ir->t)) - type = ra_allock(as, (uint64_t)(int32_t)LJ_TISNUM << 47, allow); - else - type = ra_allock(as, irt_toitype(ir->t), allow); - } else { - tmp = type = ra_allock(as, ~((int64_t)~irt_toitype(ir->t)<<47), allow); - } - idx = asm_fuseahuref(as, ir->op1, &ofs, rset_exclude(allow, type), - A64I_STRx); - if (ofs & FUSE_REG) - emit_dnm(as, (A64I_STRx^A64I_LS_R)|A64I_LS_UXTWx|A64I_LS_SH, tmp, idx, (ofs & 31)); - else - emit_lso(as, A64I_STRx, tmp, idx, ofs); - if (ra_hasreg(src)) { - if (irt_isinteger(ir->t)) { - emit_dnm(as, A64I_ADDx | A64F_EX(A64EX_UXTW), tmp, type, src); - } else { - emit_dnm(as, A64I_ADDx | A64F_SH(A64SH_LSL, 47), tmp, src, type); - } - } - } - } -} - -static void asm_sload(ASMState *as, IRIns *ir) -{ - int32_t ofs = 8*((int32_t)ir->op1-2); - IRType1 t = ir->t; - Reg dest = RID_NONE, base; - RegSet allow = RSET_GPR; - lj_assertA(!(ir->op2 & IRSLOAD_PARENT), - "bad parent SLOAD"); /* Handled by asm_head_side(). */ - lj_assertA(irt_isguard(t) || !(ir->op2 & IRSLOAD_TYPECHECK), - "inconsistent SLOAD variant"); - if ((ir->op2 & IRSLOAD_CONVERT) && irt_isguard(t) && irt_isint(t)) { - dest = ra_scratch(as, RSET_FPR); - asm_tointg(as, ir, dest); - t.irt = IRT_NUM; /* Continue with a regular number type check. */ - } else if (ra_used(ir)) { - Reg tmp = RID_NONE; - if ((ir->op2 & IRSLOAD_CONVERT)) - tmp = ra_scratch(as, irt_isint(t) ? RSET_FPR : RSET_GPR); - lj_assertA((irt_isnum(t)) || irt_isint(t) || irt_isaddr(t), - "bad SLOAD type %d", irt_type(t)); - dest = ra_dest(as, ir, irt_isnum(t) ? RSET_FPR : allow); - base = ra_alloc1(as, REF_BASE, rset_clear(allow, dest)); - if (irt_isaddr(t)) { - emit_dn(as, A64I_ANDx^emit_isk13(LJ_GCVMASK, 1), dest, dest); - } else if ((ir->op2 & IRSLOAD_CONVERT)) { - if (irt_isint(t)) { - emit_dn(as, A64I_FCVT_S32_F64, dest, (tmp & 31)); - /* If value is already loaded for type check, move it to FPR. */ - if ((ir->op2 & IRSLOAD_TYPECHECK)) - emit_dn(as, A64I_FMOV_D_R, (tmp & 31), dest); - else - dest = tmp; - t.irt = IRT_NUM; /* Check for original type. */ - } else { - emit_dn(as, A64I_FCVT_F64_S32, (dest & 31), tmp); - dest = tmp; - t.irt = IRT_INT; /* Check for original type. */ - } - } else if (irt_isint(t) && (ir->op2 & IRSLOAD_TYPECHECK)) { - emit_dm(as, A64I_MOVw, dest, dest); - } - goto dotypecheck; - } - base = ra_alloc1(as, REF_BASE, allow); -dotypecheck: - rset_clear(allow, base); - if ((ir->op2 & IRSLOAD_TYPECHECK)) { - Reg tmp; - if (ra_hasreg(dest) && rset_test(RSET_GPR, dest)) { - tmp = dest; - } else { - tmp = ra_scratch(as, allow); - rset_clear(allow, tmp); - } - if (ra_hasreg(dest) && tmp != dest) - emit_dn(as, A64I_FMOV_D_R, (dest & 31), tmp); - /* Need type check, even if the load result is unused. */ - asm_guardcc(as, irt_isnum(t) ? CC_LS : CC_NE); - if (irt_type(t) >= IRT_NUM) { - lj_assertA(irt_isinteger(t) || irt_isnum(t), - "bad SLOAD type %d", irt_type(t)); - emit_nm(as, A64I_CMPx | A64F_SH(A64SH_LSR, 32), - ra_allock(as, (ir->op2 & IRSLOAD_KEYINDEX) ? LJ_KEYINDEX : (LJ_TISNUM << 15), allow), tmp); - } else if (irt_isnil(t)) { - emit_n(as, (A64I_CMNx^A64I_K12) | A64F_U12(1), tmp); - } else if (irt_ispri(t)) { - emit_nm(as, A64I_CMPx, - ra_allock(as, ~((int64_t)~irt_toitype(t) << 47) , allow), tmp); - } else { - emit_n(as, (A64I_CMNx^A64I_K12) | A64F_U12(-irt_toitype(t)), RID_TMP); - emit_dn(as, A64I_ASRx | A64F_IMMR(47), RID_TMP, tmp); - } - emit_lso(as, A64I_LDRx, tmp, base, ofs); - return; - } - if (ra_hasreg(dest)) { - emit_lso(as, irt_isnum(t) ? A64I_LDRd : - (irt_isint(t) ? A64I_LDRw : A64I_LDRx), (dest & 31), base, - ofs ^ ((LJ_BE && irt_isint(t) ? 4 : 0))); - } -} - -/* -- Allocations --------------------------------------------------------- */ - -#if LJ_HASFFI -static void asm_cnew(ASMState *as, IRIns *ir) -{ - CTState *cts = ctype_ctsG(J2G(as->J)); - CTypeID id = (CTypeID)IR(ir->op1)->i; - CTSize sz; - CTInfo info = lj_ctype_info(cts, id, &sz); - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_mem_newgco]; - IRRef args[4]; - RegSet allow = (RSET_GPR & ~RSET_SCRATCH); - lj_assertA(sz != CTSIZE_INVALID || (ir->o == IR_CNEW && ir->op2 != REF_NIL), - "bad CNEW/CNEWI operands"); - - as->gcsteps++; - asm_setupresult(as, ir, ci); /* GCcdata * */ - /* Initialize immutable cdata object. */ - if (ir->o == IR_CNEWI) { - int32_t ofs = sizeof(GCcdata); - Reg r = ra_alloc1(as, ir->op2, allow); - lj_assertA(sz == 4 || sz == 8, "bad CNEWI size %d", sz); - emit_lso(as, sz == 8 ? A64I_STRx : A64I_STRw, r, RID_RET, ofs); - } else if (ir->op2 != REF_NIL) { /* Create VLA/VLS/aligned cdata. */ - ci = &lj_ir_callinfo[IRCALL_lj_cdata_newv]; - args[0] = ASMREF_L; /* lua_State *L */ - args[1] = ir->op1; /* CTypeID id */ - args[2] = ir->op2; /* CTSize sz */ - args[3] = ASMREF_TMP1; /* CTSize align */ - asm_gencall(as, ci, args); - emit_loadi(as, ra_releasetmp(as, ASMREF_TMP1), (int32_t)ctype_align(info)); - return; - } - - /* Initialize gct and ctypeid. lj_mem_newgco() already sets marked. */ - { - Reg r = (id < 65536) ? RID_X1 : ra_allock(as, id, allow); - emit_lso(as, A64I_STRB, RID_TMP, RID_RET, offsetof(GCcdata, gct)); - emit_lso(as, A64I_STRH, r, RID_RET, offsetof(GCcdata, ctypeid)); - emit_d(as, A64I_MOVZw | A64F_U16(~LJ_TCDATA), RID_TMP); - if (id < 65536) emit_d(as, A64I_MOVZw | A64F_U16(id), RID_X1); - } - args[0] = ASMREF_L; /* lua_State *L */ - args[1] = ASMREF_TMP1; /* MSize size */ - asm_gencall(as, ci, args); - ra_allockreg(as, (int32_t)(sz+sizeof(GCcdata)), - ra_releasetmp(as, ASMREF_TMP1)); -} -#endif - -/* -- Write barriers ------------------------------------------------------ */ - -static void asm_tbar(ASMState *as, IRIns *ir) -{ - Reg tab = ra_alloc1(as, ir->op1, RSET_GPR); - Reg link = ra_scratch(as, rset_exclude(RSET_GPR, tab)); - Reg mark = RID_TMP; - MCLabel l_end = emit_label(as); - emit_lso(as, A64I_STRB, mark, tab, (int32_t)offsetof(GCtab, marked)); - /* Keep STRx in the middle to avoid LDP/STP fusion with surrounding code. */ - emit_lso(as, A64I_STRx, link, tab, (int32_t)offsetof(GCtab, gclist)); - emit_setgl(as, tab, gc.grayagain); - emit_dn(as, A64I_ANDw^emit_isk13(~LJ_GC_BLACK, 0), mark, mark); - emit_getgl(as, link, gc.grayagain); - emit_cond_branch(as, CC_EQ, l_end); - emit_n(as, A64I_TSTw^emit_isk13(LJ_GC_BLACK, 0), mark); - emit_lso(as, A64I_LDRB, mark, tab, (int32_t)offsetof(GCtab, marked)); -} - -static void asm_obar(ASMState *as, IRIns *ir) -{ - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_barrieruv]; - IRRef args[2]; - MCLabel l_end; - Reg obj, val, tmp; - /* No need for other object barriers (yet). */ - lj_assertA(IR(ir->op1)->o == IR_UREFC, "bad OBAR type"); - ra_evictset(as, RSET_SCRATCH); - l_end = emit_label(as); - args[0] = ASMREF_TMP1; /* global_State *g */ - args[1] = ir->op1; /* TValue *tv */ - asm_gencall(as, ci, args); - emit_dm(as, A64I_MOVx, ra_releasetmp(as, ASMREF_TMP1), RID_GL); - obj = IR(ir->op1)->r; - tmp = ra_scratch(as, rset_exclude(RSET_GPR, obj)); - emit_tnb(as, A64I_TBZ, tmp, lj_ffs(LJ_GC_BLACK), l_end); - emit_cond_branch(as, CC_EQ, l_end); - emit_n(as, A64I_TSTw^emit_isk13(LJ_GC_WHITES, 0), RID_TMP); - val = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, obj)); - emit_lso(as, A64I_LDRB, tmp, obj, - (int32_t)offsetof(GCupval, marked)-(int32_t)offsetof(GCupval, tv)); - emit_lso(as, A64I_LDRB, RID_TMP, val, (int32_t)offsetof(GChead, marked)); -} - -/* -- Arithmetic and logic operations ------------------------------------- */ - -static void asm_fparith(ASMState *as, IRIns *ir, A64Ins ai) -{ - Reg dest = ra_dest(as, ir, RSET_FPR); - Reg right, left = ra_alloc2(as, ir, RSET_FPR); - right = (left >> 8); left &= 255; - emit_dnm(as, ai, (dest & 31), (left & 31), (right & 31)); -} - -static void asm_fpunary(ASMState *as, IRIns *ir, A64Ins ai) -{ - Reg dest = ra_dest(as, ir, RSET_FPR); - Reg left = ra_hintalloc(as, ir->op1, dest, RSET_FPR); - emit_dn(as, ai, (dest & 31), (left & 31)); -} - -static void asm_fpmath(ASMState *as, IRIns *ir) -{ - IRFPMathOp fpm = (IRFPMathOp)ir->op2; - if (fpm == IRFPM_SQRT) { - asm_fpunary(as, ir, A64I_FSQRTd); - } else if (fpm <= IRFPM_TRUNC) { - asm_fpunary(as, ir, fpm == IRFPM_FLOOR ? A64I_FRINTMd : - fpm == IRFPM_CEIL ? A64I_FRINTPd : A64I_FRINTZd); - } else { - asm_callid(as, ir, IRCALL_lj_vm_floor + fpm); - } -} - -static int asm_swapops(ASMState *as, IRRef lref, IRRef rref) -{ - IRIns *ir; - if (irref_isk(rref)) - return 0; /* Don't swap constants to the left. */ - if (irref_isk(lref)) - return 1; /* But swap constants to the right. */ - ir = IR(rref); - if ((ir->o >= IR_BSHL && ir->o <= IR_BROR) || - (ir->o == IR_ADD && ir->op1 == ir->op2) || - (ir->o == IR_CONV && ir->op2 == ((IRT_I64<o >= IR_BSHL && ir->o <= IR_BROR) || - (ir->o == IR_ADD && ir->op1 == ir->op2) || - (ir->o == IR_CONV && ir->op2 == ((IRT_I64<op1, rref = ir->op2; - Reg left, dest = ra_dest(as, ir, RSET_GPR); - uint32_t m; - if ((ai & ~A64I_S) != A64I_SUBw && asm_swapops(as, lref, rref)) { - IRRef tmp = lref; lref = rref; rref = tmp; - } - left = ra_hintalloc(as, lref, dest, RSET_GPR); - if (irt_is64(ir->t)) ai |= A64I_X; - m = asm_fuseopm(as, ai, rref, rset_exclude(RSET_GPR, left)); - if (irt_isguard(ir->t)) { /* For IR_ADDOV etc. */ - asm_guardcc(as, CC_VS); - ai |= A64I_S; - } - emit_dn(as, ai^m, dest, left); -} - -static void asm_intop_s(ASMState *as, IRIns *ir, A64Ins ai) -{ - if (as->flagmcp == as->mcp) { /* Drop cmp r, #0. */ - as->flagmcp = NULL; - as->mcp++; - ai |= A64I_S; - } - asm_intop(as, ir, ai); -} - -static void asm_intneg(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); - emit_dm(as, irt_is64(ir->t) ? A64I_NEGx : A64I_NEGw, dest, left); -} - -/* NYI: use add/shift for MUL(OV) with constants. FOLD only does 2^k. */ -static void asm_intmul(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_alloc1(as, ir->op1, RSET_GPR); - Reg right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); - if (irt_isguard(ir->t)) { /* IR_MULOV */ - asm_guardcc(as, CC_NE); - emit_dm(as, A64I_MOVw, dest, dest); /* Zero-extend. */ - emit_nm(as, A64I_CMPx | A64F_EX(A64EX_SXTW), dest, dest); - emit_dnm(as, A64I_SMULL, dest, right, left); - } else { - emit_dnm(as, irt_is64(ir->t) ? A64I_MULx : A64I_MULw, dest, left, right); - } -} - -static void asm_add(ASMState *as, IRIns *ir) -{ - if (irt_isnum(ir->t)) { - if (!asm_fusemadd(as, ir, A64I_FMADDd, A64I_FMADDd)) - asm_fparith(as, ir, A64I_FADDd); - return; - } - asm_intop_s(as, ir, A64I_ADDw); -} - -static void asm_sub(ASMState *as, IRIns *ir) -{ - if (irt_isnum(ir->t)) { - if (!asm_fusemadd(as, ir, A64I_FNMSUBd, A64I_FMSUBd)) - asm_fparith(as, ir, A64I_FSUBd); - return; - } - asm_intop_s(as, ir, A64I_SUBw); -} - -static void asm_mul(ASMState *as, IRIns *ir) -{ - if (irt_isnum(ir->t)) { - asm_fparith(as, ir, A64I_FMULd); - return; - } - asm_intmul(as, ir); -} - -#define asm_addov(as, ir) asm_add(as, ir) -#define asm_subov(as, ir) asm_sub(as, ir) -#define asm_mulov(as, ir) asm_mul(as, ir) - -#define asm_fpdiv(as, ir) asm_fparith(as, ir, A64I_FDIVd) -#define asm_abs(as, ir) asm_fpunary(as, ir, A64I_FABS) - -static void asm_neg(ASMState *as, IRIns *ir) -{ - if (irt_isnum(ir->t)) { - asm_fpunary(as, ir, A64I_FNEGd); - return; - } - asm_intneg(as, ir); -} - -static void asm_band(ASMState *as, IRIns *ir) -{ - A64Ins ai = A64I_ANDw; - if (asm_fuseandshift(as, ir)) - return; - if (as->flagmcp == as->mcp) { - /* Try to drop cmp r, #0. */ - as->flagmcp = NULL; - as->mcp++; - ai = A64I_ANDSw; - } - asm_intop(as, ir, ai); -} - -static void asm_borbxor(ASMState *as, IRIns *ir, A64Ins ai) -{ - IRRef lref = ir->op1, rref = ir->op2; - IRIns *irl = IR(lref), *irr = IR(rref); - if ((canfuse(as, irl) && irl->o == IR_BNOT && !irref_isk(rref)) || - (canfuse(as, irr) && irr->o == IR_BNOT && !irref_isk(lref))) { - Reg left, dest = ra_dest(as, ir, RSET_GPR); - uint32_t m; - if (irl->o == IR_BNOT) { - IRRef tmp = lref; lref = rref; rref = tmp; - } - left = ra_alloc1(as, lref, RSET_GPR); - ai |= A64I_ON; - if (irt_is64(ir->t)) ai |= A64I_X; - m = asm_fuseopm(as, ai, IR(rref)->op1, rset_exclude(RSET_GPR, left)); - emit_dn(as, ai^m, dest, left); - } else { - asm_intop(as, ir, ai); - } -} - -static void asm_bor(ASMState *as, IRIns *ir) -{ - if (asm_fuseorshift(as, ir)) - return; - asm_borbxor(as, ir, A64I_ORRw); -} - -#define asm_bxor(as, ir) asm_borbxor(as, ir, A64I_EORw) - -static void asm_bnot(ASMState *as, IRIns *ir) -{ - A64Ins ai = A64I_MVNw; - Reg dest = ra_dest(as, ir, RSET_GPR); - uint32_t m = asm_fuseopm(as, ai, ir->op1, RSET_GPR); - if (irt_is64(ir->t)) ai |= A64I_X; - emit_d(as, ai^m, dest); -} - -static void asm_bswap(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_alloc1(as, ir->op1, RSET_GPR); - emit_dn(as, irt_is64(ir->t) ? A64I_REVx : A64I_REVw, dest, left); -} - -static void asm_bitshift(ASMState *as, IRIns *ir, A64Ins ai, A64Shift sh) -{ - int32_t shmask = irt_is64(ir->t) ? 63 : 31; - if (irref_isk(ir->op2)) { /* Constant shifts. */ - Reg left, dest = ra_dest(as, ir, RSET_GPR); - int32_t shift = (IR(ir->op2)->i & shmask); - IRIns *irl = IR(ir->op1); - if (shmask == 63) ai += A64I_UBFMx - A64I_UBFMw; - - /* Fuse BSHL + BSHR/BSAR into UBFM/SBFM aka UBFX/SBFX/UBFIZ/SBFIZ. */ - if ((sh == A64SH_LSR || sh == A64SH_ASR) && canfuse(as, irl)) { - if (irl->o == IR_BSHL && irref_isk(irl->op2)) { - int32_t shift2 = (IR(irl->op2)->i & shmask); - shift = ((shift - shift2) & shmask); - shmask -= shift2; - ir = irl; - } - } - - left = ra_alloc1(as, ir->op1, RSET_GPR); - switch (sh) { - case A64SH_LSL: - emit_dn(as, ai | A64F_IMMS(shmask-shift) | - A64F_IMMR((shmask-shift+1)&shmask), dest, left); - break; - case A64SH_LSR: case A64SH_ASR: - emit_dn(as, ai | A64F_IMMS(shmask) | A64F_IMMR(shift), dest, left); - break; - case A64SH_ROR: - emit_dnm(as, ai | A64F_IMMS(shift), dest, left, left); - break; - } - } else { /* Variable-length shifts. */ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_alloc1(as, ir->op1, RSET_GPR); - Reg right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); - emit_dnm(as, (shmask == 63 ? A64I_SHRx : A64I_SHRw) | A64F_BSH(sh), dest, left, right); - } -} - -#define asm_bshl(as, ir) asm_bitshift(as, ir, A64I_UBFMw, A64SH_LSL) -#define asm_bshr(as, ir) asm_bitshift(as, ir, A64I_UBFMw, A64SH_LSR) -#define asm_bsar(as, ir) asm_bitshift(as, ir, A64I_SBFMw, A64SH_ASR) -#define asm_bror(as, ir) asm_bitshift(as, ir, A64I_EXTRw, A64SH_ROR) -#define asm_brol(as, ir) lj_assertA(0, "unexpected BROL") - -static void asm_intmin_max(ASMState *as, IRIns *ir, A64CC cc) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); - Reg right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); - emit_dnm(as, A64I_CSELw|A64F_CC(cc), dest, left, right); - emit_nm(as, A64I_CMPw, left, right); -} - -static void asm_fpmin_max(ASMState *as, IRIns *ir, A64CC fcc) -{ - Reg dest = (ra_dest(as, ir, RSET_FPR) & 31); - Reg right, left = ra_alloc2(as, ir, RSET_FPR); - right = ((left >> 8) & 31); left &= 31; - emit_dnm(as, A64I_FCSELd | A64F_CC(fcc), dest, right, left); - emit_nm(as, A64I_FCMPd, left, right); -} - -static void asm_min_max(ASMState *as, IRIns *ir, A64CC cc, A64CC fcc) -{ - if (irt_isnum(ir->t)) - asm_fpmin_max(as, ir, fcc); - else - asm_intmin_max(as, ir, cc); -} - -#define asm_min(as, ir) asm_min_max(as, ir, CC_LT, CC_PL) -#define asm_max(as, ir) asm_min_max(as, ir, CC_GT, CC_LE) - -/* -- Comparisons --------------------------------------------------------- */ - -/* Map of comparisons to flags. ORDER IR. */ -static const uint8_t asm_compmap[IR_ABC+1] = { - /* op FP swp int cc FP cc */ - /* LT */ CC_GE + (CC_HS << 4), - /* GE x */ CC_LT + (CC_HI << 4), - /* LE */ CC_GT + (CC_HI << 4), - /* GT x */ CC_LE + (CC_HS << 4), - /* ULT x */ CC_HS + (CC_LS << 4), - /* UGE */ CC_LO + (CC_LO << 4), - /* ULE x */ CC_HI + (CC_LO << 4), - /* UGT */ CC_LS + (CC_LS << 4), - /* EQ */ CC_NE + (CC_NE << 4), - /* NE */ CC_EQ + (CC_EQ << 4), - /* ABC */ CC_LS + (CC_LS << 4) /* Same as UGT. */ -}; - -/* FP comparisons. */ -static void asm_fpcomp(ASMState *as, IRIns *ir) -{ - Reg left, right; - A64Ins ai; - int swp = ((ir->o ^ (ir->o >> 2)) & ~(ir->o >> 3) & 1); - if (!swp && irref_isk(ir->op2) && ir_knum(IR(ir->op2))->u64 == 0) { - left = (ra_alloc1(as, ir->op1, RSET_FPR) & 31); - right = 0; - ai = A64I_FCMPZd; - } else { - left = ra_alloc2(as, ir, RSET_FPR); - if (swp) { - right = (left & 31); left = ((left >> 8) & 31); - } else { - right = ((left >> 8) & 31); left &= 31; - } - ai = A64I_FCMPd; - } - asm_guardcc(as, (asm_compmap[ir->o] >> 4)); - emit_nm(as, ai, left, right); -} - -/* Integer comparisons. */ -static void asm_intcomp(ASMState *as, IRIns *ir) -{ - A64CC oldcc, cc = (asm_compmap[ir->o] & 15); - A64Ins ai = irt_is64(ir->t) ? A64I_CMPx : A64I_CMPw; - IRRef lref = ir->op1, rref = ir->op2; - Reg left; - uint32_t m; - int cmpprev0 = 0; - lj_assertA(irt_is64(ir->t) || irt_isint(ir->t) || - irt_isu32(ir->t) || irt_isaddr(ir->t) || irt_isu8(ir->t), - "bad comparison data type %d", irt_type(ir->t)); - if (asm_swapops(as, lref, rref)) { - IRRef tmp = lref; lref = rref; rref = tmp; - if (cc >= CC_GE) cc ^= 7; /* LT <-> GT, LE <-> GE */ - else if (cc > CC_NE) cc ^= 11; /* LO <-> HI, LS <-> HS */ - } - oldcc = cc; - if (irref_isk(rref) && get_k64val(as, rref) == 0) { - IRIns *irl = IR(lref); - if (cc == CC_GE) cc = CC_PL; - else if (cc == CC_LT) cc = CC_MI; - else if (cc > CC_NE) goto nocombine; /* Other conds don't work with tst. */ - cmpprev0 = (irl+1 == ir); - /* Combine and-cmp-bcc into tbz/tbnz or and-cmp into tst. */ - if (cmpprev0 && irl->o == IR_BAND && !ra_used(irl)) { - IRRef blref = irl->op1, brref = irl->op2; - uint32_t m2 = 0; - Reg bleft; - if (asm_swapops(as, blref, brref)) { - Reg tmp = blref; blref = brref; brref = tmp; - } - bleft = ra_alloc1(as, blref, RSET_GPR); - if (irref_isk(brref)) { - uint64_t k = get_k64val(as, brref); - if (k && !(k & (k-1)) && (cc == CC_EQ || cc == CC_NE) && - asm_guardtnb(as, cc == CC_EQ ? A64I_TBZ : A64I_TBNZ, bleft, - emit_ctz64(k))) - return; - m2 = emit_isk13(k, irt_is64(irl->t)); - } - ai = (irt_is64(irl->t) ? A64I_TSTx : A64I_TSTw); - if (!m2) - m2 = asm_fuseopm(as, ai, brref, rset_exclude(RSET_GPR, bleft)); - asm_guardcc(as, cc); - emit_n(as, ai^m2, bleft); - return; - } - if (cc == CC_EQ || cc == CC_NE) { - /* Combine cmp-bcc into cbz/cbnz. */ - ai = cc == CC_EQ ? A64I_CBZ : A64I_CBNZ; - if (irt_is64(ir->t)) ai |= A64I_X; - asm_guardcnb(as, ai, ra_alloc1(as, lref, RSET_GPR)); - return; - } - } -nocombine: - left = ra_alloc1(as, lref, RSET_GPR); - m = asm_fuseopm(as, ai, rref, rset_exclude(RSET_GPR, left)); - asm_guardcc(as, cc); - emit_n(as, ai^m, left); - /* Signed comparison with zero and referencing previous ins? */ - if (cmpprev0 && (oldcc <= CC_NE || oldcc >= CC_GE)) - as->flagmcp = as->mcp; /* Allow elimination of the compare. */ -} - -static void asm_comp(ASMState *as, IRIns *ir) -{ - if (irt_isnum(ir->t)) - asm_fpcomp(as, ir); - else - asm_intcomp(as, ir); -} - -#define asm_equal(as, ir) asm_comp(as, ir) - -/* -- Split register ops -------------------------------------------------- */ - -/* Hiword op of a split 64/64 bit op. Previous op is the loword op. */ -static void asm_hiop(ASMState *as, IRIns *ir) -{ - /* HIOP is marked as a store because it needs its own DCE logic. */ - int uselo = ra_used(ir-1), usehi = ra_used(ir); /* Loword/hiword used? */ - if (LJ_UNLIKELY(!(as->flags & JIT_F_OPT_DCE))) uselo = usehi = 1; - if (!usehi) return; /* Skip unused hiword op for all remaining ops. */ - switch ((ir-1)->o) { - case IR_CALLN: - case IR_CALLL: - case IR_CALLS: - case IR_CALLXS: - if (!uselo) - ra_allocref(as, ir->op1, RID2RSET(RID_RETLO)); /* Mark lo op as used. */ - break; - default: lj_assertA(0, "bad HIOP for op %d", (ir-1)->o); break; - } -} - -/* -- Profiling ----------------------------------------------------------- */ - -static void asm_prof(ASMState *as, IRIns *ir) -{ - uint32_t k = emit_isk13(HOOK_PROFILE, 0); - lj_assertA(k != 0, "HOOK_PROFILE does not fit in K13"); - UNUSED(ir); - asm_guardcc(as, CC_NE); - emit_n(as, A64I_TSTw^k, RID_TMP); - emit_lsptr(as, A64I_LDRB, RID_TMP, (void *)&J2G(as->J)->hookmask); -} - -/* -- Stack handling ------------------------------------------------------ */ - -/* Check Lua stack size for overflow. Use exit handler as fallback. */ -static void asm_stack_check(ASMState *as, BCReg topslot, - IRIns *irp, RegSet allow, ExitNo exitno) -{ - uint32_t k; - Reg pbase = RID_BASE; - if (irp) { - pbase = irp->r; - if (!ra_hasreg(pbase)) - pbase = allow ? (0x40 | rset_pickbot(allow)) : (0xC0 | RID_RET); - } - emit_cond_branch(as, CC_LS, asm_exitstub_addr(as, exitno)); - if (pbase & 0x80) /* Restore temp. register. */ - emit_lso(as, A64I_LDRx, (pbase & 31), RID_SP, 0); - k = emit_isk12((8*topslot)); - lj_assertA(k, "slot offset %d does not fit in K12", 8*topslot); - emit_n(as, A64I_CMPx^k, RID_TMP); - emit_dnm(as, A64I_SUBx, RID_TMP, RID_TMP, (pbase & 31)); - emit_lso(as, A64I_LDRx, RID_TMP, RID_TMP, - (int32_t)offsetof(lua_State, maxstack)); - if (pbase & 0x40) { - emit_getgl(as, (pbase & 31), jit_base); - if (pbase & 0x80) /* Save temp register. */ - emit_lso(as, A64I_STRx, (pbase & 31), RID_SP, 0); - } - emit_getgl(as, RID_TMP, cur_L); -} - -/* Restore Lua stack from on-trace state. */ -static void asm_stack_restore(ASMState *as, SnapShot *snap) -{ - SnapEntry *map = &as->T->snapmap[snap->mapofs]; -#ifdef LUA_USE_ASSERT - SnapEntry *flinks = &as->T->snapmap[snap_nextofs(as->T, snap)-1-LJ_FR2]; -#endif - MSize n, nent = snap->nent; - /* Store the value of all modified slots to the Lua stack. */ - for (n = 0; n < nent; n++) { - SnapEntry sn = map[n]; - BCReg s = snap_slot(sn); - int32_t ofs = 8*((int32_t)s-1-LJ_FR2); - IRRef ref = snap_ref(sn); - IRIns *ir = IR(ref); - if ((sn & SNAP_NORESTORE)) - continue; - if ((sn & SNAP_KEYINDEX)) { - RegSet allow = rset_exclude(RSET_GPR, RID_BASE); - Reg r = irref_isk(ref) ? ra_allock(as, ir->i, allow) : - ra_alloc1(as, ref, allow); - rset_clear(allow, r); - emit_lso(as, A64I_STRw, r, RID_BASE, ofs); - emit_lso(as, A64I_STRw, ra_allock(as, LJ_KEYINDEX, allow), RID_BASE, ofs+4); - } else if (irt_isnum(ir->t)) { - Reg src = ra_alloc1(as, ref, RSET_FPR); - emit_lso(as, A64I_STRd, (src & 31), RID_BASE, ofs); - } else { - asm_tvstore64(as, RID_BASE, ofs, ref); - } - checkmclim(as); - } - lj_assertA(map + nent == flinks, "inconsistent frames in snapshot"); -} - -/* -- GC handling --------------------------------------------------------- */ - -/* Marker to prevent patching the GC check exit. */ -#define ARM64_NOPATCH_GC_CHECK \ - (A64I_ORRx|A64F_D(RID_ZERO)|A64F_M(RID_ZERO)|A64F_N(RID_ZERO)) - -/* Check GC threshold and do one or more GC steps. */ -static void asm_gc_check(ASMState *as) -{ - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_step_jit]; - IRRef args[2]; - MCLabel l_end; - Reg tmp2; - ra_evictset(as, RSET_SCRATCH); - l_end = emit_label(as); - /* Exit trace if in GCSatomic or GCSfinalize. Avoids syncing GC objects. */ - asm_guardcnb(as, A64I_CBNZ, RID_RET); /* Assumes asm_snap_prep() is done. */ - *--as->mcp = ARM64_NOPATCH_GC_CHECK; - args[0] = ASMREF_TMP1; /* global_State *g */ - args[1] = ASMREF_TMP2; /* MSize steps */ - asm_gencall(as, ci, args); - emit_dm(as, A64I_MOVx, ra_releasetmp(as, ASMREF_TMP1), RID_GL); - tmp2 = ra_releasetmp(as, ASMREF_TMP2); - emit_loadi(as, tmp2, as->gcsteps); - /* Jump around GC step if GC total < GC threshold. */ - emit_cond_branch(as, CC_LS, l_end); - emit_nm(as, A64I_CMPx, RID_TMP, tmp2); - emit_getgl(as, tmp2, gc.threshold); - emit_getgl(as, RID_TMP, gc.total); - as->gcsteps = 0; - checkmclim(as); -} - -/* -- Loop handling ------------------------------------------------------- */ - -/* Fixup the loop branch. */ -static void asm_loop_fixup(ASMState *as) -{ - MCode *p = as->mctop; - MCode *target = as->mcp; - if (as->loopinv) { /* Inverted loop branch? */ - uint32_t mask = (p[-2] & 0x7e000000) == 0x36000000 ? 0x3fffu : 0x7ffffu; - ptrdiff_t delta = target - (p - 2); - /* asm_guard* already inverted the bcc/tnb/cnb and patched the final b. */ - p[-2] |= ((uint32_t)delta & mask) << 5; - } else { - ptrdiff_t delta = target - (p - 1); - p[-1] = A64I_B | A64F_S26(delta); - } -} - -/* Fixup the tail of the loop. */ -static void asm_loop_tail_fixup(ASMState *as) -{ - UNUSED(as); /* Nothing to do. */ -} - -/* -- Head of trace ------------------------------------------------------- */ - -/* Coalesce BASE register for a root trace. */ -static void asm_head_root_base(ASMState *as) -{ - IRIns *ir = IR(REF_BASE); - Reg r = ir->r; - if (ra_hasreg(r)) { - ra_free(as, r); - if (rset_test(as->modset, r) || irt_ismarked(ir->t)) - ir->r = RID_INIT; /* No inheritance for modified BASE register. */ - if (r != RID_BASE) - emit_movrr(as, ir, r, RID_BASE); - } -} - -/* Coalesce BASE register for a side trace. */ -static Reg asm_head_side_base(ASMState *as, IRIns *irp) -{ - IRIns *ir = IR(REF_BASE); - Reg r = ir->r; - if (ra_hasreg(r)) { - ra_free(as, r); - if (rset_test(as->modset, r) || irt_ismarked(ir->t)) - ir->r = RID_INIT; /* No inheritance for modified BASE register. */ - if (irp->r == r) { - return r; /* Same BASE register already coalesced. */ - } else if (ra_hasreg(irp->r) && rset_test(as->freeset, irp->r)) { - /* Move from coalesced parent reg. */ - emit_movrr(as, ir, r, irp->r); - return irp->r; - } else { - emit_getgl(as, r, jit_base); /* Otherwise reload BASE. */ - } - } - return RID_NONE; -} - -/* -- Tail of trace ------------------------------------------------------- */ - -/* Fixup the tail code. */ -static void asm_tail_fixup(ASMState *as, TraceNo lnk) -{ - MCode *mcp = as->mctail; - MCode *target; - /* Undo the sp adjustment in BC_JLOOP when exiting to the interpreter. */ - int32_t spadj = as->T->spadjust + (lnk ? 0 : sps_scale(SPS_FIXED)); - if (spadj) { /* Emit stack adjustment. */ - uint32_t k = emit_isk12(spadj); - lj_assertA(k, "stack adjustment %d does not fit in K12", spadj); - *mcp++ = (A64I_ADDx^k) | A64F_D(RID_SP) | A64F_N(RID_SP); - } - /* Emit exit branch. */ - target = lnk ? traceref(as->J, lnk)->mcode : (MCode *)(void *)lj_vm_exit_interp; - if (lnk || A64F_S_OK(target - mcp, 26)) { - *mcp = A64I_B | A64F_S26(target - mcp); mcp++; - } else { - *mcp++ = A64I_LDRx | A64F_D(RID_LR) | A64F_N(RID_GL) | A64F_U12(glofs(as, &as->J->k64[LJ_K64_VM_EXIT_INTERP]) >> 3); - *mcp++ = A64I_BR_AUTH | A64F_N(RID_LR); - } - while (as->mctop > mcp) *--as->mctop = A64I_LE(A64I_NOP); -} - -/* Prepare tail of code. */ -static void asm_tail_prep(ASMState *as, TraceNo lnk) -{ - MCode *p = as->mctop - 1; /* Leave room for exit branch. */ - if (as->loopref) { - as->invmcp = as->mcp = p; - } else { - if (!lnk) { - MCode *target = (MCode *)(void *)lj_vm_exit_interp; - if (!A64F_S_OK(target - p, 26) || !A64F_S_OK(target - (p+1), 26)) p--; - } - p--; /* Leave room for stack pointer adjustment. */ - as->mcp = p; - as->invmcp = NULL; - } - as->mctail = p; - *p = 0; /* Prevent load/store merging. */ -} - -/* -- Trace setup --------------------------------------------------------- */ - -/* Ensure there are enough stack slots for call arguments. */ -static Reg asm_setup_call_slots(ASMState *as, IRIns *ir, const CCallInfo *ci) -{ -#if LJ_HASFFI - uint32_t i, nargs = CCI_XNARGS(ci); - if (nargs > (REGARG_NUMGPR < REGARG_NUMFPR ? REGARG_NUMGPR : REGARG_NUMFPR) || - (LJ_TARGET_OSX && (ci->flags & CCI_VARARG))) { - IRRef args[CCI_NARGS_MAX*2]; - int ngpr = REGARG_NUMGPR, nfpr = REGARG_NUMFPR; - int spofs = 0, spalign = LJ_TARGET_OSX ? 0 : 7, nslots; - asm_collectargs(as, ir, ci, args); -#if LJ_ABI_WIN - if ((ci->flags & CCI_VARARG)) nfpr = 0; -#endif - for (i = 0; i < nargs; i++) { - int al = spalign; - if (!args[i]) { -#if LJ_TARGET_OSX - /* Marker for start of varaargs. */ - nfpr = 0; - ngpr = 0; - spalign = 7; -#endif - } else if (irt_isfp(IR(args[i])->t)) { - if (nfpr > 0) { nfpr--; continue; } -#if LJ_ABI_WIN - if ((ci->flags & CCI_VARARG) && ngpr > 0) { ngpr--; continue; } -#elif LJ_TARGET_OSX - al |= irt_isnum(IR(args[i])->t) ? 7 : 3; -#endif - } else { - if (ngpr > 0) { ngpr--; continue; } -#if LJ_TARGET_OSX - al |= irt_size(IR(args[i])->t) - 1; -#endif - } - spofs = (spofs + 2*al+1) & ~al; /* Align and bump stack pointer. */ - } - nslots = (spofs + 3) >> 2; - if (nslots > as->evenspill) /* Leave room for args in stack slots. */ - as->evenspill = nslots; - } -#endif - return REGSP_HINT(irt_isfp(ir->t) ? RID_FPRET : RID_RET); -} - -static void asm_setup_target(ASMState *as) -{ - /* May need extra exit for asm_stack_check on side traces. */ - asm_exitstub_setup(as, as->T->nsnap + (as->parent ? 1 : 0)); -} - -#if LJ_BE -/* ARM64 instructions are always little-endian. Swap for ARM64BE. */ -static void asm_mcode_fixup(MCode *mcode, MSize size) -{ - MCode *pe = (MCode *)((char *)mcode + size); - while (mcode < pe) { - MCode ins = *mcode; - *mcode++ = lj_bswap(ins); - } -} -#define LJ_TARGET_MCODE_FIXUP 1 -#endif - -/* -- Trace patching ------------------------------------------------------ */ - -/* Patch exit jumps of existing machine code to a new target. */ -void lj_asm_patchexit(jit_State *J, GCtrace *T, ExitNo exitno, MCode *target) -{ - MCode *p = T->mcode; - MCode *pe = (MCode *)((char *)p + T->szmcode); - MCode *cstart = NULL; - MCode *mcarea = lj_mcode_patch(J, p, 0); - MCode *px = exitstub_trace_addr(T, exitno); - int patchlong = 1; - /* Note: this assumes a trace exit is only ever patched once. */ - for (; p < pe; p++) { - /* Look for exitstub branch, replace with branch to target. */ - ptrdiff_t delta = target - p; - MCode ins = A64I_LE(*p); - if ((ins & 0xff000000u) == 0x54000000u && - ((ins ^ ((px-p)<<5)) & 0x00ffffe0u) == 0) { - /* Patch bcc, if within range. */ - if (A64F_S_OK(delta, 19)) { - *p = A64I_LE((ins & 0xff00001fu) | A64F_S19(delta)); - if (!cstart) cstart = p; - } - } else if ((ins & 0xfc000000u) == 0x14000000u && - ((ins ^ (px-p)) & 0x03ffffffu) == 0) { - /* Patch b. */ - lj_assertJ(A64F_S_OK(delta, 26), "branch target out of range"); - *p = A64I_LE((ins & 0xfc000000u) | A64F_S26(delta)); - if (!cstart) cstart = p; - } else if ((ins & 0x7e000000u) == 0x34000000u && - ((ins ^ ((px-p)<<5)) & 0x00ffffe0u) == 0) { - /* Patch cbz/cbnz, if within range. */ - if (p[-1] == ARM64_NOPATCH_GC_CHECK) { - patchlong = 0; - } else if (A64F_S_OK(delta, 19)) { - *p = A64I_LE((ins & 0xff00001fu) | A64F_S19(delta)); - if (!cstart) cstart = p; - } - } else if ((ins & 0x7e000000u) == 0x36000000u && - ((ins ^ ((px-p)<<5)) & 0x0007ffe0u) == 0) { - /* Patch tbz/tbnz, if within range. */ - if (A64F_S_OK(delta, 14)) { - *p = A64I_LE((ins & 0xfff8001fu) | A64F_S14(delta)); - if (!cstart) cstart = p; - } - } - } - /* Always patch long-range branch in exit stub itself. Except, if we can't. */ - if (patchlong) { - ptrdiff_t delta = target - px; - lj_assertJ(A64F_S_OK(delta, 26), "branch target out of range"); - *px = A64I_B | A64F_S26(delta); - if (!cstart) cstart = px; - } - if (cstart) lj_mcode_sync(cstart, px+1); - lj_mcode_patch(J, mcarea, 1); -} - diff --git a/include/luajit/lj_asm_mips.h b/include/luajit/lj_asm_mips.h deleted file mode 100644 index 36ed5de..0000000 --- a/include/luajit/lj_asm_mips.h +++ /dev/null @@ -1,2820 +0,0 @@ -/* -** MIPS IR assembler (SSA IR -> machine code). -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -/* -- Register allocator extensions --------------------------------------- */ - -/* Allocate a register with a hint. */ -static Reg ra_hintalloc(ASMState *as, IRRef ref, Reg hint, RegSet allow) -{ - Reg r = IR(ref)->r; - if (ra_noreg(r)) { - if (!ra_hashint(r) && !iscrossref(as, ref)) - ra_sethint(IR(ref)->r, hint); /* Propagate register hint. */ - r = ra_allocref(as, ref, allow); - } - ra_noweak(as, r); - return r; -} - -/* Allocate a register or RID_ZERO. */ -static Reg ra_alloc1z(ASMState *as, IRRef ref, RegSet allow) -{ - Reg r = IR(ref)->r; - if (ra_noreg(r)) { - if (!(allow & RSET_FPR) && irref_isk(ref) && get_kval(as, ref) == 0) - return RID_ZERO; - r = ra_allocref(as, ref, allow); - } else { - ra_noweak(as, r); - } - return r; -} - -/* Allocate two source registers for three-operand instructions. */ -static Reg ra_alloc2(ASMState *as, IRIns *ir, RegSet allow) -{ - IRIns *irl = IR(ir->op1), *irr = IR(ir->op2); - Reg left = irl->r, right = irr->r; - if (ra_hasreg(left)) { - ra_noweak(as, left); - if (ra_noreg(right)) - right = ra_alloc1z(as, ir->op2, rset_exclude(allow, left)); - else - ra_noweak(as, right); - } else if (ra_hasreg(right)) { - ra_noweak(as, right); - left = ra_alloc1z(as, ir->op1, rset_exclude(allow, right)); - } else if (ra_hashint(right)) { - right = ra_alloc1z(as, ir->op2, allow); - left = ra_alloc1z(as, ir->op1, rset_exclude(allow, right)); - } else { - left = ra_alloc1z(as, ir->op1, allow); - right = ra_alloc1z(as, ir->op2, rset_exclude(allow, left)); - } - return left | (right << 8); -} - -/* -- Guard handling ------------------------------------------------------ */ - -/* Need some spare long-range jump slots, for out-of-range branches. */ -#define MIPS_SPAREJUMP 4 - -/* Setup spare long-range jump slots per mcarea. */ -static void asm_sparejump_setup(ASMState *as) -{ - MCode *mxp = as->mctop; - if ((char *)mxp == (char *)as->J->mcarea + as->J->szmcarea) { - mxp -= MIPS_SPAREJUMP*2; - lj_assertA(MIPSI_NOP == 0, "bad NOP"); - memset(mxp, 0, MIPS_SPAREJUMP*2*sizeof(MCode)); - as->mctop = mxp; - } -} - -static MCode *asm_sparejump_use(MCode *mcarea, MCode tjump) -{ - MCode *mxp = (MCode *)((char *)mcarea + ((MCLink *)mcarea)->size); - int slot = MIPS_SPAREJUMP; - while (slot--) { - mxp -= 2; - if (*mxp == tjump) { - return mxp; - } else if (*mxp == MIPSI_NOP) { - *mxp = tjump; - return mxp; - } - } - return NULL; -} - -/* Setup exit stub after the end of each trace. */ -static void asm_exitstub_setup(ASMState *as) -{ - uintptr_t target = (uintptr_t)(void *)lj_vm_exit_handler; - MCode *mxp = as->mctop; - *--mxp = MIPSI_LI | MIPSF_T(RID_TMP) | as->T->traceno; - if (((uintptr_t)(mxp-1) ^ target) >> 28 == 0) { - /* sw TMP, 0(sp); j ->vm_exit_handler; li TMP, traceno */ - *--mxp = MIPSI_J | ((target >> 2) & 0x03ffffffu); - } else { - /* sw TMP, 0(sp); li TMP, K*_VXH(jgl); jr TMP ; li TMP, traceno */ - *--mxp = MIPSI_JR | MIPSF_S(RID_TMP); - *--mxp = MIPSI_AL | MIPSF_T(RID_TMP) | MIPSF_S(RID_JGL) | -#if LJ_64 - jglofs(as, &as->J->k64[LJ_K64_VM_EXIT_HANDLER]); -#else - jglofs(as, &as->J->k32[LJ_K32_VM_EXIT_HANDLER]); -#endif - } - *--mxp = MIPSI_SW | MIPSF_T(RID_TMP) | MIPSF_S(RID_SP) | 0; - as->mctop = mxp; -} - -/* Keep this in-sync with exitstub_trace_addr(). */ -#define asm_exitstub_addr(as) ((as)->mctop) - -/* Emit conditional branch to exit for guard. */ -static void asm_guard(ASMState *as, MIPSIns mi, Reg rs, Reg rt) -{ - MCode *target = asm_exitstub_addr(as); - MCode *p = as->mcp; - if (LJ_UNLIKELY(p == as->invmcp)) { - as->invmcp = NULL; - as->loopinv = 1; - as->mcp = p+1; -#if !LJ_TARGET_MIPSR6 - mi = mi ^ ((mi>>28) == 1 ? 0x04000000u : 0x00010000u); /* Invert cond. */ -#else - mi = mi ^ ((mi>>28) == 1 ? 0x04000000u : - (mi>>28) == 4 ? 0x00800000u : 0x00010000u); /* Invert cond. */ -#endif - target = p; /* Patch target later in asm_loop_fixup. */ - } - emit_ti(as, MIPSI_LI, RID_TMP, as->snapno); - emit_branch(as, mi, rs, rt, target); -} - -/* -- Operand fusion ------------------------------------------------------ */ - -/* Limit linear search to this distance. Avoids O(n^2) behavior. */ -#define CONFLICT_SEARCH_LIM 31 - -/* Check if there's no conflicting instruction between curins and ref. */ -static int noconflict(ASMState *as, IRRef ref, IROp conflict) -{ - IRIns *ir = as->ir; - IRRef i = as->curins; - if (i > ref + CONFLICT_SEARCH_LIM) - return 0; /* Give up, ref is too far away. */ - while (--i > ref) - if (ir[i].o == conflict) - return 0; /* Conflict found. */ - return 1; /* Ok, no conflict. */ -} - -/* Fuse the array base of colocated arrays. */ -static int32_t asm_fuseabase(ASMState *as, IRRef ref) -{ - IRIns *ir = IR(ref); - if (ir->o == IR_TNEW && ir->op1 <= LJ_MAX_COLOSIZE && - !neverfuse(as) && noconflict(as, ref, IR_NEWREF)) - return (int32_t)sizeof(GCtab); - return 0; -} - -/* Fuse array/hash/upvalue reference into register+offset operand. */ -static Reg asm_fuseahuref(ASMState *as, IRRef ref, int32_t *ofsp, RegSet allow) -{ - IRIns *ir = IR(ref); - if (ra_noreg(ir->r)) { - if (ir->o == IR_AREF) { - if (mayfuse(as, ref)) { - if (irref_isk(ir->op2)) { - IRRef tab = IR(ir->op1)->op1; - int32_t ofs = asm_fuseabase(as, tab); - IRRef refa = ofs ? tab : ir->op1; - ofs += 8*IR(ir->op2)->i; - if (checki16(ofs)) { - *ofsp = ofs; - return ra_alloc1(as, refa, allow); - } - } - } - } else if (ir->o == IR_HREFK) { - if (mayfuse(as, ref)) { - int32_t ofs = (int32_t)(IR(ir->op2)->op2 * sizeof(Node)); - if (checki16(ofs)) { - *ofsp = ofs; - return ra_alloc1(as, ir->op1, allow); - } - } - } else if (ir->o == IR_UREFC) { - if (irref_isk(ir->op1)) { - GCfunc *fn = ir_kfunc(IR(ir->op1)); - intptr_t ofs = (intptr_t)&gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.tv; - intptr_t jgl = (intptr_t)J2G(as->J); - if ((uintptr_t)(ofs-jgl) < 65536) { - *ofsp = ofs-jgl-32768; - return RID_JGL; - } else { - *ofsp = (int16_t)ofs; - return ra_allock(as, ofs-(int16_t)ofs, allow); - } - } - } else if (ir->o == IR_TMPREF) { - *ofsp = (int32_t)(offsetof(global_State, tmptv)-32768); - return RID_JGL; - } - } - *ofsp = 0; - return ra_alloc1(as, ref, allow); -} - -/* Fuse XLOAD/XSTORE reference into load/store operand. */ -static void asm_fusexref(ASMState *as, MIPSIns mi, Reg rt, IRRef ref, - RegSet allow, int32_t ofs) -{ - IRIns *ir = IR(ref); - Reg base; - if (ra_noreg(ir->r) && canfuse(as, ir)) { - if (ir->o == IR_ADD) { - intptr_t ofs2; - if (irref_isk(ir->op2) && (ofs2 = ofs + get_kval(as, ir->op2), - checki16(ofs2))) { - ref = ir->op1; - ofs = (int32_t)ofs2; - } - } else if (ir->o == IR_STRREF) { - intptr_t ofs2 = 65536; - lj_assertA(ofs == 0, "bad usage"); - ofs = (int32_t)sizeof(GCstr); - if (irref_isk(ir->op2)) { - ofs2 = ofs + get_kval(as, ir->op2); - ref = ir->op1; - } else if (irref_isk(ir->op1)) { - ofs2 = ofs + get_kval(as, ir->op1); - ref = ir->op2; - } - if (!checki16(ofs2)) { - /* NYI: Fuse ADD with constant. */ - Reg right, left = ra_alloc2(as, ir, allow); - right = (left >> 8); left &= 255; - emit_hsi(as, mi, rt, RID_TMP, ofs); - emit_dst(as, MIPSI_AADDU, RID_TMP, left, right); - return; - } - ofs = ofs2; - } - } - base = ra_alloc1(as, ref, allow); - emit_hsi(as, mi, rt, base, ofs); -} - -/* -- Calls --------------------------------------------------------------- */ - -/* Generate a call to a C function. */ -static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args) -{ - uint32_t n, nargs = CCI_XNARGS(ci); - int32_t ofs = LJ_32 ? 16 : 0; -#if LJ_SOFTFP - Reg gpr = REGARG_FIRSTGPR; -#else - Reg gpr, fpr = REGARG_FIRSTFPR; -#endif - if ((void *)ci->func) - emit_call(as, (void *)ci->func, 1); -#if !LJ_SOFTFP - for (gpr = REGARG_FIRSTGPR; gpr <= REGARG_LASTGPR; gpr++) - as->cost[gpr] = REGCOST(~0u, ASMREF_L); - gpr = REGARG_FIRSTGPR; -#endif - for (n = 0; n < nargs; n++) { /* Setup args. */ - IRRef ref = args[n]; - if (ref) { - IRIns *ir = IR(ref); -#if !LJ_SOFTFP - if (irt_isfp(ir->t) && fpr <= REGARG_LASTFPR && - !(ci->flags & CCI_VARARG)) { - lj_assertA(rset_test(as->freeset, fpr), - "reg %d not free", fpr); /* Already evicted. */ - ra_leftov(as, fpr, ref); - fpr += LJ_32 ? 2 : 1; - gpr += (LJ_32 && irt_isnum(ir->t)) ? 2 : 1; - } else -#endif - { -#if LJ_32 && !LJ_SOFTFP - fpr = REGARG_LASTFPR+1; -#endif - if (LJ_32 && irt_isnum(ir->t)) gpr = (gpr+1) & ~1; - if (gpr <= REGARG_LASTGPR) { - lj_assertA(rset_test(as->freeset, gpr), - "reg %d not free", gpr); /* Already evicted. */ -#if !LJ_SOFTFP - if (irt_isfp(ir->t)) { - RegSet of = as->freeset; - Reg r; - /* Workaround to protect argument GPRs from being used for remat. */ - as->freeset &= ~RSET_RANGE(REGARG_FIRSTGPR, REGARG_LASTGPR+1); - r = ra_alloc1(as, ref, RSET_FPR); - as->freeset |= (of & RSET_RANGE(REGARG_FIRSTGPR, REGARG_LASTGPR+1)); - if (irt_isnum(ir->t)) { -#if LJ_32 - emit_tg(as, MIPSI_MFC1, gpr+(LJ_BE?0:1), r+1); - emit_tg(as, MIPSI_MFC1, gpr+(LJ_BE?1:0), r); - lj_assertA(rset_test(as->freeset, gpr+1), - "reg %d not free", gpr+1); /* Already evicted. */ - gpr += 2; -#else - emit_tg(as, MIPSI_DMFC1, gpr, r); - gpr++; fpr++; -#endif - } else if (irt_isfloat(ir->t)) { - emit_tg(as, MIPSI_MFC1, gpr, r); - gpr++; -#if LJ_64 - fpr++; -#endif - } - } else -#endif - { - ra_leftov(as, gpr, ref); - gpr++; -#if LJ_64 && !LJ_SOFTFP - fpr++; -#endif - } - } else { - Reg r = ra_alloc1z(as, ref, !LJ_SOFTFP && irt_isfp(ir->t) ? RSET_FPR : RSET_GPR); -#if LJ_32 - if (irt_isnum(ir->t)) ofs = (ofs + 4) & ~4; - emit_spstore(as, ir, r, ofs); - ofs += irt_isnum(ir->t) ? 8 : 4; -#else - emit_spstore(as, ir, r, ofs + ((LJ_BE && !irt_isfp(ir->t) && !irt_is64(ir->t)) ? 4 : 0)); - ofs += 8; -#endif - } - } - } else { -#if !LJ_SOFTFP - fpr = REGARG_LASTFPR+1; -#endif - if (gpr <= REGARG_LASTGPR) { - gpr++; -#if LJ_64 && !LJ_SOFTFP - fpr++; -#endif - } else { - ofs += LJ_32 ? 4 : 8; - } - } - checkmclim(as); - } -} - -/* Setup result reg/sp for call. Evict scratch regs. */ -static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci) -{ - RegSet drop = RSET_SCRATCH; - int hiop = ((ir+1)->o == IR_HIOP && !irt_isnil((ir+1)->t)); -#if !LJ_SOFTFP - if ((ci->flags & CCI_NOFPRCLOBBER)) - drop &= ~RSET_FPR; -#endif - if (ra_hasreg(ir->r)) - rset_clear(drop, ir->r); /* Dest reg handled below. */ - if (hiop && ra_hasreg((ir+1)->r)) - rset_clear(drop, (ir+1)->r); /* Dest reg handled below. */ - ra_evictset(as, drop); /* Evictions must be performed first. */ - if (ra_used(ir)) { - lj_assertA(!irt_ispri(ir->t), "PRI dest"); - if (!LJ_SOFTFP && irt_isfp(ir->t)) { - if ((ci->flags & CCI_CASTU64)) { - int32_t ofs = sps_scale(ir->s); - Reg dest = ir->r; - if (ra_hasreg(dest)) { - ra_free(as, dest); - ra_modified(as, dest); -#if LJ_32 - emit_tg(as, MIPSI_MTC1, RID_RETHI, dest+1); - emit_tg(as, MIPSI_MTC1, RID_RETLO, dest); -#else - emit_tg(as, MIPSI_DMTC1, RID_RET, dest); -#endif - } - if (ofs) { -#if LJ_32 - emit_tsi(as, MIPSI_SW, RID_RETLO, RID_SP, ofs+(LJ_BE?4:0)); - emit_tsi(as, MIPSI_SW, RID_RETHI, RID_SP, ofs+(LJ_BE?0:4)); -#else - emit_tsi(as, MIPSI_SD, RID_RET, RID_SP, ofs); -#endif - } - } else { - ra_destreg(as, ir, RID_FPRET); - } - } else if (hiop) { - ra_destpair(as, ir); - } else { - ra_destreg(as, ir, RID_RET); - } - } -} - -static void asm_callx(ASMState *as, IRIns *ir) -{ - IRRef args[CCI_NARGS_MAX*2]; - CCallInfo ci; - IRRef func; - IRIns *irf; - ci.flags = asm_callx_flags(as, ir); - asm_collectargs(as, ir, &ci, args); - asm_setupresult(as, ir, &ci); - func = ir->op2; irf = IR(func); - if (irf->o == IR_CARG) { func = irf->op1; irf = IR(func); } - if (irref_isk(func)) { /* Call to constant address. */ - ci.func = (ASMFunction)(void *)get_kval(as, func); - } else { /* Need specific register for indirect calls. */ - Reg r = ra_alloc1(as, func, RID2RSET(RID_CFUNCADDR)); - MCode *p = as->mcp; - if (r == RID_CFUNCADDR) - *--p = MIPSI_NOP; - else - *--p = MIPSI_MOVE | MIPSF_D(RID_CFUNCADDR) | MIPSF_S(r); - *--p = MIPSI_JALR | MIPSF_S(r); - as->mcp = p; - ci.func = (ASMFunction)(void *)0; - } - asm_gencall(as, &ci, args); -} - -#if !LJ_SOFTFP -static void asm_callround(ASMState *as, IRIns *ir, IRCallID id) -{ - /* The modified regs must match with the *.dasc implementation. */ - RegSet drop = RID2RSET(RID_R1)|RID2RSET(RID_R12)|RID2RSET(RID_FPRET)| - RID2RSET(RID_F2)|RID2RSET(RID_F4)|RID2RSET(REGARG_FIRSTFPR)| - RID2RSET(RID_CFUNCADDR) -#if LJ_TARGET_MIPSR6 - |RID2RSET(RID_F21) -#endif - ; - if (ra_hasreg(ir->r)) rset_clear(drop, ir->r); - ra_evictset(as, drop); - ra_destreg(as, ir, RID_FPRET); - emit_call(as, (void *)lj_ir_callinfo[id].func, 0); - ra_leftov(as, REGARG_FIRSTFPR, ir->op1); -} -#endif - -/* -- Returns ------------------------------------------------------------- */ - -/* Return to lower frame. Guard that it goes to the right spot. */ -static void asm_retf(ASMState *as, IRIns *ir) -{ - Reg base = ra_alloc1(as, REF_BASE, RSET_GPR); - void *pc = ir_kptr(IR(ir->op2)); - int32_t delta = 1+LJ_FR2+bc_a(*((const BCIns *)pc - 1)); - as->topslot -= (BCReg)delta; - if ((int32_t)as->topslot < 0) as->topslot = 0; - irt_setmark(IR(REF_BASE)->t); /* Children must not coalesce with BASE reg. */ - emit_setgl(as, base, jit_base); - emit_addptr(as, base, -8*delta); - asm_guard(as, MIPSI_BNE, RID_TMP, - ra_allock(as, igcptr(pc), rset_exclude(RSET_GPR, base))); - emit_tsi(as, MIPSI_AL, RID_TMP, base, (LJ_BE || LJ_FR2) ? -8 : -4); -} - -/* -- Buffer operations --------------------------------------------------- */ - -#if LJ_HASBUFFER -static void asm_bufhdr_write(ASMState *as, Reg sb) -{ - Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, sb)); - IRIns irgc; - irgc.ot = IRT(0, IRT_PGC); /* GC type. */ - emit_storeofs(as, &irgc, RID_TMP, sb, offsetof(SBuf, L)); - if ((as->flags & JIT_F_MIPSXXR2)) { - emit_tsml(as, LJ_64 ? MIPSI_DINS : MIPSI_INS, RID_TMP, tmp, - lj_fls(SBUF_MASK_FLAG), 0); - } else { - emit_dst(as, MIPSI_OR, RID_TMP, RID_TMP, tmp); - emit_tsi(as, MIPSI_ANDI, tmp, tmp, SBUF_MASK_FLAG); - } - emit_getgl(as, RID_TMP, cur_L); - emit_loadofs(as, &irgc, tmp, sb, offsetof(SBuf, L)); -} -#endif - -/* -- Type conversions ---------------------------------------------------- */ - -#if !LJ_SOFTFP -static void asm_tointg(ASMState *as, IRIns *ir, Reg left) -{ - Reg tmp = ra_scratch(as, rset_exclude(RSET_FPR, left)); - Reg dest = ra_dest(as, ir, RSET_GPR); -#if !LJ_TARGET_MIPSR6 - asm_guard(as, MIPSI_BC1F, 0, 0); - emit_fgh(as, MIPSI_C_EQ_D, 0, tmp, left); -#else - asm_guard(as, MIPSI_BC1EQZ, 0, (tmp&31)); - emit_fgh(as, MIPSI_CMP_EQ_D, tmp, tmp, left); -#endif - emit_fg(as, MIPSI_CVT_D_W, tmp, tmp); - emit_tg(as, MIPSI_MFC1, dest, tmp); - emit_fg(as, MIPSI_CVT_W_D, tmp, left); -} - -static void asm_tobit(ASMState *as, IRIns *ir) -{ - RegSet allow = RSET_FPR; - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_alloc1(as, ir->op1, allow); - Reg right = ra_alloc1(as, ir->op2, rset_clear(allow, left)); - Reg tmp = ra_scratch(as, rset_clear(allow, right)); - emit_tg(as, MIPSI_MFC1, dest, tmp); - emit_fgh(as, MIPSI_ADD_D, tmp, left, right); -} -#elif LJ_64 /* && LJ_SOFTFP */ -static void asm_tointg(ASMState *as, IRIns *ir, Reg r) -{ - /* The modified regs must match with the *.dasc implementation. */ - RegSet drop = RID2RSET(REGARG_FIRSTGPR)|RID2RSET(RID_RET)|RID2RSET(RID_RET+1)| - RID2RSET(RID_R1)|RID2RSET(RID_R12)|RID2RSET(RID_CFUNCADDR); - if (ra_hasreg(ir->r)) rset_clear(drop, ir->r); - ra_evictset(as, drop); - /* Return values are in RID_RET (converted value) and RID_RET+1 (status). */ - ra_destreg(as, ir, RID_RET); - asm_guard(as, MIPSI_BNE, RID_RET+1, RID_ZERO); - emit_call(as, (void *)lj_ir_callinfo[IRCALL_lj_vm_tointg].func, 0); - if (r == RID_NONE) - ra_leftov(as, REGARG_FIRSTGPR, ir->op1); - else if (r != REGARG_FIRSTGPR) - emit_move(as, REGARG_FIRSTGPR, r); -} - -static void asm_tobit(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - emit_dta(as, MIPSI_SLL, dest, dest, 0); - asm_callid(as, ir, IRCALL_lj_vm_tobit); -} -#endif - -static void asm_conv(ASMState *as, IRIns *ir) -{ - IRType st = (IRType)(ir->op2 & IRCONV_SRCMASK); -#if !LJ_SOFTFP32 - int stfp = (st == IRT_NUM || st == IRT_FLOAT); -#endif -#if LJ_64 - int st64 = (st == IRT_I64 || st == IRT_U64 || st == IRT_P64); -#endif - IRRef lref = ir->op1; -#if LJ_32 - /* 64 bit integer conversions are handled by SPLIT. */ - lj_assertA(!(irt_isint64(ir->t) || (st == IRT_I64 || st == IRT_U64)), - "IR %04d has unsplit 64 bit type", - (int)(ir - as->ir) - REF_BIAS); -#endif -#if LJ_SOFTFP32 - /* FP conversions are handled by SPLIT. */ - lj_assertA(!irt_isfp(ir->t) && !(st == IRT_NUM || st == IRT_FLOAT), - "IR %04d has FP type", - (int)(ir - as->ir) - REF_BIAS); - /* Can't check for same types: SPLIT uses CONV int.int + BXOR for sfp NEG. */ -#else - lj_assertA(irt_type(ir->t) != st, "inconsistent types for CONV"); -#if !LJ_SOFTFP - if (irt_isfp(ir->t)) { - Reg dest = ra_dest(as, ir, RSET_FPR); - if (stfp) { /* FP to FP conversion. */ - emit_fg(as, st == IRT_NUM ? MIPSI_CVT_S_D : MIPSI_CVT_D_S, - dest, ra_alloc1(as, lref, RSET_FPR)); - } else if (st == IRT_U32) { /* U32 to FP conversion. */ - /* y = (x ^ 0x8000000) + 2147483648.0 */ - Reg left = ra_alloc1(as, lref, RSET_GPR); - Reg tmp = ra_scratch(as, rset_exclude(RSET_FPR, dest)); - if (irt_isfloat(ir->t)) - emit_fg(as, MIPSI_CVT_S_D, dest, dest); - /* Must perform arithmetic with doubles to keep the precision. */ - emit_fgh(as, MIPSI_ADD_D, dest, dest, tmp); - emit_fg(as, MIPSI_CVT_D_W, dest, dest); - emit_lsptr(as, MIPSI_LDC1, (tmp & 31), - (void *)&as->J->k64[LJ_K64_2P31], RSET_GPR); - emit_tg(as, MIPSI_MTC1, RID_TMP, dest); - emit_dst(as, MIPSI_XOR, RID_TMP, RID_TMP, left); - emit_ti(as, MIPSI_LUI, RID_TMP, 0x8000); -#if LJ_64 - } else if(st == IRT_U64) { /* U64 to FP conversion. */ - /* if (x >= 1u<<63) y = (double)(int64_t)(x&(1u<<63)-1) + pow(2.0, 63) */ - Reg left = ra_alloc1(as, lref, RSET_GPR); - Reg tmp = ra_scratch(as, rset_exclude(RSET_FPR, dest)); - MCLabel l_end = emit_label(as); - if (irt_isfloat(ir->t)) { - emit_fgh(as, MIPSI_ADD_S, dest, dest, tmp); - emit_lsptr(as, MIPSI_LWC1, (tmp & 31), (void *)&as->J->k32[LJ_K32_2P63], - rset_exclude(RSET_GPR, left)); - emit_fg(as, MIPSI_CVT_S_L, dest, dest); - } else { - emit_fgh(as, MIPSI_ADD_D, dest, dest, tmp); - emit_lsptr(as, MIPSI_LDC1, (tmp & 31), (void *)&as->J->k64[LJ_K64_2P63], - rset_exclude(RSET_GPR, left)); - emit_fg(as, MIPSI_CVT_D_L, dest, dest); - } - emit_branch(as, MIPSI_BGEZ, left, RID_ZERO, l_end); - emit_tg(as, MIPSI_DMTC1, RID_TMP, dest); - emit_tsml(as, MIPSI_DEXTM, RID_TMP, left, 30, 0); -#endif - } else { /* Integer to FP conversion. */ - Reg left = ra_alloc1(as, lref, RSET_GPR); -#if LJ_32 - emit_fg(as, irt_isfloat(ir->t) ? MIPSI_CVT_S_W : MIPSI_CVT_D_W, - dest, dest); - emit_tg(as, MIPSI_MTC1, left, dest); -#else - MIPSIns mi = irt_isfloat(ir->t) ? - (st64 ? MIPSI_CVT_S_L : MIPSI_CVT_S_W) : - (st64 ? MIPSI_CVT_D_L : MIPSI_CVT_D_W); - emit_fg(as, mi, dest, dest); - emit_tg(as, st64 ? MIPSI_DMTC1 : MIPSI_MTC1, left, dest); -#endif - } - } else if (stfp) { /* FP to integer conversion. */ - if (irt_isguard(ir->t)) { - /* Checked conversions are only supported from number to int. */ - lj_assertA(irt_isint(ir->t) && st == IRT_NUM, - "bad type for checked CONV"); - asm_tointg(as, ir, ra_alloc1(as, lref, RSET_FPR)); - } else { - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_alloc1(as, lref, RSET_FPR); - Reg tmp = ra_scratch(as, rset_exclude(RSET_FPR, left)); - lj_assertA(!irt_isu32(ir->t), "bad CONV u32.fp emitted"); -#if LJ_64 - if (irt_isu64(ir->t)) { /* FP to U64 conversion. */ - MCLabel l_end = emit_label(as); - emit_tg(as, MIPSI_DMFC1, dest, tmp); - /* For result == INT64_MAX add -2^64 and convert again. */ - if (st == IRT_NUM) { - emit_fg(as, MIPSI_TRUNC_L_D, tmp, tmp); - emit_fgh(as, MIPSI_ADD_D, tmp, left, tmp); - emit_lsptr(as, MIPSI_LDC1, (tmp & 31), - (void *)&as->J->k64[LJ_K64_M2P64], - rset_exclude(RSET_GPR, dest)); /* Delay slot. */ - emit_branch(as, MIPSI_BNE, RID_TMP, dest, l_end); /* != INT64_MAX? */ - emit_dta(as, MIPSI_DSRL, RID_TMP, RID_TMP, 1); - emit_ti(as, MIPSI_LI, RID_TMP, -1); - emit_tg(as, MIPSI_DMFC1, dest, tmp); - emit_fg(as, MIPSI_TRUNC_L_D, tmp, left); - } else { - emit_fg(as, MIPSI_TRUNC_L_S, tmp, tmp); - emit_fgh(as, MIPSI_ADD_S, tmp, left, tmp); - emit_lsptr(as, MIPSI_LWC1, (tmp & 31), - (void *)&as->J->k32[LJ_K32_M2P64], - rset_exclude(RSET_GPR, dest)); /* Delay slot. */ - emit_branch(as, MIPSI_BNE, RID_TMP, dest, l_end); /* != INT64_MAX? */ - emit_dta(as, MIPSI_DSRL, RID_TMP, RID_TMP, 1); - emit_ti(as, MIPSI_LI, RID_TMP, -1); - emit_tg(as, MIPSI_DMFC1, dest, tmp); - emit_fg(as, MIPSI_TRUNC_L_S, tmp, left); - } - } else -#endif - { -#if LJ_32 - emit_tg(as, MIPSI_MFC1, dest, tmp); - emit_fg(as, st == IRT_FLOAT ? MIPSI_TRUNC_W_S : MIPSI_TRUNC_W_D, - tmp, left); -#else - MIPSIns mi = irt_is64(ir->t) ? - (st == IRT_NUM ? MIPSI_TRUNC_L_D : MIPSI_TRUNC_L_S) : - (st == IRT_NUM ? MIPSI_TRUNC_W_D : MIPSI_TRUNC_W_S); - emit_tg(as, irt_is64(ir->t) ? MIPSI_DMFC1 : MIPSI_MFC1, dest, tmp); - emit_fg(as, mi, tmp, left); -#endif - } - } - } else -#else - if (irt_isfp(ir->t)) { -#if LJ_64 && LJ_HASFFI - if (stfp) { /* FP to FP conversion. */ - asm_callid(as, ir, irt_isnum(ir->t) ? IRCALL_softfp_f2d : - IRCALL_softfp_d2f); - } else { /* Integer to FP conversion. */ - IRCallID cid = ((IRT_IS64 >> st) & 1) ? - (irt_isnum(ir->t) ? - (st == IRT_I64 ? IRCALL_fp64_l2d : IRCALL_fp64_ul2d) : - (st == IRT_I64 ? IRCALL_fp64_l2f : IRCALL_fp64_ul2f)) : - (irt_isnum(ir->t) ? - (st == IRT_INT ? IRCALL_softfp_i2d : IRCALL_softfp_ui2d) : - (st == IRT_INT ? IRCALL_softfp_i2f : IRCALL_softfp_ui2f)); - asm_callid(as, ir, cid); - } -#else - asm_callid(as, ir, IRCALL_softfp_i2d); -#endif - } else if (stfp) { /* FP to integer conversion. */ - if (irt_isguard(ir->t)) { - /* Checked conversions are only supported from number to int. */ - lj_assertA(irt_isint(ir->t) && st == IRT_NUM, - "bad type for checked CONV"); - asm_tointg(as, ir, RID_NONE); - } else { - IRCallID cid; - lj_assertA(!irt_isu32(ir->t), "bad CONV u32.fp emitted"); - lj_assertA(!(irt_is64(ir->t) && st != IRT_NUM), "bad CONV *64.float emitted"); - cid = irt_is64(ir->t) ? IRCALL_lj_vm_num2u64 : - (st == IRT_NUM ? IRCALL_softfp_d2i : IRCALL_softfp_f2i); - asm_callid(as, ir, cid); - } - } else -#endif -#endif - { - Reg dest = ra_dest(as, ir, RSET_GPR); - if (st >= IRT_I8 && st <= IRT_U16) { /* Extend to 32 bit integer. */ - Reg left = ra_alloc1(as, ir->op1, RSET_GPR); - lj_assertA(irt_isint(ir->t) || irt_isu32(ir->t), "bad type for CONV EXT"); - if ((ir->op2 & IRCONV_SEXT)) { - if (LJ_64 || (as->flags & JIT_F_MIPSXXR2)) { - emit_dst(as, st == IRT_I8 ? MIPSI_SEB : MIPSI_SEH, dest, 0, left); - } else { - uint32_t shift = st == IRT_I8 ? 24 : 16; - emit_dta(as, MIPSI_SRA, dest, dest, shift); - emit_dta(as, MIPSI_SLL, dest, left, shift); - } - } else { - emit_tsi(as, MIPSI_ANDI, dest, left, - (int32_t)(st == IRT_U8 ? 0xff : 0xffff)); - } - } else { /* 32/64 bit integer conversions. */ -#if LJ_32 - /* Only need to handle 32/32 bit no-op (cast) on 32 bit archs. */ - ra_leftov(as, dest, lref); /* Do nothing, but may need to move regs. */ -#else - if (irt_is64(ir->t)) { - if (st64) { - /* 64/64 bit no-op (cast)*/ - ra_leftov(as, dest, lref); - } else { - Reg left = ra_alloc1(as, lref, RSET_GPR); - if ((ir->op2 & IRCONV_SEXT)) { /* 32 to 64 bit sign extension. */ - emit_dta(as, MIPSI_SLL, dest, left, 0); - } else { /* 32 to 64 bit zero extension. */ - emit_tsml(as, MIPSI_DEXT, dest, left, 31, 0); - } - } - } else { - if (!irt_isu32(ir->t)) { /* Implicit sign extension. */ - Reg left = ra_alloc1(as, lref, RSET_GPR); - emit_dta(as, MIPSI_SLL, dest, left, 0); - } else if (st64 && !(ir->op2 & IRCONV_NONE)) { - /* This is either a 32 bit reg/reg mov which zeroes the hiword - ** or a load of the loword from a 64 bit address. - */ - Reg left = ra_alloc1(as, lref, RSET_GPR); - emit_tsml(as, MIPSI_DEXT, dest, left, 31, 0); - } else { /* 32/32 bit no-op (cast). */ - /* Do nothing, but may need to move regs. */ - ra_leftov(as, dest, lref); - } - } -#endif - } - } -} - -static void asm_strto(ASMState *as, IRIns *ir) -{ - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_strscan_num]; - IRRef args[2]; - int32_t ofs = 0; -#if LJ_SOFTFP32 - ra_evictset(as, RSET_SCRATCH); - if (ra_used(ir)) { - if (ra_hasspill(ir->s) && ra_hasspill((ir+1)->s) && - (ir->s & 1) == LJ_BE && (ir->s ^ 1) == (ir+1)->s) { - int i; - for (i = 0; i < 2; i++) { - Reg r = (ir+i)->r; - if (ra_hasreg(r)) { - ra_free(as, r); - ra_modified(as, r); - emit_spload(as, ir+i, r, sps_scale((ir+i)->s)); - } - } - ofs = sps_scale(ir->s & ~1); - } else { - Reg rhi = ra_dest(as, ir+1, RSET_GPR); - Reg rlo = ra_dest(as, ir, rset_exclude(RSET_GPR, rhi)); - emit_tsi(as, MIPSI_LW, rhi, RID_SP, ofs+(LJ_BE?0:4)); - emit_tsi(as, MIPSI_LW, rlo, RID_SP, ofs+(LJ_BE?4:0)); - } - } -#else - RegSet drop = RSET_SCRATCH; - if (ra_hasreg(ir->r)) rset_set(drop, ir->r); /* Spill dest reg (if any). */ - ra_evictset(as, drop); - ofs = sps_scale(ir->s); -#endif - asm_guard(as, MIPSI_BEQ, RID_RET, RID_ZERO); /* Test return status. */ - args[0] = ir->op1; /* GCstr *str */ - args[1] = ASMREF_TMP1; /* TValue *n */ - asm_gencall(as, ci, args); - /* Store the result to the spill slot or temp slots. */ - emit_tsi(as, MIPSI_AADDIU, ra_releasetmp(as, ASMREF_TMP1), - RID_SP, ofs); -} - -/* -- Memory references --------------------------------------------------- */ - -#if LJ_64 -/* Store tagged value for ref at base+ofs. */ -static void asm_tvstore64(ASMState *as, Reg base, int32_t ofs, IRRef ref) -{ - RegSet allow = rset_exclude(RSET_GPR, base); - IRIns *ir = IR(ref); - lj_assertA(irt_ispri(ir->t) || irt_isaddr(ir->t) || irt_isinteger(ir->t), - "store of IR type %d", irt_type(ir->t)); - if (irref_isk(ref)) { - TValue k; - lj_ir_kvalue(as->J->L, &k, ir); - emit_tsi(as, MIPSI_SD, ra_allock(as, (int64_t)k.u64, allow), base, ofs); - } else { - Reg src = ra_alloc1(as, ref, allow); - Reg type = ra_allock(as, (int64_t)irt_toitype(ir->t) << 47, - rset_exclude(allow, src)); - emit_tsi(as, MIPSI_SD, RID_TMP, base, ofs); - if (irt_isinteger(ir->t)) { - emit_dst(as, MIPSI_DADDU, RID_TMP, RID_TMP, type); - emit_tsml(as, MIPSI_DEXT, RID_TMP, src, 31, 0); - } else { - emit_dst(as, MIPSI_DADDU, RID_TMP, src, type); - } - } -} -#endif - -/* Get pointer to TValue. */ -static void asm_tvptr(ASMState *as, Reg dest, IRRef ref, MSize mode) -{ - int32_t tmpofs = (int32_t)(offsetof(global_State, tmptv)-32768); - if ((mode & IRTMPREF_IN1)) { - IRIns *ir = IR(ref); - if (irt_isnum(ir->t)) { - if ((mode & IRTMPREF_OUT1)) { -#if LJ_SOFTFP - emit_tsi(as, MIPSI_AADDIU, dest, RID_JGL, tmpofs); -#if LJ_64 - emit_setgl(as, ra_alloc1(as, ref, RSET_GPR), tmptv.u64); -#else - lj_assertA(irref_isk(ref), "unsplit FP op"); - emit_setgl(as, - ra_allock(as, (int32_t)ir_knum(ir)->u32.lo, RSET_GPR), - tmptv.u32.lo); - emit_setgl(as, - ra_allock(as, (int32_t)ir_knum(ir)->u32.hi, RSET_GPR), - tmptv.u32.hi); -#endif -#else - Reg src = ra_alloc1(as, ref, RSET_FPR); - emit_tsi(as, MIPSI_AADDIU, dest, RID_JGL, tmpofs); - emit_tsi(as, MIPSI_SDC1, (src & 31), RID_JGL, tmpofs); -#endif - } else if (irref_isk(ref)) { - /* Use the number constant itself as a TValue. */ - ra_allockreg(as, igcptr(ir_knum(ir)), dest); - } else { -#if LJ_SOFTFP32 - lj_assertA(0, "unsplit FP op"); -#else - /* Otherwise force a spill and use the spill slot. */ - emit_tsi(as, MIPSI_AADDIU, dest, RID_SP, ra_spill(as, ir)); -#endif - } - } else { - /* Otherwise use g->tmptv to hold the TValue. */ -#if LJ_32 - Reg type; - emit_tsi(as, MIPSI_ADDIU, dest, RID_JGL, tmpofs); - if (!irt_ispri(ir->t)) { - Reg src = ra_alloc1(as, ref, RSET_GPR); - emit_setgl(as, src, tmptv.gcr); - } - if (LJ_SOFTFP && (ir+1)->o == IR_HIOP && !irt_isnil((ir+1)->t)) - type = ra_alloc1(as, ref+1, RSET_GPR); - else - type = ra_allock(as, (int32_t)irt_toitype(ir->t), RSET_GPR); - emit_setgl(as, type, tmptv.it); -#else - asm_tvstore64(as, dest, 0, ref); - emit_tsi(as, MIPSI_DADDIU, dest, RID_JGL, tmpofs); -#endif - } - } else { - emit_tsi(as, MIPSI_AADDIU, dest, RID_JGL, tmpofs); - } -} - -static void asm_aref(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg idx, base; - if (irref_isk(ir->op2)) { - IRRef tab = IR(ir->op1)->op1; - int32_t ofs = asm_fuseabase(as, tab); - IRRef refa = ofs ? tab : ir->op1; - ofs += 8*IR(ir->op2)->i; - if (checki16(ofs)) { - base = ra_alloc1(as, refa, RSET_GPR); - emit_tsi(as, MIPSI_AADDIU, dest, base, ofs); - return; - } - } - base = ra_alloc1(as, ir->op1, RSET_GPR); - idx = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, base)); -#if !LJ_TARGET_MIPSR6 - emit_dst(as, MIPSI_AADDU, dest, RID_TMP, base); - emit_dta(as, MIPSI_SLL, RID_TMP, idx, 3); -#else - emit_dst(as, MIPSI_ALSA | MIPSF_A(3-1), dest, idx, base); -#endif -} - -/* Inlined hash lookup. Specialized for key type and for const keys. -** The equivalent C code is: -** Node *n = hashkey(t, key); -** do { -** if (lj_obj_equal(&n->key, key)) return &n->val; -** } while ((n = nextnode(n))); -** return niltv(L); -*/ -static void asm_href(ASMState *as, IRIns *ir, IROp merge) -{ - RegSet allow = RSET_GPR; - int destused = ra_used(ir); - Reg dest = ra_dest(as, ir, allow); - Reg tab = ra_alloc1(as, ir->op1, rset_clear(allow, dest)); - Reg key = RID_NONE, type = RID_NONE, tmpnum = RID_NONE, tmp1 = RID_TMP, tmp2; -#if LJ_64 - Reg cmp64 = RID_NONE; -#endif - IRRef refkey = ir->op2; - IRIns *irkey = IR(refkey); - int isk = irref_isk(refkey); - IRType1 kt = irkey->t; - uint32_t khash; - MCLabel l_end, l_loop, l_next; - - rset_clear(allow, tab); - if (!LJ_SOFTFP && irt_isnum(kt)) { - key = ra_alloc1(as, refkey, RSET_FPR); - tmpnum = ra_scratch(as, rset_exclude(RSET_FPR, key)); - } else { - if (!irt_ispri(kt)) { - key = ra_alloc1(as, refkey, allow); - rset_clear(allow, key); - } -#if LJ_32 - if (LJ_SOFTFP && irkey[1].o == IR_HIOP) { - if (ra_hasreg((irkey+1)->r)) { - type = tmpnum = (irkey+1)->r; - tmp1 = ra_scratch(as, allow); - rset_clear(allow, tmp1); - ra_noweak(as, tmpnum); - } else { - type = tmpnum = ra_allocref(as, refkey+1, allow); - } - rset_clear(allow, tmpnum); - } else { - type = ra_allock(as, (int32_t)irt_toitype(kt), allow); - rset_clear(allow, type); - } -#endif - } - tmp2 = ra_scratch(as, allow); - rset_clear(allow, tmp2); -#if LJ_64 - if (LJ_SOFTFP || !irt_isnum(kt)) { - /* Allocate cmp64 register used for 64-bit comparisons */ - if (LJ_SOFTFP && irt_isnum(kt)) { - cmp64 = key; - } else if (!isk && irt_isaddr(kt)) { - cmp64 = tmp2; - } else { - int64_t k; - if (isk && irt_isaddr(kt)) { - k = ((int64_t)irt_toitype(kt) << 47) | irkey[1].tv.u64; - } else { - lj_assertA(irt_ispri(kt) && !irt_isnil(kt), "bad HREF key type"); - k = ~((int64_t)~irt_toitype(kt) << 47); - } - cmp64 = ra_allock(as, k, allow); - rset_clear(allow, cmp64); - } - } -#endif - - /* Key not found in chain: jump to exit (if merged) or load niltv. */ - l_end = emit_label(as); - as->invmcp = NULL; - if (merge == IR_NE) - asm_guard(as, MIPSI_B, RID_ZERO, RID_ZERO); - else if (destused) - emit_loada(as, dest, niltvg(J2G(as->J))); - /* Follow hash chain until the end. */ - emit_move(as, dest, tmp1); - l_loop = --as->mcp; - emit_tsi(as, MIPSI_AL, tmp1, dest, (int32_t)offsetof(Node, next)); - l_next = emit_label(as); - - /* Type and value comparison. */ - if (merge == IR_EQ) { /* Must match asm_guard(). */ - emit_ti(as, MIPSI_LI, RID_TMP, as->snapno); - l_end = asm_exitstub_addr(as); - } - if (!LJ_SOFTFP && irt_isnum(kt)) { -#if !LJ_TARGET_MIPSR6 - emit_branch(as, MIPSI_BC1T, 0, 0, l_end); - emit_fgh(as, MIPSI_C_EQ_D, 0, tmpnum, key); -#else - emit_branch(as, MIPSI_BC1NEZ, 0, (tmpnum&31), l_end); - emit_fgh(as, MIPSI_CMP_EQ_D, tmpnum, tmpnum, key); -#endif - *--as->mcp = MIPSI_NOP; /* Avoid NaN comparison overhead. */ - emit_branch(as, MIPSI_BEQ, tmp1, RID_ZERO, l_next); - emit_tsi(as, MIPSI_SLTIU, tmp1, tmp1, (int32_t)LJ_TISNUM); -#if LJ_32 - emit_hsi(as, MIPSI_LDC1, tmpnum, dest, (int32_t)offsetof(Node, key.n)); - } else { - if (irt_ispri(kt)) { - emit_branch(as, MIPSI_BEQ, tmp1, type, l_end); - } else { - emit_branch(as, MIPSI_BEQ, tmp2, key, l_end); - emit_tsi(as, MIPSI_LW, tmp2, dest, (int32_t)offsetof(Node, key.gcr)); - emit_branch(as, MIPSI_BNE, tmp1, type, l_next); - } - } - emit_tsi(as, MIPSI_LW, tmp1, dest, (int32_t)offsetof(Node, key.it)); - *l_loop = MIPSI_BNE | MIPSF_S(tmp1) | ((as->mcp-l_loop-1) & 0xffffu); -#else - emit_dta(as, MIPSI_DSRA32, tmp1, tmp1, 15); - emit_tg(as, MIPSI_DMTC1, tmp1, tmpnum); - emit_tsi(as, MIPSI_LD, tmp1, dest, (int32_t)offsetof(Node, key.u64)); - } else { - emit_branch(as, MIPSI_BEQ, tmp1, cmp64, l_end); - emit_tsi(as, MIPSI_LD, tmp1, dest, (int32_t)offsetof(Node, key.u64)); - } - *l_loop = MIPSI_BNE | MIPSF_S(tmp1) | ((as->mcp-l_loop-1) & 0xffffu); - if (!isk && irt_isaddr(kt)) { - type = ra_allock(as, (int64_t)irt_toitype(kt) << 47, allow); - emit_dst(as, MIPSI_DADDU, tmp2, key, type); - rset_clear(allow, type); - } -#endif - - /* Load main position relative to tab->node into dest. */ - khash = isk ? ir_khash(as, irkey) : 1; - if (khash == 0) { - emit_tsi(as, MIPSI_AL, dest, tab, (int32_t)offsetof(GCtab, node)); - } else { - Reg tmphash = tmp1; - if (isk) - tmphash = ra_allock(as, khash, allow); - emit_dst(as, MIPSI_AADDU, dest, dest, tmp1); - lj_assertA(sizeof(Node) == 24, "bad Node size"); - emit_dst(as, MIPSI_SUBU, tmp1, tmp2, tmp1); - emit_dta(as, MIPSI_SLL, tmp1, tmp1, 3); - emit_dta(as, MIPSI_SLL, tmp2, tmp1, 5); - emit_dst(as, MIPSI_AND, tmp1, tmp2, tmphash); - emit_tsi(as, MIPSI_AL, dest, tab, (int32_t)offsetof(GCtab, node)); - emit_tsi(as, MIPSI_LW, tmp2, tab, (int32_t)offsetof(GCtab, hmask)); - if (isk) { - /* Nothing to do. */ - } else if (irt_isstr(kt)) { - emit_tsi(as, MIPSI_LW, tmp1, key, (int32_t)offsetof(GCstr, sid)); - } else { /* Must match with hash*() in lj_tab.c. */ - emit_dst(as, MIPSI_SUBU, tmp1, tmp1, tmp2); - emit_rotr(as, tmp2, tmp2, dest, (-HASH_ROT3)&31); - emit_dst(as, MIPSI_XOR, tmp1, tmp1, tmp2); - emit_rotr(as, tmp1, tmp1, dest, (-HASH_ROT2-HASH_ROT1)&31); - emit_dst(as, MIPSI_SUBU, tmp2, tmp2, dest); -#if LJ_32 - if (LJ_SOFTFP ? (irkey[1].o == IR_HIOP) : irt_isnum(kt)) { - emit_dst(as, MIPSI_XOR, tmp2, tmp2, tmp1); - if ((as->flags & JIT_F_MIPSXXR2)) { - emit_dta(as, MIPSI_ROTR, dest, tmp1, (-HASH_ROT1)&31); - } else { - emit_dst(as, MIPSI_OR, dest, dest, tmp1); - emit_dta(as, MIPSI_SLL, tmp1, tmp1, HASH_ROT1); - emit_dta(as, MIPSI_SRL, dest, tmp1, (-HASH_ROT1)&31); - } - emit_dst(as, MIPSI_ADDU, tmp1, tmp1, tmp1); -#if LJ_SOFTFP - emit_ds(as, MIPSI_MOVE, tmp1, type); - emit_ds(as, MIPSI_MOVE, tmp2, key); -#else - emit_tg(as, MIPSI_MFC1, tmp2, key); - emit_tg(as, MIPSI_MFC1, tmp1, key+1); -#endif - } else { - emit_dst(as, MIPSI_XOR, tmp2, key, tmp1); - emit_rotr(as, dest, tmp1, tmp2, (-HASH_ROT1)&31); - emit_dst(as, MIPSI_ADDU, tmp1, key, ra_allock(as, HASH_BIAS, allow)); - } -#else - emit_dst(as, MIPSI_XOR, tmp2, tmp2, tmp1); - emit_dta(as, MIPSI_ROTR, dest, tmp1, (-HASH_ROT1)&31); - if (irt_isnum(kt)) { - emit_dst(as, MIPSI_ADDU, tmp1, tmp1, tmp1); - emit_dta(as, MIPSI_DSRA32, tmp1, LJ_SOFTFP ? key : tmp1, 0); - emit_dta(as, MIPSI_SLL, tmp2, LJ_SOFTFP ? key : tmp1, 0); -#if !LJ_SOFTFP - emit_tg(as, MIPSI_DMFC1, tmp1, key); -#endif - } else { - checkmclim(as); - emit_dta(as, MIPSI_DSRA32, tmp1, tmp1, 0); - emit_dta(as, MIPSI_SLL, tmp2, key, 0); - emit_dst(as, MIPSI_DADDU, tmp1, key, type); - } -#endif - } - } -} - -static void asm_hrefk(ASMState *as, IRIns *ir) -{ - IRIns *kslot = IR(ir->op2); - IRIns *irkey = IR(kslot->op1); - int32_t ofs = (int32_t)(kslot->op2 * sizeof(Node)); - int32_t kofs = ofs + (int32_t)offsetof(Node, key); - Reg dest = (ra_used(ir)||ofs > 32736) ? ra_dest(as, ir, RSET_GPR) : RID_NONE; - Reg node = ra_alloc1(as, ir->op1, RSET_GPR); - RegSet allow = rset_exclude(RSET_GPR, node); - Reg idx = node; -#if LJ_32 - Reg key = RID_NONE, type = RID_TMP; - int32_t lo, hi; -#else - Reg key = ra_scratch(as, allow); - int64_t k; -#endif - lj_assertA(ofs % sizeof(Node) == 0, "unaligned HREFK slot"); - if (ofs > 32736) { - idx = dest; - rset_clear(allow, dest); - kofs = (int32_t)offsetof(Node, key); - } else if (ra_hasreg(dest)) { - emit_tsi(as, MIPSI_AADDIU, dest, node, ofs); - } -#if LJ_32 - if (!irt_ispri(irkey->t)) { - key = ra_scratch(as, allow); - rset_clear(allow, key); - } - if (irt_isnum(irkey->t)) { - lo = (int32_t)ir_knum(irkey)->u32.lo; - hi = (int32_t)ir_knum(irkey)->u32.hi; - } else { - lo = irkey->i; - hi = irt_toitype(irkey->t); - if (!ra_hasreg(key)) - goto nolo; - } - asm_guard(as, MIPSI_BNE, key, lo ? ra_allock(as, lo, allow) : RID_ZERO); -nolo: - asm_guard(as, MIPSI_BNE, type, hi ? ra_allock(as, hi, allow) : RID_ZERO); - if (ra_hasreg(key)) emit_tsi(as, MIPSI_LW, key, idx, kofs+(LJ_BE?4:0)); - emit_tsi(as, MIPSI_LW, type, idx, kofs+(LJ_BE?0:4)); -#else - if (irt_ispri(irkey->t)) { - lj_assertA(!irt_isnil(irkey->t), "bad HREFK key type"); - k = ~((int64_t)~irt_toitype(irkey->t) << 47); - } else if (irt_isnum(irkey->t)) { - k = (int64_t)ir_knum(irkey)->u64; - } else { - k = ((int64_t)irt_toitype(irkey->t) << 47) | (int64_t)ir_kgc(irkey); - } - asm_guard(as, MIPSI_BNE, key, ra_allock(as, k, allow)); - emit_tsi(as, MIPSI_LD, key, idx, kofs); -#endif - if (ofs > 32736) - emit_tsi(as, MIPSI_AADDU, dest, node, ra_allock(as, ofs, allow)); -} - -static void asm_uref(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - int guarded = (irt_t(ir->t) & (IRT_GUARD|IRT_TYPE)) == (IRT_GUARD|IRT_PGC); - if (irref_isk(ir->op1) && !guarded) { - GCfunc *fn = ir_kfunc(IR(ir->op1)); - MRef *v = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.v; - emit_lsptr(as, MIPSI_AL, dest, v, RSET_GPR); - } else { - if (guarded) - asm_guard(as, ir->o == IR_UREFC ? MIPSI_BEQ : MIPSI_BNE, RID_TMP, RID_ZERO); - if (ir->o == IR_UREFC) - emit_tsi(as, MIPSI_AADDIU, dest, dest, (int32_t)offsetof(GCupval, tv)); - else - emit_tsi(as, MIPSI_AL, dest, dest, (int32_t)offsetof(GCupval, v)); - if (guarded) - emit_tsi(as, MIPSI_LBU, RID_TMP, dest, (int32_t)offsetof(GCupval, closed)); - if (irref_isk(ir->op1)) { - GCfunc *fn = ir_kfunc(IR(ir->op1)); - GCobj *o = gcref(fn->l.uvptr[(ir->op2 >> 8)]); - emit_loada(as, dest, o); - } else { - emit_tsi(as, MIPSI_AL, dest, ra_alloc1(as, ir->op1, RSET_GPR), - (int32_t)offsetof(GCfuncL, uvptr) + - (int32_t)sizeof(MRef) * (int32_t)(ir->op2 >> 8)); - } - } -} - -static void asm_fref(ASMState *as, IRIns *ir) -{ - UNUSED(as); UNUSED(ir); - lj_assertA(!ra_used(ir), "unfused FREF"); -} - -static void asm_strref(ASMState *as, IRIns *ir) -{ -#if LJ_32 - Reg dest = ra_dest(as, ir, RSET_GPR); - IRRef ref = ir->op2, refk = ir->op1; - int32_t ofs = (int32_t)sizeof(GCstr); - Reg r; - if (irref_isk(ref)) { - IRRef tmp = refk; refk = ref; ref = tmp; - } else if (!irref_isk(refk)) { - Reg right, left = ra_alloc1(as, ir->op1, RSET_GPR); - IRIns *irr = IR(ir->op2); - if (ra_hasreg(irr->r)) { - ra_noweak(as, irr->r); - right = irr->r; - } else if (mayfuse(as, irr->op2) && - irr->o == IR_ADD && irref_isk(irr->op2) && - checki16(ofs + IR(irr->op2)->i)) { - ofs += IR(irr->op2)->i; - right = ra_alloc1(as, irr->op1, rset_exclude(RSET_GPR, left)); - } else { - right = ra_allocref(as, ir->op2, rset_exclude(RSET_GPR, left)); - } - emit_tsi(as, MIPSI_ADDIU, dest, dest, ofs); - emit_dst(as, MIPSI_ADDU, dest, left, right); - return; - } - r = ra_alloc1(as, ref, RSET_GPR); - ofs += IR(refk)->i; - if (checki16(ofs)) - emit_tsi(as, MIPSI_ADDIU, dest, r, ofs); - else - emit_dst(as, MIPSI_ADDU, dest, r, - ra_allock(as, ofs, rset_exclude(RSET_GPR, r))); -#else - RegSet allow = RSET_GPR; - Reg dest = ra_dest(as, ir, allow); - Reg base = ra_alloc1(as, ir->op1, allow); - IRIns *irr = IR(ir->op2); - int32_t ofs = sizeof(GCstr); - rset_clear(allow, base); - if (irref_isk(ir->op2) && checki16(ofs + irr->i)) { - emit_tsi(as, MIPSI_DADDIU, dest, base, ofs + irr->i); - } else { - emit_tsi(as, MIPSI_DADDIU, dest, dest, ofs); - emit_dst(as, MIPSI_DADDU, dest, base, ra_alloc1(as, ir->op2, allow)); - } -#endif -} - -/* -- Loads and stores ---------------------------------------------------- */ - -static MIPSIns asm_fxloadins(ASMState *as, IRIns *ir) -{ - UNUSED(as); - switch (irt_type(ir->t)) { - case IRT_I8: return MIPSI_LB; - case IRT_U8: return MIPSI_LBU; - case IRT_I16: return MIPSI_LH; - case IRT_U16: return MIPSI_LHU; - case IRT_NUM: - lj_assertA(!LJ_SOFTFP32, "unsplit FP op"); - if (!LJ_SOFTFP) return MIPSI_LDC1; - /* fallthrough */ - case IRT_FLOAT: if (!LJ_SOFTFP) return MIPSI_LWC1; - /* fallthrough */ - default: return (LJ_64 && irt_is64(ir->t)) ? MIPSI_LD : MIPSI_LW; - } -} - -static MIPSIns asm_fxstoreins(ASMState *as, IRIns *ir) -{ - UNUSED(as); - switch (irt_type(ir->t)) { - case IRT_I8: case IRT_U8: return MIPSI_SB; - case IRT_I16: case IRT_U16: return MIPSI_SH; - case IRT_NUM: - lj_assertA(!LJ_SOFTFP32, "unsplit FP op"); - if (!LJ_SOFTFP) return MIPSI_SDC1; - /* fallthrough */ - case IRT_FLOAT: if (!LJ_SOFTFP) return MIPSI_SWC1; - /* fallthrough */ - default: return (LJ_64 && irt_is64(ir->t)) ? MIPSI_SD : MIPSI_SW; - } -} - -static void asm_fload(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - MIPSIns mi = asm_fxloadins(as, ir); - Reg idx; - int32_t ofs; - if (ir->op1 == REF_NIL) { /* FLOAD from GG_State with offset. */ - idx = RID_JGL; - ofs = (ir->op2 << 2) - 32768 - GG_OFS(g); - } else { - idx = ra_alloc1(as, ir->op1, RSET_GPR); - if (ir->op2 == IRFL_TAB_ARRAY) { - ofs = asm_fuseabase(as, ir->op1); - if (ofs) { /* Turn the t->array load into an add for colocated arrays. */ - emit_tsi(as, MIPSI_AADDIU, dest, idx, ofs); - return; - } - } - ofs = field_ofs[ir->op2]; - lj_assertA(!irt_isfp(ir->t), "bad FP FLOAD"); - } - emit_tsi(as, mi, dest, idx, ofs); -} - -static void asm_fstore(ASMState *as, IRIns *ir) -{ - if (ir->r != RID_SINK) { - Reg src = ra_alloc1z(as, ir->op2, RSET_GPR); - IRIns *irf = IR(ir->op1); - Reg idx = ra_alloc1(as, irf->op1, rset_exclude(RSET_GPR, src)); - int32_t ofs = field_ofs[irf->op2]; - MIPSIns mi = asm_fxstoreins(as, ir); - lj_assertA(!irt_isfp(ir->t), "bad FP FSTORE"); - emit_tsi(as, mi, src, idx, ofs); - } -} - -static void asm_xload(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, - (!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR); - lj_assertA(LJ_TARGET_UNALIGNED || !(ir->op2 & IRXLOAD_UNALIGNED), - "unaligned XLOAD"); - asm_fusexref(as, asm_fxloadins(as, ir), dest, ir->op1, RSET_GPR, 0); -} - -static void asm_xstore_(ASMState *as, IRIns *ir, int32_t ofs) -{ - if (ir->r != RID_SINK) { - Reg src = ra_alloc1z(as, ir->op2, - (!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR); - asm_fusexref(as, asm_fxstoreins(as, ir), src, ir->op1, - rset_exclude(RSET_GPR, src), ofs); - } -} - -#define asm_xstore(as, ir) asm_xstore_(as, ir, 0) - -static void asm_ahuvload(ASMState *as, IRIns *ir) -{ - int hiop = (LJ_SOFTFP32 && (ir+1)->o == IR_HIOP); - Reg dest = RID_NONE, type = RID_TMP, idx; - RegSet allow = RSET_GPR; - int32_t ofs = 0; - IRType1 t = ir->t; - if (hiop) { - t.irt = IRT_NUM; - if (ra_used(ir+1)) { - type = ra_dest(as, ir+1, allow); - rset_clear(allow, type); - } - } - if (ra_used(ir)) { - lj_assertA((LJ_SOFTFP32 ? 0 : irt_isnum(ir->t)) || - irt_isint(ir->t) || irt_isaddr(ir->t), - "bad load type %d", irt_type(ir->t)); - dest = ra_dest(as, ir, (!LJ_SOFTFP && irt_isnum(t)) ? RSET_FPR : allow); - rset_clear(allow, dest); -#if LJ_64 - if (irt_isaddr(t)) - emit_tsml(as, MIPSI_DEXTM, dest, dest, 14, 0); - else if (irt_isint(t)) - emit_dta(as, MIPSI_SLL, dest, dest, 0); -#endif - } - idx = asm_fuseahuref(as, ir->op1, &ofs, allow); - if (ir->o == IR_VLOAD) ofs += 8 * ir->op2; - rset_clear(allow, idx); - if (irt_isnum(t)) { - asm_guard(as, MIPSI_BEQ, RID_TMP, RID_ZERO); - emit_tsi(as, MIPSI_SLTIU, RID_TMP, type, (int32_t)LJ_TISNUM); - } else { - asm_guard(as, MIPSI_BNE, type, - ra_allock(as, (int32_t)irt_toitype(t), allow)); - } -#if LJ_32 - if (ra_hasreg(dest)) { - if (!LJ_SOFTFP && irt_isnum(t)) - emit_hsi(as, MIPSI_LDC1, dest, idx, ofs); - else - emit_tsi(as, MIPSI_LW, dest, idx, ofs+(LJ_BE?4:0)); - } - emit_tsi(as, MIPSI_LW, type, idx, ofs+(LJ_BE?0:4)); -#else - if (ra_hasreg(dest)) { - if (!LJ_SOFTFP && irt_isnum(t)) { - emit_hsi(as, MIPSI_LDC1, dest, idx, ofs); - dest = type; - } - } else { - dest = type; - } - emit_dta(as, MIPSI_DSRA32, type, dest, 15); - emit_tsi(as, MIPSI_LD, dest, idx, ofs); -#endif -} - -static void asm_ahustore(ASMState *as, IRIns *ir) -{ - RegSet allow = RSET_GPR; - Reg idx, src = RID_NONE, type = RID_NONE; - int32_t ofs = 0; - if (ir->r == RID_SINK) - return; - if (!LJ_SOFTFP32 && irt_isnum(ir->t)) { - src = ra_alloc1(as, ir->op2, LJ_SOFTFP ? RSET_GPR : RSET_FPR); - idx = asm_fuseahuref(as, ir->op1, &ofs, allow); - emit_hsi(as, LJ_SOFTFP ? MIPSI_SD : MIPSI_SDC1, src, idx, ofs); - } else { -#if LJ_32 - if (!irt_ispri(ir->t)) { - src = ra_alloc1(as, ir->op2, allow); - rset_clear(allow, src); - } - if (LJ_SOFTFP && (ir+1)->o == IR_HIOP) - type = ra_alloc1(as, (ir+1)->op2, allow); - else - type = ra_allock(as, (int32_t)irt_toitype(ir->t), allow); - rset_clear(allow, type); - idx = asm_fuseahuref(as, ir->op1, &ofs, allow); - if (ra_hasreg(src)) - emit_tsi(as, MIPSI_SW, src, idx, ofs+(LJ_BE?4:0)); - emit_tsi(as, MIPSI_SW, type, idx, ofs+(LJ_BE?0:4)); -#else - Reg tmp = RID_TMP; - if (irt_ispri(ir->t)) { - tmp = ra_allock(as, ~((int64_t)~irt_toitype(ir->t) << 47), allow); - rset_clear(allow, tmp); - } else { - src = ra_alloc1(as, ir->op2, allow); - rset_clear(allow, src); - type = ra_allock(as, (int64_t)irt_toitype(ir->t) << 47, allow); - rset_clear(allow, type); - } - idx = asm_fuseahuref(as, ir->op1, &ofs, allow); - emit_tsi(as, MIPSI_SD, tmp, idx, ofs); - if (ra_hasreg(src)) { - if (irt_isinteger(ir->t)) { - emit_dst(as, MIPSI_DADDU, tmp, tmp, type); - emit_tsml(as, MIPSI_DEXT, tmp, src, 31, 0); - } else { - emit_dst(as, MIPSI_DADDU, tmp, src, type); - } - } -#endif - } -} - -static void asm_sload(ASMState *as, IRIns *ir) -{ - Reg dest = RID_NONE, type = RID_NONE, base; - RegSet allow = RSET_GPR; - IRType1 t = ir->t; -#if LJ_32 - int32_t ofs = 8*((int32_t)ir->op1-1) + ((ir->op2 & IRSLOAD_FRAME) ? 4 : 0); - int hiop = (LJ_SOFTFP32 && (ir+1)->o == IR_HIOP); - if (hiop) - t.irt = IRT_NUM; -#else - int32_t ofs = 8*((int32_t)ir->op1-2); -#endif - lj_assertA(!(ir->op2 & IRSLOAD_PARENT), - "bad parent SLOAD"); /* Handled by asm_head_side(). */ - lj_assertA(irt_isguard(ir->t) || !(ir->op2 & IRSLOAD_TYPECHECK), - "inconsistent SLOAD variant"); -#if LJ_SOFTFP32 - lj_assertA(!(ir->op2 & IRSLOAD_CONVERT), - "unsplit SLOAD convert"); /* Handled by LJ_SOFTFP SPLIT. */ - if (hiop && ra_used(ir+1)) { - type = ra_dest(as, ir+1, allow); - rset_clear(allow, type); - } -#else - if ((ir->op2 & IRSLOAD_CONVERT) && irt_isguard(t) && irt_isint(t)) { - dest = ra_scratch(as, LJ_SOFTFP ? allow : RSET_FPR); - asm_tointg(as, ir, dest); - t.irt = IRT_NUM; /* Continue with a regular number type check. */ - } else -#endif - if (ra_used(ir)) { - lj_assertA((LJ_SOFTFP32 ? 0 : irt_isnum(ir->t)) || - irt_isint(ir->t) || irt_isaddr(ir->t), - "bad SLOAD type %d", irt_type(ir->t)); - dest = ra_dest(as, ir, (!LJ_SOFTFP && irt_isnum(t)) ? RSET_FPR : allow); - rset_clear(allow, dest); - base = ra_alloc1(as, REF_BASE, allow); - rset_clear(allow, base); - if (!LJ_SOFTFP32 && (ir->op2 & IRSLOAD_CONVERT)) { - if (irt_isint(t)) { - Reg tmp = ra_scratch(as, LJ_SOFTFP ? RSET_GPR : RSET_FPR); -#if LJ_SOFTFP - ra_evictset(as, rset_exclude(RSET_SCRATCH, dest)); - ra_destreg(as, ir, RID_RET); - emit_call(as, (void *)lj_ir_callinfo[IRCALL_softfp_d2i].func, 0); - if (tmp != REGARG_FIRSTGPR) - emit_move(as, REGARG_FIRSTGPR, tmp); -#else - emit_tg(as, MIPSI_MFC1, dest, tmp); - emit_fg(as, MIPSI_TRUNC_W_D, tmp, tmp); -#endif - dest = tmp; - t.irt = IRT_NUM; /* Check for original type. */ - } else { - Reg tmp = ra_scratch(as, RSET_GPR); -#if LJ_SOFTFP - ra_evictset(as, rset_exclude(RSET_SCRATCH, dest)); - ra_destreg(as, ir, RID_RET); - emit_call(as, (void *)lj_ir_callinfo[IRCALL_softfp_i2d].func, 0); - emit_dta(as, MIPSI_SLL, REGARG_FIRSTGPR, tmp, 0); -#else - emit_fg(as, MIPSI_CVT_D_W, dest, dest); - emit_tg(as, MIPSI_MTC1, tmp, dest); -#endif - dest = tmp; - t.irt = IRT_INT; /* Check for original type. */ - } - } -#if LJ_64 - else if (irt_isaddr(t)) { - /* Clear type from pointers. */ - emit_tsml(as, MIPSI_DEXTM, dest, dest, 14, 0); - } else if (irt_isint(t) && (ir->op2 & IRSLOAD_TYPECHECK)) { - /* Sign-extend integers. */ - emit_dta(as, MIPSI_SLL, dest, dest, 0); - } -#endif - goto dotypecheck; - } - base = ra_alloc1(as, REF_BASE, allow); - rset_clear(allow, base); -dotypecheck: -#if LJ_32 - if ((ir->op2 & IRSLOAD_TYPECHECK)) { - if (ra_noreg(type)) - type = RID_TMP; - if (irt_isnum(t)) { - asm_guard(as, MIPSI_BEQ, RID_TMP, RID_ZERO); - emit_tsi(as, MIPSI_SLTIU, RID_TMP, type, (int32_t)LJ_TISNUM); - } else { - Reg ktype = ra_allock(as, (ir->op2 & IRSLOAD_KEYINDEX) ? LJ_KEYINDEX : irt_toitype(t), allow); - asm_guard(as, MIPSI_BNE, type, ktype); - } - } - if (ra_hasreg(dest)) { - if (!LJ_SOFTFP && irt_isnum(t)) - emit_hsi(as, MIPSI_LDC1, dest, base, ofs); - else - emit_tsi(as, MIPSI_LW, dest, base, ofs ^ (LJ_BE?4:0)); - } - if (ra_hasreg(type)) - emit_tsi(as, MIPSI_LW, type, base, ofs ^ (LJ_BE?0:4)); -#else - if ((ir->op2 & IRSLOAD_TYPECHECK)) { - type = dest < RID_MAX_GPR ? dest : RID_TMP; - if (irt_ispri(t)) { - asm_guard(as, MIPSI_BNE, type, - ra_allock(as, ~((int64_t)~irt_toitype(t) << 47) , allow)); - } else if ((ir->op2 & IRSLOAD_KEYINDEX)) { - asm_guard(as, MIPSI_BNE, RID_TMP, - ra_allock(as, (int32_t)LJ_KEYINDEX, allow)); - emit_dta(as, MIPSI_DSRA32, RID_TMP, type, 0); - } else { - if (irt_isnum(t)) { - asm_guard(as, MIPSI_BEQ, RID_TMP, RID_ZERO); - emit_tsi(as, MIPSI_SLTIU, RID_TMP, RID_TMP, (int32_t)LJ_TISNUM); - if (!LJ_SOFTFP && ra_hasreg(dest)) - emit_hsi(as, MIPSI_LDC1, dest, base, ofs); - } else { - asm_guard(as, MIPSI_BNE, RID_TMP, - ra_allock(as, (int32_t)irt_toitype(t), allow)); - } - emit_dta(as, MIPSI_DSRA32, RID_TMP, type, 15); - } - emit_tsi(as, MIPSI_LD, type, base, ofs); - } else if (ra_hasreg(dest)) { - if (!LJ_SOFTFP && irt_isnum(t)) - emit_hsi(as, MIPSI_LDC1, dest, base, ofs); - else - emit_tsi(as, irt_isint(t) ? MIPSI_LW : MIPSI_LD, dest, base, - ofs ^ ((LJ_BE && irt_isint(t)) ? 4 : 0)); - } -#endif -} - -/* -- Allocations --------------------------------------------------------- */ - -#if LJ_HASFFI -static void asm_cnew(ASMState *as, IRIns *ir) -{ - CTState *cts = ctype_ctsG(J2G(as->J)); - CTypeID id = (CTypeID)IR(ir->op1)->i; - CTSize sz; - CTInfo info = lj_ctype_info(cts, id, &sz); - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_mem_newgco]; - IRRef args[4]; - RegSet drop = RSET_SCRATCH; - lj_assertA(sz != CTSIZE_INVALID || (ir->o == IR_CNEW && ir->op2 != REF_NIL), - "bad CNEW/CNEWI operands"); - - as->gcsteps++; - if (ra_hasreg(ir->r)) - rset_clear(drop, ir->r); /* Dest reg handled below. */ - ra_evictset(as, drop); - if (ra_used(ir)) - ra_destreg(as, ir, RID_RET); /* GCcdata * */ - - /* Initialize immutable cdata object. */ - if (ir->o == IR_CNEWI) { - RegSet allow = (RSET_GPR & ~RSET_SCRATCH); -#if LJ_32 - int32_t ofs = sizeof(GCcdata); - if (sz == 8) { - ofs += 4; - lj_assertA((ir+1)->o == IR_HIOP, "expected HIOP for CNEWI"); - if (LJ_LE) ir++; - } - for (;;) { - Reg r = ra_alloc1z(as, ir->op2, allow); - emit_tsi(as, MIPSI_SW, r, RID_RET, ofs); - rset_clear(allow, r); - if (ofs == sizeof(GCcdata)) break; - ofs -= 4; if (LJ_BE) ir++; else ir--; - } -#else - emit_tsi(as, sz == 8 ? MIPSI_SD : MIPSI_SW, ra_alloc1(as, ir->op2, allow), - RID_RET, sizeof(GCcdata)); -#endif - lj_assertA(sz == 4 || sz == 8, "bad CNEWI size %d", sz); - } else if (ir->op2 != REF_NIL) { /* Create VLA/VLS/aligned cdata. */ - ci = &lj_ir_callinfo[IRCALL_lj_cdata_newv]; - args[0] = ASMREF_L; /* lua_State *L */ - args[1] = ir->op1; /* CTypeID id */ - args[2] = ir->op2; /* CTSize sz */ - args[3] = ASMREF_TMP1; /* CTSize align */ - asm_gencall(as, ci, args); - emit_loadi(as, ra_releasetmp(as, ASMREF_TMP1), (int32_t)ctype_align(info)); - return; - } - - /* Initialize gct and ctypeid. lj_mem_newgco() already sets marked. */ - emit_tsi(as, MIPSI_SB, RID_RET+1, RID_RET, offsetof(GCcdata, gct)); - emit_tsi(as, MIPSI_SH, RID_TMP, RID_RET, offsetof(GCcdata, ctypeid)); - emit_ti(as, MIPSI_LI, RID_RET+1, ~LJ_TCDATA); - emit_ti(as, MIPSI_LI, RID_TMP, id); /* Lower 16 bit used. Sign-ext ok. */ - args[0] = ASMREF_L; /* lua_State *L */ - args[1] = ASMREF_TMP1; /* MSize size */ - asm_gencall(as, ci, args); - ra_allockreg(as, (int32_t)(sz+sizeof(GCcdata)), - ra_releasetmp(as, ASMREF_TMP1)); -} -#endif - -/* -- Write barriers ------------------------------------------------------ */ - -static void asm_tbar(ASMState *as, IRIns *ir) -{ - Reg tab = ra_alloc1(as, ir->op1, RSET_GPR); - Reg mark = ra_scratch(as, rset_exclude(RSET_GPR, tab)); - Reg link = RID_TMP; - MCLabel l_end = emit_label(as); - emit_tsi(as, MIPSI_AS, link, tab, (int32_t)offsetof(GCtab, gclist)); - emit_tsi(as, MIPSI_SB, mark, tab, (int32_t)offsetof(GCtab, marked)); - emit_setgl(as, tab, gc.grayagain); - emit_getgl(as, link, gc.grayagain); - emit_dst(as, MIPSI_XOR, mark, mark, RID_TMP); /* Clear black bit. */ - emit_branch(as, MIPSI_BEQ, RID_TMP, RID_ZERO, l_end); - emit_tsi(as, MIPSI_ANDI, RID_TMP, mark, LJ_GC_BLACK); - emit_tsi(as, MIPSI_LBU, mark, tab, (int32_t)offsetof(GCtab, marked)); -} - -static void asm_obar(ASMState *as, IRIns *ir) -{ - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_barrieruv]; - IRRef args[2]; - MCLabel l_end; - Reg obj, val, tmp; - /* No need for other object barriers (yet). */ - lj_assertA(IR(ir->op1)->o == IR_UREFC, "bad OBAR type"); - ra_evictset(as, RSET_SCRATCH); - l_end = emit_label(as); - args[0] = ASMREF_TMP1; /* global_State *g */ - args[1] = ir->op1; /* TValue *tv */ - asm_gencall(as, ci, args); - emit_tsi(as, MIPSI_AADDIU, ra_releasetmp(as, ASMREF_TMP1), RID_JGL, -32768); - obj = IR(ir->op1)->r; - tmp = ra_scratch(as, rset_exclude(RSET_GPR, obj)); - emit_branch(as, MIPSI_BEQ, RID_TMP, RID_ZERO, l_end); - emit_tsi(as, MIPSI_ANDI, tmp, tmp, LJ_GC_BLACK); - emit_branch(as, MIPSI_BEQ, RID_TMP, RID_ZERO, l_end); - emit_tsi(as, MIPSI_ANDI, RID_TMP, RID_TMP, LJ_GC_WHITES); - val = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, obj)); - emit_tsi(as, MIPSI_LBU, tmp, obj, - (int32_t)offsetof(GCupval, marked)-(int32_t)offsetof(GCupval, tv)); - emit_tsi(as, MIPSI_LBU, RID_TMP, val, (int32_t)offsetof(GChead, marked)); -} - -/* -- Arithmetic and logic operations ------------------------------------- */ - -#if !LJ_SOFTFP -static void asm_fparith(ASMState *as, IRIns *ir, MIPSIns mi) -{ - Reg dest = ra_dest(as, ir, RSET_FPR); - Reg right, left = ra_alloc2(as, ir, RSET_FPR); - right = (left >> 8); left &= 255; - emit_fgh(as, mi, dest, left, right); -} - -static void asm_fpunary(ASMState *as, IRIns *ir, MIPSIns mi) -{ - Reg dest = ra_dest(as, ir, RSET_FPR); - Reg left = ra_hintalloc(as, ir->op1, dest, RSET_FPR); - emit_fg(as, mi, dest, left); -} -#endif - -#if !LJ_SOFTFP32 -static void asm_fpmath(ASMState *as, IRIns *ir) -{ -#if !LJ_SOFTFP - if (ir->op2 <= IRFPM_TRUNC) - asm_callround(as, ir, IRCALL_lj_vm_floor + ir->op2); - else if (ir->op2 == IRFPM_SQRT) - asm_fpunary(as, ir, MIPSI_SQRT_D); - else -#endif - asm_callid(as, ir, IRCALL_lj_vm_floor + ir->op2); -} -#endif - -#if !LJ_SOFTFP -#define asm_fpadd(as, ir) asm_fparith(as, ir, MIPSI_ADD_D) -#define asm_fpsub(as, ir) asm_fparith(as, ir, MIPSI_SUB_D) -#define asm_fpmul(as, ir) asm_fparith(as, ir, MIPSI_MUL_D) -#elif LJ_64 /* && LJ_SOFTFP */ -#define asm_fpadd(as, ir) asm_callid(as, ir, IRCALL_softfp_add) -#define asm_fpsub(as, ir) asm_callid(as, ir, IRCALL_softfp_sub) -#define asm_fpmul(as, ir) asm_callid(as, ir, IRCALL_softfp_mul) -#endif - -static void asm_add(ASMState *as, IRIns *ir) -{ - IRType1 t = ir->t; -#if !LJ_SOFTFP32 - if (irt_isnum(t)) { - asm_fpadd(as, ir); - } else -#endif - { - /* TODO MIPSR6: Fuse ADD(BSHL(a,1-4),b) or ADD(ADD(a,a),b) to MIPSI_ALSA. */ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg right, left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); - if (irref_isk(ir->op2)) { - intptr_t k = get_kval(as, ir->op2); - if (checki16(k)) { - emit_tsi(as, (LJ_64 && irt_is64(t)) ? MIPSI_DADDIU : MIPSI_ADDIU, dest, - left, k); - return; - } - } - right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); - emit_dst(as, (LJ_64 && irt_is64(t)) ? MIPSI_DADDU : MIPSI_ADDU, dest, - left, right); - } -} - -static void asm_sub(ASMState *as, IRIns *ir) -{ -#if !LJ_SOFTFP32 - if (irt_isnum(ir->t)) { - asm_fpsub(as, ir); - } else -#endif - { - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg right, left = ra_alloc2(as, ir, RSET_GPR); - right = (left >> 8); left &= 255; - emit_dst(as, (LJ_64 && irt_is64(ir->t)) ? MIPSI_DSUBU : MIPSI_SUBU, dest, - left, right); - } -} - -static void asm_mul(ASMState *as, IRIns *ir) -{ -#if !LJ_SOFTFP32 - if (irt_isnum(ir->t)) { - asm_fpmul(as, ir); - } else -#endif - { - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg right, left = ra_alloc2(as, ir, RSET_GPR); - right = (left >> 8); left &= 255; - if (LJ_64 && irt_is64(ir->t)) { -#if !LJ_TARGET_MIPSR6 - emit_dst(as, MIPSI_MFLO, dest, 0, 0); - emit_dst(as, MIPSI_DMULT, 0, left, right); -#else - emit_dst(as, MIPSI_DMUL, dest, left, right); -#endif - } else { - emit_dst(as, MIPSI_MUL, dest, left, right); - } - } -} - -#if !LJ_SOFTFP32 -static void asm_fpdiv(ASMState *as, IRIns *ir) -{ -#if !LJ_SOFTFP - asm_fparith(as, ir, MIPSI_DIV_D); -#else - asm_callid(as, ir, IRCALL_softfp_div); -#endif -} -#endif - -static void asm_neg(ASMState *as, IRIns *ir) -{ -#if !LJ_SOFTFP - if (irt_isnum(ir->t)) { - asm_fpunary(as, ir, MIPSI_NEG_D); - } else -#elif LJ_64 /* && LJ_SOFTFP */ - if (irt_isnum(ir->t)) { - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); - emit_dst(as, MIPSI_XOR, dest, left, - ra_allock(as, 0x8000000000000000ll, rset_exclude(RSET_GPR, dest))); - } else -#endif - { - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); - emit_dst(as, (LJ_64 && irt_is64(ir->t)) ? MIPSI_DSUBU : MIPSI_SUBU, dest, - RID_ZERO, left); - } -} - -#if !LJ_SOFTFP -#define asm_abs(as, ir) asm_fpunary(as, ir, MIPSI_ABS_D) -#elif LJ_64 /* && LJ_SOFTFP */ -static void asm_abs(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_alloc1(as, ir->op1, RSET_GPR); - emit_tsml(as, MIPSI_DEXTM, dest, left, 30, 0); -} -#endif - -static void asm_arithov(ASMState *as, IRIns *ir) -{ - /* TODO MIPSR6: bovc/bnvc. Caveat: no delay slot to load RID_TMP. */ - Reg right, left, tmp, dest = ra_dest(as, ir, RSET_GPR); - lj_assertA(!irt_is64(ir->t), "bad usage"); - if (irref_isk(ir->op2)) { - int k = IR(ir->op2)->i; - if (ir->o == IR_SUBOV) k = (int)(~(unsigned int)k+1u); - if (checki16(k)) { /* (dest < left) == (k >= 0 ? 1 : 0) */ - left = ra_alloc1(as, ir->op1, RSET_GPR); - asm_guard(as, k >= 0 ? MIPSI_BNE : MIPSI_BEQ, RID_TMP, RID_ZERO); - emit_dst(as, MIPSI_SLT, RID_TMP, dest, dest == left ? RID_TMP : left); - emit_tsi(as, MIPSI_ADDIU, dest, left, k); - if (dest == left) emit_move(as, RID_TMP, left); - return; - } - } - left = ra_alloc2(as, ir, RSET_GPR); - right = (left >> 8); left &= 255; - tmp = ra_scratch(as, rset_exclude(rset_exclude(rset_exclude(RSET_GPR, left), - right), dest)); - asm_guard(as, MIPSI_BLTZ, RID_TMP, 0); - emit_dst(as, MIPSI_AND, RID_TMP, RID_TMP, tmp); - if (ir->o == IR_ADDOV) { /* ((dest^left) & (dest^right)) < 0 */ - emit_dst(as, MIPSI_XOR, RID_TMP, dest, dest == right ? RID_TMP : right); - } else { /* ((dest^left) & (dest^~right)) < 0 */ - emit_dst(as, MIPSI_XOR, RID_TMP, RID_TMP, dest); - emit_dst(as, MIPSI_NOR, RID_TMP, dest == right ? RID_TMP : right, RID_ZERO); - } - emit_dst(as, MIPSI_XOR, tmp, dest, dest == left ? RID_TMP : left); - emit_dst(as, ir->o == IR_ADDOV ? MIPSI_ADDU : MIPSI_SUBU, dest, left, right); - if (dest == left || dest == right) - emit_move(as, RID_TMP, dest == left ? left : right); -} - -#define asm_addov(as, ir) asm_arithov(as, ir) -#define asm_subov(as, ir) asm_arithov(as, ir) - -static void asm_mulov(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg tmp, right, left = ra_alloc2(as, ir, RSET_GPR); - right = (left >> 8); left &= 255; - tmp = ra_scratch(as, rset_exclude(rset_exclude(rset_exclude(RSET_GPR, left), - right), dest)); - asm_guard(as, MIPSI_BNE, RID_TMP, tmp); - emit_dta(as, MIPSI_SRA, RID_TMP, dest, 31); -#if !LJ_TARGET_MIPSR6 - emit_dst(as, MIPSI_MFHI, tmp, 0, 0); - emit_dst(as, MIPSI_MFLO, dest, 0, 0); - emit_dst(as, MIPSI_MULT, 0, left, right); -#else - emit_dst(as, MIPSI_MUL, dest, left, right); - emit_dst(as, MIPSI_MUH, tmp, left, right); -#endif -} - -#if LJ_32 && LJ_HASFFI -static void asm_add64(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg right, left = ra_alloc1(as, ir->op1, RSET_GPR); - if (irref_isk(ir->op2)) { - int32_t k = IR(ir->op2)->i; - if (k == 0) { - emit_dst(as, MIPSI_ADDU, dest, left, RID_TMP); - goto loarith; - } else if (checki16(k)) { - emit_dst(as, MIPSI_ADDU, dest, dest, RID_TMP); - emit_tsi(as, MIPSI_ADDIU, dest, left, k); - goto loarith; - } - } - emit_dst(as, MIPSI_ADDU, dest, dest, RID_TMP); - right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); - emit_dst(as, MIPSI_ADDU, dest, left, right); -loarith: - ir--; - dest = ra_dest(as, ir, RSET_GPR); - left = ra_alloc1(as, ir->op1, RSET_GPR); - if (irref_isk(ir->op2)) { - int32_t k = IR(ir->op2)->i; - if (k == 0) { - if (dest != left) - emit_move(as, dest, left); - return; - } else if (checki16(k)) { - if (dest == left) { - Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, left)); - emit_move(as, dest, tmp); - dest = tmp; - } - emit_dst(as, MIPSI_SLTU, RID_TMP, dest, left); - emit_tsi(as, MIPSI_ADDIU, dest, left, k); - return; - } - } - right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); - if (dest == left && dest == right) { - Reg tmp = ra_scratch(as, rset_exclude(rset_exclude(RSET_GPR, left), right)); - emit_move(as, dest, tmp); - dest = tmp; - } - emit_dst(as, MIPSI_SLTU, RID_TMP, dest, dest == left ? right : left); - emit_dst(as, MIPSI_ADDU, dest, left, right); -} - -static void asm_sub64(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg right, left = ra_alloc2(as, ir, RSET_GPR); - right = (left >> 8); left &= 255; - emit_dst(as, MIPSI_SUBU, dest, dest, RID_TMP); - emit_dst(as, MIPSI_SUBU, dest, left, right); - ir--; - dest = ra_dest(as, ir, RSET_GPR); - left = ra_alloc2(as, ir, RSET_GPR); - right = (left >> 8); left &= 255; - if (dest == left) { - Reg tmp = ra_scratch(as, rset_exclude(rset_exclude(RSET_GPR, left), right)); - emit_move(as, dest, tmp); - dest = tmp; - } - emit_dst(as, MIPSI_SLTU, RID_TMP, left, dest); - emit_dst(as, MIPSI_SUBU, dest, left, right); -} - -static void asm_neg64(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_alloc1(as, ir->op1, RSET_GPR); - emit_dst(as, MIPSI_SUBU, dest, dest, RID_TMP); - emit_dst(as, MIPSI_SUBU, dest, RID_ZERO, left); - ir--; - dest = ra_dest(as, ir, RSET_GPR); - left = ra_alloc1(as, ir->op1, RSET_GPR); - emit_dst(as, MIPSI_SLTU, RID_TMP, RID_ZERO, dest); - emit_dst(as, MIPSI_SUBU, dest, RID_ZERO, left); -} -#endif - -static void asm_bnot(ASMState *as, IRIns *ir) -{ - Reg left, right, dest = ra_dest(as, ir, RSET_GPR); - IRIns *irl = IR(ir->op1); - if (mayfuse(as, ir->op1) && irl->o == IR_BOR) { - left = ra_alloc2(as, irl, RSET_GPR); - right = (left >> 8); left &= 255; - } else { - left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); - right = RID_ZERO; - } - emit_dst(as, MIPSI_NOR, dest, left, right); -} - -static void asm_bswap(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_alloc1(as, ir->op1, RSET_GPR); -#if LJ_32 - if ((as->flags & JIT_F_MIPSXXR2)) { - emit_dta(as, MIPSI_ROTR, dest, RID_TMP, 16); - emit_dst(as, MIPSI_WSBH, RID_TMP, 0, left); - } else { - Reg tmp = ra_scratch(as, rset_exclude(rset_exclude(RSET_GPR, left), dest)); - emit_dst(as, MIPSI_OR, dest, dest, tmp); - emit_dst(as, MIPSI_OR, dest, dest, RID_TMP); - emit_tsi(as, MIPSI_ANDI, dest, dest, 0xff00); - emit_dta(as, MIPSI_SLL, RID_TMP, RID_TMP, 8); - emit_dta(as, MIPSI_SRL, dest, left, 8); - emit_tsi(as, MIPSI_ANDI, RID_TMP, left, 0xff00); - emit_dst(as, MIPSI_OR, tmp, tmp, RID_TMP); - emit_dta(as, MIPSI_SRL, tmp, left, 24); - emit_dta(as, MIPSI_SLL, RID_TMP, left, 24); - } -#else - if (irt_is64(ir->t)) { - emit_dst(as, MIPSI_DSHD, dest, 0, RID_TMP); - emit_dst(as, MIPSI_DSBH, RID_TMP, 0, left); - } else { - emit_dta(as, MIPSI_ROTR, dest, RID_TMP, 16); - emit_dst(as, MIPSI_WSBH, RID_TMP, 0, left); - } -#endif -} - -static void asm_bitop(ASMState *as, IRIns *ir, MIPSIns mi, MIPSIns mik) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg right, left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); - if (irref_isk(ir->op2)) { - intptr_t k = get_kval(as, ir->op2); - if (checku16(k)) { - emit_tsi(as, mik, dest, left, k); - return; - } - } - right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); - emit_dst(as, mi, dest, left, right); -} - -#define asm_band(as, ir) asm_bitop(as, ir, MIPSI_AND, MIPSI_ANDI) -#define asm_bor(as, ir) asm_bitop(as, ir, MIPSI_OR, MIPSI_ORI) -#define asm_bxor(as, ir) asm_bitop(as, ir, MIPSI_XOR, MIPSI_XORI) - -static void asm_bitshift(ASMState *as, IRIns *ir, MIPSIns mi, MIPSIns mik) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - if (irref_isk(ir->op2)) { /* Constant shifts. */ - uint32_t shift = (uint32_t)IR(ir->op2)->i; - if (LJ_64 && irt_is64(ir->t)) mik |= (shift & 32) ? MIPSI_D32 : MIPSI_D; - emit_dta(as, mik, dest, ra_hintalloc(as, ir->op1, dest, RSET_GPR), - (shift & 31)); - } else { - Reg right, left = ra_alloc2(as, ir, RSET_GPR); - right = (left >> 8); left &= 255; - if (LJ_64 && irt_is64(ir->t)) mi |= MIPSI_DV; - emit_dst(as, mi, dest, right, left); /* Shift amount is in rs. */ - } -} - -#define asm_bshl(as, ir) asm_bitshift(as, ir, MIPSI_SLLV, MIPSI_SLL) -#define asm_bshr(as, ir) asm_bitshift(as, ir, MIPSI_SRLV, MIPSI_SRL) -#define asm_bsar(as, ir) asm_bitshift(as, ir, MIPSI_SRAV, MIPSI_SRA) -#define asm_brol(as, ir) lj_assertA(0, "unexpected BROL") - -static void asm_bror(ASMState *as, IRIns *ir) -{ - if (LJ_64 || (as->flags & JIT_F_MIPSXXR2)) { - asm_bitshift(as, ir, MIPSI_ROTRV, MIPSI_ROTR); - } else { - Reg dest = ra_dest(as, ir, RSET_GPR); - if (irref_isk(ir->op2)) { /* Constant shifts. */ - uint32_t shift = (uint32_t)(IR(ir->op2)->i & 31); - Reg left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); - emit_rotr(as, dest, left, RID_TMP, shift); - } else { - Reg right, left = ra_alloc2(as, ir, RSET_GPR); - right = (left >> 8); left &= 255; - emit_dst(as, MIPSI_OR, dest, dest, RID_TMP); - emit_dst(as, MIPSI_SRLV, dest, right, left); - emit_dst(as, MIPSI_SLLV, RID_TMP, RID_TMP, left); - emit_dst(as, MIPSI_SUBU, RID_TMP, ra_allock(as, 32, RSET_GPR), right); - } - } -} - -#if LJ_SOFTFP -static void asm_sfpmin_max(ASMState *as, IRIns *ir) -{ - CCallInfo ci = lj_ir_callinfo[(IROp)ir->o == IR_MIN ? IRCALL_lj_vm_sfmin : IRCALL_lj_vm_sfmax]; -#if LJ_64 - IRRef args[2]; - args[0] = ir->op1; - args[1] = ir->op2; -#else - IRRef args[4]; - args[0^LJ_BE] = ir->op1; - args[1^LJ_BE] = (ir+1)->op1; - args[2^LJ_BE] = ir->op2; - args[3^LJ_BE] = (ir+1)->op2; -#endif - asm_setupresult(as, ir, &ci); - emit_call(as, (void *)ci.func, 0); - ci.func = NULL; - asm_gencall(as, &ci, args); -} -#endif - -static void asm_min_max(ASMState *as, IRIns *ir, int ismax) -{ - if (!LJ_SOFTFP32 && irt_isnum(ir->t)) { -#if LJ_SOFTFP - asm_sfpmin_max(as, ir); -#else - Reg dest = ra_dest(as, ir, RSET_FPR); - Reg right, left = ra_alloc2(as, ir, RSET_FPR); - right = (left >> 8); left &= 255; -#if !LJ_TARGET_MIPSR6 - if (dest == left) { - emit_fg(as, MIPSI_MOVF_D, dest, right); - } else { - emit_fg(as, MIPSI_MOVT_D, dest, left); - if (dest != right) emit_fg(as, MIPSI_MOV_D, dest, right); - } - emit_fgh(as, MIPSI_C_OLT_D, 0, ismax ? right : left, ismax ? left : right); -#else - emit_fgh(as, ismax ? MIPSI_MAX_D : MIPSI_MIN_D, dest, left, right); -#endif -#endif - } else { - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg right, left = ra_alloc2(as, ir, RSET_GPR); - right = (left >> 8); left &= 255; - if (left == right) { - if (dest != left) emit_move(as, dest, left); - } else { -#if !LJ_TARGET_MIPSR6 - if (dest == left) { - emit_dst(as, MIPSI_MOVN, dest, right, RID_TMP); - } else { - emit_dst(as, MIPSI_MOVZ, dest, left, RID_TMP); - if (dest != right) emit_move(as, dest, right); - } -#else - emit_dst(as, MIPSI_OR, dest, dest, RID_TMP); - if (dest != right) { - emit_dst(as, MIPSI_SELNEZ, RID_TMP, right, RID_TMP); - emit_dst(as, MIPSI_SELEQZ, dest, left, RID_TMP); - } else { - emit_dst(as, MIPSI_SELEQZ, RID_TMP, left, RID_TMP); - emit_dst(as, MIPSI_SELNEZ, dest, right, RID_TMP); - } -#endif - emit_dst(as, MIPSI_SLT, RID_TMP, - ismax ? left : right, ismax ? right : left); - } - } -} - -#define asm_min(as, ir) asm_min_max(as, ir, 0) -#define asm_max(as, ir) asm_min_max(as, ir, 1) - -/* -- Comparisons --------------------------------------------------------- */ - -#if LJ_SOFTFP -/* SFP comparisons. */ -static void asm_sfpcomp(ASMState *as, IRIns *ir) -{ - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_softfp_cmp]; - RegSet drop = RSET_SCRATCH; - Reg r; -#if LJ_64 - IRRef args[2]; - args[0] = ir->op1; - args[1] = ir->op2; -#else - IRRef args[4]; - args[LJ_LE ? 0 : 1] = ir->op1; args[LJ_LE ? 1 : 0] = (ir+1)->op1; - args[LJ_LE ? 2 : 3] = ir->op2; args[LJ_LE ? 3 : 2] = (ir+1)->op2; -#endif - - for (r = REGARG_FIRSTGPR; r <= REGARG_FIRSTGPR+(LJ_64?1:3); r++) { - if (!rset_test(as->freeset, r) && - regcost_ref(as->cost[r]) == args[r-REGARG_FIRSTGPR]) - rset_clear(drop, r); - } - ra_evictset(as, drop); - - asm_setupresult(as, ir, ci); - - switch ((IROp)ir->o) { - case IR_LT: - asm_guard(as, MIPSI_BGEZ, RID_RET, 0); - break; - case IR_ULT: - asm_guard(as, MIPSI_BEQ, RID_RET, RID_TMP); - emit_loadi(as, RID_TMP, 1); - asm_guard(as, MIPSI_BEQ, RID_RET, RID_ZERO); - break; - case IR_GE: - asm_guard(as, MIPSI_BEQ, RID_RET, RID_TMP); - emit_loadi(as, RID_TMP, 2); - asm_guard(as, MIPSI_BLTZ, RID_RET, 0); - break; - case IR_LE: - asm_guard(as, MIPSI_BGTZ, RID_RET, 0); - break; - case IR_GT: - asm_guard(as, MIPSI_BEQ, RID_RET, RID_TMP); - emit_loadi(as, RID_TMP, 2); - asm_guard(as, MIPSI_BLEZ, RID_RET, 0); - break; - case IR_UGE: - asm_guard(as, MIPSI_BLTZ, RID_RET, 0); - break; - case IR_ULE: - asm_guard(as, MIPSI_BEQ, RID_RET, RID_TMP); - emit_loadi(as, RID_TMP, 1); - break; - case IR_UGT: case IR_ABC: - asm_guard(as, MIPSI_BLEZ, RID_RET, 0); - break; - case IR_EQ: case IR_NE: - asm_guard(as, (ir->o & 1) ? MIPSI_BEQ : MIPSI_BNE, RID_RET, RID_ZERO); - default: - break; - } - asm_gencall(as, ci, args); -} -#endif - -static void asm_comp(ASMState *as, IRIns *ir) -{ - /* ORDER IR: LT GE LE GT ULT UGE ULE UGT. */ - IROp op = ir->o; - if (!LJ_SOFTFP32 && irt_isnum(ir->t)) { -#if LJ_SOFTFP - asm_sfpcomp(as, ir); -#else -#if !LJ_TARGET_MIPSR6 - Reg right, left = ra_alloc2(as, ir, RSET_FPR); - right = (left >> 8); left &= 255; - asm_guard(as, (op&1) ? MIPSI_BC1T : MIPSI_BC1F, 0, 0); - emit_fgh(as, MIPSI_C_OLT_D + ((op&3) ^ ((op>>2)&1)), 0, left, right); -#else - Reg tmp, right, left = ra_alloc2(as, ir, RSET_FPR); - right = (left >> 8); left &= 255; - tmp = ra_scratch(as, rset_exclude(rset_exclude(RSET_FPR, left), right)); - asm_guard(as, (op&1) ? MIPSI_BC1NEZ : MIPSI_BC1EQZ, 0, (tmp&31)); - emit_fgh(as, MIPSI_CMP_LT_D + ((op&3) ^ ((op>>2)&1)), tmp, left, right); -#endif -#endif - } else { - Reg right, left = ra_alloc1(as, ir->op1, RSET_GPR); - if (op == IR_ABC) op = IR_UGT; - if ((op&4) == 0 && irref_isk(ir->op2) && get_kval(as, ir->op2) == 0) { - MIPSIns mi = (op&2) ? ((op&1) ? MIPSI_BLEZ : MIPSI_BGTZ) : - ((op&1) ? MIPSI_BLTZ : MIPSI_BGEZ); - asm_guard(as, mi, left, 0); - } else { - if (irref_isk(ir->op2)) { - intptr_t k = get_kval(as, ir->op2); - if ((op&2)) k++; - if (checki16(k)) { - asm_guard(as, (op&1) ? MIPSI_BNE : MIPSI_BEQ, RID_TMP, RID_ZERO); - emit_tsi(as, (op&4) ? MIPSI_SLTIU : MIPSI_SLTI, - RID_TMP, left, k); - return; - } - } - right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); - asm_guard(as, ((op^(op>>1))&1) ? MIPSI_BNE : MIPSI_BEQ, RID_TMP, RID_ZERO); - emit_dst(as, (op&4) ? MIPSI_SLTU : MIPSI_SLT, - RID_TMP, (op&2) ? right : left, (op&2) ? left : right); - } - } -} - -static void asm_equal(ASMState *as, IRIns *ir) -{ - Reg right, left = ra_alloc2(as, ir, (!LJ_SOFTFP && irt_isnum(ir->t)) ? - RSET_FPR : RSET_GPR); - right = (left >> 8); left &= 255; - if (!LJ_SOFTFP32 && irt_isnum(ir->t)) { -#if LJ_SOFTFP - asm_sfpcomp(as, ir); -#elif !LJ_TARGET_MIPSR6 - asm_guard(as, (ir->o & 1) ? MIPSI_BC1T : MIPSI_BC1F, 0, 0); - emit_fgh(as, MIPSI_C_EQ_D, 0, left, right); -#else - Reg tmp = ra_scratch(as, rset_exclude(rset_exclude(RSET_FPR, left), right)); - asm_guard(as, (ir->o & 1) ? MIPSI_BC1NEZ : MIPSI_BC1EQZ, 0, (tmp&31)); - emit_fgh(as, MIPSI_CMP_EQ_D, tmp, left, right); -#endif - } else { - asm_guard(as, (ir->o & 1) ? MIPSI_BEQ : MIPSI_BNE, left, right); - } -} - -#if LJ_32 && LJ_HASFFI -/* 64 bit integer comparisons. */ -static void asm_comp64(ASMState *as, IRIns *ir) -{ - /* ORDER IR: LT GE LE GT ULT UGE ULE UGT. */ - IROp op = (ir-1)->o; - MCLabel l_end; - Reg rightlo, leftlo, righthi, lefthi = ra_alloc2(as, ir, RSET_GPR); - righthi = (lefthi >> 8); lefthi &= 255; - leftlo = ra_alloc2(as, ir-1, - rset_exclude(rset_exclude(RSET_GPR, lefthi), righthi)); - rightlo = (leftlo >> 8); leftlo &= 255; - asm_guard(as, ((op^(op>>1))&1) ? MIPSI_BNE : MIPSI_BEQ, RID_TMP, RID_ZERO); - l_end = emit_label(as); - if (lefthi != righthi) - emit_dst(as, (op&4) ? MIPSI_SLTU : MIPSI_SLT, RID_TMP, - (op&2) ? righthi : lefthi, (op&2) ? lefthi : righthi); - emit_dst(as, MIPSI_SLTU, RID_TMP, - (op&2) ? rightlo : leftlo, (op&2) ? leftlo : rightlo); - if (lefthi != righthi) - emit_branch(as, MIPSI_BEQ, lefthi, righthi, l_end); -} - -static void asm_comp64eq(ASMState *as, IRIns *ir) -{ - Reg tmp, right, left = ra_alloc2(as, ir, RSET_GPR); - right = (left >> 8); left &= 255; - asm_guard(as, ((ir-1)->o & 1) ? MIPSI_BEQ : MIPSI_BNE, RID_TMP, RID_ZERO); - tmp = ra_scratch(as, rset_exclude(rset_exclude(RSET_GPR, left), right)); - emit_dst(as, MIPSI_OR, RID_TMP, RID_TMP, tmp); - emit_dst(as, MIPSI_XOR, tmp, left, right); - left = ra_alloc2(as, ir-1, RSET_GPR); - right = (left >> 8); left &= 255; - emit_dst(as, MIPSI_XOR, RID_TMP, left, right); -} -#endif - -/* -- Split register ops -------------------------------------------------- */ - -/* Hiword op of a split 32/32 or 64/64 bit op. Previous op is the loword op. */ -static void asm_hiop(ASMState *as, IRIns *ir) -{ - /* HIOP is marked as a store because it needs its own DCE logic. */ - int uselo = ra_used(ir-1), usehi = ra_used(ir); /* Loword/hiword used? */ - if (LJ_UNLIKELY(!(as->flags & JIT_F_OPT_DCE))) uselo = usehi = 1; -#if LJ_32 && (LJ_HASFFI || LJ_SOFTFP) - if ((ir-1)->o == IR_CONV) { /* Conversions to/from 64 bit. */ - as->curins--; /* Always skip the CONV. */ -#if LJ_HASFFI && !LJ_SOFTFP - if (usehi || uselo) - asm_conv64(as, ir); - return; -#endif - } else if ((ir-1)->o < IR_EQ) { /* 64 bit integer comparisons. ORDER IR. */ - as->curins--; /* Always skip the loword comparison. */ -#if LJ_SOFTFP - if (!irt_isint(ir->t)) { - asm_sfpcomp(as, ir-1); - return; - } -#endif -#if LJ_HASFFI - asm_comp64(as, ir); -#endif - return; - } else if ((ir-1)->o <= IR_NE) { /* 64 bit integer comparisons. ORDER IR. */ - as->curins--; /* Always skip the loword comparison. */ -#if LJ_SOFTFP - if (!irt_isint(ir->t)) { - asm_sfpcomp(as, ir-1); - return; - } -#endif -#if LJ_HASFFI - asm_comp64eq(as, ir); -#endif - return; -#if LJ_SOFTFP - } else if ((ir-1)->o == IR_MIN || (ir-1)->o == IR_MAX) { - as->curins--; /* Always skip the loword min/max. */ - if (uselo || usehi) - asm_sfpmin_max(as, ir-1); - return; -#endif - } else if ((ir-1)->o == IR_XSTORE) { - as->curins--; /* Handle both stores here. */ - if ((ir-1)->r != RID_SINK) { - asm_xstore_(as, ir, LJ_LE ? 4 : 0); - asm_xstore_(as, ir-1, LJ_LE ? 0 : 4); - } - return; - } -#endif - if (!usehi) return; /* Skip unused hiword op for all remaining ops. */ - switch ((ir-1)->o) { -#if LJ_32 && LJ_HASFFI - case IR_ADD: as->curins--; asm_add64(as, ir); break; - case IR_SUB: as->curins--; asm_sub64(as, ir); break; - case IR_NEG: as->curins--; asm_neg64(as, ir); break; - case IR_CNEWI: - /* Nothing to do here. Handled by lo op itself. */ - break; -#endif -#if LJ_32 && LJ_SOFTFP - case IR_SLOAD: case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD: - case IR_STRTO: - if (!uselo) - ra_allocref(as, ir->op1, RSET_GPR); /* Mark lo op as used. */ - break; - case IR_ASTORE: case IR_HSTORE: case IR_USTORE: case IR_TOSTR: case IR_TMPREF: - /* Nothing to do here. Handled by lo op itself. */ - break; -#endif - case IR_CALLN: case IR_CALLL: case IR_CALLS: case IR_CALLXS: - if (!uselo) - ra_allocref(as, ir->op1, RID2RSET(RID_RETLO)); /* Mark lo op as used. */ - break; - default: lj_assertA(0, "bad HIOP for op %d", (ir-1)->o); break; - } -} - -/* -- Profiling ----------------------------------------------------------- */ - -static void asm_prof(ASMState *as, IRIns *ir) -{ - UNUSED(ir); - asm_guard(as, MIPSI_BNE, RID_TMP, RID_ZERO); - emit_tsi(as, MIPSI_ANDI, RID_TMP, RID_TMP, HOOK_PROFILE); - emit_lsglptr(as, MIPSI_LBU, RID_TMP, - (int32_t)offsetof(global_State, hookmask)); -} - -/* -- Stack handling ------------------------------------------------------ */ - -/* Check Lua stack size for overflow. Use exit handler as fallback. */ -static void asm_stack_check(ASMState *as, BCReg topslot, - IRIns *irp, RegSet allow, ExitNo exitno) -{ - /* Try to get an unused temp. register, otherwise spill/restore RID_RET*. */ - Reg tmp, pbase = irp ? (ra_hasreg(irp->r) ? irp->r : RID_TMP) : RID_BASE; - ExitNo oldsnap = as->snapno; - rset_clear(allow, pbase); -#if LJ_32 - tmp = allow ? rset_pickbot(allow) : - (pbase == RID_RETHI ? RID_RETLO : RID_RETHI); -#else - tmp = allow ? rset_pickbot(allow) : RID_RET; -#endif - as->snapno = exitno; - asm_guard(as, MIPSI_BNE, RID_TMP, RID_ZERO); - as->snapno = oldsnap; - if (allow == RSET_EMPTY) /* Restore temp. register. */ - emit_tsi(as, MIPSI_AL, tmp, RID_SP, 0); - else - ra_modified(as, tmp); - emit_tsi(as, MIPSI_SLTIU, RID_TMP, RID_TMP, (int32_t)(8*topslot)); - emit_dst(as, MIPSI_ASUBU, RID_TMP, tmp, pbase); - emit_tsi(as, MIPSI_AL, tmp, tmp, offsetof(lua_State, maxstack)); - if (pbase == RID_TMP) - emit_getgl(as, RID_TMP, jit_base); - emit_getgl(as, tmp, cur_L); - if (allow == RSET_EMPTY) /* Spill temp. register. */ - emit_tsi(as, MIPSI_AS, tmp, RID_SP, 0); -} - -/* Restore Lua stack from on-trace state. */ -static void asm_stack_restore(ASMState *as, SnapShot *snap) -{ - SnapEntry *map = &as->T->snapmap[snap->mapofs]; -#if LJ_32 || defined(LUA_USE_ASSERT) - SnapEntry *flinks = &as->T->snapmap[snap_nextofs(as->T, snap)-1-LJ_FR2]; -#endif - MSize n, nent = snap->nent; - /* Store the value of all modified slots to the Lua stack. */ - for (n = 0; n < nent; n++) { - SnapEntry sn = map[n]; - BCReg s = snap_slot(sn); - int32_t ofs = 8*((int32_t)s-1-LJ_FR2); - IRRef ref = snap_ref(sn); - IRIns *ir = IR(ref); - if ((sn & SNAP_NORESTORE)) - continue; - if (irt_isnum(ir->t)) { -#if LJ_SOFTFP32 - Reg tmp; - RegSet allow = rset_exclude(RSET_GPR, RID_BASE); - /* LJ_SOFTFP: must be a number constant. */ - lj_assertA(irref_isk(ref), "unsplit FP op"); - tmp = ra_allock(as, (int32_t)ir_knum(ir)->u32.lo, allow); - emit_tsi(as, MIPSI_SW, tmp, RID_BASE, ofs+(LJ_BE?4:0)); - if (rset_test(as->freeset, tmp+1)) allow = RID2RSET(tmp+1); - tmp = ra_allock(as, (int32_t)ir_knum(ir)->u32.hi, allow); - emit_tsi(as, MIPSI_SW, tmp, RID_BASE, ofs+(LJ_BE?0:4)); -#elif LJ_SOFTFP /* && LJ_64 */ - Reg src = ra_alloc1(as, ref, rset_exclude(RSET_GPR, RID_BASE)); - emit_tsi(as, MIPSI_SD, src, RID_BASE, ofs); -#else - Reg src = ra_alloc1(as, ref, RSET_FPR); - emit_hsi(as, MIPSI_SDC1, src, RID_BASE, ofs); -#endif - } else { -#if LJ_32 - RegSet allow = rset_exclude(RSET_GPR, RID_BASE); - Reg type; - lj_assertA(irt_ispri(ir->t) || irt_isaddr(ir->t) || irt_isinteger(ir->t), - "restore of IR type %d", irt_type(ir->t)); - if (!irt_ispri(ir->t)) { - Reg src = ra_alloc1(as, ref, allow); - rset_clear(allow, src); - emit_tsi(as, MIPSI_SW, src, RID_BASE, ofs+(LJ_BE?4:0)); - } - if ((sn & (SNAP_CONT|SNAP_FRAME))) { - if (s == 0) continue; /* Do not overwrite link to previous frame. */ - type = ra_allock(as, (int32_t)(*flinks--), allow); -#if LJ_SOFTFP - } else if ((sn & SNAP_SOFTFPNUM)) { - type = ra_alloc1(as, ref+1, rset_exclude(RSET_GPR, RID_BASE)); -#endif - } else if ((sn & SNAP_KEYINDEX)) { - type = ra_allock(as, (int32_t)LJ_KEYINDEX, allow); - } else { - type = ra_allock(as, (int32_t)irt_toitype(ir->t), allow); - } - emit_tsi(as, MIPSI_SW, type, RID_BASE, ofs+(LJ_BE?0:4)); -#else - if ((sn & SNAP_KEYINDEX)) { - RegSet allow = rset_exclude(RSET_GPR, RID_BASE); - int64_t kki = (int64_t)LJ_KEYINDEX << 32; - if (irref_isk(ref)) { - emit_tsi(as, MIPSI_SD, - ra_allock(as, kki | (int64_t)(uint32_t)ir->i, allow), - RID_BASE, ofs); - } else { - Reg src = ra_alloc1(as, ref, allow); - Reg rki = ra_allock(as, kki, rset_exclude(allow, src)); - emit_tsi(as, MIPSI_SD, RID_TMP, RID_BASE, ofs); - emit_dst(as, MIPSI_DADDU, RID_TMP, src, rki); - } - } else { - asm_tvstore64(as, RID_BASE, ofs, ref); - } -#endif - } - checkmclim(as); - } - lj_assertA(map + nent == flinks, "inconsistent frames in snapshot"); -} - -/* -- GC handling --------------------------------------------------------- */ - -/* Marker to prevent patching the GC check exit. */ -#define MIPS_NOPATCH_GC_CHECK MIPSI_OR - -/* Check GC threshold and do one or more GC steps. */ -static void asm_gc_check(ASMState *as) -{ - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_step_jit]; - IRRef args[2]; - MCLabel l_end; - Reg tmp; - ra_evictset(as, RSET_SCRATCH); - l_end = emit_label(as); - /* Exit trace if in GCSatomic or GCSfinalize. Avoids syncing GC objects. */ - /* Assumes asm_snap_prep() already done. */ - asm_guard(as, MIPSI_BNE, RID_RET, RID_ZERO); - args[0] = ASMREF_TMP1; /* global_State *g */ - args[1] = ASMREF_TMP2; /* MSize steps */ - asm_gencall(as, ci, args); - l_end[-3] = MIPS_NOPATCH_GC_CHECK; /* Replace the nop after the call. */ - emit_tsi(as, MIPSI_AADDIU, ra_releasetmp(as, ASMREF_TMP1), RID_JGL, -32768); - tmp = ra_releasetmp(as, ASMREF_TMP2); - emit_loadi(as, tmp, as->gcsteps); - /* Jump around GC step if GC total < GC threshold. */ - emit_branch(as, MIPSI_BNE, RID_TMP, RID_ZERO, l_end); - emit_dst(as, MIPSI_SLTU, RID_TMP, RID_TMP, tmp); - emit_getgl(as, tmp, gc.threshold); - emit_getgl(as, RID_TMP, gc.total); - as->gcsteps = 0; - checkmclim(as); -} - -/* -- Loop handling ------------------------------------------------------- */ - -/* Fixup the loop branch. */ -static void asm_loop_fixup(ASMState *as) -{ - MCode *p = as->mctop; - MCode *target = as->mcp; - p[-1] = MIPSI_NOP; - if (as->loopinv) { /* Inverted loop branch? */ - /* asm_guard already inverted the cond branch. Only patch the target. */ - p[-3] |= ((target-p+2) & 0x0000ffffu); - } else { - p[-2] = MIPSI_J|(((uintptr_t)target>>2)&0x03ffffffu); - } -} - -/* Fixup the tail of the loop. */ -static void asm_loop_tail_fixup(ASMState *as) -{ - if (as->loopinv) as->mctop--; -} - -/* -- Head of trace ------------------------------------------------------- */ - -/* Coalesce BASE register for a root trace. */ -static void asm_head_root_base(ASMState *as) -{ - IRIns *ir = IR(REF_BASE); - Reg r = ir->r; - if (ra_hasreg(r)) { - ra_free(as, r); - if (rset_test(as->modset, r) || irt_ismarked(ir->t)) - ir->r = RID_INIT; /* No inheritance for modified BASE register. */ - if (r != RID_BASE) - emit_move(as, r, RID_BASE); - } -} - -/* Coalesce BASE register for a side trace. */ -static Reg asm_head_side_base(ASMState *as, IRIns *irp) -{ - IRIns *ir = IR(REF_BASE); - Reg r = ir->r; - if (ra_hasreg(r)) { - ra_free(as, r); - if (rset_test(as->modset, r) || irt_ismarked(ir->t)) - ir->r = RID_INIT; /* No inheritance for modified BASE register. */ - if (irp->r == r) { - return r; /* Same BASE register already coalesced. */ - } else if (ra_hasreg(irp->r) && rset_test(as->freeset, irp->r)) { - emit_move(as, r, irp->r); /* Move from coalesced parent reg. */ - return irp->r; - } else { - emit_getgl(as, r, jit_base); /* Otherwise reload BASE. */ - } - } - return RID_NONE; -} - -/* -- Tail of trace ------------------------------------------------------- */ - -/* Fixup the tail code. */ -static void asm_tail_fixup(ASMState *as, TraceNo lnk) -{ - uintptr_t target = lnk ? (uintptr_t)traceref(as->J, lnk)->mcode : (uintptr_t)(void *)lj_vm_exit_interp; - MCode *mcp = as->mctail; - int32_t spadj = as->T->spadjust; - if (((uintptr_t)mcp ^ target) >> 28 == 0) { - *mcp++ = MIPSI_J | ((target >> 2) & 0x03ffffffu); - } else { - *mcp++ = MIPSI_AL | MIPSF_T(RID_TMP) | MIPSF_S(RID_JGL) | -#if LJ_64 - jglofs(as, &as->J->k64[LJ_K64_VM_EXIT_INTERP]); -#else - jglofs(as, &as->J->k32[LJ_K32_VM_EXIT_INTERP]); -#endif - *mcp++ = MIPSI_JR | MIPSF_S(RID_TMP); - } - *mcp++ = spadj ? (MIPSI_AADDIU|MIPSF_T(RID_SP)|MIPSF_S(RID_SP)|spadj) : MIPSI_NOP; -} - -/* Prepare tail of code. */ -static void asm_tail_prep(ASMState *as, TraceNo lnk) -{ - as->mcp = as->mctop - 2; /* Leave room for branch plus nop or stack adj. */ - if (as->loopref) { - as->invmcp = as->mcp; - } else { - if (!lnk) { - uintptr_t target = (uintptr_t)(void *)lj_vm_exit_interp; - if (((uintptr_t)as->mcp ^ target) >> 28 != 0) as->mcp--; - } - as->invmcp = NULL; - } - as->mctail = as->mcp; -} - -/* -- Trace setup --------------------------------------------------------- */ - -/* Ensure there are enough stack slots for call arguments. */ -static Reg asm_setup_call_slots(ASMState *as, IRIns *ir, const CCallInfo *ci) -{ - IRRef args[CCI_NARGS_MAX*2]; - uint32_t i, nargs = CCI_XNARGS(ci); -#if LJ_32 - int nslots = 4, ngpr = REGARG_NUMGPR, nfpr = REGARG_NUMFPR; -#else - int nslots = 0, ngpr = REGARG_NUMGPR; -#endif - asm_collectargs(as, ir, ci, args); - for (i = 0; i < nargs; i++) { -#if LJ_32 - if (!LJ_SOFTFP && args[i] && irt_isfp(IR(args[i])->t) && - nfpr > 0 && !(ci->flags & CCI_VARARG)) { - nfpr--; - ngpr -= irt_isnum(IR(args[i])->t) ? 2 : 1; - } else if (!LJ_SOFTFP && args[i] && irt_isnum(IR(args[i])->t)) { - nfpr = 0; - ngpr = ngpr & ~1; - if (ngpr > 0) ngpr -= 2; else nslots = (nslots+3) & ~1; - } else { - nfpr = 0; - if (ngpr > 0) ngpr--; else nslots++; - } -#else - if (ngpr > 0) ngpr--; else nslots += 2; -#endif - } - if (nslots > as->evenspill) /* Leave room for args in stack slots. */ - as->evenspill = nslots; - return irt_isfp(ir->t) ? REGSP_HINT(RID_FPRET) : REGSP_HINT(RID_RET); -} - -static void asm_setup_target(ASMState *as) -{ - asm_sparejump_setup(as); - asm_exitstub_setup(as); -} - -/* -- Trace patching ------------------------------------------------------ */ - -/* Patch exit jumps of existing machine code to a new target. */ -void lj_asm_patchexit(jit_State *J, GCtrace *T, ExitNo exitno, MCode *target) -{ - MCode *p = T->mcode; - MCode *pe = (MCode *)((char *)p + T->szmcode); - MCode *px = exitstub_trace_addr(T, exitno); - MCode *cstart = NULL, *cstop = NULL; - MCode *mcarea = lj_mcode_patch(J, p, 0); - MCode exitload = MIPSI_LI | MIPSF_T(RID_TMP) | exitno; - MCode tjump = MIPSI_J|(((uintptr_t)target>>2)&0x03ffffffu); - for (p++; p < pe; p++) { - if (*p == exitload) { /* Look for load of exit number. */ - /* Look for exitstub branch. Yes, this covers all used branch variants. */ - if (((p[-1] ^ (px-p)) & 0xffffu) == 0 && - ((p[-1] & 0xf0000000u) == MIPSI_BEQ || - (p[-1] & 0xfc1e0000u) == MIPSI_BLTZ || -#if !LJ_TARGET_MIPSR6 - (p[-1] & 0xffe00000u) == MIPSI_BC1F -#else - (p[-1] & 0xff600000u) == MIPSI_BC1EQZ -#endif - ) && p[-2] != MIPS_NOPATCH_GC_CHECK) { - ptrdiff_t delta = target - p; - if (((delta + 0x8000) >> 16) == 0) { /* Patch in-range branch. */ - patchbranch: - p[-1] = (p[-1] & 0xffff0000u) | (delta & 0xffffu); - *p = MIPSI_NOP; /* Replace the load of the exit number. */ - cstop = p+1; - if (!cstart) cstart = p-1; - } else { /* Branch out of range. Use spare jump slot in mcarea. */ - MCode *mcjump = asm_sparejump_use(mcarea, tjump); - if (mcjump) { - lj_mcode_sync(mcjump, mcjump+1); - delta = mcjump - p; - if (((delta + 0x8000) >> 16) == 0) { - goto patchbranch; - } else { - lj_assertJ(0, "spare jump out of range: -Osizemcode too big"); - } - } - /* Ignore jump slot overflow. Child trace is simply not attached. */ - } - } else if (p+1 == pe) { - /* Patch NOP after code for inverted loop branch. Use of J is ok. */ - lj_assertJ(p[1] == MIPSI_NOP, "expected NOP"); - p[1] = tjump; - *p = MIPSI_NOP; /* Replace the load of the exit number. */ - cstop = p+2; - if (!cstart) cstart = p+1; - } - } - } - if (cstart) lj_mcode_sync(cstart, cstop); - lj_mcode_patch(J, mcarea, 1); -} - diff --git a/include/luajit/lj_asm_ppc.h b/include/luajit/lj_asm_ppc.h deleted file mode 100644 index 9e2af41..0000000 --- a/include/luajit/lj_asm_ppc.h +++ /dev/null @@ -1,2338 +0,0 @@ -/* -** PPC IR assembler (SSA IR -> machine code). -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -/* -- Register allocator extensions --------------------------------------- */ - -/* Allocate a register with a hint. */ -static Reg ra_hintalloc(ASMState *as, IRRef ref, Reg hint, RegSet allow) -{ - Reg r = IR(ref)->r; - if (ra_noreg(r)) { - if (!ra_hashint(r) && !iscrossref(as, ref)) - ra_sethint(IR(ref)->r, hint); /* Propagate register hint. */ - r = ra_allocref(as, ref, allow); - } - ra_noweak(as, r); - return r; -} - -/* Allocate two source registers for three-operand instructions. */ -static Reg ra_alloc2(ASMState *as, IRIns *ir, RegSet allow) -{ - IRIns *irl = IR(ir->op1), *irr = IR(ir->op2); - Reg left = irl->r, right = irr->r; - if (ra_hasreg(left)) { - ra_noweak(as, left); - if (ra_noreg(right)) - right = ra_allocref(as, ir->op2, rset_exclude(allow, left)); - else - ra_noweak(as, right); - } else if (ra_hasreg(right)) { - ra_noweak(as, right); - left = ra_allocref(as, ir->op1, rset_exclude(allow, right)); - } else if (ra_hashint(right)) { - right = ra_allocref(as, ir->op2, allow); - left = ra_alloc1(as, ir->op1, rset_exclude(allow, right)); - } else { - left = ra_allocref(as, ir->op1, allow); - right = ra_alloc1(as, ir->op2, rset_exclude(allow, left)); - } - return left | (right << 8); -} - -/* -- Guard handling ------------------------------------------------------ */ - -/* Setup exit stubs after the end of each trace. */ -static void asm_exitstub_setup(ASMState *as, ExitNo nexits) -{ - ExitNo i; - int ind; - uintptr_t target = (uintptr_t)(void *)lj_vm_exit_handler; - MCode *mxp = as->mctop; - if (mxp - (nexits + 4 + MCLIM_REDZONE) < as->mclim) - asm_mclimit(as); - ind = ((target - (uintptr_t)(mxp - nexits - 2) + 0x02000000u) >> 26) ? 2 : 0; - /* !ind: 1: mflr r0; bl ->vm_exit_handler; li r0, traceno; - ** ind: 1: lwz r0, K32_VXH(jgl); mtctr r0; mflr r0; bctrl; li r0, traceno; - ** bl <1; bl <1; ... - */ - for (i = nexits-1; (int32_t)i >= 0; i--) - *--mxp = PPCI_BL | (((-3-ind-i) & 0x00ffffffu) << 2); - as->mcexit = mxp; - *--mxp = PPCI_LI|PPCF_T(RID_TMP)|as->T->traceno; /* Read by exit handler. */ - if (ind) { - *--mxp = PPCI_BCTRL; - *--mxp = PPCI_MFLR | PPCF_T(RID_TMP); - *--mxp = PPCI_MTCTR | PPCF_T(RID_TMP); - *--mxp = PPCI_LWZ | PPCF_T(RID_TMP) | PPCF_A(RID_JGL) | - jglofs(as, &as->J->k32[LJ_K32_VM_EXIT_HANDLER]); - } else { - mxp--; - *mxp = PPCI_BL | ((target - (uintptr_t)mxp) & 0x03fffffcu); - *--mxp = PPCI_MFLR | PPCF_T(RID_TMP); - } - as->mctop = mxp; -} - -static MCode *asm_exitstub_addr(ASMState *as, ExitNo exitno) -{ - /* Keep this in-sync with exitstub_trace_addr(). */ - return as->mcexit + exitno; -} - -/* Emit conditional branch to exit for guard. */ -static void asm_guardcc(ASMState *as, PPCCC cc) -{ - MCode *target = asm_exitstub_addr(as, as->snapno); - MCode *p = as->mcp; - if (LJ_UNLIKELY(p == as->invmcp)) { - as->loopinv = 1; - *p = PPCI_B | (((target-p) & 0x00ffffffu) << 2); - emit_condbranch(as, PPCI_BC, cc^4, p); - return; - } - emit_condbranch(as, PPCI_BC, cc, target); -} - -/* -- Operand fusion ------------------------------------------------------ */ - -/* Limit linear search to this distance. Avoids O(n^2) behavior. */ -#define CONFLICT_SEARCH_LIM 31 - -/* Check if there's no conflicting instruction between curins and ref. */ -static int noconflict(ASMState *as, IRRef ref, IROp conflict) -{ - IRIns *ir = as->ir; - IRRef i = as->curins; - if (i > ref + CONFLICT_SEARCH_LIM) - return 0; /* Give up, ref is too far away. */ - while (--i > ref) - if (ir[i].o == conflict) - return 0; /* Conflict found. */ - return 1; /* Ok, no conflict. */ -} - -/* Fuse the array base of colocated arrays. */ -static int32_t asm_fuseabase(ASMState *as, IRRef ref) -{ - IRIns *ir = IR(ref); - if (ir->o == IR_TNEW && ir->op1 <= LJ_MAX_COLOSIZE && - !neverfuse(as) && noconflict(as, ref, IR_NEWREF)) - return (int32_t)sizeof(GCtab); - return 0; -} - -/* Indicates load/store indexed is ok. */ -#define AHUREF_LSX ((int32_t)0x80000000) - -/* Fuse array/hash/upvalue reference into register+offset operand. */ -static Reg asm_fuseahuref(ASMState *as, IRRef ref, int32_t *ofsp, RegSet allow) -{ - IRIns *ir = IR(ref); - if (ra_noreg(ir->r)) { - if (ir->o == IR_AREF) { - if (mayfuse(as, ref)) { - if (irref_isk(ir->op2)) { - IRRef tab = IR(ir->op1)->op1; - int32_t ofs = asm_fuseabase(as, tab); - IRRef refa = ofs ? tab : ir->op1; - ofs += 8*IR(ir->op2)->i; - if (checki16(ofs)) { - *ofsp = ofs; - return ra_alloc1(as, refa, allow); - } - } - if (*ofsp == AHUREF_LSX) { - Reg base = ra_alloc1(as, ir->op1, allow); - Reg idx = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, base)); - return base | (idx << 8); - } - } - } else if (ir->o == IR_HREFK) { - if (mayfuse(as, ref)) { - int32_t ofs = (int32_t)(IR(ir->op2)->op2 * sizeof(Node)); - if (checki16(ofs)) { - *ofsp = ofs; - return ra_alloc1(as, ir->op1, allow); - } - } - } else if (ir->o == IR_UREFC) { - if (irref_isk(ir->op1)) { - GCfunc *fn = ir_kfunc(IR(ir->op1)); - int32_t ofs = i32ptr(&gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.tv); - int32_t jgl = (intptr_t)J2G(as->J); - if ((uint32_t)(ofs-jgl) < 65536) { - *ofsp = ofs-jgl-32768; - return RID_JGL; - } else { - *ofsp = (int16_t)ofs; - return ra_allock(as, ofs-(int16_t)ofs, allow); - } - } - } else if (ir->o == IR_TMPREF) { - *ofsp = (int32_t)(offsetof(global_State, tmptv)-32768); - return RID_JGL; - } - } - *ofsp = 0; - return ra_alloc1(as, ref, allow); -} - -/* Fuse XLOAD/XSTORE reference into load/store operand. */ -static void asm_fusexref(ASMState *as, PPCIns pi, Reg rt, IRRef ref, - RegSet allow, int32_t ofs) -{ - IRIns *ir = IR(ref); - Reg base; - if (ra_noreg(ir->r) && canfuse(as, ir)) { - if (ir->o == IR_ADD) { - int32_t ofs2; - if (irref_isk(ir->op2) && (ofs2 = ofs + IR(ir->op2)->i, checki16(ofs2))) { - ofs = ofs2; - ref = ir->op1; - } else if (ofs == 0) { - Reg right, left = ra_alloc2(as, ir, allow); - right = (left >> 8); left &= 255; - emit_fab(as, PPCI_LWZX | ((pi >> 20) & 0x780), rt, left, right); - return; - } - } else if (ir->o == IR_STRREF) { - lj_assertA(ofs == 0, "bad usage"); - ofs = (int32_t)sizeof(GCstr); - if (irref_isk(ir->op2)) { - ofs += IR(ir->op2)->i; - ref = ir->op1; - } else if (irref_isk(ir->op1)) { - ofs += IR(ir->op1)->i; - ref = ir->op2; - } else { - /* NYI: Fuse ADD with constant. */ - Reg tmp, right, left = ra_alloc2(as, ir, allow); - right = (left >> 8); left &= 255; - tmp = ra_scratch(as, rset_exclude(rset_exclude(allow, left), right)); - emit_fai(as, pi, rt, tmp, ofs); - emit_tab(as, PPCI_ADD, tmp, left, right); - return; - } - if (!checki16(ofs)) { - Reg left = ra_alloc1(as, ref, allow); - Reg right = ra_allock(as, ofs, rset_exclude(allow, left)); - emit_fab(as, PPCI_LWZX | ((pi >> 20) & 0x780), rt, left, right); - return; - } - } - } - base = ra_alloc1(as, ref, allow); - emit_fai(as, pi, rt, base, ofs); -} - -/* Fuse XLOAD/XSTORE reference into indexed-only load/store operand. */ -static void asm_fusexrefx(ASMState *as, PPCIns pi, Reg rt, IRRef ref, - RegSet allow) -{ - IRIns *ira = IR(ref); - Reg right, left; - if (canfuse(as, ira) && ira->o == IR_ADD && ra_noreg(ira->r)) { - left = ra_alloc2(as, ira, allow); - right = (left >> 8); left &= 255; - } else { - right = ra_alloc1(as, ref, allow); - left = RID_R0; - } - emit_tab(as, pi, rt, left, right); -} - -#if !LJ_SOFTFP -/* Fuse to multiply-add/sub instruction. */ -static int asm_fusemadd(ASMState *as, IRIns *ir, PPCIns pi, PPCIns pir) -{ - IRRef lref = ir->op1, rref = ir->op2; - IRIns *irm; - if ((as->flags & JIT_F_OPT_FMA) && - lref != rref && - ((mayfuse(as, lref) && (irm = IR(lref), irm->o == IR_MUL) && - ra_noreg(irm->r)) || - (mayfuse(as, rref) && (irm = IR(rref), irm->o == IR_MUL) && - (rref = lref, pi = pir, ra_noreg(irm->r))))) { - Reg dest = ra_dest(as, ir, RSET_FPR); - Reg add = ra_alloc1(as, rref, RSET_FPR); - Reg right, left = ra_alloc2(as, irm, rset_exclude(RSET_FPR, add)); - right = (left >> 8); left &= 255; - emit_facb(as, pi, dest, left, right, add); - return 1; - } - return 0; -} -#endif - -/* -- Calls --------------------------------------------------------------- */ - -/* Generate a call to a C function. */ -static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args) -{ - uint32_t n, nargs = CCI_XNARGS(ci); - int32_t ofs = 8; - Reg gpr = REGARG_FIRSTGPR; -#if !LJ_SOFTFP - Reg fpr = REGARG_FIRSTFPR; -#endif - if ((void *)ci->func) - emit_call(as, (void *)ci->func); - for (n = 0; n < nargs; n++) { /* Setup args. */ - IRRef ref = args[n]; - if (ref) { - IRIns *ir = IR(ref); -#if !LJ_SOFTFP - if (irt_isfp(ir->t)) { - if (fpr <= REGARG_LASTFPR) { - lj_assertA(rset_test(as->freeset, fpr), - "reg %d not free", fpr); /* Already evicted. */ - ra_leftov(as, fpr, ref); - fpr++; - } else { - Reg r = ra_alloc1(as, ref, RSET_FPR); - if (irt_isnum(ir->t)) ofs = (ofs + 4) & ~4; - emit_spstore(as, ir, r, ofs); - ofs += irt_isnum(ir->t) ? 8 : 4; - } - } else -#endif - { - if (gpr <= REGARG_LASTGPR) { - lj_assertA(rset_test(as->freeset, gpr), - "reg %d not free", gpr); /* Already evicted. */ - ra_leftov(as, gpr, ref); - gpr++; - } else { - Reg r = ra_alloc1(as, ref, RSET_GPR); - emit_spstore(as, ir, r, ofs); - ofs += 4; - } - } - } else { - if (gpr <= REGARG_LASTGPR) - gpr++; - else - ofs += 4; - } - checkmclim(as); - } -#if !LJ_SOFTFP - if ((ci->flags & CCI_VARARG)) /* Vararg calls need to know about FPR use. */ - emit_tab(as, fpr == REGARG_FIRSTFPR ? PPCI_CRXOR : PPCI_CREQV, 6, 6, 6); -#endif -} - -/* Setup result reg/sp for call. Evict scratch regs. */ -static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci) -{ - RegSet drop = RSET_SCRATCH; - int hiop = ((ir+1)->o == IR_HIOP && !irt_isnil((ir+1)->t)); -#if !LJ_SOFTFP - if ((ci->flags & CCI_NOFPRCLOBBER)) - drop &= ~RSET_FPR; -#endif - if (ra_hasreg(ir->r)) - rset_clear(drop, ir->r); /* Dest reg handled below. */ - if (hiop && ra_hasreg((ir+1)->r)) - rset_clear(drop, (ir+1)->r); /* Dest reg handled below. */ - ra_evictset(as, drop); /* Evictions must be performed first. */ - if (ra_used(ir)) { - lj_assertA(!irt_ispri(ir->t), "PRI dest"); - if (!LJ_SOFTFP && irt_isfp(ir->t)) { - if ((ci->flags & CCI_CASTU64)) { - /* Use spill slot or temp slots. */ - int32_t ofs = ir->s ? sps_scale(ir->s) : SPOFS_TMP; - Reg dest = ir->r; - if (ra_hasreg(dest)) { - ra_free(as, dest); - ra_modified(as, dest); - emit_fai(as, PPCI_LFD, dest, RID_SP, ofs); - } - emit_tai(as, PPCI_STW, RID_RETHI, RID_SP, ofs); - emit_tai(as, PPCI_STW, RID_RETLO, RID_SP, ofs+4); - } else { - ra_destreg(as, ir, RID_FPRET); - } - } else if (hiop) { - ra_destpair(as, ir); - } else { - ra_destreg(as, ir, RID_RET); - } - } -} - -static void asm_callx(ASMState *as, IRIns *ir) -{ - IRRef args[CCI_NARGS_MAX*2]; - CCallInfo ci; - IRRef func; - IRIns *irf; - ci.flags = asm_callx_flags(as, ir); - asm_collectargs(as, ir, &ci, args); - asm_setupresult(as, ir, &ci); - func = ir->op2; irf = IR(func); - if (irf->o == IR_CARG) { func = irf->op1; irf = IR(func); } - if (irref_isk(func)) { /* Call to constant address. */ - ci.func = (ASMFunction)(void *)(intptr_t)(irf->i); - } else { /* Need a non-argument register for indirect calls. */ - RegSet allow = RSET_GPR & ~RSET_RANGE(RID_R0, REGARG_LASTGPR+1); - Reg freg = ra_alloc1(as, func, allow); - *--as->mcp = PPCI_BCTRL; - *--as->mcp = PPCI_MTCTR | PPCF_T(freg); - ci.func = (ASMFunction)(void *)0; - } - asm_gencall(as, &ci, args); -} - -/* -- Returns ------------------------------------------------------------- */ - -/* Return to lower frame. Guard that it goes to the right spot. */ -static void asm_retf(ASMState *as, IRIns *ir) -{ - Reg base = ra_alloc1(as, REF_BASE, RSET_GPR); - void *pc = ir_kptr(IR(ir->op2)); - int32_t delta = 1+LJ_FR2+bc_a(*((const BCIns *)pc - 1)); - as->topslot -= (BCReg)delta; - if ((int32_t)as->topslot < 0) as->topslot = 0; - irt_setmark(IR(REF_BASE)->t); /* Children must not coalesce with BASE reg. */ - emit_setgl(as, base, jit_base); - emit_addptr(as, base, -8*delta); - asm_guardcc(as, CC_NE); - emit_ab(as, PPCI_CMPW, RID_TMP, - ra_allock(as, i32ptr(pc), rset_exclude(RSET_GPR, base))); - emit_tai(as, PPCI_LWZ, RID_TMP, base, -8); -} - -/* -- Buffer operations --------------------------------------------------- */ - -#if LJ_HASBUFFER -static void asm_bufhdr_write(ASMState *as, Reg sb) -{ - Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, sb)); - IRIns irgc; - irgc.ot = IRT(0, IRT_PGC); /* GC type. */ - emit_storeofs(as, &irgc, RID_TMP, sb, offsetof(SBuf, L)); - emit_rot(as, PPCI_RLWIMI, RID_TMP, tmp, 0, 31-lj_fls(SBUF_MASK_FLAG), 31); - emit_getgl(as, RID_TMP, cur_L); - emit_loadofs(as, &irgc, tmp, sb, offsetof(SBuf, L)); -} -#endif - -/* -- Type conversions ---------------------------------------------------- */ - -#if !LJ_SOFTFP -static void asm_tointg(ASMState *as, IRIns *ir, Reg left) -{ - RegSet allow = RSET_FPR; - Reg tmp = ra_scratch(as, rset_clear(allow, left)); - Reg fbias = ra_scratch(as, rset_clear(allow, tmp)); - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg hibias = ra_allock(as, 0x43300000, rset_exclude(RSET_GPR, dest)); - asm_guardcc(as, CC_NE); - emit_fab(as, PPCI_FCMPU, 0, tmp, left); - emit_fab(as, PPCI_FSUB, tmp, tmp, fbias); - emit_fai(as, PPCI_LFD, tmp, RID_SP, SPOFS_TMP); - emit_tai(as, PPCI_STW, RID_TMP, RID_SP, SPOFS_TMPLO); - emit_tai(as, PPCI_STW, hibias, RID_SP, SPOFS_TMPHI); - emit_asi(as, PPCI_XORIS, RID_TMP, dest, 0x8000); - emit_tai(as, PPCI_LWZ, dest, RID_SP, SPOFS_TMPLO); - emit_lsptr(as, PPCI_LFS, (fbias & 31), - (void *)&as->J->k32[LJ_K32_2P52_2P31], RSET_GPR); - emit_fai(as, PPCI_STFD, tmp, RID_SP, SPOFS_TMP); - emit_fb(as, PPCI_FCTIWZ, tmp, left); -} - -static void asm_tobit(ASMState *as, IRIns *ir) -{ - RegSet allow = RSET_FPR; - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_alloc1(as, ir->op1, allow); - Reg right = ra_alloc1(as, ir->op2, rset_clear(allow, left)); - Reg tmp = ra_scratch(as, rset_clear(allow, right)); - emit_tai(as, PPCI_LWZ, dest, RID_SP, SPOFS_TMPLO); - emit_fai(as, PPCI_STFD, tmp, RID_SP, SPOFS_TMP); - emit_fab(as, PPCI_FADD, tmp, left, right); -} -#endif - -static void asm_conv(ASMState *as, IRIns *ir) -{ - IRType st = (IRType)(ir->op2 & IRCONV_SRCMASK); -#if !LJ_SOFTFP - int stfp = (st == IRT_NUM || st == IRT_FLOAT); -#endif - IRRef lref = ir->op1; - /* 64 bit integer conversions are handled by SPLIT. */ - lj_assertA(!(irt_isint64(ir->t) || (st == IRT_I64 || st == IRT_U64)), - "IR %04d has unsplit 64 bit type", - (int)(ir - as->ir) - REF_BIAS); -#if LJ_SOFTFP - /* FP conversions are handled by SPLIT. */ - lj_assertA(!irt_isfp(ir->t) && !(st == IRT_NUM || st == IRT_FLOAT), - "IR %04d has FP type", - (int)(ir - as->ir) - REF_BIAS); - /* Can't check for same types: SPLIT uses CONV int.int + BXOR for sfp NEG. */ -#else - lj_assertA(irt_type(ir->t) != st, "inconsistent types for CONV"); - if (irt_isfp(ir->t)) { - Reg dest = ra_dest(as, ir, RSET_FPR); - if (stfp) { /* FP to FP conversion. */ - if (st == IRT_NUM) /* double -> float conversion. */ - emit_fb(as, PPCI_FRSP, dest, ra_alloc1(as, lref, RSET_FPR)); - else /* float -> double conversion is a no-op on PPC. */ - ra_leftov(as, dest, lref); /* Do nothing, but may need to move regs. */ - } else { /* Integer to FP conversion. */ - /* IRT_INT: Flip hibit, bias with 2^52, subtract 2^52+2^31. */ - /* IRT_U32: Bias with 2^52, subtract 2^52. */ - RegSet allow = RSET_GPR; - Reg left = ra_alloc1(as, lref, allow); - Reg hibias = ra_allock(as, 0x43300000, rset_clear(allow, left)); - Reg fbias = ra_scratch(as, rset_exclude(RSET_FPR, dest)); - if (irt_isfloat(ir->t)) emit_fb(as, PPCI_FRSP, dest, dest); - emit_fab(as, PPCI_FSUB, dest, dest, fbias); - emit_fai(as, PPCI_LFD, dest, RID_SP, SPOFS_TMP); - emit_lsptr(as, PPCI_LFS, (fbias & 31), - &as->J->k32[st == IRT_U32 ? LJ_K32_2P52 : LJ_K32_2P52_2P31], - rset_clear(allow, hibias)); - emit_tai(as, PPCI_STW, st == IRT_U32 ? left : RID_TMP, - RID_SP, SPOFS_TMPLO); - emit_tai(as, PPCI_STW, hibias, RID_SP, SPOFS_TMPHI); - if (st != IRT_U32) emit_asi(as, PPCI_XORIS, RID_TMP, left, 0x8000); - } - } else if (stfp) { /* FP to integer conversion. */ - if (irt_isguard(ir->t)) { - /* Checked conversions are only supported from number to int. */ - lj_assertA(irt_isint(ir->t) && st == IRT_NUM, - "bad type for checked CONV"); - asm_tointg(as, ir, ra_alloc1(as, lref, RSET_FPR)); - } else { - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_alloc1(as, lref, RSET_FPR); - Reg tmp = ra_scratch(as, rset_exclude(RSET_FPR, left)); - lj_assertA(!irt_isu32(ir->t), "bad CONV u32.fp emitted"); - emit_tai(as, PPCI_LWZ, dest, RID_SP, SPOFS_TMPLO); - emit_fai(as, PPCI_STFD, tmp, RID_SP, SPOFS_TMP); - emit_fb(as, PPCI_FCTIWZ, tmp, left); - } - } else -#endif - { - Reg dest = ra_dest(as, ir, RSET_GPR); - if (st >= IRT_I8 && st <= IRT_U16) { /* Extend to 32 bit integer. */ - Reg left = ra_alloc1(as, ir->op1, RSET_GPR); - lj_assertA(irt_isint(ir->t) || irt_isu32(ir->t), "bad type for CONV EXT"); - if ((ir->op2 & IRCONV_SEXT)) - emit_as(as, st == IRT_I8 ? PPCI_EXTSB : PPCI_EXTSH, dest, left); - else - emit_rot(as, PPCI_RLWINM, dest, left, 0, st == IRT_U8 ? 24 : 16, 31); - } else { /* 32/64 bit integer conversions. */ - /* Only need to handle 32/32 bit no-op (cast) on 32 bit archs. */ - ra_leftov(as, dest, lref); /* Do nothing, but may need to move regs. */ - } - } -} - -static void asm_strto(ASMState *as, IRIns *ir) -{ - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_strscan_num]; - IRRef args[2]; - int32_t ofs = SPOFS_TMP; -#if LJ_SOFTFP - ra_evictset(as, RSET_SCRATCH); - if (ra_used(ir)) { - if (ra_hasspill(ir->s) && ra_hasspill((ir+1)->s) && - (ir->s & 1) == LJ_BE && (ir->s ^ 1) == (ir+1)->s) { - int i; - for (i = 0; i < 2; i++) { - Reg r = (ir+i)->r; - if (ra_hasreg(r)) { - ra_free(as, r); - ra_modified(as, r); - emit_spload(as, ir+i, r, sps_scale((ir+i)->s)); - } - } - ofs = sps_scale(ir->s & ~1); - } else { - Reg rhi = ra_dest(as, ir+1, RSET_GPR); - Reg rlo = ra_dest(as, ir, rset_exclude(RSET_GPR, rhi)); - emit_tai(as, PPCI_LWZ, rhi, RID_SP, ofs); - emit_tai(as, PPCI_LWZ, rlo, RID_SP, ofs+4); - } - } -#else - RegSet drop = RSET_SCRATCH; - if (ra_hasreg(ir->r)) rset_set(drop, ir->r); /* Spill dest reg (if any). */ - ra_evictset(as, drop); - if (ir->s) ofs = sps_scale(ir->s); -#endif - asm_guardcc(as, CC_EQ); - emit_ai(as, PPCI_CMPWI, RID_RET, 0); /* Test return status. */ - args[0] = ir->op1; /* GCstr *str */ - args[1] = ASMREF_TMP1; /* TValue *n */ - asm_gencall(as, ci, args); - /* Store the result to the spill slot or temp slots. */ - emit_tai(as, PPCI_ADDI, ra_releasetmp(as, ASMREF_TMP1), RID_SP, ofs); -} - -/* -- Memory references --------------------------------------------------- */ - -/* Get pointer to TValue. */ -static void asm_tvptr(ASMState *as, Reg dest, IRRef ref, MSize mode) -{ - int32_t tmpofs = (int32_t)(offsetof(global_State, tmptv)-32768); - if ((mode & IRTMPREF_IN1)) { - IRIns *ir = IR(ref); - if (irt_isnum(ir->t)) { - if ((mode & IRTMPREF_OUT1)) { -#if LJ_SOFTFP - lj_assertA(irref_isk(ref), "unsplit FP op"); - emit_tai(as, PPCI_ADDI, dest, RID_JGL, tmpofs); - emit_setgl(as, - ra_allock(as, (int32_t)ir_knum(ir)->u32.lo, RSET_GPR), - tmptv.u32.lo); - emit_setgl(as, - ra_allock(as, (int32_t)ir_knum(ir)->u32.hi, RSET_GPR), - tmptv.u32.hi); -#else - Reg src = ra_alloc1(as, ref, RSET_FPR); - emit_tai(as, PPCI_ADDI, dest, RID_JGL, tmpofs); - emit_fai(as, PPCI_STFD, src, RID_JGL, tmpofs); -#endif - } else if (irref_isk(ref)) { - /* Use the number constant itself as a TValue. */ - ra_allockreg(as, i32ptr(ir_knum(ir)), dest); - } else { -#if LJ_SOFTFP - lj_assertA(0, "unsplit FP op"); -#else - /* Otherwise force a spill and use the spill slot. */ - emit_tai(as, PPCI_ADDI, dest, RID_SP, ra_spill(as, ir)); -#endif - } - } else { - /* Otherwise use g->tmptv to hold the TValue. */ - Reg type; - emit_tai(as, PPCI_ADDI, dest, RID_JGL, tmpofs); - if (!irt_ispri(ir->t)) { - Reg src = ra_alloc1(as, ref, RSET_GPR); - emit_setgl(as, src, tmptv.gcr); - } - if (LJ_SOFTFP && (ir+1)->o == IR_HIOP && !irt_isnil((ir+1)->t)) - type = ra_alloc1(as, ref+1, RSET_GPR); - else - type = ra_allock(as, irt_toitype(ir->t), RSET_GPR); - emit_setgl(as, type, tmptv.it); - } - } else { - emit_tai(as, PPCI_ADDI, dest, RID_JGL, tmpofs); - } -} - -static void asm_aref(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg idx, base; - if (irref_isk(ir->op2)) { - IRRef tab = IR(ir->op1)->op1; - int32_t ofs = asm_fuseabase(as, tab); - IRRef refa = ofs ? tab : ir->op1; - ofs += 8*IR(ir->op2)->i; - if (checki16(ofs)) { - base = ra_alloc1(as, refa, RSET_GPR); - emit_tai(as, PPCI_ADDI, dest, base, ofs); - return; - } - } - base = ra_alloc1(as, ir->op1, RSET_GPR); - idx = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, base)); - emit_tab(as, PPCI_ADD, dest, RID_TMP, base); - emit_slwi(as, RID_TMP, idx, 3); -} - -/* Inlined hash lookup. Specialized for key type and for const keys. -** The equivalent C code is: -** Node *n = hashkey(t, key); -** do { -** if (lj_obj_equal(&n->key, key)) return &n->val; -** } while ((n = nextnode(n))); -** return niltv(L); -*/ -static void asm_href(ASMState *as, IRIns *ir, IROp merge) -{ - RegSet allow = RSET_GPR; - int destused = ra_used(ir); - Reg dest = ra_dest(as, ir, allow); - Reg tab = ra_alloc1(as, ir->op1, rset_clear(allow, dest)); - Reg key = RID_NONE, tmp1 = RID_TMP, tmp2; - Reg tisnum = RID_NONE, tmpnum = RID_NONE; - IRRef refkey = ir->op2; - IRIns *irkey = IR(refkey); - int isk = irref_isk(refkey); - IRType1 kt = irkey->t; - uint32_t khash; - MCLabel l_end, l_loop, l_next; - - rset_clear(allow, tab); -#if LJ_SOFTFP - if (!isk) { - key = ra_alloc1(as, refkey, allow); - rset_clear(allow, key); - if (irkey[1].o == IR_HIOP) { - if (ra_hasreg((irkey+1)->r)) { - tmpnum = (irkey+1)->r; - ra_noweak(as, tmpnum); - } else { - tmpnum = ra_allocref(as, refkey+1, allow); - } - rset_clear(allow, tmpnum); - } - } -#else - if (irt_isnum(kt)) { - key = ra_alloc1(as, refkey, RSET_FPR); - tmpnum = ra_scratch(as, rset_exclude(RSET_FPR, key)); - tisnum = ra_allock(as, (int32_t)LJ_TISNUM, allow); - rset_clear(allow, tisnum); - } else if (!irt_ispri(kt)) { - key = ra_alloc1(as, refkey, allow); - rset_clear(allow, key); - } -#endif - tmp2 = ra_scratch(as, allow); - rset_clear(allow, tmp2); - - /* Key not found in chain: jump to exit (if merged) or load niltv. */ - l_end = emit_label(as); - as->invmcp = NULL; - if (merge == IR_NE) - asm_guardcc(as, CC_EQ); - else if (destused) - emit_loada(as, dest, niltvg(J2G(as->J))); - - /* Follow hash chain until the end. */ - l_loop = --as->mcp; - emit_ai(as, PPCI_CMPWI, dest, 0); - emit_tai(as, PPCI_LWZ, dest, dest, (int32_t)offsetof(Node, next)); - l_next = emit_label(as); - - /* Type and value comparison. */ - if (merge == IR_EQ) - asm_guardcc(as, CC_EQ); - else - emit_condbranch(as, PPCI_BC|PPCF_Y, CC_EQ, l_end); - if (!LJ_SOFTFP && irt_isnum(kt)) { - emit_fab(as, PPCI_FCMPU, 0, tmpnum, key); - emit_condbranch(as, PPCI_BC, CC_GE, l_next); - emit_ab(as, PPCI_CMPLW, tmp1, tisnum); - emit_fai(as, PPCI_LFD, tmpnum, dest, (int32_t)offsetof(Node, key.n)); - } else { - if (!irt_ispri(kt)) { - emit_ab(as, PPCI_CMPW, tmp2, key); - emit_condbranch(as, PPCI_BC, CC_NE, l_next); - } - if (LJ_SOFTFP && ra_hasreg(tmpnum)) - emit_ab(as, PPCI_CMPW, tmp1, tmpnum); - else - emit_ai(as, PPCI_CMPWI, tmp1, irt_toitype(irkey->t)); - if (!irt_ispri(kt)) - emit_tai(as, PPCI_LWZ, tmp2, dest, (int32_t)offsetof(Node, key.gcr)); - } - emit_tai(as, PPCI_LWZ, tmp1, dest, (int32_t)offsetof(Node, key.it)); - *l_loop = PPCI_BC | PPCF_Y | PPCF_CC(CC_NE) | - (((char *)as->mcp-(char *)l_loop) & 0xffffu); - - /* Load main position relative to tab->node into dest. */ - khash = isk ? ir_khash(as, irkey) : 1; - if (khash == 0) { - emit_tai(as, PPCI_LWZ, dest, tab, (int32_t)offsetof(GCtab, node)); - } else { - Reg tmphash = tmp1; - if (isk) - tmphash = ra_allock(as, khash, allow); - emit_tab(as, PPCI_ADD, dest, dest, tmp1); - emit_tai(as, PPCI_MULLI, tmp1, tmp1, sizeof(Node)); - emit_asb(as, PPCI_AND, tmp1, tmp2, tmphash); - emit_tai(as, PPCI_LWZ, dest, tab, (int32_t)offsetof(GCtab, node)); - emit_tai(as, PPCI_LWZ, tmp2, tab, (int32_t)offsetof(GCtab, hmask)); - if (isk) { - /* Nothing to do. */ - } else if (irt_isstr(kt)) { - emit_tai(as, PPCI_LWZ, tmp1, key, (int32_t)offsetof(GCstr, sid)); - } else { /* Must match with hash*() in lj_tab.c. */ - emit_tab(as, PPCI_SUBF, tmp1, tmp2, tmp1); - emit_rotlwi(as, tmp2, tmp2, HASH_ROT3); - emit_asb(as, PPCI_XOR, tmp1, tmp1, tmp2); - emit_rotlwi(as, tmp1, tmp1, (HASH_ROT2+HASH_ROT1)&31); - emit_tab(as, PPCI_SUBF, tmp2, dest, tmp2); - if (LJ_SOFTFP ? (irkey[1].o == IR_HIOP) : irt_isnum(kt)) { -#if LJ_SOFTFP - emit_asb(as, PPCI_XOR, tmp2, key, tmp1); - emit_rotlwi(as, dest, tmp1, HASH_ROT1); - emit_tab(as, PPCI_ADD, tmp1, tmpnum, tmpnum); -#else - int32_t ofs = ra_spill(as, irkey); - emit_asb(as, PPCI_XOR, tmp2, tmp2, tmp1); - emit_rotlwi(as, dest, tmp1, HASH_ROT1); - emit_tab(as, PPCI_ADD, tmp1, tmp1, tmp1); - emit_tai(as, PPCI_LWZ, tmp2, RID_SP, ofs+4); - emit_tai(as, PPCI_LWZ, tmp1, RID_SP, ofs); -#endif - } else { - emit_asb(as, PPCI_XOR, tmp2, key, tmp1); - emit_rotlwi(as, dest, tmp1, HASH_ROT1); - emit_tai(as, PPCI_ADDI, tmp1, tmp2, HASH_BIAS); - emit_tai(as, PPCI_ADDIS, tmp2, key, (HASH_BIAS + 32768)>>16); - } - } - } -} - -static void asm_hrefk(ASMState *as, IRIns *ir) -{ - IRIns *kslot = IR(ir->op2); - IRIns *irkey = IR(kslot->op1); - int32_t ofs = (int32_t)(kslot->op2 * sizeof(Node)); - int32_t kofs = ofs + (int32_t)offsetof(Node, key); - Reg dest = (ra_used(ir)||ofs > 32736) ? ra_dest(as, ir, RSET_GPR) : RID_NONE; - Reg node = ra_alloc1(as, ir->op1, RSET_GPR); - Reg key = RID_NONE, type = RID_TMP, idx = node; - RegSet allow = rset_exclude(RSET_GPR, node); - lj_assertA(ofs % sizeof(Node) == 0, "unaligned HREFK slot"); - if (ofs > 32736) { - idx = dest; - rset_clear(allow, dest); - kofs = (int32_t)offsetof(Node, key); - } else if (ra_hasreg(dest)) { - emit_tai(as, PPCI_ADDI, dest, node, ofs); - } - asm_guardcc(as, CC_NE); - if (!irt_ispri(irkey->t)) { - key = ra_scratch(as, allow); - rset_clear(allow, key); - } - rset_clear(allow, type); - if (irt_isnum(irkey->t)) { - emit_cmpi(as, key, (int32_t)ir_knum(irkey)->u32.lo); - asm_guardcc(as, CC_NE); - emit_cmpi(as, type, (int32_t)ir_knum(irkey)->u32.hi); - } else { - if (ra_hasreg(key)) { - emit_cmpi(as, key, irkey->i); /* May use RID_TMP, i.e. type. */ - asm_guardcc(as, CC_NE); - } - emit_ai(as, PPCI_CMPWI, type, irt_toitype(irkey->t)); - } - if (ra_hasreg(key)) emit_tai(as, PPCI_LWZ, key, idx, kofs+4); - emit_tai(as, PPCI_LWZ, type, idx, kofs); - if (ofs > 32736) { - emit_tai(as, PPCI_ADDIS, dest, dest, (ofs + 32768) >> 16); - emit_tai(as, PPCI_ADDI, dest, node, ofs); - } -} - -static void asm_uref(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - int guarded = (irt_t(ir->t) & (IRT_GUARD|IRT_TYPE)) == (IRT_GUARD|IRT_PGC); - if (irref_isk(ir->op1) && !guarded) { - GCfunc *fn = ir_kfunc(IR(ir->op1)); - MRef *v = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.v; - emit_lsptr(as, PPCI_LWZ, dest, v, RSET_GPR); - } else { - if (guarded) { - asm_guardcc(as, ir->o == IR_UREFC ? CC_NE : CC_EQ); - emit_ai(as, PPCI_CMPWI, RID_TMP, 1); - } - if (ir->o == IR_UREFC) - emit_tai(as, PPCI_ADDI, dest, dest, (int32_t)offsetof(GCupval, tv)); - else - emit_tai(as, PPCI_LWZ, dest, dest, (int32_t)offsetof(GCupval, v)); - if (guarded) - emit_tai(as, PPCI_LBZ, RID_TMP, dest, (int32_t)offsetof(GCupval, closed)); - if (irref_isk(ir->op1)) { - GCfunc *fn = ir_kfunc(IR(ir->op1)); - int32_t k = (int32_t)gcrefu(fn->l.uvptr[(ir->op2 >> 8)]); - emit_loadi(as, dest, k); - } else { - emit_tai(as, PPCI_LWZ, dest, ra_alloc1(as, ir->op1, RSET_GPR), - (int32_t)offsetof(GCfuncL, uvptr) + 4*(int32_t)(ir->op2 >> 8)); - } - } -} - -static void asm_fref(ASMState *as, IRIns *ir) -{ - UNUSED(as); UNUSED(ir); - lj_assertA(!ra_used(ir), "unfused FREF"); -} - -static void asm_strref(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - IRRef ref = ir->op2, refk = ir->op1; - int32_t ofs = (int32_t)sizeof(GCstr); - Reg r; - if (irref_isk(ref)) { - IRRef tmp = refk; refk = ref; ref = tmp; - } else if (!irref_isk(refk)) { - Reg right, left = ra_alloc1(as, ir->op1, RSET_GPR); - IRIns *irr = IR(ir->op2); - if (ra_hasreg(irr->r)) { - ra_noweak(as, irr->r); - right = irr->r; - } else if (mayfuse(as, irr->op2) && - irr->o == IR_ADD && irref_isk(irr->op2) && - checki16(ofs + IR(irr->op2)->i)) { - ofs += IR(irr->op2)->i; - right = ra_alloc1(as, irr->op1, rset_exclude(RSET_GPR, left)); - } else { - right = ra_allocref(as, ir->op2, rset_exclude(RSET_GPR, left)); - } - emit_tai(as, PPCI_ADDI, dest, dest, ofs); - emit_tab(as, PPCI_ADD, dest, left, right); - return; - } - r = ra_alloc1(as, ref, RSET_GPR); - ofs += IR(refk)->i; - if (checki16(ofs)) - emit_tai(as, PPCI_ADDI, dest, r, ofs); - else - emit_tab(as, PPCI_ADD, dest, r, - ra_allock(as, ofs, rset_exclude(RSET_GPR, r))); -} - -/* -- Loads and stores ---------------------------------------------------- */ - -static PPCIns asm_fxloadins(ASMState *as, IRIns *ir) -{ - UNUSED(as); - switch (irt_type(ir->t)) { - case IRT_I8: return PPCI_LBZ; /* Needs sign-extension. */ - case IRT_U8: return PPCI_LBZ; - case IRT_I16: return PPCI_LHA; - case IRT_U16: return PPCI_LHZ; - case IRT_NUM: lj_assertA(!LJ_SOFTFP, "unsplit FP op"); return PPCI_LFD; - case IRT_FLOAT: if (!LJ_SOFTFP) return PPCI_LFS; - default: return PPCI_LWZ; - } -} - -static PPCIns asm_fxstoreins(ASMState *as, IRIns *ir) -{ - UNUSED(as); - switch (irt_type(ir->t)) { - case IRT_I8: case IRT_U8: return PPCI_STB; - case IRT_I16: case IRT_U16: return PPCI_STH; - case IRT_NUM: lj_assertA(!LJ_SOFTFP, "unsplit FP op"); return PPCI_STFD; - case IRT_FLOAT: if (!LJ_SOFTFP) return PPCI_STFS; - default: return PPCI_STW; - } -} - -static void asm_fload(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - PPCIns pi = asm_fxloadins(as, ir); - Reg idx; - int32_t ofs; - if (ir->op1 == REF_NIL) { /* FLOAD from GG_State with offset. */ - idx = RID_JGL; - ofs = (ir->op2 << 2) - 32768 - GG_OFS(g); - } else { - idx = ra_alloc1(as, ir->op1, RSET_GPR); - if (ir->op2 == IRFL_TAB_ARRAY) { - ofs = asm_fuseabase(as, ir->op1); - if (ofs) { /* Turn the t->array load into an add for colocated arrays. */ - emit_tai(as, PPCI_ADDI, dest, idx, ofs); - return; - } - } - ofs = field_ofs[ir->op2]; - } - lj_assertA(!irt_isi8(ir->t), "unsupported FLOAD I8"); - emit_tai(as, pi, dest, idx, ofs); -} - -static void asm_fstore(ASMState *as, IRIns *ir) -{ - if (ir->r != RID_SINK) { - Reg src = ra_alloc1(as, ir->op2, RSET_GPR); - IRIns *irf = IR(ir->op1); - Reg idx = ra_alloc1(as, irf->op1, rset_exclude(RSET_GPR, src)); - int32_t ofs = field_ofs[irf->op2]; - PPCIns pi = asm_fxstoreins(as, ir); - emit_tai(as, pi, src, idx, ofs); - } -} - -static void asm_xload(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, - (!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR); - lj_assertA(!(ir->op2 & IRXLOAD_UNALIGNED), "unaligned XLOAD"); - if (irt_isi8(ir->t)) - emit_as(as, PPCI_EXTSB, dest, dest); - asm_fusexref(as, asm_fxloadins(as, ir), dest, ir->op1, RSET_GPR, 0); -} - -static void asm_xstore_(ASMState *as, IRIns *ir, int32_t ofs) -{ - IRIns *irb; - if (ir->r == RID_SINK) - return; - if (ofs == 0 && mayfuse(as, ir->op2) && (irb = IR(ir->op2))->o == IR_BSWAP && - ra_noreg(irb->r) && (irt_isint(ir->t) || irt_isu32(ir->t))) { - /* Fuse BSWAP with XSTORE to stwbrx. */ - Reg src = ra_alloc1(as, irb->op1, RSET_GPR); - asm_fusexrefx(as, PPCI_STWBRX, src, ir->op1, rset_exclude(RSET_GPR, src)); - } else { - Reg src = ra_alloc1(as, ir->op2, - (!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR); - asm_fusexref(as, asm_fxstoreins(as, ir), src, ir->op1, - rset_exclude(RSET_GPR, src), ofs); - } -} - -#define asm_xstore(as, ir) asm_xstore_(as, ir, 0) - -static void asm_ahuvload(ASMState *as, IRIns *ir) -{ - IRType1 t = ir->t; - Reg dest = RID_NONE, type = RID_TMP, tmp = RID_TMP, idx; - RegSet allow = RSET_GPR; - int32_t ofs = AHUREF_LSX; - if (LJ_SOFTFP && (ir+1)->o == IR_HIOP) { - t.irt = IRT_NUM; - if (ra_used(ir+1)) { - type = ra_dest(as, ir+1, allow); - rset_clear(allow, type); - } - ofs = 0; - } - if (ra_used(ir)) { - lj_assertA((LJ_SOFTFP ? 0 : irt_isnum(ir->t)) || - irt_isint(ir->t) || irt_isaddr(ir->t), - "bad load type %d", irt_type(ir->t)); - if (LJ_SOFTFP || !irt_isnum(t)) ofs = 0; - dest = ra_dest(as, ir, (!LJ_SOFTFP && irt_isnum(t)) ? RSET_FPR : allow); - rset_clear(allow, dest); - } - idx = asm_fuseahuref(as, ir->op1, &ofs, allow); - if (ir->o == IR_VLOAD) { - ofs = ofs != AHUREF_LSX ? ofs + 8 * ir->op2 : - ir->op2 ? 8 * ir->op2 : AHUREF_LSX; - } - if (irt_isnum(t)) { - Reg tisnum = ra_allock(as, (int32_t)LJ_TISNUM, rset_exclude(allow, idx)); - asm_guardcc(as, CC_GE); - emit_ab(as, PPCI_CMPLW, type, tisnum); - if (ra_hasreg(dest)) { - if (!LJ_SOFTFP && ofs == AHUREF_LSX) { - tmp = ra_scratch(as, rset_exclude(rset_exclude(RSET_GPR, - (idx&255)), (idx>>8))); - emit_fab(as, PPCI_LFDX, dest, (idx&255), tmp); - } else { - emit_fai(as, LJ_SOFTFP ? PPCI_LWZ : PPCI_LFD, dest, idx, - ofs+4*LJ_SOFTFP); - } - } - } else { - asm_guardcc(as, CC_NE); - emit_ai(as, PPCI_CMPWI, type, irt_toitype(t)); - if (ra_hasreg(dest)) emit_tai(as, PPCI_LWZ, dest, idx, ofs+4); - } - if (ofs == AHUREF_LSX) { - emit_tab(as, PPCI_LWZX, type, (idx&255), tmp); - emit_slwi(as, tmp, (idx>>8), 3); - } else { - emit_tai(as, PPCI_LWZ, type, idx, ofs); - } -} - -static void asm_ahustore(ASMState *as, IRIns *ir) -{ - RegSet allow = RSET_GPR; - Reg idx, src = RID_NONE, type = RID_NONE; - int32_t ofs = AHUREF_LSX; - if (ir->r == RID_SINK) - return; - if (!LJ_SOFTFP && irt_isnum(ir->t)) { - src = ra_alloc1(as, ir->op2, RSET_FPR); - } else { - if (!irt_ispri(ir->t)) { - src = ra_alloc1(as, ir->op2, allow); - rset_clear(allow, src); - ofs = 0; - } - if (LJ_SOFTFP && (ir+1)->o == IR_HIOP) - type = ra_alloc1(as, (ir+1)->op2, allow); - else - type = ra_allock(as, (int32_t)irt_toitype(ir->t), allow); - rset_clear(allow, type); - } - idx = asm_fuseahuref(as, ir->op1, &ofs, allow); - if (!LJ_SOFTFP && irt_isnum(ir->t)) { - if (ofs == AHUREF_LSX) { - emit_fab(as, PPCI_STFDX, src, (idx&255), RID_TMP); - emit_slwi(as, RID_TMP, (idx>>8), 3); - } else { - emit_fai(as, PPCI_STFD, src, idx, ofs); - } - } else { - if (ra_hasreg(src)) - emit_tai(as, PPCI_STW, src, idx, ofs+4); - if (ofs == AHUREF_LSX) { - emit_tab(as, PPCI_STWX, type, (idx&255), RID_TMP); - emit_slwi(as, RID_TMP, (idx>>8), 3); - } else { - emit_tai(as, PPCI_STW, type, idx, ofs); - } - } -} - -static void asm_sload(ASMState *as, IRIns *ir) -{ - int32_t ofs = 8*((int32_t)ir->op1-1) + ((ir->op2 & IRSLOAD_FRAME) ? 0 : 4); - IRType1 t = ir->t; - Reg dest = RID_NONE, type = RID_NONE, base; - RegSet allow = RSET_GPR; - int hiop = (LJ_SOFTFP && (ir+1)->o == IR_HIOP); - if (hiop) - t.irt = IRT_NUM; - lj_assertA(!(ir->op2 & IRSLOAD_PARENT), - "bad parent SLOAD"); /* Handled by asm_head_side(). */ - lj_assertA(irt_isguard(ir->t) || !(ir->op2 & IRSLOAD_TYPECHECK), - "inconsistent SLOAD variant"); - lj_assertA(LJ_DUALNUM || - !irt_isint(t) || - (ir->op2 & (IRSLOAD_CONVERT|IRSLOAD_FRAME|IRSLOAD_KEYINDEX)), - "bad SLOAD type"); -#if LJ_SOFTFP - lj_assertA(!(ir->op2 & IRSLOAD_CONVERT), - "unsplit SLOAD convert"); /* Handled by LJ_SOFTFP SPLIT. */ - if (hiop && ra_used(ir+1)) { - type = ra_dest(as, ir+1, allow); - rset_clear(allow, type); - } -#else - if ((ir->op2 & IRSLOAD_CONVERT) && irt_isguard(t) && irt_isint(t)) { - dest = ra_scratch(as, RSET_FPR); - asm_tointg(as, ir, dest); - t.irt = IRT_NUM; /* Continue with a regular number type check. */ - } else -#endif - if (ra_used(ir)) { - lj_assertA(irt_isnum(t) || irt_isint(t) || irt_isaddr(t), - "bad SLOAD type %d", irt_type(ir->t)); - dest = ra_dest(as, ir, (!LJ_SOFTFP && irt_isnum(t)) ? RSET_FPR : allow); - rset_clear(allow, dest); - base = ra_alloc1(as, REF_BASE, allow); - rset_clear(allow, base); - if (!LJ_SOFTFP && (ir->op2 & IRSLOAD_CONVERT)) { - if (irt_isint(t)) { - emit_tai(as, PPCI_LWZ, dest, RID_SP, SPOFS_TMPLO); - dest = ra_scratch(as, RSET_FPR); - emit_fai(as, PPCI_STFD, dest, RID_SP, SPOFS_TMP); - emit_fb(as, PPCI_FCTIWZ, dest, dest); - t.irt = IRT_NUM; /* Check for original type. */ - } else { - Reg tmp = ra_scratch(as, allow); - Reg hibias = ra_allock(as, 0x43300000, rset_clear(allow, tmp)); - Reg fbias = ra_scratch(as, rset_exclude(RSET_FPR, dest)); - emit_fab(as, PPCI_FSUB, dest, dest, fbias); - emit_fai(as, PPCI_LFD, dest, RID_SP, SPOFS_TMP); - emit_lsptr(as, PPCI_LFS, (fbias & 31), - (void *)&as->J->k32[LJ_K32_2P52_2P31], - rset_clear(allow, hibias)); - emit_tai(as, PPCI_STW, tmp, RID_SP, SPOFS_TMPLO); - emit_tai(as, PPCI_STW, hibias, RID_SP, SPOFS_TMPHI); - emit_asi(as, PPCI_XORIS, tmp, tmp, 0x8000); - dest = tmp; - t.irt = IRT_INT; /* Check for original type. */ - } - } - goto dotypecheck; - } - base = ra_alloc1(as, REF_BASE, allow); - rset_clear(allow, base); -dotypecheck: - if (irt_isnum(t)) { - if ((ir->op2 & IRSLOAD_TYPECHECK)) { - Reg tisnum = ra_allock(as, (int32_t)LJ_TISNUM, allow); - asm_guardcc(as, CC_GE); -#if !LJ_SOFTFP - type = RID_TMP; -#endif - emit_ab(as, PPCI_CMPLW, type, tisnum); - } - if (ra_hasreg(dest)) emit_fai(as, LJ_SOFTFP ? PPCI_LWZ : PPCI_LFD, dest, - base, ofs-(LJ_SOFTFP?0:4)); - } else { - if ((ir->op2 & IRSLOAD_TYPECHECK)) { - asm_guardcc(as, CC_NE); - if ((ir->op2 & IRSLOAD_KEYINDEX)) { - emit_ai(as, PPCI_CMPWI, RID_TMP, (LJ_KEYINDEX & 0xffff)); - emit_asi(as, PPCI_XORIS, RID_TMP, RID_TMP, (LJ_KEYINDEX >> 16)); - } else { - emit_ai(as, PPCI_CMPWI, RID_TMP, irt_toitype(t)); - } - type = RID_TMP; - } - if (ra_hasreg(dest)) emit_tai(as, PPCI_LWZ, dest, base, ofs); - } - if (ra_hasreg(type)) emit_tai(as, PPCI_LWZ, type, base, ofs-4); -} - -/* -- Allocations --------------------------------------------------------- */ - -#if LJ_HASFFI -static void asm_cnew(ASMState *as, IRIns *ir) -{ - CTState *cts = ctype_ctsG(J2G(as->J)); - CTypeID id = (CTypeID)IR(ir->op1)->i; - CTSize sz; - CTInfo info = lj_ctype_info(cts, id, &sz); - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_mem_newgco]; - IRRef args[4]; - RegSet drop = RSET_SCRATCH; - lj_assertA(sz != CTSIZE_INVALID || (ir->o == IR_CNEW && ir->op2 != REF_NIL), - "bad CNEW/CNEWI operands"); - - as->gcsteps++; - if (ra_hasreg(ir->r)) - rset_clear(drop, ir->r); /* Dest reg handled below. */ - ra_evictset(as, drop); - if (ra_used(ir)) - ra_destreg(as, ir, RID_RET); /* GCcdata * */ - - /* Initialize immutable cdata object. */ - if (ir->o == IR_CNEWI) { - RegSet allow = (RSET_GPR & ~RSET_SCRATCH); - int32_t ofs = sizeof(GCcdata); - lj_assertA(sz == 4 || sz == 8, "bad CNEWI size %d", sz); - if (sz == 8) { - ofs += 4; - lj_assertA((ir+1)->o == IR_HIOP, "expected HIOP for CNEWI"); - } - for (;;) { - Reg r = ra_alloc1(as, ir->op2, allow); - emit_tai(as, PPCI_STW, r, RID_RET, ofs); - rset_clear(allow, r); - if (ofs == sizeof(GCcdata)) break; - ofs -= 4; ir++; - } - } else if (ir->op2 != REF_NIL) { /* Create VLA/VLS/aligned cdata. */ - ci = &lj_ir_callinfo[IRCALL_lj_cdata_newv]; - args[0] = ASMREF_L; /* lua_State *L */ - args[1] = ir->op1; /* CTypeID id */ - args[2] = ir->op2; /* CTSize sz */ - args[3] = ASMREF_TMP1; /* CTSize align */ - asm_gencall(as, ci, args); - emit_loadi(as, ra_releasetmp(as, ASMREF_TMP1), (int32_t)ctype_align(info)); - return; - } - - /* Initialize gct and ctypeid. lj_mem_newgco() already sets marked. */ - emit_tai(as, PPCI_STB, RID_RET+1, RID_RET, offsetof(GCcdata, gct)); - emit_tai(as, PPCI_STH, RID_TMP, RID_RET, offsetof(GCcdata, ctypeid)); - emit_ti(as, PPCI_LI, RID_RET+1, ~LJ_TCDATA); - emit_ti(as, PPCI_LI, RID_TMP, id); /* Lower 16 bit used. Sign-ext ok. */ - args[0] = ASMREF_L; /* lua_State *L */ - args[1] = ASMREF_TMP1; /* MSize size */ - asm_gencall(as, ci, args); - ra_allockreg(as, (int32_t)(sz+sizeof(GCcdata)), - ra_releasetmp(as, ASMREF_TMP1)); -} -#endif - -/* -- Write barriers ------------------------------------------------------ */ - -static void asm_tbar(ASMState *as, IRIns *ir) -{ - Reg tab = ra_alloc1(as, ir->op1, RSET_GPR); - Reg mark = ra_scratch(as, rset_exclude(RSET_GPR, tab)); - Reg link = RID_TMP; - MCLabel l_end = emit_label(as); - emit_tai(as, PPCI_STW, link, tab, (int32_t)offsetof(GCtab, gclist)); - emit_tai(as, PPCI_STB, mark, tab, (int32_t)offsetof(GCtab, marked)); - emit_setgl(as, tab, gc.grayagain); - lj_assertA(LJ_GC_BLACK == 0x04, "bad LJ_GC_BLACK"); - emit_rot(as, PPCI_RLWINM, mark, mark, 0, 30, 28); /* Clear black bit. */ - emit_getgl(as, link, gc.grayagain); - emit_condbranch(as, PPCI_BC|PPCF_Y, CC_EQ, l_end); - emit_asi(as, PPCI_ANDIDOT, RID_TMP, mark, LJ_GC_BLACK); - emit_tai(as, PPCI_LBZ, mark, tab, (int32_t)offsetof(GCtab, marked)); -} - -static void asm_obar(ASMState *as, IRIns *ir) -{ - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_barrieruv]; - IRRef args[2]; - MCLabel l_end; - Reg obj, val, tmp; - /* No need for other object barriers (yet). */ - lj_assertA(IR(ir->op1)->o == IR_UREFC, "bad OBAR type"); - ra_evictset(as, RSET_SCRATCH); - l_end = emit_label(as); - args[0] = ASMREF_TMP1; /* global_State *g */ - args[1] = ir->op1; /* TValue *tv */ - asm_gencall(as, ci, args); - emit_tai(as, PPCI_ADDI, ra_releasetmp(as, ASMREF_TMP1), RID_JGL, -32768); - obj = IR(ir->op1)->r; - tmp = ra_scratch(as, rset_exclude(RSET_GPR, obj)); - emit_condbranch(as, PPCI_BC|PPCF_Y, CC_EQ, l_end); - emit_asi(as, PPCI_ANDIDOT, tmp, tmp, LJ_GC_BLACK); - emit_condbranch(as, PPCI_BC, CC_EQ, l_end); - emit_asi(as, PPCI_ANDIDOT, RID_TMP, RID_TMP, LJ_GC_WHITES); - val = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, obj)); - emit_tai(as, PPCI_LBZ, tmp, obj, - (int32_t)offsetof(GCupval, marked)-(int32_t)offsetof(GCupval, tv)); - emit_tai(as, PPCI_LBZ, RID_TMP, val, (int32_t)offsetof(GChead, marked)); -} - -/* -- Arithmetic and logic operations ------------------------------------- */ - -#if !LJ_SOFTFP -static void asm_fparith(ASMState *as, IRIns *ir, PPCIns pi) -{ - Reg dest = ra_dest(as, ir, RSET_FPR); - Reg right, left = ra_alloc2(as, ir, RSET_FPR); - right = (left >> 8); left &= 255; - if (pi == PPCI_FMUL) - emit_fac(as, pi, dest, left, right); - else - emit_fab(as, pi, dest, left, right); -} - -static void asm_fpunary(ASMState *as, IRIns *ir, PPCIns pi) -{ - Reg dest = ra_dest(as, ir, RSET_FPR); - Reg left = ra_hintalloc(as, ir->op1, dest, RSET_FPR); - emit_fb(as, pi, dest, left); -} - -static void asm_fpmath(ASMState *as, IRIns *ir) -{ - if (ir->op2 == IRFPM_SQRT && (as->flags & JIT_F_SQRT)) - asm_fpunary(as, ir, PPCI_FSQRT); - else - asm_callid(as, ir, IRCALL_lj_vm_floor + ir->op2); -} -#endif - -static void asm_add(ASMState *as, IRIns *ir) -{ -#if !LJ_SOFTFP - if (irt_isnum(ir->t)) { - if (!asm_fusemadd(as, ir, PPCI_FMADD, PPCI_FMADD)) - asm_fparith(as, ir, PPCI_FADD); - } else -#endif - { - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg right, left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); - PPCIns pi; - if (irref_isk(ir->op2)) { - int32_t k = IR(ir->op2)->i; - if (checki16(k)) { - pi = PPCI_ADDI; - /* May fail due to spills/restores above, but simplifies the logic. */ - if (as->flagmcp == as->mcp) { - as->flagmcp = NULL; - as->mcp++; - pi = PPCI_ADDICDOT; - } - emit_tai(as, pi, dest, left, k); - return; - } else if ((k & 0xffff) == 0) { - emit_tai(as, PPCI_ADDIS, dest, left, (k >> 16)); - return; - } else if (!as->sectref) { - emit_tai(as, PPCI_ADDIS, dest, dest, (k + 32768) >> 16); - emit_tai(as, PPCI_ADDI, dest, left, k); - return; - } - } - pi = PPCI_ADD; - /* May fail due to spills/restores above, but simplifies the logic. */ - if (as->flagmcp == as->mcp) { - as->flagmcp = NULL; - as->mcp++; - pi |= PPCF_DOT; - } - right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); - emit_tab(as, pi, dest, left, right); - } -} - -static void asm_sub(ASMState *as, IRIns *ir) -{ -#if !LJ_SOFTFP - if (irt_isnum(ir->t)) { - if (!asm_fusemadd(as, ir, PPCI_FMSUB, PPCI_FNMSUB)) - asm_fparith(as, ir, PPCI_FSUB); - } else -#endif - { - PPCIns pi = PPCI_SUBF; - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left, right; - if (irref_isk(ir->op1)) { - int32_t k = IR(ir->op1)->i; - if (checki16(k)) { - right = ra_alloc1(as, ir->op2, RSET_GPR); - emit_tai(as, PPCI_SUBFIC, dest, right, k); - return; - } - } - /* May fail due to spills/restores above, but simplifies the logic. */ - if (as->flagmcp == as->mcp) { - as->flagmcp = NULL; - as->mcp++; - pi |= PPCF_DOT; - } - left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); - right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); - emit_tab(as, pi, dest, right, left); /* Subtract right _from_ left. */ - } -} - -static void asm_mul(ASMState *as, IRIns *ir) -{ -#if !LJ_SOFTFP - if (irt_isnum(ir->t)) { - asm_fparith(as, ir, PPCI_FMUL); - } else -#endif - { - PPCIns pi = PPCI_MULLW; - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg right, left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); - if (irref_isk(ir->op2)) { - int32_t k = IR(ir->op2)->i; - if (checki16(k)) { - emit_tai(as, PPCI_MULLI, dest, left, k); - return; - } - } - /* May fail due to spills/restores above, but simplifies the logic. */ - if (as->flagmcp == as->mcp) { - as->flagmcp = NULL; - as->mcp++; - pi |= PPCF_DOT; - } - right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); - emit_tab(as, pi, dest, left, right); - } -} - -#define asm_fpdiv(as, ir) asm_fparith(as, ir, PPCI_FDIV) - -static void asm_neg(ASMState *as, IRIns *ir) -{ -#if !LJ_SOFTFP - if (irt_isnum(ir->t)) { - asm_fpunary(as, ir, PPCI_FNEG); - } else -#endif - { - Reg dest, left; - PPCIns pi = PPCI_NEG; - if (as->flagmcp == as->mcp) { - as->flagmcp = NULL; - as->mcp++; - pi |= PPCF_DOT; - } - dest = ra_dest(as, ir, RSET_GPR); - left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); - emit_tab(as, pi, dest, left, 0); - } -} - -#define asm_abs(as, ir) asm_fpunary(as, ir, PPCI_FABS) - -static void asm_arithov(ASMState *as, IRIns *ir, PPCIns pi) -{ - Reg dest, left, right; - if (as->flagmcp == as->mcp) { - as->flagmcp = NULL; - as->mcp++; - } - asm_guardcc(as, CC_SO); - dest = ra_dest(as, ir, RSET_GPR); - left = ra_alloc2(as, ir, RSET_GPR); - right = (left >> 8); left &= 255; - if (pi == PPCI_SUBFO) { Reg tmp = left; left = right; right = tmp; } - emit_tab(as, pi|PPCF_DOT, dest, left, right); -} - -#define asm_addov(as, ir) asm_arithov(as, ir, PPCI_ADDO) -#define asm_subov(as, ir) asm_arithov(as, ir, PPCI_SUBFO) -#define asm_mulov(as, ir) asm_arithov(as, ir, PPCI_MULLWO) - -#if LJ_HASFFI -static void asm_add64(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg right, left = ra_alloc1(as, ir->op1, RSET_GPR); - PPCIns pi = PPCI_ADDE; - if (irref_isk(ir->op2)) { - int32_t k = IR(ir->op2)->i; - if (k == 0) - pi = PPCI_ADDZE; - else if (k == -1) - pi = PPCI_ADDME; - else - goto needright; - right = 0; - } else { - needright: - right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); - } - emit_tab(as, pi, dest, left, right); - ir--; - dest = ra_dest(as, ir, RSET_GPR); - left = ra_alloc1(as, ir->op1, RSET_GPR); - if (irref_isk(ir->op2)) { - int32_t k = IR(ir->op2)->i; - if (checki16(k)) { - emit_tai(as, PPCI_ADDIC, dest, left, k); - return; - } - } - right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); - emit_tab(as, PPCI_ADDC, dest, left, right); -} - -static void asm_sub64(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left, right = ra_alloc1(as, ir->op2, RSET_GPR); - PPCIns pi = PPCI_SUBFE; - if (irref_isk(ir->op1)) { - int32_t k = IR(ir->op1)->i; - if (k == 0) - pi = PPCI_SUBFZE; - else if (k == -1) - pi = PPCI_SUBFME; - else - goto needleft; - left = 0; - } else { - needleft: - left = ra_alloc1(as, ir->op1, rset_exclude(RSET_GPR, right)); - } - emit_tab(as, pi, dest, right, left); /* Subtract right _from_ left. */ - ir--; - dest = ra_dest(as, ir, RSET_GPR); - right = ra_alloc1(as, ir->op2, RSET_GPR); - if (irref_isk(ir->op1)) { - int32_t k = IR(ir->op1)->i; - if (checki16(k)) { - emit_tai(as, PPCI_SUBFIC, dest, right, k); - return; - } - } - left = ra_alloc1(as, ir->op1, rset_exclude(RSET_GPR, right)); - emit_tab(as, PPCI_SUBFC, dest, right, left); -} - -static void asm_neg64(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg left = ra_alloc1(as, ir->op1, RSET_GPR); - emit_tab(as, PPCI_SUBFZE, dest, left, 0); - ir--; - dest = ra_dest(as, ir, RSET_GPR); - left = ra_alloc1(as, ir->op1, RSET_GPR); - emit_tai(as, PPCI_SUBFIC, dest, left, 0); -} -#endif - -static void asm_bnot(ASMState *as, IRIns *ir) -{ - Reg dest, left, right; - PPCIns pi = PPCI_NOR; - if (as->flagmcp == as->mcp) { - as->flagmcp = NULL; - as->mcp++; - pi |= PPCF_DOT; - } - dest = ra_dest(as, ir, RSET_GPR); - if (mayfuse(as, ir->op1)) { - IRIns *irl = IR(ir->op1); - if (irl->o == IR_BAND) - pi ^= (PPCI_NOR ^ PPCI_NAND); - else if (irl->o == IR_BXOR) - pi ^= (PPCI_NOR ^ PPCI_EQV); - else if (irl->o != IR_BOR) - goto nofuse; - left = ra_hintalloc(as, irl->op1, dest, RSET_GPR); - right = ra_alloc1(as, irl->op2, rset_exclude(RSET_GPR, left)); - } else { -nofuse: - left = right = ra_hintalloc(as, ir->op1, dest, RSET_GPR); - } - emit_asb(as, pi, dest, left, right); -} - -static void asm_bswap(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - IRIns *irx; - if (mayfuse(as, ir->op1) && (irx = IR(ir->op1))->o == IR_XLOAD && - ra_noreg(irx->r) && (irt_isint(irx->t) || irt_isu32(irx->t))) { - /* Fuse BSWAP with XLOAD to lwbrx. */ - asm_fusexrefx(as, PPCI_LWBRX, dest, irx->op1, RSET_GPR); - } else { - Reg left = ra_alloc1(as, ir->op1, RSET_GPR); - Reg tmp = dest; - if (tmp == left) { - tmp = RID_TMP; - emit_mr(as, dest, RID_TMP); - } - emit_rot(as, PPCI_RLWIMI, tmp, left, 24, 16, 23); - emit_rot(as, PPCI_RLWIMI, tmp, left, 24, 0, 7); - emit_rotlwi(as, tmp, left, 8); - } -} - -/* Fuse BAND with contiguous bitmask and a shift to rlwinm. */ -static void asm_fuseandsh(ASMState *as, PPCIns pi, int32_t mask, IRRef ref) -{ - IRIns *ir; - Reg left; - if (mayfuse(as, ref) && (ir = IR(ref), ra_noreg(ir->r)) && - irref_isk(ir->op2) && ir->o >= IR_BSHL && ir->o <= IR_BROR) { - int32_t sh = (IR(ir->op2)->i & 31); - switch (ir->o) { - case IR_BSHL: - if ((mask & ((1u<>sh))) goto nofuse; - sh = ((32-sh)&31); - break; - case IR_BROL: - break; - default: - goto nofuse; - } - left = ra_alloc1(as, ir->op1, RSET_GPR); - *--as->mcp = pi | PPCF_T(left) | PPCF_B(sh); - return; - } -nofuse: - left = ra_alloc1(as, ref, RSET_GPR); - *--as->mcp = pi | PPCF_T(left); -} - -static void asm_band(ASMState *as, IRIns *ir) -{ - Reg dest, left, right; - IRRef lref = ir->op1; - PPCIns dot = 0; - IRRef op2; - if (as->flagmcp == as->mcp) { - as->flagmcp = NULL; - as->mcp++; - dot = PPCF_DOT; - } - dest = ra_dest(as, ir, RSET_GPR); - if (irref_isk(ir->op2)) { - int32_t k = IR(ir->op2)->i; - if (k) { - /* First check for a contiguous bitmask as used by rlwinm. */ - uint32_t s1 = lj_ffs((uint32_t)k); - uint32_t k1 = ((uint32_t)k >> s1); - if ((k1 & (k1+1)) == 0) { - asm_fuseandsh(as, PPCI_RLWINM|dot | PPCF_A(dest) | - PPCF_MB(31-lj_fls((uint32_t)k)) | PPCF_ME(31-s1), - k, lref); - return; - } - if (~(uint32_t)k) { - uint32_t s2 = lj_ffs(~(uint32_t)k); - uint32_t k2 = (~(uint32_t)k >> s2); - if ((k2 & (k2+1)) == 0) { - asm_fuseandsh(as, PPCI_RLWINM|dot | PPCF_A(dest) | - PPCF_MB(32-s2) | PPCF_ME(30-lj_fls(~(uint32_t)k)), - k, lref); - return; - } - } - } - if (checku16(k)) { - left = ra_alloc1(as, lref, RSET_GPR); - emit_asi(as, PPCI_ANDIDOT, dest, left, k); - return; - } else if ((k & 0xffff) == 0) { - left = ra_alloc1(as, lref, RSET_GPR); - emit_asi(as, PPCI_ANDISDOT, dest, left, (k >> 16)); - return; - } - } - op2 = ir->op2; - if (mayfuse(as, op2) && IR(op2)->o == IR_BNOT && ra_noreg(IR(op2)->r)) { - dot ^= (PPCI_AND ^ PPCI_ANDC); - op2 = IR(op2)->op1; - } - left = ra_hintalloc(as, lref, dest, RSET_GPR); - right = ra_alloc1(as, op2, rset_exclude(RSET_GPR, left)); - emit_asb(as, PPCI_AND ^ dot, dest, left, right); -} - -static void asm_bitop(ASMState *as, IRIns *ir, PPCIns pi, PPCIns pik) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg right, left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); - if (irref_isk(ir->op2)) { - int32_t k = IR(ir->op2)->i; - Reg tmp = left; - if ((checku16(k) || (k & 0xffff) == 0) || (tmp = dest, !as->sectref)) { - if (!checku16(k)) { - emit_asi(as, pik ^ (PPCI_ORI ^ PPCI_ORIS), dest, tmp, (k >> 16)); - if ((k & 0xffff) == 0) return; - } - emit_asi(as, pik, dest, left, k); - return; - } - } - /* May fail due to spills/restores above, but simplifies the logic. */ - if (as->flagmcp == as->mcp) { - as->flagmcp = NULL; - as->mcp++; - pi |= PPCF_DOT; - } - right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); - emit_asb(as, pi, dest, left, right); -} - -#define asm_bor(as, ir) asm_bitop(as, ir, PPCI_OR, PPCI_ORI) -#define asm_bxor(as, ir) asm_bitop(as, ir, PPCI_XOR, PPCI_XORI) - -static void asm_bitshift(ASMState *as, IRIns *ir, PPCIns pi, PPCIns pik) -{ - Reg dest, left; - Reg dot = 0; - if (as->flagmcp == as->mcp) { - as->flagmcp = NULL; - as->mcp++; - dot = PPCF_DOT; - } - dest = ra_dest(as, ir, RSET_GPR); - left = ra_alloc1(as, ir->op1, RSET_GPR); - if (irref_isk(ir->op2)) { /* Constant shifts. */ - int32_t shift = (IR(ir->op2)->i & 31); - if (pik == 0) /* SLWI */ - emit_rot(as, PPCI_RLWINM|dot, dest, left, shift, 0, 31-shift); - else if (pik == 1) /* SRWI */ - emit_rot(as, PPCI_RLWINM|dot, dest, left, (32-shift)&31, shift, 31); - else - emit_asb(as, pik|dot, dest, left, shift); - } else { - Reg right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); - emit_asb(as, pi|dot, dest, left, right); - } -} - -#define asm_bshl(as, ir) asm_bitshift(as, ir, PPCI_SLW, 0) -#define asm_bshr(as, ir) asm_bitshift(as, ir, PPCI_SRW, 1) -#define asm_bsar(as, ir) asm_bitshift(as, ir, PPCI_SRAW, PPCI_SRAWI) -#define asm_brol(as, ir) \ - asm_bitshift(as, ir, PPCI_RLWNM|PPCF_MB(0)|PPCF_ME(31), \ - PPCI_RLWINM|PPCF_MB(0)|PPCF_ME(31)) -#define asm_bror(as, ir) lj_assertA(0, "unexpected BROR") - -#if LJ_SOFTFP -static void asm_sfpmin_max(ASMState *as, IRIns *ir) -{ - CCallInfo ci = lj_ir_callinfo[IRCALL_softfp_cmp]; - IRRef args[4]; - MCLabel l_right, l_end; - Reg desthi = ra_dest(as, ir, RSET_GPR), destlo = ra_dest(as, ir+1, RSET_GPR); - Reg righthi, lefthi = ra_alloc2(as, ir, RSET_GPR); - Reg rightlo, leftlo = ra_alloc2(as, ir+1, RSET_GPR); - PPCCC cond = (IROp)ir->o == IR_MIN ? CC_EQ : CC_NE; - righthi = (lefthi >> 8); lefthi &= 255; - rightlo = (leftlo >> 8); leftlo &= 255; - args[0^LJ_BE] = ir->op1; args[1^LJ_BE] = (ir+1)->op1; - args[2^LJ_BE] = ir->op2; args[3^LJ_BE] = (ir+1)->op2; - l_end = emit_label(as); - if (desthi != righthi) emit_mr(as, desthi, righthi); - if (destlo != rightlo) emit_mr(as, destlo, rightlo); - l_right = emit_label(as); - if (l_end != l_right) emit_jmp(as, l_end); - if (desthi != lefthi) emit_mr(as, desthi, lefthi); - if (destlo != leftlo) emit_mr(as, destlo, leftlo); - if (l_right == as->mcp+1) { - cond ^= 4; l_right = l_end; ++as->mcp; - } - emit_condbranch(as, PPCI_BC, cond, l_right); - ra_evictset(as, RSET_SCRATCH); - emit_cmpi(as, RID_RET, 1); - asm_gencall(as, &ci, args); -} -#endif - -static void asm_min_max(ASMState *as, IRIns *ir, int ismax) -{ - if (!LJ_SOFTFP && irt_isnum(ir->t)) { - Reg dest = ra_dest(as, ir, RSET_FPR); - Reg tmp = dest; - Reg right, left = ra_alloc2(as, ir, RSET_FPR); - right = (left >> 8); left &= 255; - if (tmp == left || tmp == right) - tmp = ra_scratch(as, rset_exclude(rset_exclude(rset_exclude(RSET_FPR, - dest), left), right)); - emit_facb(as, PPCI_FSEL, dest, tmp, left, right); - emit_fab(as, PPCI_FSUB, tmp, ismax ? left : right, ismax ? right : left); - } else { - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg tmp1 = RID_TMP, tmp2 = dest; - Reg right, left = ra_alloc2(as, ir, RSET_GPR); - right = (left >> 8); left &= 255; - if (tmp2 == left || tmp2 == right) - tmp2 = ra_scratch(as, rset_exclude(rset_exclude(rset_exclude(RSET_GPR, - dest), left), right)); - emit_tab(as, PPCI_ADD, dest, tmp2, right); - emit_asb(as, ismax ? PPCI_ANDC : PPCI_AND, tmp2, tmp2, tmp1); - emit_tab(as, PPCI_SUBFE, tmp1, tmp1, tmp1); - emit_tab(as, PPCI_SUBFC, tmp2, tmp2, tmp1); - emit_asi(as, PPCI_XORIS, tmp2, right, 0x8000); - emit_asi(as, PPCI_XORIS, tmp1, left, 0x8000); - } -} - -#define asm_min(as, ir) asm_min_max(as, ir, 0) -#define asm_max(as, ir) asm_min_max(as, ir, 1) - -/* -- Comparisons --------------------------------------------------------- */ - -#define CC_UNSIGNED 0x08 /* Unsigned integer comparison. */ -#define CC_TWO 0x80 /* Check two flags for FP comparison. */ - -/* Map of comparisons to flags. ORDER IR. */ -static const uint8_t asm_compmap[IR_ABC+1] = { - /* op int cc FP cc */ - /* LT */ CC_GE + (CC_GE<<4), - /* GE */ CC_LT + (CC_LE<<4) + CC_TWO, - /* LE */ CC_GT + (CC_GE<<4) + CC_TWO, - /* GT */ CC_LE + (CC_LE<<4), - /* ULT */ CC_GE + CC_UNSIGNED + (CC_GT<<4) + CC_TWO, - /* UGE */ CC_LT + CC_UNSIGNED + (CC_LT<<4), - /* ULE */ CC_GT + CC_UNSIGNED + (CC_GT<<4), - /* UGT */ CC_LE + CC_UNSIGNED + (CC_LT<<4) + CC_TWO, - /* EQ */ CC_NE + (CC_NE<<4), - /* NE */ CC_EQ + (CC_EQ<<4), - /* ABC */ CC_LE + CC_UNSIGNED + (CC_LT<<4) + CC_TWO /* Same as UGT. */ -}; - -static void asm_intcomp_(ASMState *as, IRRef lref, IRRef rref, Reg cr, PPCCC cc) -{ - Reg right, left = ra_alloc1(as, lref, RSET_GPR); - if (irref_isk(rref)) { - int32_t k = IR(rref)->i; - if ((cc & CC_UNSIGNED) == 0) { /* Signed comparison with constant. */ - if (checki16(k)) { - emit_tai(as, PPCI_CMPWI, cr, left, k); - /* Signed comparison with zero and referencing previous ins? */ - if (k == 0 && lref == as->curins-1) - as->flagmcp = as->mcp; /* Allow elimination of the compare. */ - return; - } else if ((cc & 3) == (CC_EQ & 3)) { /* Use CMPLWI for EQ or NE. */ - if (checku16(k)) { - emit_tai(as, PPCI_CMPLWI, cr, left, k); - return; - } else if (!as->sectref && ra_noreg(IR(rref)->r)) { - emit_tai(as, PPCI_CMPLWI, cr, RID_TMP, k); - emit_asi(as, PPCI_XORIS, RID_TMP, left, (k >> 16)); - return; - } - } - } else { /* Unsigned comparison with constant. */ - if (checku16(k)) { - emit_tai(as, PPCI_CMPLWI, cr, left, k); - return; - } - } - } - right = ra_alloc1(as, rref, rset_exclude(RSET_GPR, left)); - emit_tab(as, (cc & CC_UNSIGNED) ? PPCI_CMPLW : PPCI_CMPW, cr, left, right); -} - -static void asm_comp(ASMState *as, IRIns *ir) -{ - PPCCC cc = asm_compmap[ir->o]; - if (!LJ_SOFTFP && irt_isnum(ir->t)) { - Reg right, left = ra_alloc2(as, ir, RSET_FPR); - right = (left >> 8); left &= 255; - asm_guardcc(as, (cc >> 4)); - if ((cc & CC_TWO)) - emit_tab(as, PPCI_CROR, ((cc>>4)&3), ((cc>>4)&3), (CC_EQ&3)); - emit_fab(as, PPCI_FCMPU, 0, left, right); - } else { - IRRef lref = ir->op1, rref = ir->op2; - if (irref_isk(lref) && !irref_isk(rref)) { - /* Swap constants to the right (only for ABC). */ - IRRef tmp = lref; lref = rref; rref = tmp; - if ((cc & 2) == 0) cc ^= 1; /* LT <-> GT, LE <-> GE */ - } - asm_guardcc(as, cc); - asm_intcomp_(as, lref, rref, 0, cc); - } -} - -#define asm_equal(as, ir) asm_comp(as, ir) - -#if LJ_SOFTFP -/* SFP comparisons. */ -static void asm_sfpcomp(ASMState *as, IRIns *ir) -{ - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_softfp_cmp]; - RegSet drop = RSET_SCRATCH; - Reg r; - IRRef args[4]; - args[0^LJ_BE] = ir->op1; args[1^LJ_BE] = (ir+1)->op1; - args[2^LJ_BE] = ir->op2; args[3^LJ_BE] = (ir+1)->op2; - - for (r = REGARG_FIRSTGPR; r <= REGARG_FIRSTGPR+3; r++) { - if (!rset_test(as->freeset, r) && - regcost_ref(as->cost[r]) == args[r-REGARG_FIRSTGPR]) - rset_clear(drop, r); - } - ra_evictset(as, drop); - asm_setupresult(as, ir, ci); - switch ((IROp)ir->o) { - case IR_ULT: - asm_guardcc(as, CC_EQ); - emit_ai(as, PPCI_CMPWI, RID_RET, 0); - case IR_ULE: - asm_guardcc(as, CC_EQ); - emit_ai(as, PPCI_CMPWI, RID_RET, 1); - break; - case IR_GE: case IR_GT: - asm_guardcc(as, CC_EQ); - emit_ai(as, PPCI_CMPWI, RID_RET, 2); - default: - asm_guardcc(as, (asm_compmap[ir->o] & 0xf)); - emit_ai(as, PPCI_CMPWI, RID_RET, 0); - break; - } - asm_gencall(as, ci, args); -} -#endif - -#if LJ_HASFFI -/* 64 bit integer comparisons. */ -static void asm_comp64(ASMState *as, IRIns *ir) -{ - PPCCC cc = asm_compmap[(ir-1)->o]; - if ((cc&3) == (CC_EQ&3)) { - asm_guardcc(as, cc); - emit_tab(as, (cc&4) ? PPCI_CRAND : PPCI_CROR, - (CC_EQ&3), (CC_EQ&3), 4+(CC_EQ&3)); - } else { - asm_guardcc(as, CC_EQ); - emit_tab(as, PPCI_CROR, (CC_EQ&3), (CC_EQ&3), ((cc^~(cc>>2))&1)); - emit_tab(as, (cc&4) ? PPCI_CRAND : PPCI_CRANDC, - (CC_EQ&3), (CC_EQ&3), 4+(cc&3)); - } - /* Loword comparison sets cr1 and is unsigned, except for equality. */ - asm_intcomp_(as, (ir-1)->op1, (ir-1)->op2, 4, - cc | ((cc&3) == (CC_EQ&3) ? 0 : CC_UNSIGNED)); - /* Hiword comparison sets cr0. */ - asm_intcomp_(as, ir->op1, ir->op2, 0, cc); - as->flagmcp = NULL; /* Doesn't work here. */ -} -#endif - -/* -- Split register ops -------------------------------------------------- */ - -/* Hiword op of a split 32/32 bit op. Previous op is be the loword op. */ -static void asm_hiop(ASMState *as, IRIns *ir) -{ - /* HIOP is marked as a store because it needs its own DCE logic. */ - int uselo = ra_used(ir-1), usehi = ra_used(ir); /* Loword/hiword used? */ - if (LJ_UNLIKELY(!(as->flags & JIT_F_OPT_DCE))) uselo = usehi = 1; -#if LJ_HASFFI || LJ_SOFTFP - if ((ir-1)->o == IR_CONV) { /* Conversions to/from 64 bit. */ - as->curins--; /* Always skip the CONV. */ -#if LJ_HASFFI && !LJ_SOFTFP - if (usehi || uselo) - asm_conv64(as, ir); - return; -#endif - } else if ((ir-1)->o <= IR_NE) { /* 64 bit integer comparisons. ORDER IR. */ - as->curins--; /* Always skip the loword comparison. */ -#if LJ_SOFTFP - if (!irt_isint(ir->t)) { - asm_sfpcomp(as, ir-1); - return; - } -#endif -#if LJ_HASFFI - asm_comp64(as, ir); -#endif - return; -#if LJ_SOFTFP - } else if ((ir-1)->o == IR_MIN || (ir-1)->o == IR_MAX) { - as->curins--; /* Always skip the loword min/max. */ - if (uselo || usehi) - asm_sfpmin_max(as, ir-1); - return; -#endif - } else if ((ir-1)->o == IR_XSTORE) { - as->curins--; /* Handle both stores here. */ - if ((ir-1)->r != RID_SINK) { - asm_xstore_(as, ir, 0); - asm_xstore_(as, ir-1, 4); - } - return; - } -#endif - if (!usehi) return; /* Skip unused hiword op for all remaining ops. */ - switch ((ir-1)->o) { -#if LJ_HASFFI - case IR_ADD: as->curins--; asm_add64(as, ir); break; - case IR_SUB: as->curins--; asm_sub64(as, ir); break; - case IR_NEG: as->curins--; asm_neg64(as, ir); break; - case IR_CNEWI: - /* Nothing to do here. Handled by lo op itself. */ - break; -#endif -#if LJ_SOFTFP - case IR_SLOAD: case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD: - case IR_STRTO: - if (!uselo) - ra_allocref(as, ir->op1, RSET_GPR); /* Mark lo op as used. */ - break; - case IR_ASTORE: case IR_HSTORE: case IR_USTORE: case IR_TOSTR: case IR_TMPREF: - /* Nothing to do here. Handled by lo op itself. */ - break; -#endif - case IR_CALLN: case IR_CALLL: case IR_CALLS: case IR_CALLXS: - if (!uselo) - ra_allocref(as, ir->op1, RID2RSET(RID_RETLO)); /* Mark lo op as used. */ - break; - default: lj_assertA(0, "bad HIOP for op %d", (ir-1)->o); break; - } -} - -/* -- Profiling ----------------------------------------------------------- */ - -static void asm_prof(ASMState *as, IRIns *ir) -{ - UNUSED(ir); - asm_guardcc(as, CC_NE); - emit_asi(as, PPCI_ANDIDOT, RID_TMP, RID_TMP, HOOK_PROFILE); - emit_lsglptr(as, PPCI_LBZ, RID_TMP, - (int32_t)offsetof(global_State, hookmask)); -} - -/* -- Stack handling ------------------------------------------------------ */ - -/* Check Lua stack size for overflow. Use exit handler as fallback. */ -static void asm_stack_check(ASMState *as, BCReg topslot, - IRIns *irp, RegSet allow, ExitNo exitno) -{ - /* Try to get an unused temp. register, otherwise spill/restore RID_RET*. */ - Reg tmp, pbase = irp ? (ra_hasreg(irp->r) ? irp->r : RID_TMP) : RID_BASE; - rset_clear(allow, pbase); - tmp = allow ? rset_pickbot(allow) : - (pbase == RID_RETHI ? RID_RETLO : RID_RETHI); - emit_condbranch(as, PPCI_BC, CC_LT, asm_exitstub_addr(as, exitno)); - if (allow == RSET_EMPTY) /* Restore temp. register. */ - emit_tai(as, PPCI_LWZ, tmp, RID_SP, SPOFS_TMPW); - else - ra_modified(as, tmp); - emit_ai(as, PPCI_CMPLWI, RID_TMP, (int32_t)(8*topslot)); - emit_tab(as, PPCI_SUBF, RID_TMP, pbase, tmp); - emit_tai(as, PPCI_LWZ, tmp, tmp, offsetof(lua_State, maxstack)); - if (pbase == RID_TMP) - emit_getgl(as, RID_TMP, jit_base); - emit_getgl(as, tmp, cur_L); - if (allow == RSET_EMPTY) /* Spill temp. register. */ - emit_tai(as, PPCI_STW, tmp, RID_SP, SPOFS_TMPW); -} - -/* Restore Lua stack from on-trace state. */ -static void asm_stack_restore(ASMState *as, SnapShot *snap) -{ - SnapEntry *map = &as->T->snapmap[snap->mapofs]; - SnapEntry *flinks = &as->T->snapmap[snap_nextofs(as->T, snap)-1]; - MSize n, nent = snap->nent; - /* Store the value of all modified slots to the Lua stack. */ - for (n = 0; n < nent; n++) { - SnapEntry sn = map[n]; - BCReg s = snap_slot(sn); - int32_t ofs = 8*((int32_t)s-1); - IRRef ref = snap_ref(sn); - IRIns *ir = IR(ref); - if ((sn & SNAP_NORESTORE)) - continue; - if (irt_isnum(ir->t)) { -#if LJ_SOFTFP - Reg tmp; - RegSet allow = rset_exclude(RSET_GPR, RID_BASE); - /* LJ_SOFTFP: must be a number constant. */ - lj_assertA(irref_isk(ref), "unsplit FP op"); - tmp = ra_allock(as, (int32_t)ir_knum(ir)->u32.lo, allow); - emit_tai(as, PPCI_STW, tmp, RID_BASE, ofs+(LJ_BE?4:0)); - if (rset_test(as->freeset, tmp+1)) allow = RID2RSET(tmp+1); - tmp = ra_allock(as, (int32_t)ir_knum(ir)->u32.hi, allow); - emit_tai(as, PPCI_STW, tmp, RID_BASE, ofs+(LJ_BE?0:4)); -#else - Reg src = ra_alloc1(as, ref, RSET_FPR); - emit_fai(as, PPCI_STFD, src, RID_BASE, ofs); -#endif - } else { - Reg type; - RegSet allow = rset_exclude(RSET_GPR, RID_BASE); - lj_assertA(irt_ispri(ir->t) || irt_isaddr(ir->t) || irt_isinteger(ir->t), - "restore of IR type %d", irt_type(ir->t)); - if (!irt_ispri(ir->t)) { - Reg src = ra_alloc1(as, ref, allow); - rset_clear(allow, src); - emit_tai(as, PPCI_STW, src, RID_BASE, ofs+4); - } - if ((sn & (SNAP_CONT|SNAP_FRAME))) { - if (s == 0) continue; /* Do not overwrite link to previous frame. */ - type = ra_allock(as, (int32_t)(*flinks--), allow); -#if LJ_SOFTFP - } else if ((sn & SNAP_SOFTFPNUM)) { - type = ra_alloc1(as, ref+1, rset_exclude(RSET_GPR, RID_BASE)); -#endif - } else if ((sn & SNAP_KEYINDEX)) { - type = ra_allock(as, (int32_t)LJ_KEYINDEX, allow); - } else { - type = ra_allock(as, (int32_t)irt_toitype(ir->t), allow); - } - emit_tai(as, PPCI_STW, type, RID_BASE, ofs); - } - checkmclim(as); - } - lj_assertA(map + nent == flinks, "inconsistent frames in snapshot"); -} - -/* -- GC handling --------------------------------------------------------- */ - -/* Marker to prevent patching the GC check exit. */ -#define PPC_NOPATCH_GC_CHECK PPCI_ORIS - -/* Check GC threshold and do one or more GC steps. */ -static void asm_gc_check(ASMState *as) -{ - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_step_jit]; - IRRef args[2]; - MCLabel l_end; - Reg tmp; - ra_evictset(as, RSET_SCRATCH); - l_end = emit_label(as); - /* Exit trace if in GCSatomic or GCSfinalize. Avoids syncing GC objects. */ - asm_guardcc(as, CC_NE); /* Assumes asm_snap_prep() already done. */ - *--as->mcp = PPC_NOPATCH_GC_CHECK; - emit_ai(as, PPCI_CMPWI, RID_RET, 0); - args[0] = ASMREF_TMP1; /* global_State *g */ - args[1] = ASMREF_TMP2; /* MSize steps */ - asm_gencall(as, ci, args); - emit_tai(as, PPCI_ADDI, ra_releasetmp(as, ASMREF_TMP1), RID_JGL, -32768); - tmp = ra_releasetmp(as, ASMREF_TMP2); - emit_loadi(as, tmp, as->gcsteps); - /* Jump around GC step if GC total < GC threshold. */ - emit_condbranch(as, PPCI_BC|PPCF_Y, CC_LT, l_end); - emit_ab(as, PPCI_CMPLW, RID_TMP, tmp); - emit_getgl(as, tmp, gc.threshold); - emit_getgl(as, RID_TMP, gc.total); - as->gcsteps = 0; - checkmclim(as); -} - -/* -- Loop handling ------------------------------------------------------- */ - -/* Fixup the loop branch. */ -static void asm_loop_fixup(ASMState *as) -{ - MCode *p = as->mctop; - MCode *target = as->mcp; - if (as->loopinv) { /* Inverted loop branch? */ - /* asm_guardcc already inverted the cond branch and patched the final b. */ - p[-2] = (p[-2] & (0xffff0000u & ~PPCF_Y)) | (((target-p+2) & 0x3fffu) << 2); - } else { - p[-1] = PPCI_B|(((target-p+1)&0x00ffffffu)<<2); - } -} - -/* Fixup the tail of the loop. */ -static void asm_loop_tail_fixup(ASMState *as) -{ - UNUSED(as); /* Nothing to do. */ -} - -/* -- Head of trace ------------------------------------------------------- */ - -/* Coalesce BASE register for a root trace. */ -static void asm_head_root_base(ASMState *as) -{ - IRIns *ir = IR(REF_BASE); - Reg r = ir->r; - if (ra_hasreg(r)) { - ra_free(as, r); - if (rset_test(as->modset, r) || irt_ismarked(ir->t)) - ir->r = RID_INIT; /* No inheritance for modified BASE register. */ - if (r != RID_BASE) - emit_mr(as, r, RID_BASE); - } -} - -/* Coalesce BASE register for a side trace. */ -static Reg asm_head_side_base(ASMState *as, IRIns *irp) -{ - IRIns *ir = IR(REF_BASE); - Reg r = ir->r; - if (ra_hasreg(r)) { - ra_free(as, r); - if (rset_test(as->modset, r) || irt_ismarked(ir->t)) - ir->r = RID_INIT; /* No inheritance for modified BASE register. */ - if (irp->r == r) { - return r; /* Same BASE register already coalesced. */ - } else if (ra_hasreg(irp->r) && rset_test(as->freeset, irp->r)) { - emit_mr(as, r, irp->r); /* Move from coalesced parent reg. */ - return irp->r; - } else { - emit_getgl(as, r, jit_base); /* Otherwise reload BASE. */ - } - } - return RID_NONE; -} - -/* -- Tail of trace ------------------------------------------------------- */ - -/* Fixup the tail code. */ -static void asm_tail_fixup(ASMState *as, TraceNo lnk) -{ - uintptr_t target = lnk ? (uintptr_t)traceref(as->J, lnk)->mcode : (uintptr_t)(void *)lj_vm_exit_interp; - MCode *mcp = as->mctail; - int32_t spadj = as->T->spadjust; - if (spadj) { /* Emit stack adjustment. */ - lj_assertA(checki16(CFRAME_SIZE+spadj), "stack adjustment out of range"); - *mcp++ = PPCI_ADDI | PPCF_T(RID_TMP) | PPCF_A(RID_SP) | (CFRAME_SIZE+spadj); - *mcp++ = PPCI_STWU | PPCF_T(RID_TMP) | PPCF_A(RID_SP) | spadj; - } - /* Emit exit branch. */ - if ((((target - (uintptr_t)mcp) + 0x02000000u) >> 26) == 0) { - *mcp = PPCI_B | ((target - (uintptr_t)mcp) & 0x03fffffcu); mcp++; - } else { - *mcp++ = PPCI_LWZ | PPCF_T(RID_TMP) | PPCF_A(RID_JGL) | - jglofs(as, &as->J->k32[LJ_K32_VM_EXIT_INTERP]); - *mcp++ = PPCI_MTCTR | PPCF_T(RID_TMP); - *mcp++ = PPCI_BCTR; - } - while (as->mctop > mcp) *--as->mctop = PPCI_NOP; -} - -/* Prepare tail of code. */ -static void asm_tail_prep(ASMState *as, TraceNo lnk) -{ - MCode *p = as->mctop - 1; /* Leave room for exit branch. */ - if (as->loopref) { - as->invmcp = as->mcp = p; - } else { - if (!lnk) { - uintptr_t target = (uintptr_t)(void *)lj_vm_exit_interp; - if ((((target - (uintptr_t)p) + 0x02000000u) >> 26) || - (((target - (uintptr_t)(p-2)) + 0x02000000u) >> 26)) p -= 2; - } - p -= 2; /* Leave room for stack pointer adjustment. */ - as->mcp = p; - as->invmcp = NULL; - } - as->mctail = p; -} - -/* -- Trace setup --------------------------------------------------------- */ - -/* Ensure there are enough stack slots for call arguments. */ -static Reg asm_setup_call_slots(ASMState *as, IRIns *ir, const CCallInfo *ci) -{ - IRRef args[CCI_NARGS_MAX*2]; - uint32_t i, nargs = CCI_XNARGS(ci); - int nslots = 2, ngpr = REGARG_NUMGPR, nfpr = REGARG_NUMFPR; - asm_collectargs(as, ir, ci, args); - for (i = 0; i < nargs; i++) - if (!LJ_SOFTFP && args[i] && irt_isfp(IR(args[i])->t)) { - if (nfpr > 0) nfpr--; else nslots = (nslots+3) & ~1; - } else { - if (ngpr > 0) ngpr--; else nslots++; - } - if (nslots > as->evenspill) /* Leave room for args in stack slots. */ - as->evenspill = nslots; - return (!LJ_SOFTFP && irt_isfp(ir->t)) ? REGSP_HINT(RID_FPRET) : - REGSP_HINT(RID_RET); -} - -static void asm_setup_target(ASMState *as) -{ - asm_exitstub_setup(as, as->T->nsnap + (as->parent ? 1 : 0)); -} - -/* -- Trace patching ------------------------------------------------------ */ - -/* Patch exit jumps of existing machine code to a new target. */ -void lj_asm_patchexit(jit_State *J, GCtrace *T, ExitNo exitno, MCode *target) -{ - MCode *p = T->mcode; - MCode *pe = (MCode *)((char *)p + T->szmcode); - MCode *px = exitstub_trace_addr(T, exitno); - MCode *cstart = NULL; - MCode *mcarea = lj_mcode_patch(J, p, 0); - int clearso = 0, patchlong = 1; - for (; p < pe; p++) { - /* Look for exitstub branch, try to replace with branch to target. */ - uint32_t ins = *p; - if ((ins & 0xfc000000u) == 0x40000000u && - ((ins ^ ((char *)px-(char *)p)) & 0xffffu) == 0) { - ptrdiff_t delta = (char *)target - (char *)p; - if (((ins >> 16) & 3) == (CC_SO&3)) { - clearso = sizeof(MCode); - delta -= sizeof(MCode); - } - /* Many, but not all short-range branches can be patched directly. */ - if (p[-1] == PPC_NOPATCH_GC_CHECK) { - patchlong = 0; - } else if (((delta + 0x8000) >> 16) == 0) { - *p = (ins & 0xffdf0000u) | ((uint32_t)delta & 0xffffu) | - ((delta & 0x8000) * (PPCF_Y/0x8000)); - if (!cstart) cstart = p; - } - } else if ((ins & 0xfc000000u) == PPCI_B && - ((ins ^ ((char *)px-(char *)p)) & 0x03ffffffu) == 0) { - ptrdiff_t delta = (char *)target - (char *)p; - lj_assertJ(((delta + 0x02000000) >> 26) == 0, - "branch target out of range"); - *p = PPCI_B | ((uint32_t)delta & 0x03ffffffu); - if (!cstart) cstart = p; - } - } - /* Always patch long-range branch in exit stub itself. Except, if we can't. */ - if (patchlong) { - ptrdiff_t delta = (char *)target - (char *)px - clearso; - lj_assertJ(((delta + 0x02000000) >> 26) == 0, - "branch target out of range"); - *px = PPCI_B | ((uint32_t)delta & 0x03ffffffu); - } - if (!cstart) cstart = px; - lj_mcode_sync(cstart, px+1); - if (clearso) { /* Extend the current trace. Ugly workaround. */ - MCode *pp = J->cur.mcode; - J->cur.szmcode += sizeof(MCode); - *--pp = PPCI_MCRXR; /* Clear SO flag. */ - J->cur.mcode = pp; - lj_mcode_sync(pp, pp+1); - } - lj_mcode_patch(J, mcarea, 1); -} - diff --git a/include/luajit/lj_asm_x86.h b/include/luajit/lj_asm_x86.h deleted file mode 100644 index bdbce11..0000000 --- a/include/luajit/lj_asm_x86.h +++ /dev/null @@ -1,3165 +0,0 @@ -/* -** x86/x64 IR assembler (SSA IR -> machine code). -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -/* -- Guard handling ------------------------------------------------------ */ - -/* Generate an exit stub group at the bottom of the reserved MCode memory. */ -static MCode *asm_exitstub_gen(ASMState *as, ExitNo group) -{ - ExitNo i, groupofs = (group*EXITSTUBS_PER_GROUP) & 0xff; - MCode *target = (MCode *)(void *)lj_vm_exit_handler; - MCode *mxp = as->mcbot; - MCode *mxpstart = mxp; - if (mxp + ((2+2)*EXITSTUBS_PER_GROUP + - (LJ_GC64 ? 0 : 8) + - (LJ_64 ? 6 : 5)) >= as->mctop) - asm_mclimit(as); - /* Push low byte of exitno for each exit stub. */ - *mxp++ = XI_PUSHi8; *mxp++ = (MCode)groupofs; - for (i = 1; i < EXITSTUBS_PER_GROUP; i++) { - *mxp++ = XI_JMPs; *mxp++ = (MCode)((2+2)*(EXITSTUBS_PER_GROUP - i) - 2); - *mxp++ = XI_PUSHi8; *mxp++ = (MCode)(groupofs + i); - } - /* Push the high byte of the exitno for each exit stub group. */ - *mxp++ = XI_PUSHi8; *mxp++ = (MCode)((group*EXITSTUBS_PER_GROUP)>>8); -#if !LJ_GC64 - /* Store DISPATCH at original stack slot 0. Account for the two push ops. */ - *mxp++ = XI_MOVmi; - *mxp++ = MODRM(XM_OFS8, 0, RID_ESP); - *mxp++ = MODRM(XM_SCALE1, RID_ESP, RID_ESP); - *mxp++ = 2*sizeof(void *); - *(int32_t *)mxp = ptr2addr(J2GG(as->J)->dispatch); mxp += 4; -#endif - /* Jump to exit handler which fills in the ExitState. */ - if (jmprel_ok(mxp + 5, target)) { /* Direct jump. */ - *mxp++ = XI_JMP; mxp += 4; - *((int32_t *)(mxp-4)) = jmprel(as->J, mxp, target); - } else { /* RIP-relative indirect jump. */ - *mxp++ = XI_GROUP5; *mxp++ = XM_OFS0 + (XOg_JMP<<3) + RID_EBP; mxp += 4; - *((int32_t *)(mxp-4)) = (int32_t)((group ? as->J->exitstubgroup[0] : mxpstart) - 8 - mxp); - } - /* Commit the code for this group (even if assembly fails later on). */ - lj_mcode_commitbot(as->J, mxp); - as->mcbot = mxp; - as->mclim = as->mcbot + MCLIM_REDZONE; - return mxpstart; -} - -/* Setup all needed exit stubs. */ -static void asm_exitstub_setup(ASMState *as, ExitNo nexits) -{ - ExitNo i; - if (nexits >= EXITSTUBS_PER_GROUP*LJ_MAX_EXITSTUBGR) - lj_trace_err(as->J, LJ_TRERR_SNAPOV); -#if LJ_64 - if (as->J->exitstubgroup[0] == NULL) { - /* Store the two potentially out-of-range targets below group 0. */ - MCode *mxp = as->mcbot; - while ((uintptr_t)mxp & 7) *mxp++ = XI_INT3; - *((void **)mxp) = (void *)lj_vm_exit_interp; mxp += 8; - *((void **)mxp) = (void *)lj_vm_exit_handler; mxp += 8; - as->mcbot = mxp; /* Don't bother to commit, done in asm_exitstub_gen. */ - } -#endif - for (i = 0; i < (nexits+EXITSTUBS_PER_GROUP-1)/EXITSTUBS_PER_GROUP; i++) - if (as->J->exitstubgroup[i] == NULL) - as->J->exitstubgroup[i] = asm_exitstub_gen(as, i); -} - -/* Emit conditional branch to exit for guard. -** It's important to emit this *after* all registers have been allocated, -** because rematerializations may invalidate the flags. -*/ -static void asm_guardcc(ASMState *as, int cc) -{ - MCode *target = exitstub_addr(as->J, as->snapno); - MCode *p = as->mcp; - if (LJ_UNLIKELY(p == as->invmcp)) { - as->loopinv = 1; - *(int32_t *)(p+1) = jmprel(as->J, p+5, target); - target = p; - cc ^= 1; - if (as->realign) { - if (LJ_GC64 && LJ_UNLIKELY(as->mrm.base == RID_RIP)) - as->mrm.ofs += 2; /* Fixup RIP offset for pending fused load. */ - emit_sjcc(as, cc, target); - return; - } - } - if (LJ_GC64 && LJ_UNLIKELY(as->mrm.base == RID_RIP)) - as->mrm.ofs += 6; /* Fixup RIP offset for pending fused load. */ - emit_jcc(as, cc, target); -} - -/* -- Memory operand fusion ----------------------------------------------- */ - -/* Limit linear search to this distance. Avoids O(n^2) behavior. */ -#define CONFLICT_SEARCH_LIM 31 - -/* Check if a reference is a signed 32 bit constant. */ -static int asm_isk32(ASMState *as, IRRef ref, int32_t *k) -{ - if (irref_isk(ref)) { - IRIns *ir = IR(ref); -#if LJ_GC64 - if (ir->o == IR_KNULL || !irt_is64(ir->t)) { - *k = ir->i; - return 1; - } else if (checki32((int64_t)ir_k64(ir)->u64)) { - *k = (int32_t)ir_k64(ir)->u64; - return 1; - } -#else - if (ir->o != IR_KINT64) { - *k = ir->i; - return 1; - } else if (checki32((int64_t)ir_kint64(ir)->u64)) { - *k = (int32_t)ir_kint64(ir)->u64; - return 1; - } -#endif - } - return 0; -} - -/* Check if there's no conflicting instruction between curins and ref. -** Also avoid fusing loads if there are multiple references. -*/ -static int noconflict(ASMState *as, IRRef ref, IROp conflict, int check) -{ - IRIns *ir = as->ir; - IRRef i = as->curins; - if (i > ref + CONFLICT_SEARCH_LIM) - return 0; /* Give up, ref is too far away. */ - while (--i > ref) { - if (ir[i].o == conflict) - return 0; /* Conflict found. */ - else if ((check & 1) && (ir[i].o == IR_NEWREF || ir[i].o == IR_CALLS)) - return 0; - else if ((check & 2) && (ir[i].op1 == ref || ir[i].op2 == ref)) - return 0; - } - return 1; /* Ok, no conflict. */ -} - -/* Fuse array base into memory operand. */ -static IRRef asm_fuseabase(ASMState *as, IRRef ref) -{ - IRIns *irb = IR(ref); - as->mrm.ofs = 0; - if (irb->o == IR_FLOAD) { - IRIns *ira = IR(irb->op1); - lj_assertA(irb->op2 == IRFL_TAB_ARRAY, "expected FLOAD TAB_ARRAY"); - /* We can avoid the FLOAD of t->array for colocated arrays. */ - if (ira->o == IR_TNEW && ira->op1 <= LJ_MAX_COLOSIZE && - !neverfuse(as) && noconflict(as, irb->op1, IR_NEWREF, 0)) { - as->mrm.ofs = (int32_t)sizeof(GCtab); /* Ofs to colocated array. */ - return irb->op1; /* Table obj. */ - } - } else if (irb->o == IR_ADD && irref_isk(irb->op2)) { - /* Fuse base offset (vararg load). */ - IRIns *irk = IR(irb->op2); - as->mrm.ofs = irk->o == IR_KINT ? irk->i : (int32_t)ir_kint64(irk)->u64; - return irb->op1; - } - return ref; /* Otherwise use the given array base. */ -} - -/* Fuse array reference into memory operand. */ -static void asm_fusearef(ASMState *as, IRIns *ir, RegSet allow) -{ - IRIns *irx; - lj_assertA(ir->o == IR_AREF, "expected AREF"); - as->mrm.base = (uint8_t)ra_alloc1(as, asm_fuseabase(as, ir->op1), allow); - irx = IR(ir->op2); - if (irref_isk(ir->op2)) { - as->mrm.ofs += 8*irx->i; - as->mrm.idx = RID_NONE; - } else { - rset_clear(allow, as->mrm.base); - as->mrm.scale = XM_SCALE8; - /* Fuse a constant ADD (e.g. t[i+1]) into the offset. - ** Doesn't help much without ABCelim, but reduces register pressure. - */ - if (!LJ_64 && /* Has bad effects with negative index on x64. */ - mayfuse(as, ir->op2) && ra_noreg(irx->r) && - irx->o == IR_ADD && irref_isk(irx->op2)) { - as->mrm.ofs += 8*IR(irx->op2)->i; - as->mrm.idx = (uint8_t)ra_alloc1(as, irx->op1, allow); - } else { - as->mrm.idx = (uint8_t)ra_alloc1(as, ir->op2, allow); - } - } -} - -/* Fuse array/hash/upvalue reference into memory operand. -** Caveat: this may allocate GPRs for the base/idx registers. Be sure to -** pass the final allow mask, excluding any GPRs used for other inputs. -** In particular: 2-operand GPR instructions need to call ra_dest() first! -*/ -static void asm_fuseahuref(ASMState *as, IRRef ref, RegSet allow) -{ - IRIns *ir = IR(ref); - if (ra_noreg(ir->r)) { - switch ((IROp)ir->o) { - case IR_AREF: - if (mayfuse(as, ref)) { - asm_fusearef(as, ir, allow); - return; - } - break; - case IR_HREFK: - if (mayfuse(as, ref)) { - as->mrm.base = (uint8_t)ra_alloc1(as, ir->op1, allow); - as->mrm.ofs = (int32_t)(IR(ir->op2)->op2 * sizeof(Node)); - as->mrm.idx = RID_NONE; - return; - } - break; - case IR_UREFC: - if (irref_isk(ir->op1)) { - GCfunc *fn = ir_kfunc(IR(ir->op1)); - GCupval *uv = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv; -#if LJ_GC64 - int64_t ofs = dispofs(as, &uv->tv); - if (checki32(ofs) && checki32(ofs+4)) { - as->mrm.ofs = (int32_t)ofs; - as->mrm.base = RID_DISPATCH; - as->mrm.idx = RID_NONE; - return; - } -#else - as->mrm.ofs = ptr2addr(&uv->tv); - as->mrm.base = as->mrm.idx = RID_NONE; - return; -#endif - } - break; - case IR_TMPREF: -#if LJ_GC64 - as->mrm.ofs = (int32_t)dispofs(as, &J2G(as->J)->tmptv); - as->mrm.base = RID_DISPATCH; - as->mrm.idx = RID_NONE; -#else - as->mrm.ofs = igcptr(&J2G(as->J)->tmptv); - as->mrm.base = as->mrm.idx = RID_NONE; -#endif - return; - default: - break; - } - } - as->mrm.base = (uint8_t)ra_alloc1(as, ref, allow); - as->mrm.ofs = 0; - as->mrm.idx = RID_NONE; -} - -/* Fuse FLOAD/FREF reference into memory operand. */ -static void asm_fusefref(ASMState *as, IRIns *ir, RegSet allow) -{ - lj_assertA(ir->o == IR_FLOAD || ir->o == IR_FREF, - "bad IR op %d", ir->o); - as->mrm.idx = RID_NONE; - if (ir->op1 == REF_NIL) { /* FLOAD from GG_State with offset. */ -#if LJ_GC64 - as->mrm.ofs = (int32_t)(ir->op2 << 2) - GG_OFS(dispatch); - as->mrm.base = RID_DISPATCH; -#else - as->mrm.ofs = (int32_t)(ir->op2 << 2) + ptr2addr(J2GG(as->J)); - as->mrm.base = RID_NONE; -#endif - return; - } - as->mrm.ofs = field_ofs[ir->op2]; - if (irref_isk(ir->op1)) { - IRIns *op1 = IR(ir->op1); -#if LJ_GC64 - if (ir->op1 == REF_NIL) { - as->mrm.ofs -= GG_OFS(dispatch); - as->mrm.base = RID_DISPATCH; - return; - } else if (op1->o == IR_KPTR || op1->o == IR_KKPTR) { - intptr_t ofs = dispofs(as, ir_kptr(op1)); - if (checki32(as->mrm.ofs + ofs)) { - as->mrm.ofs += (int32_t)ofs; - as->mrm.base = RID_DISPATCH; - return; - } - } -#else - as->mrm.ofs += op1->i; - as->mrm.base = RID_NONE; - return; -#endif - } - as->mrm.base = (uint8_t)ra_alloc1(as, ir->op1, allow); -} - -/* Fuse string reference into memory operand. */ -static void asm_fusestrref(ASMState *as, IRIns *ir, RegSet allow) -{ - IRIns *irr; - lj_assertA(ir->o == IR_STRREF, "bad IR op %d", ir->o); - as->mrm.base = as->mrm.idx = RID_NONE; - as->mrm.scale = XM_SCALE1; - as->mrm.ofs = sizeof(GCstr); - if (!LJ_GC64 && irref_isk(ir->op1)) { - as->mrm.ofs += IR(ir->op1)->i; - } else { - Reg r = ra_alloc1(as, ir->op1, allow); - rset_clear(allow, r); - as->mrm.base = (uint8_t)r; - } - irr = IR(ir->op2); - if (irref_isk(ir->op2)) { - as->mrm.ofs += irr->i; - } else { - Reg r; - /* Fuse a constant add into the offset, e.g. string.sub(s, i+10). */ - if (!LJ_64 && /* Has bad effects with negative index on x64. */ - mayfuse(as, ir->op2) && irr->o == IR_ADD && irref_isk(irr->op2)) { - as->mrm.ofs += IR(irr->op2)->i; - r = ra_alloc1(as, irr->op1, allow); - } else { - r = ra_alloc1(as, ir->op2, allow); - } - if (as->mrm.base == RID_NONE) - as->mrm.base = (uint8_t)r; - else - as->mrm.idx = (uint8_t)r; - } -} - -static void asm_fusexref(ASMState *as, IRRef ref, RegSet allow) -{ - IRIns *ir = IR(ref); - as->mrm.idx = RID_NONE; - if (ir->o == IR_KPTR || ir->o == IR_KKPTR) { -#if LJ_GC64 - intptr_t ofs = dispofs(as, ir_kptr(ir)); - if (checki32(ofs)) { - as->mrm.ofs = (int32_t)ofs; - as->mrm.base = RID_DISPATCH; - return; - } - } if (0) { -#else - as->mrm.ofs = ir->i; - as->mrm.base = RID_NONE; - } else if (ir->o == IR_STRREF) { - asm_fusestrref(as, ir, allow); -#endif - } else { - as->mrm.ofs = 0; - if (canfuse(as, ir) && ir->o == IR_ADD && ra_noreg(ir->r)) { - /* Gather (base+idx*sz)+ofs as emitted by cdata ptr/array indexing. */ - IRIns *irx; - IRRef idx; - Reg r; - if (asm_isk32(as, ir->op2, &as->mrm.ofs)) { /* Recognize x+ofs. */ - ref = ir->op1; - ir = IR(ref); - if (!(ir->o == IR_ADD && canfuse(as, ir) && ra_noreg(ir->r))) - goto noadd; - } - as->mrm.scale = XM_SCALE1; - idx = ir->op1; - ref = ir->op2; - irx = IR(idx); - if (!(irx->o == IR_BSHL || irx->o == IR_ADD)) { /* Try other operand. */ - idx = ir->op2; - ref = ir->op1; - irx = IR(idx); - } - if (canfuse(as, irx) && ra_noreg(irx->r)) { - if (irx->o == IR_BSHL && irref_isk(irx->op2) && IR(irx->op2)->i <= 3) { - /* Recognize idx<op1; - as->mrm.scale = (uint8_t)(IR(irx->op2)->i << 6); - } else if (irx->o == IR_ADD && irx->op1 == irx->op2) { - /* FOLD does idx*2 ==> idx<<1 ==> idx+idx. */ - idx = irx->op1; - as->mrm.scale = XM_SCALE2; - } - } - r = ra_alloc1(as, idx, allow); - rset_clear(allow, r); - as->mrm.idx = (uint8_t)r; - } - noadd: - as->mrm.base = (uint8_t)ra_alloc1(as, ref, allow); - } -} - -/* Fuse load of 64 bit IR constant into memory operand. */ -static Reg asm_fuseloadk64(ASMState *as, IRIns *ir) -{ - const uint64_t *k = &ir_k64(ir)->u64; - if (!LJ_GC64 || checki32((intptr_t)k)) { - as->mrm.ofs = ptr2addr(k); - as->mrm.base = RID_NONE; -#if LJ_GC64 - } else if (checki32(dispofs(as, k))) { - as->mrm.ofs = (int32_t)dispofs(as, k); - as->mrm.base = RID_DISPATCH; - } else if (checki32(mcpofs(as, k)) && checki32(mcpofs(as, k+1)) && - checki32(mctopofs(as, k)) && checki32(mctopofs(as, k+1))) { - as->mrm.ofs = (int32_t)mcpofs(as, k); - as->mrm.base = RID_RIP; - } else { /* Intern 64 bit constant at bottom of mcode. */ - if (ir->i) { - lj_assertA(*k == *(uint64_t*)(as->mctop - ir->i), - "bad interned 64 bit constant"); - } else { - while ((uintptr_t)as->mcbot & 7) *as->mcbot++ = XI_INT3; - *(uint64_t *)as->mcbot = *k; - ir->i = (int32_t)(as->mctop - as->mcbot); - as->mcbot += 8; - as->mclim = as->mcbot + MCLIM_REDZONE; - lj_mcode_commitbot(as->J, as->mcbot); - } - as->mrm.ofs = (int32_t)mcpofs(as, as->mctop - ir->i); - as->mrm.base = RID_RIP; -#endif - } - as->mrm.idx = RID_NONE; - return RID_MRM; -} - -/* Fuse load into memory operand. -** -** Important caveat: this may emit RIP-relative loads! So don't place any -** code emitters between this function and the use of its result. -** The only permitted exception is asm_guardcc(). -*/ -static Reg asm_fuseload(ASMState *as, IRRef ref, RegSet allow) -{ - IRIns *ir = IR(ref); - if (ra_hasreg(ir->r)) { - if (allow != RSET_EMPTY) { /* Fast path. */ - ra_noweak(as, ir->r); - return ir->r; - } - fusespill: - /* Force a spill if only memory operands are allowed (asm_x87load). */ - as->mrm.base = RID_ESP; - as->mrm.ofs = ra_spill(as, ir); - as->mrm.idx = RID_NONE; - return RID_MRM; - } - if (ir->o == IR_KNUM) { - RegSet avail = as->freeset & ~as->modset & RSET_FPR; - lj_assertA(allow != RSET_EMPTY, "no register allowed"); - if (!(avail & (avail-1))) /* Fuse if less than two regs available. */ - return asm_fuseloadk64(as, ir); - } else if (ref == REF_BASE || ir->o == IR_KINT64) { - RegSet avail = as->freeset & ~as->modset & RSET_GPR; - lj_assertA(allow != RSET_EMPTY, "no register allowed"); - if (!(avail & (avail-1))) { /* Fuse if less than two regs available. */ - if (ref == REF_BASE) { -#if LJ_GC64 - as->mrm.ofs = (int32_t)dispofs(as, &J2G(as->J)->jit_base); - as->mrm.base = RID_DISPATCH; -#else - as->mrm.ofs = ptr2addr(&J2G(as->J)->jit_base); - as->mrm.base = RID_NONE; -#endif - as->mrm.idx = RID_NONE; - return RID_MRM; - } else { - return asm_fuseloadk64(as, ir); - } - } - } else if (mayfuse(as, ref)) { - RegSet xallow = (allow & RSET_GPR) ? allow : RSET_GPR; - if (ir->o == IR_SLOAD) { - if (!(ir->op2 & (IRSLOAD_PARENT|IRSLOAD_CONVERT)) && - noconflict(as, ref, IR_RETF, 2) && - !(LJ_GC64 && irt_isaddr(ir->t))) { - as->mrm.base = (uint8_t)ra_alloc1(as, REF_BASE, xallow); - as->mrm.ofs = 8*((int32_t)ir->op1-1-LJ_FR2) + - (!LJ_FR2 && (ir->op2 & IRSLOAD_FRAME) ? 4 : 0); - as->mrm.idx = RID_NONE; - return RID_MRM; - } - } else if (ir->o == IR_FLOAD) { - /* Generic fusion is only ok for 32 bit operand (but see asm_comp). */ - if ((irt_isint(ir->t) || irt_isu32(ir->t) || irt_isaddr(ir->t)) && - noconflict(as, ref, IR_FSTORE, 2)) { - asm_fusefref(as, ir, xallow); - return RID_MRM; - } - } else if (ir->o == IR_ALOAD || ir->o == IR_HLOAD || ir->o == IR_ULOAD) { - if (noconflict(as, ref, ir->o + IRDELTA_L2S, 2+(ir->o != IR_ULOAD)) && - !(LJ_GC64 && irt_isaddr(ir->t))) { - asm_fuseahuref(as, ir->op1, xallow); - return RID_MRM; - } - } else if (ir->o == IR_XLOAD) { - /* Generic fusion is not ok for 8/16 bit operands (but see asm_comp). - ** Fusing unaligned memory operands is ok on x86 (except for SIMD types). - */ - if ((!irt_typerange(ir->t, IRT_I8, IRT_U16)) && - noconflict(as, ref, IR_XSTORE, 2)) { - asm_fusexref(as, ir->op1, xallow); - return RID_MRM; - } - } else if (ir->o == IR_VLOAD && IR(ir->op1)->o == IR_AREF && - !(LJ_GC64 && irt_isaddr(ir->t))) { - asm_fuseahuref(as, ir->op1, xallow); - as->mrm.ofs += 8 * ir->op2; - return RID_MRM; - } - } - if (ir->o == IR_FLOAD && ir->op1 == REF_NIL) { - asm_fusefref(as, ir, RSET_EMPTY); - return RID_MRM; - } - if (!(as->freeset & allow) && !emit_canremat(ref) && - (allow == RSET_EMPTY || ra_hasspill(ir->s) || iscrossref(as, ref))) - goto fusespill; - return ra_allocref(as, ref, allow); -} - -#if LJ_64 -/* Don't fuse a 32 bit load into a 64 bit operation. */ -static Reg asm_fuseloadm(ASMState *as, IRRef ref, RegSet allow, int is64) -{ - if (is64 && !irt_is64(IR(ref)->t)) - return ra_alloc1(as, ref, allow); - return asm_fuseload(as, ref, allow); -} -#else -#define asm_fuseloadm(as, ref, allow, is64) asm_fuseload(as, (ref), (allow)) -#endif - -/* -- Calls --------------------------------------------------------------- */ - -/* Count the required number of stack slots for a call. */ -static int asm_count_call_slots(ASMState *as, const CCallInfo *ci, IRRef *args) -{ - uint32_t i, nargs = CCI_XNARGS(ci); - int nslots = 0; -#if LJ_64 - if (LJ_ABI_WIN) { - nslots = (int)(nargs*2); /* Only matters for more than four args. */ - } else { - int ngpr = REGARG_NUMGPR, nfpr = REGARG_NUMFPR; - for (i = 0; i < nargs; i++) - if (args[i] && irt_isfp(IR(args[i])->t)) { - if (nfpr > 0) nfpr--; else nslots += 2; - } else { - if (ngpr > 0) ngpr--; else nslots += 2; - } - } -#else - int ngpr = 0; - if ((ci->flags & CCI_CC_MASK) == CCI_CC_FASTCALL) - ngpr = 2; - else if ((ci->flags & CCI_CC_MASK) == CCI_CC_THISCALL) - ngpr = 1; - for (i = 0; i < nargs; i++) - if (args[i] && irt_isfp(IR(args[i])->t)) { - nslots += irt_isnum(IR(args[i])->t) ? 2 : 1; - } else { - if (ngpr > 0) ngpr--; else nslots++; - } -#endif - return nslots; -} - -/* Generate a call to a C function. */ -static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args) -{ - uint32_t n, nargs = CCI_XNARGS(ci); - int32_t ofs = STACKARG_OFS; -#if LJ_64 - uint32_t gprs = REGARG_GPRS; - Reg fpr = REGARG_FIRSTFPR; -#if !LJ_ABI_WIN - MCode *patchnfpr = NULL; -#endif -#else - uint32_t gprs = 0; - if ((ci->flags & CCI_CC_MASK) != CCI_CC_CDECL) { - if ((ci->flags & CCI_CC_MASK) == CCI_CC_THISCALL) - gprs = (REGARG_GPRS & 31); - else if ((ci->flags & CCI_CC_MASK) == CCI_CC_FASTCALL) - gprs = REGARG_GPRS; - } -#endif - if ((void *)ci->func) - emit_call(as, ci->func); -#if LJ_64 - if ((ci->flags & CCI_VARARG)) { /* Special handling for vararg calls. */ -#if LJ_ABI_WIN - for (n = 0; n < 4 && n < nargs; n++) { - IRIns *ir = IR(args[n]); - if (irt_isfp(ir->t)) /* Duplicate FPRs in GPRs. */ - emit_rr(as, XO_MOVDto, (irt_isnum(ir->t) ? REX_64 : 0) | (fpr+n), - ((gprs >> (n*5)) & 31)); /* Either MOVD or MOVQ. */ - } -#else - patchnfpr = --as->mcp; /* Indicate number of used FPRs in register al. */ - *--as->mcp = XI_MOVrib | RID_EAX; -#endif - } -#endif - for (n = 0; n < nargs; n++) { /* Setup args. */ - IRRef ref = args[n]; - IRIns *ir = IR(ref); - Reg r; -#if LJ_64 && LJ_ABI_WIN - /* Windows/x64 argument registers are strictly positional. */ - r = irt_isfp(ir->t) ? (fpr <= REGARG_LASTFPR ? fpr : 0) : (gprs & 31); - fpr++; gprs >>= 5; -#elif LJ_64 - /* POSIX/x64 argument registers are used in order of appearance. */ - if (irt_isfp(ir->t)) { - r = fpr <= REGARG_LASTFPR ? fpr++ : 0; - } else { - r = gprs & 31; gprs >>= 5; - } -#else - if (ref && irt_isfp(ir->t)) { - r = 0; - } else { - r = gprs & 31; gprs >>= 5; - if (!ref) continue; - } -#endif - if (r) { /* Argument is in a register. */ - if (r < RID_MAX_GPR && ref < ASMREF_TMP1) { -#if LJ_64 - if (LJ_GC64 ? !(ir->o == IR_KINT || ir->o == IR_KNULL) : ir->o == IR_KINT64) - emit_loadu64(as, r, ir_k64(ir)->u64); - else -#endif - emit_loadi(as, r, ir->i); - } else { - /* Must have been evicted. */ - lj_assertA(rset_test(as->freeset, r), "reg %d not free", r); - if (ra_hasreg(ir->r)) { - ra_noweak(as, ir->r); - emit_movrr(as, ir, r, ir->r); - } else { - ra_allocref(as, ref, RID2RSET(r)); - } - } - } else if (irt_isfp(ir->t)) { /* FP argument is on stack. */ - lj_assertA(!(irt_isfloat(ir->t) && irref_isk(ref)), - "unexpected float constant"); - if (LJ_32 && (ofs & 4) && irref_isk(ref)) { - /* Split stores for unaligned FP consts. */ - emit_movmroi(as, RID_ESP, ofs, (int32_t)ir_knum(ir)->u32.lo); - emit_movmroi(as, RID_ESP, ofs+4, (int32_t)ir_knum(ir)->u32.hi); - } else { - r = ra_alloc1(as, ref, RSET_FPR); - emit_rmro(as, irt_isnum(ir->t) ? XO_MOVSDto : XO_MOVSSto, - r, RID_ESP, ofs); - } - ofs += (LJ_32 && irt_isfloat(ir->t)) ? 4 : 8; - } else { /* Non-FP argument is on stack. */ - if (LJ_32 && ref < ASMREF_TMP1) { - emit_movmroi(as, RID_ESP, ofs, ir->i); - } else { - r = ra_alloc1(as, ref, RSET_GPR); - emit_movtomro(as, REX_64 + r, RID_ESP, ofs); - } - ofs += sizeof(intptr_t); - } - checkmclim(as); - } -#if LJ_64 && !LJ_ABI_WIN - if (patchnfpr) *patchnfpr = fpr - REGARG_FIRSTFPR; -#endif -} - -/* Setup result reg/sp for call. Evict scratch regs. */ -static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci) -{ - RegSet drop = RSET_SCRATCH; - int hiop = ((ir+1)->o == IR_HIOP && !irt_isnil((ir+1)->t)); - if ((ci->flags & CCI_NOFPRCLOBBER)) - drop &= ~RSET_FPR; - if (ra_hasreg(ir->r)) - rset_clear(drop, ir->r); /* Dest reg handled below. */ - if (hiop && ra_hasreg((ir+1)->r)) - rset_clear(drop, (ir+1)->r); /* Dest reg handled below. */ - ra_evictset(as, drop); /* Evictions must be performed first. */ - if (ra_used(ir)) { - if (irt_isfp(ir->t)) { - int32_t ofs = sps_scale(ir->s); /* Use spill slot or temp slots. */ -#if LJ_64 - if ((ci->flags & CCI_CASTU64)) { - Reg dest = ir->r; - if (ra_hasreg(dest)) { - ra_free(as, dest); - ra_modified(as, dest); - emit_rr(as, XO_MOVD, dest|REX_64, RID_RET); /* Really MOVQ. */ - } - if (ofs) emit_movtomro(as, RID_RET|REX_64, RID_ESP, ofs); - } else { - ra_destreg(as, ir, RID_FPRET); - } -#else - /* Number result is in x87 st0 for x86 calling convention. */ - Reg dest = ir->r; - if (ra_hasreg(dest)) { - ra_free(as, dest); - ra_modified(as, dest); - emit_rmro(as, irt_isnum(ir->t) ? XO_MOVSD : XO_MOVSS, - dest, RID_ESP, ofs); - } - if ((ci->flags & CCI_CASTU64)) { - emit_movtomro(as, RID_RETLO, RID_ESP, ofs); - emit_movtomro(as, RID_RETHI, RID_ESP, ofs+4); - } else { - emit_rmro(as, irt_isnum(ir->t) ? XO_FSTPq : XO_FSTPd, - irt_isnum(ir->t) ? XOg_FSTPq : XOg_FSTPd, RID_ESP, ofs); - } -#endif - } else if (hiop) { - ra_destpair(as, ir); - } else { - lj_assertA(!irt_ispri(ir->t), "PRI dest"); - ra_destreg(as, ir, RID_RET); - } - } else if (LJ_32 && irt_isfp(ir->t) && !(ci->flags & CCI_CASTU64)) { - emit_x87op(as, XI_FPOP); /* Pop unused result from x87 st0. */ - } -} - -/* Return a constant function pointer or NULL for indirect calls. */ -static void *asm_callx_func(ASMState *as, IRIns *irf, IRRef func) -{ -#if LJ_32 - UNUSED(as); - if (irref_isk(func)) - return (void *)irf->i; -#else - if (irref_isk(func)) { - MCode *p; - if (irf->o == IR_KINT64) - p = (MCode *)(void *)ir_k64(irf)->u64; - else - p = (MCode *)(void *)(uintptr_t)(uint32_t)irf->i; - if (jmprel_ok(p, as->mcp)) - return p; /* Call target is still in +-2GB range. */ - /* Avoid the indirect case of emit_call(). Try to hoist func addr. */ - } -#endif - return NULL; -} - -static void asm_callx(ASMState *as, IRIns *ir) -{ - IRRef args[CCI_NARGS_MAX*2]; - CCallInfo ci; - IRRef func; - IRIns *irf; - int32_t spadj = 0; - ci.flags = asm_callx_flags(as, ir); - asm_collectargs(as, ir, &ci, args); - asm_setupresult(as, ir, &ci); -#if LJ_32 - /* Have to readjust stack after non-cdecl calls due to callee cleanup. */ - if ((ci.flags & CCI_CC_MASK) != CCI_CC_CDECL) - spadj = 4 * asm_count_call_slots(as, &ci, args); -#endif - func = ir->op2; irf = IR(func); - if (irf->o == IR_CARG) { func = irf->op1; irf = IR(func); } - ci.func = (ASMFunction)asm_callx_func(as, irf, func); - if (!(void *)ci.func) { - /* Use a (hoistable) non-scratch register for indirect calls. */ - RegSet allow = (RSET_GPR & ~RSET_SCRATCH); - Reg r = ra_alloc1(as, func, allow); - if (LJ_32) emit_spsub(as, spadj); /* Above code may cause restores! */ - emit_rr(as, XO_GROUP5, XOg_CALL, r); - } else if (LJ_32) { - emit_spsub(as, spadj); - } - asm_gencall(as, &ci, args); -} - -/* -- Returns ------------------------------------------------------------- */ - -/* Return to lower frame. Guard that it goes to the right spot. */ -static void asm_retf(ASMState *as, IRIns *ir) -{ - Reg base = ra_alloc1(as, REF_BASE, RSET_GPR); -#if LJ_FR2 - Reg rpc = ra_scratch(as, rset_exclude(RSET_GPR, base)); -#endif - void *pc = ir_kptr(IR(ir->op2)); - int32_t delta = 1+LJ_FR2+bc_a(*((const BCIns *)pc - 1)); - as->topslot -= (BCReg)delta; - if ((int32_t)as->topslot < 0) as->topslot = 0; - irt_setmark(IR(REF_BASE)->t); /* Children must not coalesce with BASE reg. */ - emit_setgl(as, base, jit_base); - emit_addptr(as, base, -8*delta); - asm_guardcc(as, CC_NE); -#if LJ_FR2 - emit_rmro(as, XO_CMP, rpc|REX_GC64, base, -8); - emit_loadu64(as, rpc, u64ptr(pc)); -#else - emit_gmroi(as, XG_ARITHi(XOg_CMP), base, -4, ptr2addr(pc)); -#endif -} - -/* -- Buffer operations --------------------------------------------------- */ - -#if LJ_HASBUFFER -static void asm_bufhdr_write(ASMState *as, Reg sb) -{ - Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, sb)); - IRIns irgc; - irgc.ot = IRT(0, IRT_PGC); /* GC type. */ - emit_storeofs(as, &irgc, tmp, sb, offsetof(SBuf, L)); - emit_opgl(as, XO_ARITH(XOg_OR), tmp|REX_GC64, cur_L); - emit_gri(as, XG_ARITHi(XOg_AND), tmp, SBUF_MASK_FLAG); - emit_loadofs(as, &irgc, tmp, sb, offsetof(SBuf, L)); -} -#endif - -/* -- Type conversions ---------------------------------------------------- */ - -static void asm_tointg(ASMState *as, IRIns *ir, Reg left) -{ - Reg tmp = ra_scratch(as, rset_exclude(RSET_FPR, left)); - Reg dest = ra_dest(as, ir, RSET_GPR); - asm_guardcc(as, CC_P); - asm_guardcc(as, CC_NE); - emit_rr(as, XO_UCOMISD, left, tmp); - emit_rr(as, XO_CVTSI2SD, tmp, dest); - emit_rr(as, XO_XORPS, tmp, tmp); /* Avoid partial register stall. */ - checkmclim(as); - emit_rr(as, XO_CVTTSD2SI, dest, left); - /* Can't fuse since left is needed twice. */ -} - -static void asm_tobit(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - Reg tmp = ra_noreg(IR(ir->op1)->r) ? - ra_alloc1(as, ir->op1, RSET_FPR) : - ra_scratch(as, RSET_FPR); - Reg right; - emit_rr(as, XO_MOVDto, tmp, dest); - right = asm_fuseload(as, ir->op2, rset_exclude(RSET_FPR, tmp)); - emit_mrm(as, XO_ADDSD, tmp, right); - ra_left(as, tmp, ir->op1); -} - -static void asm_conv(ASMState *as, IRIns *ir) -{ - IRType st = (IRType)(ir->op2 & IRCONV_SRCMASK); - int st64 = (st == IRT_I64 || st == IRT_U64 || (LJ_64 && st == IRT_P64)); - int stfp = (st == IRT_NUM || st == IRT_FLOAT); - IRRef lref = ir->op1; - lj_assertA(irt_type(ir->t) != st, "inconsistent types for CONV"); - lj_assertA(!(LJ_32 && (irt_isint64(ir->t) || st64)), - "IR %04d has unsplit 64 bit type", - (int)(ir - as->ir) - REF_BIAS); - if (irt_isfp(ir->t)) { - Reg dest = ra_dest(as, ir, RSET_FPR); - if (stfp) { /* FP to FP conversion. */ - Reg left = asm_fuseload(as, lref, RSET_FPR); - emit_mrm(as, st == IRT_NUM ? XO_CVTSD2SS : XO_CVTSS2SD, dest, left); - if (left == dest) return; /* Avoid the XO_XORPS. */ - } else if (LJ_32 && st == IRT_U32) { /* U32 to FP conversion on x86. */ - /* number = (2^52+2^51 .. u32) - (2^52+2^51) */ - cTValue *k = &as->J->k64[LJ_K64_TOBIT]; - Reg bias = ra_scratch(as, rset_exclude(RSET_FPR, dest)); - if (irt_isfloat(ir->t)) - emit_rr(as, XO_CVTSD2SS, dest, dest); - emit_rr(as, XO_SUBSD, dest, bias); /* Subtract 2^52+2^51 bias. */ - emit_rr(as, XO_XORPS, dest, bias); /* Merge bias and integer. */ - emit_rma(as, XO_MOVSD, bias, k); - checkmclim(as); - emit_mrm(as, XO_MOVD, dest, asm_fuseload(as, lref, RSET_GPR)); - return; - } else { /* Integer to FP conversion. */ - Reg left = (LJ_64 && (st == IRT_U32 || st == IRT_U64)) ? - ra_alloc1(as, lref, RSET_GPR) : - asm_fuseloadm(as, lref, RSET_GPR, st64); - if (LJ_64 && st == IRT_U64) { - MCLabel l_end = emit_label(as); - cTValue *k = &as->J->k64[LJ_K64_2P64]; - emit_rma(as, XO_ADDSD, dest, k); /* Add 2^64 to compensate. */ - emit_sjcc(as, CC_NS, l_end); - emit_rr(as, XO_TEST, left|REX_64, left); /* Check if u64 >= 2^63. */ - } - emit_mrm(as, irt_isnum(ir->t) ? XO_CVTSI2SD : XO_CVTSI2SS, - dest|((LJ_64 && (st64 || st == IRT_U32)) ? REX_64 : 0), left); - } - emit_rr(as, XO_XORPS, dest, dest); /* Avoid partial register stall. */ - } else if (stfp) { /* FP to integer conversion. */ - if (irt_isguard(ir->t)) { - /* Checked conversions are only supported from number to int. */ - lj_assertA(irt_isint(ir->t) && st == IRT_NUM, - "bad type for checked CONV"); - asm_tointg(as, ir, ra_alloc1(as, lref, RSET_FPR)); - } else { - Reg dest = ra_dest(as, ir, RSET_GPR); - x86Op op = st == IRT_NUM ? XO_CVTTSD2SI : XO_CVTTSS2SI; - lj_assertA(!irt_isu32(ir->t), "bad CONV u32.fp emitted"); -#if LJ_64 - if (irt_isu64(ir->t)) { - /* For the indefinite result -2^63, add -2^64 and convert again. */ - Reg tmp = ra_noreg(IR(lref)->r) ? ra_alloc1(as, lref, RSET_FPR) : - ra_scratch(as, RSET_FPR); - MCLabel l_end = emit_label(as); - emit_rr(as, op, dest|REX_64, tmp); - if (st == IRT_NUM) - emit_rma(as, XO_ADDSD, tmp, &as->J->k64[LJ_K64_M2P64]); - else - emit_rma(as, XO_ADDSS, tmp, &as->J->k32[LJ_K32_M2P64]); - emit_sjcc(as, CC_NO, l_end); - emit_gmrmi(as, XG_ARITHi(XOg_CMP), dest|REX_64, 1); - emit_rr(as, op, dest|REX_64, tmp); - ra_left(as, tmp, lref); - - } else -#endif - { - emit_mrm(as, op, - dest|((LJ_64 && irt_is64(ir->t)) ? REX_64 : 0), - asm_fuseload(as, lref, RSET_FPR)); - } - } - } else if (st >= IRT_I8 && st <= IRT_U16) { /* Extend to 32 bit integer. */ - Reg left, dest = ra_dest(as, ir, RSET_GPR); - RegSet allow = RSET_GPR; - x86Op op; - lj_assertA(irt_isint(ir->t) || irt_isu32(ir->t), "bad type for CONV EXT"); - if (st == IRT_I8) { - op = XO_MOVSXb; allow = RSET_GPR8; dest |= FORCE_REX; - } else if (st == IRT_U8) { - op = XO_MOVZXb; allow = RSET_GPR8; dest |= FORCE_REX; - } else if (st == IRT_I16) { - op = XO_MOVSXw; - } else { - op = XO_MOVZXw; - } - left = asm_fuseload(as, lref, allow); - /* Add extra MOV if source is already in wrong register. */ - if (!LJ_64 && left != RID_MRM && !rset_test(allow, left)) { - Reg tmp = ra_scratch(as, allow); - emit_rr(as, op, dest, tmp); - emit_rr(as, XO_MOV, tmp, left); - } else { - emit_mrm(as, op, dest, left); - } - } else { /* 32/64 bit integer conversions. */ - if (LJ_32) { /* Only need to handle 32/32 bit no-op (cast) on x86. */ - Reg dest = ra_dest(as, ir, RSET_GPR); - ra_left(as, dest, lref); /* Do nothing, but may need to move regs. */ - } else if (irt_is64(ir->t)) { - Reg dest = ra_dest(as, ir, RSET_GPR); - if (st64 || !(ir->op2 & IRCONV_SEXT)) { - /* 64/64 bit no-op (cast) or 32 to 64 bit zero extension. */ - ra_left(as, dest, lref); /* Do nothing, but may need to move regs. */ - } else { /* 32 to 64 bit sign extension. */ - Reg left = asm_fuseload(as, lref, RSET_GPR); - emit_mrm(as, XO_MOVSXd, dest|REX_64, left); - } - } else { - Reg dest = ra_dest(as, ir, RSET_GPR); - if (st64 && !(ir->op2 & IRCONV_NONE)) { - Reg left = asm_fuseload(as, lref, RSET_GPR); - /* This is either a 32 bit reg/reg mov which zeroes the hiword - ** or a load of the loword from a 64 bit address. - */ - emit_mrm(as, XO_MOV, dest, left); - } else { /* 32/32 bit no-op (cast). */ - ra_left(as, dest, lref); /* Do nothing, but may need to move regs. */ - } - } - } -} - -#if LJ_32 && LJ_HASFFI -/* No SSE conversions to/from 64 bit on x86, so resort to ugly x87 code. */ - -/* 64 bit integer to FP conversion in 32 bit mode. */ -static void asm_conv_fp_int64(ASMState *as, IRIns *ir) -{ - Reg hi = ra_alloc1(as, ir->op1, RSET_GPR); - Reg lo = ra_alloc1(as, (ir-1)->op1, rset_exclude(RSET_GPR, hi)); - int32_t ofs = sps_scale(ir->s); /* Use spill slot or temp slots. */ - Reg dest = ir->r; - if (ra_hasreg(dest)) { - ra_free(as, dest); - ra_modified(as, dest); - emit_rmro(as, irt_isnum(ir->t) ? XO_MOVSD : XO_MOVSS, dest, RID_ESP, ofs); - } - emit_rmro(as, irt_isnum(ir->t) ? XO_FSTPq : XO_FSTPd, - irt_isnum(ir->t) ? XOg_FSTPq : XOg_FSTPd, RID_ESP, ofs); - if (((ir-1)->op2 & IRCONV_SRCMASK) == IRT_U64) { - /* For inputs in [2^63,2^64-1] add 2^64 to compensate. */ - MCLabel l_end = emit_label(as); - emit_rma(as, XO_FADDq, XOg_FADDq, &as->J->k64[LJ_K64_2P64]); - emit_sjcc(as, CC_NS, l_end); - emit_rr(as, XO_TEST, hi, hi); /* Check if u64 >= 2^63. */ - } else { - lj_assertA(((ir-1)->op2 & IRCONV_SRCMASK) == IRT_I64, "bad type for CONV"); - } - emit_rmro(as, XO_FILDq, XOg_FILDq, RID_ESP, 0); - /* NYI: Avoid narrow-to-wide store-to-load forwarding stall. */ - emit_rmro(as, XO_MOVto, hi, RID_ESP, 4); - emit_rmro(as, XO_MOVto, lo, RID_ESP, 0); -} - -/* FP to 64 bit integer conversion in 32 bit mode. */ -static void asm_conv_int64_fp(ASMState *as, IRIns *ir) -{ - IRType st = (IRType)((ir-1)->op2 & IRCONV_SRCMASK); - IRType dt = (((ir-1)->op2 & IRCONV_DSTMASK) >> IRCONV_DSH); - Reg lo, hi; - int usehi = ra_used(ir); - lj_assertA(st == IRT_NUM || st == IRT_FLOAT, "bad type for CONV"); - lj_assertA(dt == IRT_I64 || dt == IRT_U64, "bad type for CONV"); - hi = ra_dest(as, ir, RSET_GPR); - lo = ra_dest(as, ir-1, rset_exclude(RSET_GPR, hi)); - if (ra_used(ir-1)) emit_rmro(as, XO_MOV, lo, RID_ESP, 0); - /* NYI: Avoid wide-to-narrow store-to-load forwarding stall. */ - if (!(as->flags & JIT_F_SSE3)) { /* Set FPU rounding mode to default. */ - emit_rmro(as, XO_FLDCW, XOg_FLDCW, RID_ESP, 4); - emit_rmro(as, XO_MOVto, lo, RID_ESP, 4); - emit_gri(as, XG_ARITHi(XOg_AND), lo, 0xf3ff); - } - if (dt == IRT_U64) { - /* For the indefinite result -2^63, add -2^64 and convert again. */ - MCLabel l_pop, l_end = emit_label(as); - emit_x87op(as, XI_FPOP); - l_pop = emit_label(as); - emit_sjmp(as, l_end); - if (usehi) emit_rmro(as, XO_MOV, hi, RID_ESP, 4); - if ((as->flags & JIT_F_SSE3)) - emit_rmro(as, XO_FISTTPq, XOg_FISTTPq, RID_ESP, 0); - else - emit_rmro(as, XO_FISTPq, XOg_FISTPq, RID_ESP, 0); - emit_rma(as, XO_FADDd, XOg_FADDd, &as->J->k32[LJ_K32_M2P64]); - emit_sjcc(as, CC_NE, l_pop); - emit_gmroi(as, XG_ARITHi(XOg_CMP), RID_ESP, 0, 0); - emit_sjcc(as, CC_NO, l_pop); - emit_gmrmi(as, XG_ARITHi(XOg_CMP), hi, 1); - usehi = 1; - } - if (usehi) emit_rmro(as, XO_MOV, hi, RID_ESP, 4); - if ((as->flags & JIT_F_SSE3)) { /* Truncation is easy with SSE3. */ - emit_rmro(as, XO_FISTTPq, XOg_FISTTPq, RID_ESP, 0); - } else { /* Otherwise set FPU rounding mode to truncate before the store. */ - emit_rmro(as, XO_FISTPq, XOg_FISTPq, RID_ESP, 0); - emit_rmro(as, XO_FLDCW, XOg_FLDCW, RID_ESP, 0); - emit_rmro(as, XO_MOVtow, lo, RID_ESP, 0); - emit_rmro(as, XO_ARITHw(XOg_OR), lo, RID_ESP, 0); - emit_loadi(as, lo, 0xc00); - emit_rmro(as, XO_FNSTCW, XOg_FNSTCW, RID_ESP, 0); - } - if (dt == IRT_U64) - emit_x87op(as, XI_FDUP); - emit_mrm(as, st == IRT_NUM ? XO_FLDq : XO_FLDd, - st == IRT_NUM ? XOg_FLDq: XOg_FLDd, - asm_fuseload(as, ir->op1, RSET_EMPTY)); -} - -static void asm_conv64(ASMState *as, IRIns *ir) -{ - if (irt_isfp(ir->t)) - asm_conv_fp_int64(as, ir); - else - asm_conv_int64_fp(as, ir); -} -#endif - -static void asm_strto(ASMState *as, IRIns *ir) -{ - /* Force a spill slot for the destination register (if any). */ - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_strscan_num]; - IRRef args[2]; - RegSet drop = RSET_SCRATCH; - if ((drop & RSET_FPR) != RSET_FPR && ra_hasreg(ir->r)) - rset_set(drop, ir->r); /* WIN64 doesn't spill all FPRs. */ - ra_evictset(as, drop); - asm_guardcc(as, CC_E); - emit_rr(as, XO_TEST, RID_RET, RID_RET); /* Test return status. */ - args[0] = ir->op1; /* GCstr *str */ - args[1] = ASMREF_TMP1; /* TValue *n */ - asm_gencall(as, ci, args); - /* Store the result to the spill slot or temp slots. */ - emit_rmro(as, XO_LEA, ra_releasetmp(as, ASMREF_TMP1)|REX_64, - RID_ESP, sps_scale(ir->s)); -} - -/* -- Memory references --------------------------------------------------- */ - -/* Get pointer to TValue. */ -static void asm_tvptr(ASMState *as, Reg dest, IRRef ref, MSize mode) -{ - if ((mode & IRTMPREF_IN1)) { - IRIns *ir = IR(ref); - if (irt_isnum(ir->t)) { - if (irref_isk(ref) && !(mode & IRTMPREF_OUT1)) { - /* Use the number constant itself as a TValue. */ - emit_loada(as, dest, ir_knum(ir)); - return; - } - emit_rmro(as, XO_MOVSDto, ra_alloc1(as, ref, RSET_FPR), dest, 0); - } else { -#if LJ_GC64 - if (irref_isk(ref)) { - TValue k; - lj_ir_kvalue(as->J->L, &k, ir); - emit_movmroi(as, dest, 4, k.u32.hi); - emit_movmroi(as, dest, 0, k.u32.lo); - } else { - /* TODO: 64 bit store + 32 bit load-modify-store is suboptimal. */ - Reg src = ra_alloc1(as, ref, rset_exclude(RSET_GPR, dest)); - if (irt_is64(ir->t)) { - emit_u32(as, irt_toitype(ir->t) << 15); - emit_rmro(as, XO_ARITHi, XOg_OR, dest, 4); - } else { - emit_movmroi(as, dest, 4, (irt_toitype(ir->t) << 15)); - } - emit_movtomro(as, REX_64IR(ir, src), dest, 0); - } -#else - if (!irref_isk(ref)) { - Reg src = ra_alloc1(as, ref, rset_exclude(RSET_GPR, dest)); - emit_movtomro(as, REX_64IR(ir, src), dest, 0); - } else if (!irt_ispri(ir->t)) { - emit_movmroi(as, dest, 0, ir->i); - } - if (!(LJ_64 && irt_islightud(ir->t))) - emit_movmroi(as, dest, 4, irt_toitype(ir->t)); -#endif - } - } - emit_loada(as, dest, &J2G(as->J)->tmptv); /* g->tmptv holds the TValue(s). */ -} - -static void asm_aref(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - asm_fusearef(as, ir, RSET_GPR); - if (!(as->mrm.idx == RID_NONE && as->mrm.ofs == 0)) - emit_mrm(as, XO_LEA, dest|REX_GC64, RID_MRM); - else if (as->mrm.base != dest) - emit_rr(as, XO_MOV, dest|REX_GC64, as->mrm.base); -} - -/* Inlined hash lookup. Specialized for key type and for const keys. -** The equivalent C code is: -** Node *n = hashkey(t, key); -** do { -** if (lj_obj_equal(&n->key, key)) return &n->val; -** } while ((n = nextnode(n))); -** return niltv(L); -*/ -static void asm_href(ASMState *as, IRIns *ir, IROp merge) -{ - RegSet allow = RSET_GPR; - int destused = ra_used(ir); - Reg dest = ra_dest(as, ir, allow); - Reg tab = ra_alloc1(as, ir->op1, rset_clear(allow, dest)); - Reg key = RID_NONE, tmp = RID_NONE; - IRIns *irkey = IR(ir->op2); - int isk = irref_isk(ir->op2); - IRType1 kt = irkey->t; - uint32_t khash; - MCLabel l_end, l_loop, l_next; - - if (!isk) { - rset_clear(allow, tab); - key = ra_alloc1(as, ir->op2, irt_isnum(kt) ? RSET_FPR : allow); - if (LJ_GC64 || !irt_isstr(kt)) - tmp = ra_scratch(as, rset_exclude(allow, key)); - } - - /* Key not found in chain: jump to exit (if merged) or load niltv. */ - l_end = emit_label(as); - if (merge == IR_NE) - asm_guardcc(as, CC_E); /* XI_JMP is not found by lj_asm_patchexit. */ - else if (destused) - emit_loada(as, dest, niltvg(J2G(as->J))); - - /* Follow hash chain until the end. */ - l_loop = emit_sjcc_label(as, CC_NZ); - emit_rr(as, XO_TEST, dest|REX_GC64, dest); - emit_rmro(as, XO_MOV, dest|REX_GC64, dest, offsetof(Node, next)); - l_next = emit_label(as); - - /* Type and value comparison. */ - if (merge == IR_EQ) - asm_guardcc(as, CC_E); - else - emit_sjcc(as, CC_E, l_end); - checkmclim(as); - if (irt_isnum(kt)) { - if (isk) { - /* Assumes -0.0 is already canonicalized to +0.0. */ - emit_gmroi(as, XG_ARITHi(XOg_CMP), dest, offsetof(Node, key.u32.lo), - (int32_t)ir_knum(irkey)->u32.lo); - emit_sjcc(as, CC_NE, l_next); - emit_gmroi(as, XG_ARITHi(XOg_CMP), dest, offsetof(Node, key.u32.hi), - (int32_t)ir_knum(irkey)->u32.hi); - } else { - emit_sjcc(as, CC_P, l_next); - emit_rmro(as, XO_UCOMISD, key, dest, offsetof(Node, key.n)); - emit_sjcc(as, CC_AE, l_next); - /* The type check avoids NaN penalties and complaints from Valgrind. */ -#if LJ_64 && !LJ_GC64 - emit_u32(as, LJ_TISNUM); - emit_rmro(as, XO_ARITHi, XOg_CMP, dest, offsetof(Node, key.it)); -#else - emit_i8(as, LJ_TISNUM); - emit_rmro(as, XO_ARITHi8, XOg_CMP, dest, offsetof(Node, key.it)); -#endif - } -#if LJ_64 && !LJ_GC64 - } else if (irt_islightud(kt)) { - emit_rmro(as, XO_CMP, key|REX_64, dest, offsetof(Node, key.u64)); -#endif -#if LJ_GC64 - } else if (irt_isaddr(kt)) { - if (isk) { - TValue k; - k.u64 = ((uint64_t)irt_toitype(irkey->t) << 47) | irkey[1].tv.u64; - emit_gmroi(as, XG_ARITHi(XOg_CMP), dest, offsetof(Node, key.u32.lo), - k.u32.lo); - emit_sjcc(as, CC_NE, l_next); - emit_gmroi(as, XG_ARITHi(XOg_CMP), dest, offsetof(Node, key.u32.hi), - k.u32.hi); - } else { - emit_rmro(as, XO_CMP, tmp|REX_64, dest, offsetof(Node, key.u64)); - } - } else { - lj_assertA(irt_ispri(kt) && !irt_isnil(kt), "bad HREF key type"); - emit_u32(as, (irt_toitype(kt)<<15)|0x7fff); - emit_rmro(as, XO_ARITHi, XOg_CMP, dest, offsetof(Node, key.it)); -#else - } else { - if (!irt_ispri(kt)) { - lj_assertA(irt_isaddr(kt), "bad HREF key type"); - if (isk) - emit_gmroi(as, XG_ARITHi(XOg_CMP), dest, offsetof(Node, key.gcr), - ptr2addr(ir_kgc(irkey))); - else - emit_rmro(as, XO_CMP, key, dest, offsetof(Node, key.gcr)); - emit_sjcc(as, CC_NE, l_next); - } - lj_assertA(!irt_isnil(kt), "bad HREF key type"); - emit_i8(as, irt_toitype(kt)); - emit_rmro(as, XO_ARITHi8, XOg_CMP, dest, offsetof(Node, key.it)); -#endif - } - emit_sfixup(as, l_loop); -#if LJ_GC64 - if (!isk && irt_isaddr(kt)) { - emit_rr(as, XO_OR, tmp|REX_64, key); - emit_loadu64(as, tmp, (uint64_t)irt_toitype(kt) << 47); - } -#endif - - /* Load main position relative to tab->node into dest. */ - khash = isk ? ir_khash(as, irkey) : 1; - if (khash == 0) { - emit_rmro(as, XO_MOV, dest|REX_GC64, tab, offsetof(GCtab, node)); - } else { - emit_rmro(as, XO_ARITH(XOg_ADD), dest|REX_GC64, tab, offsetof(GCtab,node)); - emit_shifti(as, XOg_SHL, dest, 3); - emit_rmrxo(as, XO_LEA, dest, dest, dest, XM_SCALE2, 0); - if (isk) { - emit_gri(as, XG_ARITHi(XOg_AND), dest, (int32_t)khash); - emit_rmro(as, XO_MOV, dest, tab, offsetof(GCtab, hmask)); - } else if (irt_isstr(kt)) { - emit_rmro(as, XO_ARITH(XOg_AND), dest, key, offsetof(GCstr, sid)); - emit_rmro(as, XO_MOV, dest, tab, offsetof(GCtab, hmask)); - } else { /* Must match with hashrot() in lj_tab.c. */ - emit_rmro(as, XO_ARITH(XOg_AND), dest, tab, offsetof(GCtab, hmask)); - emit_rr(as, XO_ARITH(XOg_SUB), dest, tmp); - emit_shifti(as, XOg_ROL, tmp, HASH_ROT3); - emit_rr(as, XO_ARITH(XOg_XOR), dest, tmp); - checkmclim(as); - emit_shifti(as, XOg_ROL, dest, HASH_ROT2); - emit_rr(as, XO_ARITH(XOg_SUB), tmp, dest); - emit_shifti(as, XOg_ROL, dest, HASH_ROT1); - emit_rr(as, XO_ARITH(XOg_XOR), tmp, dest); - if (irt_isnum(kt)) { - emit_rr(as, XO_ARITH(XOg_ADD), dest, dest); -#if LJ_64 - emit_shifti(as, XOg_SHR|REX_64, dest, 32); - emit_rr(as, XO_MOV, tmp, dest); - emit_rr(as, XO_MOVDto, key|REX_64, dest); -#else - emit_rmro(as, XO_MOV, dest, RID_ESP, ra_spill(as, irkey)+4); - emit_rr(as, XO_MOVDto, key, tmp); -#endif - } else { - emit_rr(as, XO_MOV, tmp, key); -#if LJ_GC64 - emit_gri(as, XG_ARITHi(XOg_XOR), dest, irt_toitype(kt) << 15); - if ((as->flags & JIT_F_BMI2)) { - emit_i8(as, 32); - emit_mrm(as, XV_RORX|VEX_64, dest, key); - } else { - emit_shifti(as, XOg_SHR|REX_64, dest, 32); - emit_rr(as, XO_MOV, dest|REX_64, key|REX_64); - } -#else - emit_rmro(as, XO_LEA, dest, key, HASH_BIAS); -#endif - } - } - } -} - -static void asm_hrefk(ASMState *as, IRIns *ir) -{ - IRIns *kslot = IR(ir->op2); - IRIns *irkey = IR(kslot->op1); - int32_t ofs = (int32_t)(kslot->op2 * sizeof(Node)); - Reg dest = ra_used(ir) ? ra_dest(as, ir, RSET_GPR) : RID_NONE; - Reg node = ra_alloc1(as, ir->op1, RSET_GPR); -#if !LJ_64 - MCLabel l_exit; -#endif - lj_assertA(ofs % sizeof(Node) == 0, "unaligned HREFK slot"); - if (ra_hasreg(dest)) { - if (ofs != 0) { - if (dest == node) - emit_gri(as, XG_ARITHi(XOg_ADD), dest|REX_GC64, ofs); - else - emit_rmro(as, XO_LEA, dest|REX_GC64, node, ofs); - } else if (dest != node) { - emit_rr(as, XO_MOV, dest|REX_GC64, node); - } - } - asm_guardcc(as, CC_NE); -#if LJ_64 - if (!irt_ispri(irkey->t)) { - Reg key = ra_scratch(as, rset_exclude(RSET_GPR, node)); - emit_rmro(as, XO_CMP, key|REX_64, node, - ofs + (int32_t)offsetof(Node, key.u64)); - lj_assertA(irt_isnum(irkey->t) || irt_isgcv(irkey->t), - "bad HREFK key type"); - /* Assumes -0.0 is already canonicalized to +0.0. */ - emit_loadu64(as, key, irt_isnum(irkey->t) ? ir_knum(irkey)->u64 : -#if LJ_GC64 - ((uint64_t)irt_toitype(irkey->t) << 47) | - (uint64_t)ir_kgc(irkey)); -#else - ((uint64_t)irt_toitype(irkey->t) << 32) | - (uint64_t)(uint32_t)ptr2addr(ir_kgc(irkey))); -#endif - } else { - lj_assertA(!irt_isnil(irkey->t), "bad HREFK key type"); -#if LJ_GC64 - emit_i32(as, (irt_toitype(irkey->t)<<15)|0x7fff); - emit_rmro(as, XO_ARITHi, XOg_CMP, node, - ofs + (int32_t)offsetof(Node, key.it)); -#else - emit_i8(as, irt_toitype(irkey->t)); - emit_rmro(as, XO_ARITHi8, XOg_CMP, node, - ofs + (int32_t)offsetof(Node, key.it)); -#endif - } -#else - l_exit = emit_label(as); - if (irt_isnum(irkey->t)) { - /* Assumes -0.0 is already canonicalized to +0.0. */ - emit_gmroi(as, XG_ARITHi(XOg_CMP), node, - ofs + (int32_t)offsetof(Node, key.u32.lo), - (int32_t)ir_knum(irkey)->u32.lo); - emit_sjcc(as, CC_NE, l_exit); - emit_gmroi(as, XG_ARITHi(XOg_CMP), node, - ofs + (int32_t)offsetof(Node, key.u32.hi), - (int32_t)ir_knum(irkey)->u32.hi); - } else { - if (!irt_ispri(irkey->t)) { - lj_assertA(irt_isgcv(irkey->t), "bad HREFK key type"); - emit_gmroi(as, XG_ARITHi(XOg_CMP), node, - ofs + (int32_t)offsetof(Node, key.gcr), - ptr2addr(ir_kgc(irkey))); - emit_sjcc(as, CC_NE, l_exit); - } - lj_assertA(!irt_isnil(irkey->t), "bad HREFK key type"); - emit_i8(as, irt_toitype(irkey->t)); - emit_rmro(as, XO_ARITHi8, XOg_CMP, node, - ofs + (int32_t)offsetof(Node, key.it)); - } -#endif -} - -static void asm_uref(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - int guarded = (irt_t(ir->t) & (IRT_GUARD|IRT_TYPE)) == (IRT_GUARD|IRT_PGC); - if (irref_isk(ir->op1) && !guarded) { - GCfunc *fn = ir_kfunc(IR(ir->op1)); - MRef *v = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.v; - emit_rma(as, XO_MOV, dest|REX_GC64, v); - } else { - Reg uv = ra_scratch(as, RSET_GPR); - if (ir->o == IR_UREFC) - emit_rmro(as, XO_LEA, dest|REX_GC64, uv, offsetof(GCupval, tv)); - else - emit_rmro(as, XO_MOV, dest|REX_GC64, uv, offsetof(GCupval, v)); - if (guarded) { - asm_guardcc(as, ir->o == IR_UREFC ? CC_E : CC_NE); - emit_i8(as, 0); - emit_rmro(as, XO_ARITHib, XOg_CMP, uv, offsetof(GCupval, closed)); - } - if (irref_isk(ir->op1)) { - GCfunc *fn = ir_kfunc(IR(ir->op1)); - GCobj *o = gcref(fn->l.uvptr[(ir->op2 >> 8)]); - emit_loada(as, uv, o); - } else { - emit_rmro(as, XO_MOV, uv|REX_GC64, ra_alloc1(as, ir->op1, RSET_GPR), - (int32_t)offsetof(GCfuncL, uvptr) + - (int32_t)sizeof(MRef) * (int32_t)(ir->op2 >> 8)); - } - } -} - -static void asm_fref(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - asm_fusefref(as, ir, RSET_GPR); - emit_mrm(as, XO_LEA, dest, RID_MRM); -} - -static void asm_strref(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - asm_fusestrref(as, ir, RSET_GPR); - if (as->mrm.base == RID_NONE) - emit_loadi(as, dest, as->mrm.ofs); - else if (as->mrm.base == dest && as->mrm.idx == RID_NONE) - emit_gri(as, XG_ARITHi(XOg_ADD), dest|REX_GC64, as->mrm.ofs); - else - emit_mrm(as, XO_LEA, dest|REX_GC64, RID_MRM); -} - -/* -- Loads and stores ---------------------------------------------------- */ - -static void asm_fxload(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR); - x86Op xo; - if (ir->o == IR_FLOAD) - asm_fusefref(as, ir, RSET_GPR); - else - asm_fusexref(as, ir->op1, RSET_GPR); - /* ir->op2 is ignored -- unaligned loads are ok on x86. */ - switch (irt_type(ir->t)) { - case IRT_I8: xo = XO_MOVSXb; break; - case IRT_U8: xo = XO_MOVZXb; break; - case IRT_I16: xo = XO_MOVSXw; break; - case IRT_U16: xo = XO_MOVZXw; break; - case IRT_NUM: xo = XO_MOVSD; break; - case IRT_FLOAT: xo = XO_MOVSS; break; - default: - if (LJ_64 && irt_is64(ir->t)) - dest |= REX_64; - else - lj_assertA(irt_isint(ir->t) || irt_isu32(ir->t) || irt_isaddr(ir->t), - "unsplit 64 bit load"); - xo = XO_MOV; - break; - } - emit_mrm(as, xo, dest, RID_MRM); -} - -#define asm_fload(as, ir) asm_fxload(as, ir) -#define asm_xload(as, ir) asm_fxload(as, ir) - -static void asm_fxstore(ASMState *as, IRIns *ir) -{ - RegSet allow = RSET_GPR; - Reg src = RID_NONE, osrc = RID_NONE; - int32_t k = 0; - if (ir->r == RID_SINK) - return; - /* The IRT_I16/IRT_U16 stores should never be simplified for constant - ** values since mov word [mem], imm16 has a length-changing prefix. - */ - if (irt_isi16(ir->t) || irt_isu16(ir->t) || irt_isfp(ir->t) || - !asm_isk32(as, ir->op2, &k)) { - RegSet allow8 = irt_isfp(ir->t) ? RSET_FPR : - (irt_isi8(ir->t) || irt_isu8(ir->t)) ? RSET_GPR8 : RSET_GPR; - src = osrc = ra_alloc1(as, ir->op2, allow8); - if (!LJ_64 && !rset_test(allow8, src)) { /* Already in wrong register. */ - rset_clear(allow, osrc); - src = ra_scratch(as, allow8); - } - rset_clear(allow, src); - } - if (ir->o == IR_FSTORE) { - asm_fusefref(as, IR(ir->op1), allow); - } else { - asm_fusexref(as, ir->op1, allow); - if (LJ_32 && ir->o == IR_HIOP) as->mrm.ofs += 4; - } - if (ra_hasreg(src)) { - x86Op xo; - switch (irt_type(ir->t)) { - case IRT_I8: case IRT_U8: xo = XO_MOVtob; src |= FORCE_REX; break; - case IRT_I16: case IRT_U16: xo = XO_MOVtow; break; - case IRT_NUM: xo = XO_MOVSDto; break; - case IRT_FLOAT: xo = XO_MOVSSto; break; -#if LJ_64 && !LJ_GC64 - case IRT_LIGHTUD: - /* NYI: mask 64 bit lightuserdata. */ - lj_assertA(0, "store of lightuserdata"); -#endif - default: - if (LJ_64 && irt_is64(ir->t)) - src |= REX_64; - else - lj_assertA(irt_isint(ir->t) || irt_isu32(ir->t) || irt_isaddr(ir->t), - "unsplit 64 bit store"); - xo = XO_MOVto; - break; - } - emit_mrm(as, xo, src, RID_MRM); - if (!LJ_64 && src != osrc) { - ra_noweak(as, osrc); - emit_rr(as, XO_MOV, src, osrc); - } - } else { - if (irt_isi8(ir->t) || irt_isu8(ir->t)) { - emit_i8(as, k); - emit_mrm(as, XO_MOVmib, 0, RID_MRM); - } else { - lj_assertA(irt_is64(ir->t) || irt_isint(ir->t) || irt_isu32(ir->t) || - irt_isaddr(ir->t), "bad store type"); - emit_i32(as, k); - emit_mrm(as, XO_MOVmi, REX_64IR(ir, 0), RID_MRM); - } - } -} - -#define asm_fstore(as, ir) asm_fxstore(as, ir) -#define asm_xstore(as, ir) asm_fxstore(as, ir) - -#if LJ_64 && !LJ_GC64 -static Reg asm_load_lightud64(ASMState *as, IRIns *ir, int typecheck) -{ - if (ra_used(ir) || typecheck) { - Reg dest = ra_dest(as, ir, RSET_GPR); - if (typecheck) { - Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, dest)); - asm_guardcc(as, CC_NE); - emit_i8(as, -2); - emit_rr(as, XO_ARITHi8, XOg_CMP, tmp); - emit_shifti(as, XOg_SAR|REX_64, tmp, 47); - emit_rr(as, XO_MOV, tmp|REX_64, dest); - } - return dest; - } else { - return RID_NONE; - } -} -#endif - -static void asm_ahuvload(ASMState *as, IRIns *ir) -{ -#if LJ_GC64 - Reg tmp = RID_NONE; -#endif - lj_assertA(irt_isnum(ir->t) || irt_ispri(ir->t) || irt_isaddr(ir->t) || - (LJ_DUALNUM && irt_isint(ir->t)), - "bad load type %d", irt_type(ir->t)); -#if LJ_64 && !LJ_GC64 - if (irt_islightud(ir->t)) { - Reg dest = asm_load_lightud64(as, ir, 1); - if (ra_hasreg(dest)) { - checkmclim(as); - asm_fuseahuref(as, ir->op1, RSET_GPR); - if (ir->o == IR_VLOAD) as->mrm.ofs += 8 * ir->op2; - emit_mrm(as, XO_MOV, dest|REX_64, RID_MRM); - } - return; - } else -#endif - if (ra_used(ir)) { - RegSet allow = irt_isnum(ir->t) ? RSET_FPR : RSET_GPR; - Reg dest = ra_dest(as, ir, allow); - asm_fuseahuref(as, ir->op1, RSET_GPR); - if (ir->o == IR_VLOAD) as->mrm.ofs += 8 * ir->op2; -#if LJ_GC64 - if (irt_isaddr(ir->t)) { - emit_shifti(as, XOg_SHR|REX_64, dest, 17); - asm_guardcc(as, CC_NE); - emit_i8(as, irt_toitype(ir->t)); - emit_rr(as, XO_ARITHi8, XOg_CMP, dest); - emit_i8(as, XI_O16); - if ((as->flags & JIT_F_BMI2)) { - emit_i8(as, 47); - emit_mrm(as, XV_RORX|VEX_64, dest, RID_MRM); - } else { - emit_shifti(as, XOg_ROR|REX_64, dest, 47); - emit_mrm(as, XO_MOV, dest|REX_64, RID_MRM); - } - return; - } else -#endif - emit_mrm(as, dest < RID_MAX_GPR ? XO_MOV : XO_MOVSD, dest, RID_MRM); - } else { - RegSet gpr = RSET_GPR; -#if LJ_GC64 - if (irt_isaddr(ir->t)) { - tmp = ra_scratch(as, RSET_GPR); - gpr = rset_exclude(gpr, tmp); - } -#endif - asm_fuseahuref(as, ir->op1, gpr); - if (ir->o == IR_VLOAD) as->mrm.ofs += 8 * ir->op2; - } - /* Always do the type check, even if the load result is unused. */ - as->mrm.ofs += 4; - asm_guardcc(as, irt_isnum(ir->t) ? CC_AE : CC_NE); - if (LJ_64 && irt_type(ir->t) >= IRT_NUM) { - lj_assertA(irt_isinteger(ir->t) || irt_isnum(ir->t), - "bad load type %d", irt_type(ir->t)); - checkmclim(as); -#if LJ_GC64 - emit_u32(as, LJ_TISNUM << 15); -#else - emit_u32(as, LJ_TISNUM); -#endif - emit_mrm(as, XO_ARITHi, XOg_CMP, RID_MRM); -#if LJ_GC64 - } else if (irt_isaddr(ir->t)) { - as->mrm.ofs -= 4; - emit_i8(as, irt_toitype(ir->t)); - emit_mrm(as, XO_ARITHi8, XOg_CMP, tmp); - emit_shifti(as, XOg_SAR|REX_64, tmp, 47); - emit_mrm(as, XO_MOV, tmp|REX_64, RID_MRM); - } else if (irt_isnil(ir->t)) { - as->mrm.ofs -= 4; - emit_i8(as, -1); - emit_mrm(as, XO_ARITHi8, XOg_CMP|REX_64, RID_MRM); - } else { - emit_u32(as, (irt_toitype(ir->t) << 15) | 0x7fff); - emit_mrm(as, XO_ARITHi, XOg_CMP, RID_MRM); -#else - } else { - emit_i8(as, irt_toitype(ir->t)); - emit_mrm(as, XO_ARITHi8, XOg_CMP, RID_MRM); -#endif - } -} - -static void asm_ahustore(ASMState *as, IRIns *ir) -{ - if (ir->r == RID_SINK) - return; - if (irt_isnum(ir->t)) { - Reg src = ra_alloc1(as, ir->op2, RSET_FPR); - asm_fuseahuref(as, ir->op1, RSET_GPR); - emit_mrm(as, XO_MOVSDto, src, RID_MRM); -#if LJ_64 && !LJ_GC64 - } else if (irt_islightud(ir->t)) { - Reg src = ra_alloc1(as, ir->op2, RSET_GPR); - asm_fuseahuref(as, ir->op1, rset_exclude(RSET_GPR, src)); - emit_mrm(as, XO_MOVto, src|REX_64, RID_MRM); -#endif -#if LJ_GC64 - } else if (irref_isk(ir->op2)) { - TValue k; - lj_ir_kvalue(as->J->L, &k, IR(ir->op2)); - asm_fuseahuref(as, ir->op1, RSET_GPR); - if (tvisnil(&k)) { - emit_i32(as, -1); - emit_mrm(as, XO_MOVmi, REX_64, RID_MRM); - } else { - emit_u32(as, k.u32.lo); - emit_mrm(as, XO_MOVmi, 0, RID_MRM); - as->mrm.ofs += 4; - emit_u32(as, k.u32.hi); - emit_mrm(as, XO_MOVmi, 0, RID_MRM); - } -#endif - } else { - IRIns *irr = IR(ir->op2); - RegSet allow = RSET_GPR; - Reg src = RID_NONE; - if (!irref_isk(ir->op2)) { - src = ra_alloc1(as, ir->op2, allow); - rset_clear(allow, src); - } - asm_fuseahuref(as, ir->op1, allow); - if (ra_hasreg(src)) { -#if LJ_GC64 - if (!(LJ_DUALNUM && irt_isinteger(ir->t))) { - /* TODO: 64 bit store + 32 bit load-modify-store is suboptimal. */ - as->mrm.ofs += 4; - emit_u32(as, irt_toitype(ir->t) << 15); - emit_mrm(as, XO_ARITHi, XOg_OR, RID_MRM); - as->mrm.ofs -= 4; - emit_mrm(as, XO_MOVto, src|REX_64, RID_MRM); - return; - } -#endif - emit_mrm(as, XO_MOVto, src, RID_MRM); - } else if (!irt_ispri(irr->t)) { - lj_assertA(irt_isaddr(ir->t) || (LJ_DUALNUM && irt_isinteger(ir->t)), - "bad store type"); - emit_i32(as, irr->i); - emit_mrm(as, XO_MOVmi, 0, RID_MRM); - } - as->mrm.ofs += 4; -#if LJ_GC64 - lj_assertA(LJ_DUALNUM && irt_isinteger(ir->t), "bad store type"); - emit_i32(as, LJ_TNUMX << 15); -#else - emit_i32(as, (int32_t)irt_toitype(ir->t)); -#endif - emit_mrm(as, XO_MOVmi, 0, RID_MRM); - } -} - -static void asm_sload(ASMState *as, IRIns *ir) -{ - int32_t ofs = 8*((int32_t)ir->op1-1-LJ_FR2) + - (!LJ_FR2 && (ir->op2 & IRSLOAD_FRAME) ? 4 : 0); - IRType1 t = ir->t; - Reg base; - lj_assertA(!(ir->op2 & IRSLOAD_PARENT), - "bad parent SLOAD"); /* Handled by asm_head_side(). */ - lj_assertA(irt_isguard(t) || !(ir->op2 & IRSLOAD_TYPECHECK), - "inconsistent SLOAD variant"); - lj_assertA(LJ_DUALNUM || - !irt_isint(t) || - (ir->op2 & (IRSLOAD_CONVERT|IRSLOAD_FRAME|IRSLOAD_KEYINDEX)), - "bad SLOAD type"); - if ((ir->op2 & IRSLOAD_CONVERT) && irt_isguard(t) && irt_isint(t)) { - Reg left = ra_scratch(as, RSET_FPR); - asm_tointg(as, ir, left); /* Frees dest reg. Do this before base alloc. */ - base = ra_alloc1(as, REF_BASE, RSET_GPR); - emit_rmro(as, XO_MOVSD, left, base, ofs); - t.irt = IRT_NUM; /* Continue with a regular number type check. */ -#if LJ_64 && !LJ_GC64 - } else if (irt_islightud(t)) { - Reg dest = asm_load_lightud64(as, ir, (ir->op2 & IRSLOAD_TYPECHECK)); - if (ra_hasreg(dest)) { - base = ra_alloc1(as, REF_BASE, RSET_GPR); - emit_rmro(as, XO_MOV, dest|REX_64, base, ofs); - } - return; -#endif - } else if (ra_used(ir)) { - RegSet allow = irt_isnum(t) ? RSET_FPR : RSET_GPR; - Reg dest = ra_dest(as, ir, allow); - base = ra_alloc1(as, REF_BASE, RSET_GPR); - lj_assertA(irt_isnum(t) || irt_isint(t) || irt_isaddr(t), - "bad SLOAD type %d", irt_type(t)); - if ((ir->op2 & IRSLOAD_CONVERT)) { - t.irt = irt_isint(t) ? IRT_NUM : IRT_INT; /* Check for original type. */ - emit_rmro(as, irt_isint(t) ? XO_CVTSI2SD : XO_CVTTSD2SI, dest, base, ofs); - } else { -#if LJ_GC64 - if (irt_isaddr(t)) { - /* LJ_GC64 type check + tag removal without BMI2 and with BMI2: - ** - ** mov r64, [addr] rorx r64, [addr], 47 - ** ror r64, 47 - ** cmp r16, itype cmp r16, itype - ** jne ->exit jne ->exit - ** shr r64, 16 shr r64, 16 - */ - emit_shifti(as, XOg_SHR|REX_64, dest, 17); - if ((ir->op2 & IRSLOAD_TYPECHECK)) { - asm_guardcc(as, CC_NE); - emit_i8(as, irt_toitype(t)); - emit_rr(as, XO_ARITHi8, XOg_CMP, dest); - emit_i8(as, XI_O16); - } - if ((as->flags & JIT_F_BMI2)) { - emit_i8(as, 47); - emit_rmro(as, XV_RORX|VEX_64, dest, base, ofs); - } else { - if ((ir->op2 & IRSLOAD_TYPECHECK)) - emit_shifti(as, XOg_ROR|REX_64, dest, 47); - else - emit_shifti(as, XOg_SHL|REX_64, dest, 17); - emit_rmro(as, XO_MOV, dest|REX_64, base, ofs); - } - return; - } else -#endif - emit_rmro(as, irt_isnum(t) ? XO_MOVSD : XO_MOV, dest, base, ofs); - } - } else { - if (!(ir->op2 & IRSLOAD_TYPECHECK)) - return; /* No type check: avoid base alloc. */ - base = ra_alloc1(as, REF_BASE, RSET_GPR); - } - if ((ir->op2 & IRSLOAD_TYPECHECK)) { - /* Need type check, even if the load result is unused. */ - asm_guardcc(as, irt_isnum(t) ? CC_AE : CC_NE); - if ((LJ_64 && irt_type(t) >= IRT_NUM) || (ir->op2 & IRSLOAD_KEYINDEX)) { - lj_assertA(irt_isinteger(t) || irt_isnum(t), - "bad SLOAD type %d", irt_type(t)); - emit_u32(as, (ir->op2 & IRSLOAD_KEYINDEX) ? LJ_KEYINDEX : - LJ_GC64 ? (LJ_TISNUM << 15) : LJ_TISNUM); - emit_rmro(as, XO_ARITHi, XOg_CMP, base, ofs+4); -#if LJ_GC64 - } else if (irt_isnil(t)) { - /* LJ_GC64 type check for nil: - ** - ** cmp qword [addr], -1 - ** jne ->exit - */ - emit_i8(as, -1); - emit_rmro(as, XO_ARITHi8, XOg_CMP|REX_64, base, ofs); - } else if (irt_ispri(t)) { - emit_u32(as, (irt_toitype(t) << 15) | 0x7fff); - emit_rmro(as, XO_ARITHi, XOg_CMP, base, ofs+4); - } else { - /* LJ_GC64 type check only: - ** - ** mov r64, [addr] - ** sar r64, 47 - ** cmp r32, itype - ** jne ->exit - */ - Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, base)); - emit_i8(as, irt_toitype(t)); - emit_rr(as, XO_ARITHi8, XOg_CMP, tmp); - emit_shifti(as, XOg_SAR|REX_64, tmp, 47); - emit_rmro(as, XO_MOV, tmp|REX_64, base, ofs); -#else - } else { - emit_i8(as, irt_toitype(t)); - emit_rmro(as, XO_ARITHi8, XOg_CMP, base, ofs+4); -#endif - } - } -} - -/* -- Allocations --------------------------------------------------------- */ - -#if LJ_HASFFI -static void asm_cnew(ASMState *as, IRIns *ir) -{ - CTState *cts = ctype_ctsG(J2G(as->J)); - CTypeID id = (CTypeID)IR(ir->op1)->i; - CTSize sz; - CTInfo info = lj_ctype_info(cts, id, &sz); - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_mem_newgco]; - IRRef args[4]; - lj_assertA(sz != CTSIZE_INVALID || (ir->o == IR_CNEW && ir->op2 != REF_NIL), - "bad CNEW/CNEWI operands"); - - as->gcsteps++; - asm_setupresult(as, ir, ci); /* GCcdata * */ - - /* Initialize immutable cdata object. */ - if (ir->o == IR_CNEWI) { - RegSet allow = (RSET_GPR & ~RSET_SCRATCH); -#if LJ_64 - Reg r64 = sz == 8 ? REX_64 : 0; - if (irref_isk(ir->op2)) { - IRIns *irk = IR(ir->op2); - uint64_t k = (irk->o == IR_KINT64 || - (LJ_GC64 && (irk->o == IR_KPTR || irk->o == IR_KKPTR))) ? - ir_k64(irk)->u64 : (uint64_t)(uint32_t)irk->i; - if (sz == 4 || checki32((int64_t)k)) { - emit_i32(as, (int32_t)k); - emit_rmro(as, XO_MOVmi, r64, RID_RET, sizeof(GCcdata)); - } else { - emit_movtomro(as, RID_ECX + r64, RID_RET, sizeof(GCcdata)); - emit_loadu64(as, RID_ECX, k); - } - } else { - Reg r = ra_alloc1(as, ir->op2, allow); - emit_movtomro(as, r + r64, RID_RET, sizeof(GCcdata)); - } -#else - int32_t ofs = sizeof(GCcdata); - if (sz == 8) { - ofs += 4; ir++; - lj_assertA(ir->o == IR_HIOP, "missing CNEWI HIOP"); - } - do { - if (irref_isk(ir->op2)) { - emit_movmroi(as, RID_RET, ofs, IR(ir->op2)->i); - } else { - Reg r = ra_alloc1(as, ir->op2, allow); - emit_movtomro(as, r, RID_RET, ofs); - rset_clear(allow, r); - } - if (ofs == sizeof(GCcdata)) break; - ofs -= 4; ir--; - } while (1); -#endif - lj_assertA(sz == 4 || sz == 8, "bad CNEWI size %d", sz); - } else if (ir->op2 != REF_NIL) { /* Create VLA/VLS/aligned cdata. */ - ci = &lj_ir_callinfo[IRCALL_lj_cdata_newv]; - args[0] = ASMREF_L; /* lua_State *L */ - args[1] = ir->op1; /* CTypeID id */ - args[2] = ir->op2; /* CTSize sz */ - args[3] = ASMREF_TMP1; /* CTSize align */ - asm_gencall(as, ci, args); - emit_loadi(as, ra_releasetmp(as, ASMREF_TMP1), (int32_t)ctype_align(info)); - return; - } - - /* Combine initialization of marked, gct and ctypeid. */ - emit_movtomro(as, RID_ECX, RID_RET, offsetof(GCcdata, marked)); - emit_gri(as, XG_ARITHi(XOg_OR), RID_ECX, - (int32_t)((~LJ_TCDATA<<8)+(id<<16))); - emit_gri(as, XG_ARITHi(XOg_AND), RID_ECX, LJ_GC_WHITES); - emit_opgl(as, XO_MOVZXb, RID_ECX, gc.currentwhite); - - args[0] = ASMREF_L; /* lua_State *L */ - args[1] = ASMREF_TMP1; /* MSize size */ - asm_gencall(as, ci, args); - emit_loadi(as, ra_releasetmp(as, ASMREF_TMP1), (int32_t)(sz+sizeof(GCcdata))); -} -#endif - -/* -- Write barriers ------------------------------------------------------ */ - -static void asm_tbar(ASMState *as, IRIns *ir) -{ - Reg tab = ra_alloc1(as, ir->op1, RSET_GPR); - Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, tab)); - MCLabel l_end = emit_label(as); - emit_movtomro(as, tmp|REX_GC64, tab, offsetof(GCtab, gclist)); - emit_setgl(as, tab, gc.grayagain); - emit_getgl(as, tmp, gc.grayagain); - emit_i8(as, ~LJ_GC_BLACK); - emit_rmro(as, XO_ARITHib, XOg_AND, tab, offsetof(GCtab, marked)); - emit_sjcc(as, CC_Z, l_end); - emit_i8(as, LJ_GC_BLACK); - emit_rmro(as, XO_GROUP3b, XOg_TEST, tab, offsetof(GCtab, marked)); -} - -static void asm_obar(ASMState *as, IRIns *ir) -{ - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_barrieruv]; - IRRef args[2]; - MCLabel l_end; - Reg obj; - /* No need for other object barriers (yet). */ - lj_assertA(IR(ir->op1)->o == IR_UREFC, "bad OBAR type"); - ra_evictset(as, RSET_SCRATCH); - l_end = emit_label(as); - args[0] = ASMREF_TMP1; /* global_State *g */ - args[1] = ir->op1; /* TValue *tv */ - asm_gencall(as, ci, args); - emit_loada(as, ra_releasetmp(as, ASMREF_TMP1), J2G(as->J)); - obj = IR(ir->op1)->r; - emit_sjcc(as, CC_Z, l_end); - emit_i8(as, LJ_GC_WHITES); - if (irref_isk(ir->op2)) { - GCobj *vp = ir_kgc(IR(ir->op2)); - emit_rma(as, XO_GROUP3b, XOg_TEST, &vp->gch.marked); - } else { - Reg val = ra_alloc1(as, ir->op2, rset_exclude(RSET_SCRATCH&RSET_GPR, obj)); - emit_rmro(as, XO_GROUP3b, XOg_TEST, val, (int32_t)offsetof(GChead, marked)); - } - emit_sjcc(as, CC_Z, l_end); - emit_i8(as, LJ_GC_BLACK); - emit_rmro(as, XO_GROUP3b, XOg_TEST, obj, - (int32_t)offsetof(GCupval, marked)-(int32_t)offsetof(GCupval, tv)); -} - -/* -- FP/int arithmetic and logic operations ------------------------------ */ - -/* Load reference onto x87 stack. Force a spill to memory if needed. */ -static void asm_x87load(ASMState *as, IRRef ref) -{ - IRIns *ir = IR(ref); - if (ir->o == IR_KNUM) { - cTValue *tv = ir_knum(ir); - if (tvispzero(tv)) /* Use fldz only for +0. */ - emit_x87op(as, XI_FLDZ); - else if (tvispone(tv)) - emit_x87op(as, XI_FLD1); - else - emit_rma(as, XO_FLDq, XOg_FLDq, tv); - } else if (ir->o == IR_CONV && ir->op2 == IRCONV_NUM_INT && !ra_used(ir) && - !irref_isk(ir->op1) && mayfuse(as, ir->op1)) { - IRIns *iri = IR(ir->op1); - emit_rmro(as, XO_FILDd, XOg_FILDd, RID_ESP, ra_spill(as, iri)); - } else { - emit_mrm(as, XO_FLDq, XOg_FLDq, asm_fuseload(as, ref, RSET_EMPTY)); - } -} - -static void asm_fpmath(ASMState *as, IRIns *ir) -{ - IRFPMathOp fpm = (IRFPMathOp)ir->op2; - if (fpm == IRFPM_SQRT) { - Reg dest = ra_dest(as, ir, RSET_FPR); - Reg left = asm_fuseload(as, ir->op1, RSET_FPR); - emit_mrm(as, XO_SQRTSD, dest, left); - } else if (fpm <= IRFPM_TRUNC) { - if (as->flags & JIT_F_SSE4_1) { /* SSE4.1 has a rounding instruction. */ - Reg dest = ra_dest(as, ir, RSET_FPR); - Reg left = asm_fuseload(as, ir->op1, RSET_FPR); - /* ROUNDSD has a 4-byte opcode which doesn't fit in x86Op. - ** Let's pretend it's a 3-byte opcode, and compensate afterwards. - ** This is atrocious, but the alternatives are much worse. - */ - /* Round down/up/trunc == 1001/1010/1011. */ - emit_i8(as, 0x09 + fpm); - emit_mrm(as, XO_ROUNDSD, dest, left); - if (LJ_64 && as->mcp[1] != (MCode)(XO_ROUNDSD >> 16)) { - as->mcp[0] = as->mcp[1]; as->mcp[1] = 0x0f; /* Swap 0F and REX. */ - } - *--as->mcp = 0x66; /* 1st byte of ROUNDSD opcode. */ - } else { /* Call helper functions for SSE2 variant. */ - /* The modified regs must match with the *.dasc implementation. */ - RegSet drop = RSET_RANGE(RID_XMM0, RID_XMM3+1)|RID2RSET(RID_EAX); - if (ra_hasreg(ir->r)) - rset_clear(drop, ir->r); /* Dest reg handled below. */ - ra_evictset(as, drop); - ra_destreg(as, ir, RID_XMM0); - emit_call(as, fpm == IRFPM_FLOOR ? lj_vm_floor_sse : - fpm == IRFPM_CEIL ? lj_vm_ceil_sse : lj_vm_trunc_sse); - ra_left(as, RID_XMM0, ir->op1); - } - } else { - asm_callid(as, ir, IRCALL_lj_vm_floor + fpm); - } -} - -static void asm_ldexp(ASMState *as, IRIns *ir) -{ - int32_t ofs = sps_scale(ir->s); /* Use spill slot or temp slots. */ - Reg dest = ir->r; - if (ra_hasreg(dest)) { - ra_free(as, dest); - ra_modified(as, dest); - emit_rmro(as, XO_MOVSD, dest, RID_ESP, ofs); - } - emit_rmro(as, XO_FSTPq, XOg_FSTPq, RID_ESP, ofs); - emit_x87op(as, XI_FPOP1); - emit_x87op(as, XI_FSCALE); - asm_x87load(as, ir->op1); - asm_x87load(as, ir->op2); -} - -static int asm_swapops(ASMState *as, IRIns *ir) -{ - IRIns *irl = IR(ir->op1); - IRIns *irr = IR(ir->op2); - lj_assertA(ra_noreg(irr->r), "bad usage"); - if (!irm_iscomm(lj_ir_mode[ir->o])) - return 0; /* Can't swap non-commutative operations. */ - if (irref_isk(ir->op2)) - return 0; /* Don't swap constants to the left. */ - if (ra_hasreg(irl->r)) - return 1; /* Swap if left already has a register. */ - if (ra_samehint(ir->r, irr->r)) - return 1; /* Swap if dest and right have matching hints. */ - if (as->curins > as->loopref) { /* In variant part? */ - if (ir->op2 < as->loopref && !irt_isphi(irr->t)) - return 0; /* Keep invariants on the right. */ - if (ir->op1 < as->loopref && !irt_isphi(irl->t)) - return 1; /* Swap invariants to the right. */ - } - if (opisfusableload(irl->o)) - return 1; /* Swap fusable loads to the right. */ - return 0; /* Otherwise don't swap. */ -} - -static void asm_fparith(ASMState *as, IRIns *ir, x86Op xo) -{ - IRRef lref = ir->op1; - IRRef rref = ir->op2; - RegSet allow = RSET_FPR; - Reg dest; - Reg right = IR(rref)->r; - if (ra_hasreg(right)) { - rset_clear(allow, right); - ra_noweak(as, right); - } - dest = ra_dest(as, ir, allow); - if (lref == rref) { - right = dest; - } else if (ra_noreg(right)) { - if (asm_swapops(as, ir)) { - IRRef tmp = lref; lref = rref; rref = tmp; - } - right = asm_fuseload(as, rref, rset_clear(allow, dest)); - } - emit_mrm(as, xo, dest, right); - ra_left(as, dest, lref); -} - -static void asm_intarith(ASMState *as, IRIns *ir, x86Arith xa) -{ - IRRef lref = ir->op1; - IRRef rref = ir->op2; - RegSet allow = RSET_GPR; - Reg dest, right; - int32_t k = 0; - if (as->flagmcp == as->mcp && xa != XOg_X_IMUL) { - /* Drop test r,r instruction. */ - MCode *p = as->mcp + ((LJ_64 && *as->mcp < XI_TESTb) ? 3 : 2); - MCode *q = p[0] == 0x0f ? p+1 : p; - if ((*q & 15) < 14) { - if ((*q & 15) >= 12) *q -= 4; /* L <->S, NL <-> NS */ - as->flagmcp = NULL; - as->mcp = p; - } /* else: cannot transform LE/NLE to cc without use of OF. */ - } - right = IR(rref)->r; - if (ra_hasreg(right)) { - rset_clear(allow, right); - ra_noweak(as, right); - } - dest = ra_dest(as, ir, allow); - if (lref == rref) { - right = dest; - } else if (ra_noreg(right) && !asm_isk32(as, rref, &k)) { - if (asm_swapops(as, ir)) { - IRRef tmp = lref; lref = rref; rref = tmp; - } - right = asm_fuseloadm(as, rref, rset_clear(allow, dest), irt_is64(ir->t)); - } - if (irt_isguard(ir->t)) /* For IR_ADDOV etc. */ - asm_guardcc(as, CC_O); - if (xa != XOg_X_IMUL) { - if (ra_hasreg(right)) - emit_mrm(as, XO_ARITH(xa), REX_64IR(ir, dest), right); - else - emit_gri(as, XG_ARITHi(xa), REX_64IR(ir, dest), k); - } else if (ra_hasreg(right)) { /* IMUL r, mrm. */ - emit_mrm(as, XO_IMUL, REX_64IR(ir, dest), right); - } else { /* IMUL r, r, k. */ - /* NYI: use lea/shl/add/sub (FOLD only does 2^k) depending on CPU. */ - Reg left = asm_fuseloadm(as, lref, RSET_GPR, irt_is64(ir->t)); - x86Op xo; - if (checki8(k)) { emit_i8(as, k); xo = XO_IMULi8; - } else { emit_i32(as, k); xo = XO_IMULi; } - emit_mrm(as, xo, REX_64IR(ir, dest), left); - return; - } - ra_left(as, dest, lref); -} - -/* LEA is really a 4-operand ADD with an independent destination register, -** up to two source registers and an immediate. One register can be scaled -** by 1, 2, 4 or 8. This can be used to avoid moves or to fuse several -** instructions. -** -** Currently only a few common cases are supported: -** - 3-operand ADD: y = a+b; y = a+k with a and b already allocated -** - Left ADD fusion: y = (a+b)+k; y = (a+k)+b -** - Right ADD fusion: y = a+(b+k) -** The ommited variants have already been reduced by FOLD. -** -** There are more fusion opportunities, like gathering shifts or joining -** common references. But these are probably not worth the trouble, since -** array indexing is not decomposed and already makes use of all fields -** of the ModRM operand. -*/ -static int asm_lea(ASMState *as, IRIns *ir) -{ - IRIns *irl = IR(ir->op1); - IRIns *irr = IR(ir->op2); - RegSet allow = RSET_GPR; - Reg dest; - as->mrm.base = as->mrm.idx = RID_NONE; - as->mrm.scale = XM_SCALE1; - as->mrm.ofs = 0; - if (ra_hasreg(irl->r)) { - rset_clear(allow, irl->r); - ra_noweak(as, irl->r); - as->mrm.base = irl->r; - if (irref_isk(ir->op2) || ra_hasreg(irr->r)) { - /* The PHI renaming logic does a better job in some cases. */ - if (ra_hasreg(ir->r) && - ((irt_isphi(irl->t) && as->phireg[ir->r] == ir->op1) || - (irt_isphi(irr->t) && as->phireg[ir->r] == ir->op2))) - return 0; - if (irref_isk(ir->op2)) { - as->mrm.ofs = irr->i; - } else { - rset_clear(allow, irr->r); - ra_noweak(as, irr->r); - as->mrm.idx = irr->r; - } - } else if (irr->o == IR_ADD && mayfuse(as, ir->op2) && - irref_isk(irr->op2)) { - Reg idx = ra_alloc1(as, irr->op1, allow); - rset_clear(allow, idx); - as->mrm.idx = (uint8_t)idx; - as->mrm.ofs = IR(irr->op2)->i; - } else { - return 0; - } - } else if (ir->op1 != ir->op2 && irl->o == IR_ADD && mayfuse(as, ir->op1) && - (irref_isk(ir->op2) || irref_isk(irl->op2))) { - Reg idx, base = ra_alloc1(as, irl->op1, allow); - rset_clear(allow, base); - as->mrm.base = (uint8_t)base; - if (irref_isk(ir->op2)) { - as->mrm.ofs = irr->i; - idx = ra_alloc1(as, irl->op2, allow); - } else { - as->mrm.ofs = IR(irl->op2)->i; - idx = ra_alloc1(as, ir->op2, allow); - } - rset_clear(allow, idx); - as->mrm.idx = (uint8_t)idx; - } else { - return 0; - } - dest = ra_dest(as, ir, allow); - emit_mrm(as, XO_LEA, dest, RID_MRM); - return 1; /* Success. */ -} - -static void asm_add(ASMState *as, IRIns *ir) -{ - if (irt_isnum(ir->t)) - asm_fparith(as, ir, XO_ADDSD); - else if (as->flagmcp == as->mcp || irt_is64(ir->t) || !asm_lea(as, ir)) - asm_intarith(as, ir, XOg_ADD); -} - -static void asm_sub(ASMState *as, IRIns *ir) -{ - if (irt_isnum(ir->t)) - asm_fparith(as, ir, XO_SUBSD); - else /* Note: no need for LEA trick here. i-k is encoded as i+(-k). */ - asm_intarith(as, ir, XOg_SUB); -} - -static void asm_mul(ASMState *as, IRIns *ir) -{ - if (irt_isnum(ir->t)) - asm_fparith(as, ir, XO_MULSD); - else - asm_intarith(as, ir, XOg_X_IMUL); -} - -#define asm_fpdiv(as, ir) asm_fparith(as, ir, XO_DIVSD) - -static void asm_neg_not(ASMState *as, IRIns *ir, x86Group3 xg) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - emit_rr(as, XO_GROUP3, REX_64IR(ir, xg), dest); - ra_left(as, dest, ir->op1); -} - -static void asm_neg(ASMState *as, IRIns *ir) -{ - if (irt_isnum(ir->t)) - asm_fparith(as, ir, XO_XORPS); - else - asm_neg_not(as, ir, XOg_NEG); -} - -#define asm_abs(as, ir) asm_fparith(as, ir, XO_ANDPS) - -static void asm_intmin_max(ASMState *as, IRIns *ir, int cc) -{ - Reg right, dest = ra_dest(as, ir, RSET_GPR); - IRRef lref = ir->op1, rref = ir->op2; - if (irref_isk(rref)) { lref = rref; rref = ir->op1; } - right = ra_alloc1(as, rref, rset_exclude(RSET_GPR, dest)); - emit_rr(as, XO_CMOV + (cc<<24), REX_64IR(ir, dest), right); - emit_rr(as, XO_CMP, REX_64IR(ir, dest), right); - ra_left(as, dest, lref); -} - -static void asm_min(ASMState *as, IRIns *ir) -{ - if (irt_isnum(ir->t)) - asm_fparith(as, ir, XO_MINSD); - else - asm_intmin_max(as, ir, CC_G); -} - -static void asm_max(ASMState *as, IRIns *ir) -{ - if (irt_isnum(ir->t)) - asm_fparith(as, ir, XO_MAXSD); - else - asm_intmin_max(as, ir, CC_L); -} - -/* Note: don't use LEA for overflow-checking arithmetic! */ -#define asm_addov(as, ir) asm_intarith(as, ir, XOg_ADD) -#define asm_subov(as, ir) asm_intarith(as, ir, XOg_SUB) -#define asm_mulov(as, ir) asm_intarith(as, ir, XOg_X_IMUL) - -#define asm_bnot(as, ir) asm_neg_not(as, ir, XOg_NOT) - -static void asm_bswap(ASMState *as, IRIns *ir) -{ - Reg dest = ra_dest(as, ir, RSET_GPR); - as->mcp = emit_op(XO_BSWAP + ((dest&7) << 24), - REX_64IR(ir, 0), dest, 0, as->mcp, 1); - ra_left(as, dest, ir->op1); -} - -#define asm_band(as, ir) asm_intarith(as, ir, XOg_AND) -#define asm_bor(as, ir) asm_intarith(as, ir, XOg_OR) -#define asm_bxor(as, ir) asm_intarith(as, ir, XOg_XOR) - -static void asm_bitshift(ASMState *as, IRIns *ir, x86Shift xs, x86Op xv) -{ - IRRef rref = ir->op2; - IRIns *irr = IR(rref); - Reg dest; - if (irref_isk(rref)) { /* Constant shifts. */ - int shift; - dest = ra_dest(as, ir, RSET_GPR); - shift = irr->i & (irt_is64(ir->t) ? 63 : 31); - if (!xv && shift && (as->flags & JIT_F_BMI2)) { - Reg left = asm_fuseloadm(as, ir->op1, RSET_GPR, irt_is64(ir->t)); - if (left != dest) { /* BMI2 rotate right by constant. */ - emit_i8(as, xs == XOg_ROL ? -shift : shift); - emit_mrm(as, VEX_64IR(ir, XV_RORX), dest, left); - return; - } - } - switch (shift) { - case 0: break; - case 1: emit_rr(as, XO_SHIFT1, REX_64IR(ir, xs), dest); break; - default: emit_shifti(as, REX_64IR(ir, xs), dest, shift); break; - } - } else if ((as->flags & JIT_F_BMI2) && xv) { /* BMI2 variable shifts. */ - Reg left, right; - dest = ra_dest(as, ir, RSET_GPR); - right = ra_alloc1(as, rref, RSET_GPR); - left = asm_fuseloadm(as, ir->op1, rset_exclude(RSET_GPR, right), - irt_is64(ir->t)); - emit_mrm(as, VEX_64IR(ir, xv) ^ (right << 19), dest, left); - return; - } else { /* Variable shifts implicitly use register cl (i.e. ecx). */ - Reg right; - dest = ra_dest(as, ir, rset_exclude(RSET_GPR, RID_ECX)); - if (dest == RID_ECX) { - dest = ra_scratch(as, rset_exclude(RSET_GPR, RID_ECX)); - emit_rr(as, XO_MOV, REX_64IR(ir, RID_ECX), dest); - } - right = irr->r; - if (ra_noreg(right)) - right = ra_allocref(as, rref, RID2RSET(RID_ECX)); - else if (right != RID_ECX) - ra_scratch(as, RID2RSET(RID_ECX)); - emit_rr(as, XO_SHIFTcl, REX_64IR(ir, xs), dest); - ra_noweak(as, right); - if (right != RID_ECX) - emit_rr(as, XO_MOV, RID_ECX, right); - } - ra_left(as, dest, ir->op1); - /* - ** Note: avoid using the flags resulting from a shift or rotate! - ** All of them cause a partial flag stall, except for r,1 shifts - ** (but not rotates). And a shift count of 0 leaves the flags unmodified. - */ -} - -#define asm_bshl(as, ir) asm_bitshift(as, ir, XOg_SHL, XV_SHLX) -#define asm_bshr(as, ir) asm_bitshift(as, ir, XOg_SHR, XV_SHRX) -#define asm_bsar(as, ir) asm_bitshift(as, ir, XOg_SAR, XV_SARX) -#define asm_brol(as, ir) asm_bitshift(as, ir, XOg_ROL, 0) -#define asm_bror(as, ir) asm_bitshift(as, ir, XOg_ROR, 0) - -/* -- Comparisons --------------------------------------------------------- */ - -/* Virtual flags for unordered FP comparisons. */ -#define VCC_U 0x1000 /* Unordered. */ -#define VCC_P 0x2000 /* Needs extra CC_P branch. */ -#define VCC_S 0x4000 /* Swap avoids CC_P branch. */ -#define VCC_PS (VCC_P|VCC_S) - -/* Map of comparisons to flags. ORDER IR. */ -#define COMPFLAGS(ci, cin, cu, cf) ((ci)+((cu)<<4)+((cin)<<8)+(cf)) -static const uint16_t asm_compmap[IR_ABC+1] = { - /* signed non-eq unsigned flags */ - /* LT */ COMPFLAGS(CC_GE, CC_G, CC_AE, VCC_PS), - /* GE */ COMPFLAGS(CC_L, CC_L, CC_B, 0), - /* LE */ COMPFLAGS(CC_G, CC_G, CC_A, VCC_PS), - /* GT */ COMPFLAGS(CC_LE, CC_L, CC_BE, 0), - /* ULT */ COMPFLAGS(CC_AE, CC_A, CC_AE, VCC_U), - /* UGE */ COMPFLAGS(CC_B, CC_B, CC_B, VCC_U|VCC_PS), - /* ULE */ COMPFLAGS(CC_A, CC_A, CC_A, VCC_U), - /* UGT */ COMPFLAGS(CC_BE, CC_B, CC_BE, VCC_U|VCC_PS), - /* EQ */ COMPFLAGS(CC_NE, CC_NE, CC_NE, VCC_P), - /* NE */ COMPFLAGS(CC_E, CC_E, CC_E, VCC_U|VCC_P), - /* ABC */ COMPFLAGS(CC_BE, CC_B, CC_BE, VCC_U|VCC_PS) /* Same as UGT. */ -}; - -/* FP and integer comparisons. */ -static void asm_comp(ASMState *as, IRIns *ir) -{ - uint32_t cc = asm_compmap[ir->o]; - if (irt_isnum(ir->t)) { - IRRef lref = ir->op1; - IRRef rref = ir->op2; - Reg left, right; - MCLabel l_around; - /* - ** An extra CC_P branch is required to preserve ordered/unordered - ** semantics for FP comparisons. This can be avoided by swapping - ** the operands and inverting the condition (except for EQ and UNE). - ** So always try to swap if possible. - ** - ** Another option would be to swap operands to achieve better memory - ** operand fusion. But it's unlikely that this outweighs the cost - ** of the extra branches. - */ - if (cc & VCC_S) { /* Swap? */ - IRRef tmp = lref; lref = rref; rref = tmp; - cc ^= (VCC_PS|(5<<4)); /* A <-> B, AE <-> BE, PS <-> none */ - } - left = ra_alloc1(as, lref, RSET_FPR); - l_around = emit_label(as); - asm_guardcc(as, cc >> 4); - if (cc & VCC_P) { /* Extra CC_P branch required? */ - if (!(cc & VCC_U)) { - asm_guardcc(as, CC_P); /* Branch to exit for ordered comparisons. */ - } else if (l_around != as->invmcp) { - emit_sjcc(as, CC_P, l_around); /* Branch around for unordered. */ - } else { - /* Patched to mcloop by asm_loop_fixup. */ - as->loopinv = 2; - if (as->realign) - emit_sjcc(as, CC_P, as->mcp); - else - emit_jcc(as, CC_P, as->mcp); - } - } - right = asm_fuseload(as, rref, rset_exclude(RSET_FPR, left)); - emit_mrm(as, XO_UCOMISD, left, right); - } else { - IRRef lref = ir->op1, rref = ir->op2; - IROp leftop = (IROp)(IR(lref)->o); - Reg r64 = REX_64IR(ir, 0); - int32_t imm = 0; - lj_assertA(irt_is64(ir->t) || irt_isint(ir->t) || - irt_isu32(ir->t) || irt_isaddr(ir->t) || irt_isu8(ir->t), - "bad comparison data type %d", irt_type(ir->t)); - /* Swap constants (only for ABC) and fusable loads to the right. */ - if (irref_isk(lref) || (!irref_isk(rref) && opisfusableload(leftop))) { - if ((cc & 0xc) == 0xc) cc ^= 0x53; /* L <-> G, LE <-> GE */ - else if ((cc & 0xa) == 0x2) cc ^= 0x55; /* A <-> B, AE <-> BE */ - lref = ir->op2; rref = ir->op1; - } - if (asm_isk32(as, rref, &imm)) { - IRIns *irl = IR(lref); - /* Check wether we can use test ins. Not for unsigned, since CF=0. */ - int usetest = (imm == 0 && (cc & 0xa) != 0x2); - if (usetest && irl->o == IR_BAND && irl+1 == ir && !ra_used(irl)) { - /* Combine comp(BAND(ref, r/imm), 0) into test mrm, r/imm. */ - Reg right, left = RID_NONE; - RegSet allow = RSET_GPR; - if (!asm_isk32(as, irl->op2, &imm)) { - left = ra_alloc1(as, irl->op2, allow); - rset_clear(allow, left); - } else { /* Try to Fuse IRT_I8/IRT_U8 loads, too. See below. */ - IRIns *irll = IR(irl->op1); - if (opisfusableload((IROp)irll->o) && - (irt_isi8(irll->t) || irt_isu8(irll->t))) { - IRType1 origt = irll->t; /* Temporarily flip types. */ - irll->t.irt = (irll->t.irt & ~IRT_TYPE) | IRT_INT; - as->curins--; /* Skip to BAND to avoid failing in noconflict(). */ - right = asm_fuseload(as, irl->op1, RSET_GPR); - as->curins++; - irll->t = origt; - if (right != RID_MRM) goto test_nofuse; - /* Fusion succeeded, emit test byte mrm, imm8. */ - asm_guardcc(as, cc); - emit_i8(as, (imm & 0xff)); - emit_mrm(as, XO_GROUP3b, XOg_TEST, RID_MRM); - return; - } - } - as->curins--; /* Skip to BAND to avoid failing in noconflict(). */ - right = asm_fuseloadm(as, irl->op1, allow, r64); - as->curins++; /* Undo the above. */ - test_nofuse: - asm_guardcc(as, cc); - if (ra_noreg(left)) { - emit_i32(as, imm); - emit_mrm(as, XO_GROUP3, r64 + XOg_TEST, right); - } else { - emit_mrm(as, XO_TEST, r64 + left, right); - } - } else { - Reg left; - if (opisfusableload((IROp)irl->o) && - ((irt_isu8(irl->t) && checku8(imm)) || - ((irt_isi8(irl->t) || irt_isi16(irl->t)) && checki8(imm)) || - (irt_isu16(irl->t) && checku16(imm) && checki8((int16_t)imm)))) { - /* Only the IRT_INT case is fused by asm_fuseload. - ** The IRT_I8/IRT_U8 loads and some IRT_I16/IRT_U16 loads - ** are handled here. - ** Note that cmp word [mem], imm16 should not be generated, - ** since it has a length-changing prefix. Compares of a word - ** against a sign-extended imm8 are ok, however. - */ - IRType1 origt = irl->t; /* Temporarily flip types. */ - irl->t.irt = (irl->t.irt & ~IRT_TYPE) | IRT_INT; - left = asm_fuseload(as, lref, RSET_GPR); - irl->t = origt; - if (left == RID_MRM) { /* Fusion succeeded? */ - if (irt_isu8(irl->t) || irt_isu16(irl->t)) - cc >>= 4; /* Need unsigned compare. */ - asm_guardcc(as, cc); - emit_i8(as, imm); - emit_mrm(as, (irt_isi8(origt) || irt_isu8(origt)) ? - XO_ARITHib : XO_ARITHiw8, r64 + XOg_CMP, RID_MRM); - return; - } /* Otherwise handle register case as usual. */ - } else { - left = asm_fuseloadm(as, lref, - irt_isu8(ir->t) ? RSET_GPR8 : RSET_GPR, r64); - } - asm_guardcc(as, cc); - if (usetest && left != RID_MRM) { - /* Use test r,r instead of cmp r,0. */ - x86Op xo = XO_TEST; - if (irt_isu8(ir->t)) { - lj_assertA(ir->o == IR_EQ || ir->o == IR_NE, "bad usage"); - xo = XO_TESTb; - if (!rset_test(RSET_RANGE(RID_EAX, RID_EBX+1), left)) { - if (LJ_64) { - left |= FORCE_REX; - } else { - emit_i32(as, 0xff); - emit_mrm(as, XO_GROUP3, XOg_TEST, left); - return; - } - } - } - emit_rr(as, xo, r64 + left, left); - if (irl+1 == ir) /* Referencing previous ins? */ - as->flagmcp = as->mcp; /* Set flag to drop test r,r if possible. */ - } else { - emit_gmrmi(as, XG_ARITHi(XOg_CMP), r64 + left, imm); - } - } - } else { - Reg left = ra_alloc1(as, lref, RSET_GPR); - Reg right = asm_fuseloadm(as, rref, rset_exclude(RSET_GPR, left), r64); - asm_guardcc(as, cc); - emit_mrm(as, XO_CMP, r64 + left, right); - } - } -} - -#define asm_equal(as, ir) asm_comp(as, ir) - -#if LJ_32 && LJ_HASFFI -/* 64 bit integer comparisons in 32 bit mode. */ -static void asm_comp_int64(ASMState *as, IRIns *ir) -{ - uint32_t cc = asm_compmap[(ir-1)->o]; - RegSet allow = RSET_GPR; - Reg lefthi = RID_NONE, leftlo = RID_NONE; - Reg righthi = RID_NONE, rightlo = RID_NONE; - MCLabel l_around; - x86ModRM mrm; - - as->curins--; /* Skip loword ins. Avoids failing in noconflict(), too. */ - - /* Allocate/fuse hiword operands. */ - if (irref_isk(ir->op2)) { - lefthi = asm_fuseload(as, ir->op1, allow); - } else { - lefthi = ra_alloc1(as, ir->op1, allow); - rset_clear(allow, lefthi); - righthi = asm_fuseload(as, ir->op2, allow); - if (righthi == RID_MRM) { - if (as->mrm.base != RID_NONE) rset_clear(allow, as->mrm.base); - if (as->mrm.idx != RID_NONE) rset_clear(allow, as->mrm.idx); - } else { - rset_clear(allow, righthi); - } - } - mrm = as->mrm; /* Save state for hiword instruction. */ - - /* Allocate/fuse loword operands. */ - if (irref_isk((ir-1)->op2)) { - leftlo = asm_fuseload(as, (ir-1)->op1, allow); - } else { - leftlo = ra_alloc1(as, (ir-1)->op1, allow); - rset_clear(allow, leftlo); - rightlo = asm_fuseload(as, (ir-1)->op2, allow); - } - - /* All register allocations must be performed _before_ this point. */ - l_around = emit_label(as); - as->invmcp = as->flagmcp = NULL; /* Cannot use these optimizations. */ - - /* Loword comparison and branch. */ - asm_guardcc(as, cc >> 4); /* Always use unsigned compare for loword. */ - if (ra_noreg(rightlo)) { - int32_t imm = IR((ir-1)->op2)->i; - if (imm == 0 && ((cc >> 4) & 0xa) != 0x2 && leftlo != RID_MRM) - emit_rr(as, XO_TEST, leftlo, leftlo); - else - emit_gmrmi(as, XG_ARITHi(XOg_CMP), leftlo, imm); - } else { - emit_mrm(as, XO_CMP, leftlo, rightlo); - } - - /* Hiword comparison and branches. */ - if ((cc & 15) != CC_NE) - emit_sjcc(as, CC_NE, l_around); /* Hiword unequal: skip loword compare. */ - if ((cc & 15) != CC_E) - asm_guardcc(as, cc >> 8); /* Hiword compare without equality check. */ - as->mrm = mrm; /* Restore state. */ - if (ra_noreg(righthi)) { - int32_t imm = IR(ir->op2)->i; - if (imm == 0 && (cc & 0xa) != 0x2 && lefthi != RID_MRM) - emit_rr(as, XO_TEST, lefthi, lefthi); - else - emit_gmrmi(as, XG_ARITHi(XOg_CMP), lefthi, imm); - } else { - emit_mrm(as, XO_CMP, lefthi, righthi); - } -} -#endif - -/* -- Split register ops -------------------------------------------------- */ - -/* Hiword op of a split 32/32 or 64/64 bit op. Previous op is the loword op. */ -static void asm_hiop(ASMState *as, IRIns *ir) -{ - /* HIOP is marked as a store because it needs its own DCE logic. */ - int uselo = ra_used(ir-1), usehi = ra_used(ir); /* Loword/hiword used? */ - if (LJ_UNLIKELY(!(as->flags & JIT_F_OPT_DCE))) uselo = usehi = 1; -#if LJ_32 && LJ_HASFFI - if ((ir-1)->o == IR_CONV) { /* Conversions to/from 64 bit. */ - as->curins--; /* Always skip the CONV. */ - if (usehi || uselo) - asm_conv64(as, ir); - return; - } else if ((ir-1)->o <= IR_NE) { /* 64 bit integer comparisons. ORDER IR. */ - asm_comp_int64(as, ir); - return; - } else if ((ir-1)->o == IR_XSTORE) { - if ((ir-1)->r != RID_SINK) - asm_fxstore(as, ir); - return; - } -#endif - if (!usehi) return; /* Skip unused hiword op for all remaining ops. */ - switch ((ir-1)->o) { -#if LJ_32 && LJ_HASFFI - case IR_ADD: - as->flagmcp = NULL; - as->curins--; - asm_intarith(as, ir, XOg_ADC); - asm_intarith(as, ir-1, XOg_ADD); - break; - case IR_SUB: - as->flagmcp = NULL; - as->curins--; - asm_intarith(as, ir, XOg_SBB); - asm_intarith(as, ir-1, XOg_SUB); - break; - case IR_NEG: { - Reg dest = ra_dest(as, ir, RSET_GPR); - emit_rr(as, XO_GROUP3, XOg_NEG, dest); - emit_i8(as, 0); - emit_rr(as, XO_ARITHi8, XOg_ADC, dest); - ra_left(as, dest, ir->op1); - as->curins--; - asm_neg_not(as, ir-1, XOg_NEG); - break; - } - case IR_CNEWI: - /* Nothing to do here. Handled by CNEWI itself. */ - break; -#endif - case IR_CALLN: case IR_CALLL: case IR_CALLS: case IR_CALLXS: - if (!uselo) - ra_allocref(as, ir->op1, RID2RSET(RID_RETLO)); /* Mark lo op as used. */ - break; - default: lj_assertA(0, "bad HIOP for op %d", (ir-1)->o); break; - } -} - -/* -- Profiling ----------------------------------------------------------- */ - -static void asm_prof(ASMState *as, IRIns *ir) -{ - UNUSED(ir); - asm_guardcc(as, CC_NE); - emit_i8(as, HOOK_PROFILE); - emit_rma(as, XO_GROUP3b, XOg_TEST, &J2G(as->J)->hookmask); -} - -/* -- Stack handling ------------------------------------------------------ */ - -/* Check Lua stack size for overflow. Use exit handler as fallback. */ -static void asm_stack_check(ASMState *as, BCReg topslot, - IRIns *irp, RegSet allow, ExitNo exitno) -{ - /* Try to get an unused temp. register, otherwise spill/restore eax. */ - Reg pbase = irp ? irp->r : RID_BASE; - Reg r = allow ? rset_pickbot(allow) : RID_EAX; - emit_jcc(as, CC_B, exitstub_addr(as->J, exitno)); - if (allow == RSET_EMPTY) /* Restore temp. register. */ - emit_rmro(as, XO_MOV, r|REX_64, RID_ESP, 0); - else - ra_modified(as, r); - emit_gri(as, XG_ARITHi(XOg_CMP), r|REX_GC64, (int32_t)(8*topslot)); - if (ra_hasreg(pbase) && pbase != r) - emit_rr(as, XO_ARITH(XOg_SUB), r|REX_GC64, pbase); - else -#if LJ_GC64 - emit_rmro(as, XO_ARITH(XOg_SUB), r|REX_64, RID_DISPATCH, - (int32_t)dispofs(as, &J2G(as->J)->jit_base)); -#else - emit_rmro(as, XO_ARITH(XOg_SUB), r, RID_NONE, - ptr2addr(&J2G(as->J)->jit_base)); -#endif - emit_rmro(as, XO_MOV, r|REX_GC64, r, offsetof(lua_State, maxstack)); - emit_getgl(as, r, cur_L); - if (allow == RSET_EMPTY) /* Spill temp. register. */ - emit_rmro(as, XO_MOVto, r|REX_64, RID_ESP, 0); -} - -/* Restore Lua stack from on-trace state. */ -static void asm_stack_restore(ASMState *as, SnapShot *snap) -{ - SnapEntry *map = &as->T->snapmap[snap->mapofs]; -#if !LJ_FR2 || defined(LUA_USE_ASSERT) - SnapEntry *flinks = &as->T->snapmap[snap_nextofs(as->T, snap)-1-LJ_FR2]; -#endif - MSize n, nent = snap->nent; - /* Store the value of all modified slots to the Lua stack. */ - for (n = 0; n < nent; n++) { - SnapEntry sn = map[n]; - BCReg s = snap_slot(sn); - int32_t ofs = 8*((int32_t)s-1-LJ_FR2); - IRRef ref = snap_ref(sn); - IRIns *ir = IR(ref); - if ((sn & SNAP_NORESTORE)) - continue; - if ((sn & SNAP_KEYINDEX)) { - emit_movmroi(as, RID_BASE, ofs+4, LJ_KEYINDEX); - if (irref_isk(ref)) { - emit_movmroi(as, RID_BASE, ofs, ir->i); - } else { - Reg src = ra_alloc1(as, ref, rset_exclude(RSET_GPR, RID_BASE)); - emit_movtomro(as, src, RID_BASE, ofs); - } - } else if (irt_isnum(ir->t)) { - Reg src = ra_alloc1(as, ref, RSET_FPR); - emit_rmro(as, XO_MOVSDto, src, RID_BASE, ofs); - } else { - lj_assertA(irt_ispri(ir->t) || irt_isaddr(ir->t) || - (LJ_DUALNUM && irt_isinteger(ir->t)), - "restore of IR type %d", irt_type(ir->t)); - if (!irref_isk(ref)) { - Reg src = ra_alloc1(as, ref, rset_exclude(RSET_GPR, RID_BASE)); -#if LJ_GC64 - if (irt_is64(ir->t)) { - /* TODO: 64 bit store + 32 bit load-modify-store is suboptimal. */ - emit_u32(as, irt_toitype(ir->t) << 15); - emit_rmro(as, XO_ARITHi, XOg_OR, RID_BASE, ofs+4); - } else if (LJ_DUALNUM && irt_isinteger(ir->t)) { - emit_movmroi(as, RID_BASE, ofs+4, LJ_TISNUM << 15); - } else { - emit_movmroi(as, RID_BASE, ofs+4, (irt_toitype(ir->t)<<15)|0x7fff); - } -#endif - emit_movtomro(as, REX_64IR(ir, src), RID_BASE, ofs); -#if LJ_GC64 - } else { - TValue k; - lj_ir_kvalue(as->J->L, &k, ir); - if (tvisnil(&k)) { - emit_i32(as, -1); - emit_rmro(as, XO_MOVmi, REX_64, RID_BASE, ofs); - } else { - emit_movmroi(as, RID_BASE, ofs+4, k.u32.hi); - emit_movmroi(as, RID_BASE, ofs, k.u32.lo); - } -#else - } else if (!irt_ispri(ir->t)) { - emit_movmroi(as, RID_BASE, ofs, ir->i); -#endif - } - if ((sn & (SNAP_CONT|SNAP_FRAME))) { -#if !LJ_FR2 - if (s != 0) /* Do not overwrite link to previous frame. */ - emit_movmroi(as, RID_BASE, ofs+4, (int32_t)(*flinks--)); -#endif -#if !LJ_GC64 - } else { - if (!(LJ_64 && irt_islightud(ir->t))) - emit_movmroi(as, RID_BASE, ofs+4, irt_toitype(ir->t)); -#endif - } - } - checkmclim(as); - } - lj_assertA(map + nent == flinks, "inconsistent frames in snapshot"); -} - -/* -- GC handling --------------------------------------------------------- */ - -/* Check GC threshold and do one or more GC steps. */ -static void asm_gc_check(ASMState *as) -{ - const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_step_jit]; - IRRef args[2]; - MCLabel l_end; - Reg tmp; - ra_evictset(as, RSET_SCRATCH); - l_end = emit_label(as); - /* Exit trace if in GCSatomic or GCSfinalize. Avoids syncing GC objects. */ - asm_guardcc(as, CC_NE); /* Assumes asm_snap_prep() already done. */ - emit_rr(as, XO_TEST, RID_RET, RID_RET); - args[0] = ASMREF_TMP1; /* global_State *g */ - args[1] = ASMREF_TMP2; /* MSize steps */ - /* Insert nop to simplify GC exit recognition in lj_asm_patchexit. */ - if (!jmprel_ok(as->mcp, (MCode *)(void *)ci->func)) *--as->mcp = XI_NOP; - asm_gencall(as, ci, args); - tmp = ra_releasetmp(as, ASMREF_TMP1); -#if LJ_GC64 - emit_rmro(as, XO_LEA, tmp|REX_64, RID_DISPATCH, GG_DISP2G); -#else - emit_loada(as, tmp, J2G(as->J)); -#endif - emit_loadi(as, ra_releasetmp(as, ASMREF_TMP2), as->gcsteps); - /* Jump around GC step if GC total < GC threshold. */ - emit_sjcc(as, CC_B, l_end); - emit_opgl(as, XO_ARITH(XOg_CMP), tmp|REX_GC64, gc.threshold); - emit_getgl(as, tmp, gc.total); - as->gcsteps = 0; - checkmclim(as); -} - -/* -- Loop handling ------------------------------------------------------- */ - -/* Fixup the loop branch. */ -static void asm_loop_fixup(ASMState *as) -{ - MCode *p = as->mctop; - MCode *target = as->mcp; - if (as->realign) { /* Realigned loops use short jumps. */ - as->realign = NULL; /* Stop another retry. */ - lj_assertA(((intptr_t)target & 15) == 0, "loop realign failed"); - if (as->loopinv) { /* Inverted loop branch? */ - p -= 5; - p[0] = XI_JMP; - lj_assertA(target - p >= -128, "loop realign failed"); - p[-1] = (MCode)(target - p); /* Patch sjcc. */ - if (as->loopinv == 2) - p[-3] = (MCode)(target - p + 2); /* Patch opt. short jp. */ - } else { - lj_assertA(target - p >= -128, "loop realign failed"); - p[-1] = (MCode)(int8_t)(target - p); /* Patch short jmp. */ - p[-2] = XI_JMPs; - } - } else { - MCode *newloop; - p[-5] = XI_JMP; - if (as->loopinv) { /* Inverted loop branch? */ - /* asm_guardcc already inverted the jcc and patched the jmp. */ - p -= 5; - newloop = target+4; - *(int32_t *)(p-4) = (int32_t)(target - p); /* Patch jcc. */ - if (as->loopinv == 2) { - *(int32_t *)(p-10) = (int32_t)(target - p + 6); /* Patch opt. jp. */ - newloop = target+8; - } - } else { /* Otherwise just patch jmp. */ - *(int32_t *)(p-4) = (int32_t)(target - p); - newloop = target+3; - } - /* Realign small loops and shorten the loop branch. */ - if (newloop >= p - 128) { - as->realign = newloop; /* Force a retry and remember alignment. */ - as->curins = as->stopins; /* Abort asm_trace now. */ - as->T->nins = as->orignins; /* Remove any added renames. */ - } - } -} - -/* Fixup the tail of the loop. */ -static void asm_loop_tail_fixup(ASMState *as) -{ - UNUSED(as); /* Nothing to do. */ -} - -/* -- Head of trace ------------------------------------------------------- */ - -/* Coalesce BASE register for a root trace. */ -static void asm_head_root_base(ASMState *as) -{ - IRIns *ir = IR(REF_BASE); - Reg r = ir->r; - if (ra_hasreg(r)) { - ra_free(as, r); - if (rset_test(as->modset, r) || irt_ismarked(ir->t)) - ir->r = RID_INIT; /* No inheritance for modified BASE register. */ - if (r != RID_BASE) - emit_rr(as, XO_MOV, r|REX_GC64, RID_BASE); - } -} - -/* Coalesce or reload BASE register for a side trace. */ -static Reg asm_head_side_base(ASMState *as, IRIns *irp) -{ - IRIns *ir = IR(REF_BASE); - Reg r = ir->r; - if (ra_hasreg(r)) { - ra_free(as, r); - if (rset_test(as->modset, r) || irt_ismarked(ir->t)) - ir->r = RID_INIT; /* No inheritance for modified BASE register. */ - if (irp->r == r) { - return r; /* Same BASE register already coalesced. */ - } else if (ra_hasreg(irp->r) && rset_test(as->freeset, irp->r)) { - /* Move from coalesced parent reg. */ - emit_rr(as, XO_MOV, r|REX_GC64, irp->r); - return irp->r; - } else { - emit_getgl(as, r, jit_base); /* Otherwise reload BASE. */ - } - } - return RID_NONE; -} - -/* -- Tail of trace ------------------------------------------------------- */ - -/* Fixup the tail code. */ -static void asm_tail_fixup(ASMState *as, TraceNo lnk) -{ - /* Note: don't use as->mcp swap + emit_*: emit_op overwrites more bytes. */ - MCode *mcp = as->mctail; - MCode *target; - int32_t spadj = as->T->spadjust; - if (spadj) { /* Emit stack adjustment. */ - if (LJ_64) *mcp++ = 0x48; - if (checki8(spadj)) { - *mcp++ = XI_ARITHi8; - *mcp++ = MODRM(XM_REG, XOg_ADD, RID_ESP); - *mcp++ = (MCode)spadj; - } else { - *mcp++ = XI_ARITHi; - *mcp++ = MODRM(XM_REG, XOg_ADD, RID_ESP); - *(int32_t *)mcp = spadj; mcp += 4; - } - } - /* Emit exit branch. */ - target = lnk ? traceref(as->J, lnk)->mcode : (MCode *)(void *)lj_vm_exit_interp; - if (lnk || jmprel_ok(mcp + 5, target)) { /* Direct jump. */ - *mcp++ = XI_JMP; mcp += 4; - *(int32_t *)(mcp-4) = jmprel(as->J, mcp, target); - } else { /* RIP-relative indirect jump. */ - *mcp++ = XI_GROUP5; *mcp++ = XM_OFS0 + (XOg_JMP<<3) + RID_EBP; mcp += 4; - *((int32_t *)(mcp-4)) = (int32_t)(as->J->exitstubgroup[0] - 16 - mcp); - } - /* Drop unused mcode tail. Fill with NOPs to make the prefetcher happy. */ - while (as->mctop > mcp) *--as->mctop = XI_NOP; -} - -/* Prepare tail of code. */ -static void asm_tail_prep(ASMState *as, TraceNo lnk) -{ - MCode *p = as->mctop; - /* Realign and leave room for backwards loop branch or exit branch. */ - if (as->realign) { - int i = ((int)(intptr_t)as->realign) & 15; - /* Fill unused mcode tail with NOPs to make the prefetcher happy. */ - while (i-- > 0) - *--p = XI_NOP; - as->mctop = p; - p -= (as->loopinv ? 5 : 2); /* Space for short/near jmp. */ - } else { - p -= (LJ_64 && !lnk) ? 6 : 5; /* Space for exit branch. */ - } - if (as->loopref) { - as->invmcp = as->mcp = p; - } else { - /* Leave room for ESP adjustment: add esp, imm */ - p -= LJ_64 ? 7 : 6; - as->mcp = p; - as->invmcp = NULL; - } - as->mctail = p; -} - -/* -- Trace setup --------------------------------------------------------- */ - -/* Ensure there are enough stack slots for call arguments. */ -static Reg asm_setup_call_slots(ASMState *as, IRIns *ir, const CCallInfo *ci) -{ - IRRef args[CCI_NARGS_MAX*2]; - int nslots; - asm_collectargs(as, ir, ci, args); - nslots = asm_count_call_slots(as, ci, args); - if (nslots > as->evenspill) /* Leave room for args in stack slots. */ - as->evenspill = nslots; -#if LJ_64 - return irt_isfp(ir->t) ? REGSP_HINT(RID_FPRET) : REGSP_HINT(RID_RET); -#else - return irt_isfp(ir->t) ? REGSP_INIT : REGSP_HINT(RID_RET); -#endif -} - -/* Target-specific setup. */ -static void asm_setup_target(ASMState *as) -{ - asm_exitstub_setup(as, as->T->nsnap); - as->mrm.base = 0; -} - -/* -- Trace patching ------------------------------------------------------ */ - -static const uint8_t map_op1[256] = { -0x92,0x92,0x92,0x92,0x52,0x45,0x51,0x51,0x92,0x92,0x92,0x92,0x52,0x45,0x51,0x20, -0x92,0x92,0x92,0x92,0x52,0x45,0x51,0x51,0x92,0x92,0x92,0x92,0x52,0x45,0x51,0x51, -0x92,0x92,0x92,0x92,0x52,0x45,0x10,0x51,0x92,0x92,0x92,0x92,0x52,0x45,0x10,0x51, -0x92,0x92,0x92,0x92,0x52,0x45,0x10,0x51,0x92,0x92,0x92,0x92,0x52,0x45,0x10,0x51, -#if LJ_64 -0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14, -#else -0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51, -#endif -0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51, -0x51,0x51,0x92,0x92,0x10,0x10,0x12,0x11,0x45,0x86,0x52,0x93,0x51,0x51,0x51,0x51, -0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52, -0x93,0x86,0x93,0x93,0x92,0x92,0x92,0x92,0x92,0x92,0x92,0x92,0x92,0x92,0x92,0x92, -0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x47,0x51,0x51,0x51,0x51,0x51, -#if LJ_64 -0x59,0x59,0x59,0x59,0x51,0x51,0x51,0x51,0x52,0x45,0x51,0x51,0x51,0x51,0x51,0x51, -#else -0x55,0x55,0x55,0x55,0x51,0x51,0x51,0x51,0x52,0x45,0x51,0x51,0x51,0x51,0x51,0x51, -#endif -0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x05,0x05,0x05,0x05,0x05,0x05,0x05,0x05, -0x93,0x93,0x53,0x51,0x70,0x71,0x93,0x86,0x54,0x51,0x53,0x51,0x51,0x52,0x51,0x51, -0x92,0x92,0x92,0x92,0x52,0x52,0x51,0x51,0x92,0x92,0x92,0x92,0x92,0x92,0x92,0x92, -0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x45,0x45,0x47,0x52,0x51,0x51,0x51,0x51, -0x10,0x51,0x10,0x10,0x51,0x51,0x63,0x66,0x51,0x51,0x51,0x51,0x51,0x51,0x92,0x92 -}; - -static const uint8_t map_op2[256] = { -0x93,0x93,0x93,0x93,0x52,0x52,0x52,0x52,0x52,0x52,0x51,0x52,0x51,0x93,0x52,0x94, -0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93, -0x53,0x53,0x53,0x53,0x53,0x53,0x53,0x53,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93, -0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x34,0x51,0x35,0x51,0x51,0x51,0x51,0x51, -0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93, -0x53,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93, -0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93, -0x94,0x54,0x54,0x54,0x93,0x93,0x93,0x52,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93, -0x46,0x46,0x46,0x46,0x46,0x46,0x46,0x46,0x46,0x46,0x46,0x46,0x46,0x46,0x46,0x46, -0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93, -0x52,0x52,0x52,0x93,0x94,0x93,0x51,0x51,0x52,0x52,0x52,0x93,0x94,0x93,0x93,0x93, -0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x94,0x93,0x93,0x93,0x93,0x93, -0x93,0x93,0x94,0x93,0x94,0x94,0x94,0x93,0x52,0x52,0x52,0x52,0x52,0x52,0x52,0x52, -0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93, -0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93, -0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x93,0x52 -}; - -static uint32_t asm_x86_inslen(const uint8_t* p) -{ - uint32_t result = 0; - uint32_t prefixes = 0; - uint32_t x = map_op1[*p]; - for (;;) { - switch (x >> 4) { - case 0: return result + x + (prefixes & 4); - case 1: prefixes |= x; x = map_op1[*++p]; result++; break; - case 2: x = map_op2[*++p]; break; - case 3: p++; goto mrm; - case 4: result -= (prefixes & 2); /* fallthrough */ - case 5: return result + (x & 15); - case 6: /* Group 3. */ - if (p[1] & 0x38) x = 2; - else if ((prefixes & 2) && (x == 0x66)) x = 4; - goto mrm; - case 7: /* VEX c4/c5. */ - if (LJ_32 && p[1] < 0xc0) { - x = 2; - goto mrm; - } - if (x == 0x70) { - x = *++p & 0x1f; - result++; - if (x >= 2) { - p += 2; - result += 2; - goto mrm; - } - } - p++; - result++; - x = map_op2[*++p]; - break; - case 8: result -= (prefixes & 2); /* fallthrough */ - case 9: mrm: /* ModR/M and possibly SIB. */ - result += (x & 15); - x = *++p; - switch (x >> 6) { - case 0: if ((x & 7) == 5) return result + 4; break; - case 1: result++; break; - case 2: result += 4; break; - case 3: return result; - } - if ((x & 7) == 4) { - result++; - if (x < 0x40 && (p[1] & 7) == 5) result += 4; - } - return result; - } - } -} - -/* Patch exit jumps of existing machine code to a new target. */ -void lj_asm_patchexit(jit_State *J, GCtrace *T, ExitNo exitno, MCode *target) -{ - MCode *p = T->mcode; - MCode *mcarea = lj_mcode_patch(J, p, 0); - MSize len = T->szmcode; - MCode *px = exitstub_addr(J, exitno) - 6; - MCode *pe = p+len-6; - MCode *pgc = NULL; -#if LJ_GC64 - uint32_t statei = (uint32_t)(GG_OFS(g.vmstate) - GG_OFS(dispatch)); -#else - uint32_t statei = u32ptr(&J2G(J)->vmstate); -#endif - if (len > 5 && p[len-5] == XI_JMP && p+len-6 + *(int32_t *)(p+len-4) == px) - *(int32_t *)(p+len-4) = jmprel(J, p+len, target); - /* Do not patch parent exit for a stack check. Skip beyond vmstate update. */ - for (; p < pe; p += asm_x86_inslen(p)) { - intptr_t ofs = LJ_GC64 ? (p[0] & 0xf0) == 0x40 : LJ_64; - if (*(uint32_t *)(p+2+ofs) == statei && p[ofs+LJ_GC64-LJ_64] == XI_MOVmi) - break; - } - lj_assertJ(p < pe, "instruction length decoder failed"); - for (; p < pe; p += asm_x86_inslen(p)) { - if ((*(uint16_t *)p & 0xf0ff) == 0x800f && p + *(int32_t *)(p+2) == px && - p != pgc) { - *(int32_t *)(p+2) = jmprel(J, p+6, target); - } else if (*p == XI_CALL && - (void *)(p+5+*(int32_t *)(p+1)) == (void *)lj_gc_step_jit) { - pgc = p+7; /* Do not patch GC check exit. */ - } else if (LJ_64 && *p == 0xff && - p[1] == MODRM(XM_REG, XOg_CALL, RID_RET) && - p[2] == XI_NOP) { - pgc = p+5; /* Do not patch GC check exit. */ - } - } - lj_mcode_sync(T->mcode, T->mcode + T->szmcode); - lj_mcode_patch(J, mcarea, 1); -} - diff --git a/include/luajit/lj_bc.h b/include/luajit/lj_bc.h deleted file mode 100644 index 53b3e50..0000000 --- a/include/luajit/lj_bc.h +++ /dev/null @@ -1,270 +0,0 @@ -/* -** Bytecode instruction format. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_BC_H -#define _LJ_BC_H - -#include "lj_def.h" -#include "lj_arch.h" - -/* Bytecode instruction format, 32 bit wide, fields of 8 or 16 bit: -** -** +----+----+----+----+ -** | B | C | A | OP | Format ABC -** +----+----+----+----+ -** | D | A | OP | Format AD -** +-------------------- -** MSB LSB -** -** In-memory instructions are always stored in host byte order. -*/ - -/* Operand ranges and related constants. */ -#define BCMAX_A 0xff -#define BCMAX_B 0xff -#define BCMAX_C 0xff -#define BCMAX_D 0xffff -#define BCBIAS_J 0x8000 -#define NO_REG BCMAX_A -#define NO_JMP (~(BCPos)0) - -/* Macros to get instruction fields. */ -#define bc_op(i) ((BCOp)((i)&0xff)) -#define bc_a(i) ((BCReg)(((i)>>8)&0xff)) -#define bc_b(i) ((BCReg)((i)>>24)) -#define bc_c(i) ((BCReg)(((i)>>16)&0xff)) -#define bc_d(i) ((BCReg)((i)>>16)) -#define bc_j(i) ((ptrdiff_t)bc_d(i)-BCBIAS_J) - -/* Macros to set instruction fields. */ -#define setbc_byte(p, x, ofs) \ - ((uint8_t *)(p))[LJ_ENDIAN_SELECT(ofs, 3-ofs)] = (uint8_t)(x) -#define setbc_op(p, x) setbc_byte(p, (x), 0) -#define setbc_a(p, x) setbc_byte(p, (x), 1) -#define setbc_b(p, x) setbc_byte(p, (x), 3) -#define setbc_c(p, x) setbc_byte(p, (x), 2) -#define setbc_d(p, x) \ - ((uint16_t *)(p))[LJ_ENDIAN_SELECT(1, 0)] = (uint16_t)(x) -#define setbc_j(p, x) setbc_d(p, (BCPos)((int32_t)(x)+BCBIAS_J)) - -/* Macros to compose instructions. */ -#define BCINS_ABC(o, a, b, c) \ - (((BCIns)(o))|((BCIns)(a)<<8)|((BCIns)(b)<<24)|((BCIns)(c)<<16)) -#define BCINS_AD(o, a, d) \ - (((BCIns)(o))|((BCIns)(a)<<8)|((BCIns)(d)<<16)) -#define BCINS_AJ(o, a, j) BCINS_AD(o, a, (BCPos)((int32_t)(j)+BCBIAS_J)) - -/* Bytecode instruction definition. Order matters, see below. -** -** (name, filler, Amode, Bmode, Cmode or Dmode, metamethod) -** -** The opcode name suffixes specify the type for RB/RC or RD: -** V = variable slot -** S = string const -** N = number const -** P = primitive type (~itype) -** B = unsigned byte literal -** M = multiple args/results -*/ -#define BCDEF(_) \ - /* Comparison ops. ORDER OPR. */ \ - _(ISLT, var, ___, var, lt) \ - _(ISGE, var, ___, var, lt) \ - _(ISLE, var, ___, var, le) \ - _(ISGT, var, ___, var, le) \ - \ - _(ISEQV, var, ___, var, eq) \ - _(ISNEV, var, ___, var, eq) \ - _(ISEQS, var, ___, str, eq) \ - _(ISNES, var, ___, str, eq) \ - _(ISEQN, var, ___, num, eq) \ - _(ISNEN, var, ___, num, eq) \ - _(ISEQP, var, ___, pri, eq) \ - _(ISNEP, var, ___, pri, eq) \ - \ - /* Unary test and copy ops. */ \ - _(ISTC, dst, ___, var, ___) \ - _(ISFC, dst, ___, var, ___) \ - _(IST, ___, ___, var, ___) \ - _(ISF, ___, ___, var, ___) \ - _(ISTYPE, var, ___, lit, ___) \ - _(ISNUM, var, ___, lit, ___) \ - \ - /* Unary ops. */ \ - _(MOV, dst, ___, var, ___) \ - _(NOT, dst, ___, var, ___) \ - _(UNM, dst, ___, var, unm) \ - _(LEN, dst, ___, var, len) \ - \ - /* Binary ops. ORDER OPR. VV last, POW must be next. */ \ - _(ADDVN, dst, var, num, add) \ - _(SUBVN, dst, var, num, sub) \ - _(MULVN, dst, var, num, mul) \ - _(DIVVN, dst, var, num, div) \ - _(MODVN, dst, var, num, mod) \ - \ - _(ADDNV, dst, var, num, add) \ - _(SUBNV, dst, var, num, sub) \ - _(MULNV, dst, var, num, mul) \ - _(DIVNV, dst, var, num, div) \ - _(MODNV, dst, var, num, mod) \ - \ - _(ADDVV, dst, var, var, add) \ - _(SUBVV, dst, var, var, sub) \ - _(MULVV, dst, var, var, mul) \ - _(DIVVV, dst, var, var, div) \ - _(MODVV, dst, var, var, mod) \ - \ - _(POW, dst, var, var, pow) \ - _(CAT, dst, rbase, rbase, concat) \ - \ - /* Constant ops. */ \ - _(KSTR, dst, ___, str, ___) \ - _(KCDATA, dst, ___, cdata, ___) \ - _(KSHORT, dst, ___, lits, ___) \ - _(KNUM, dst, ___, num, ___) \ - _(KPRI, dst, ___, pri, ___) \ - _(KNIL, base, ___, base, ___) \ - \ - /* Upvalue and function ops. */ \ - _(UGET, dst, ___, uv, ___) \ - _(USETV, uv, ___, var, ___) \ - _(USETS, uv, ___, str, ___) \ - _(USETN, uv, ___, num, ___) \ - _(USETP, uv, ___, pri, ___) \ - _(UCLO, rbase, ___, jump, ___) \ - _(FNEW, dst, ___, func, gc) \ - \ - /* Table ops. */ \ - _(TNEW, dst, ___, lit, gc) \ - _(TDUP, dst, ___, tab, gc) \ - _(GGET, dst, ___, str, index) \ - _(GSET, var, ___, str, newindex) \ - _(TGETV, dst, var, var, index) \ - _(TGETS, dst, var, str, index) \ - _(TGETB, dst, var, lit, index) \ - _(TGETR, dst, var, var, index) \ - _(TSETV, var, var, var, newindex) \ - _(TSETS, var, var, str, newindex) \ - _(TSETB, var, var, lit, newindex) \ - _(TSETM, base, ___, num, newindex) \ - _(TSETR, var, var, var, newindex) \ - \ - /* Calls and vararg handling. T = tail call. */ \ - _(CALLM, base, lit, lit, call) \ - _(CALL, base, lit, lit, call) \ - _(CALLMT, base, ___, lit, call) \ - _(CALLT, base, ___, lit, call) \ - _(ITERC, base, lit, lit, call) \ - _(ITERN, base, lit, lit, call) \ - _(VARG, base, lit, lit, ___) \ - _(ISNEXT, base, ___, jump, ___) \ - \ - /* Returns. */ \ - _(RETM, base, ___, lit, ___) \ - _(RET, rbase, ___, lit, ___) \ - _(RET0, rbase, ___, lit, ___) \ - _(RET1, rbase, ___, lit, ___) \ - \ - /* Loops and branches. I/J = interp/JIT, I/C/L = init/call/loop. */ \ - _(FORI, base, ___, jump, ___) \ - _(JFORI, base, ___, jump, ___) \ - \ - _(FORL, base, ___, jump, ___) \ - _(IFORL, base, ___, jump, ___) \ - _(JFORL, base, ___, lit, ___) \ - \ - _(ITERL, base, ___, jump, ___) \ - _(IITERL, base, ___, jump, ___) \ - _(JITERL, base, ___, lit, ___) \ - \ - _(LOOP, rbase, ___, jump, ___) \ - _(ILOOP, rbase, ___, jump, ___) \ - _(JLOOP, rbase, ___, lit, ___) \ - \ - _(JMP, rbase, ___, jump, ___) \ - \ - /* Function headers. I/J = interp/JIT, F/V/C = fixarg/vararg/C func. */ \ - _(FUNCF, rbase, ___, ___, ___) \ - _(IFUNCF, rbase, ___, ___, ___) \ - _(JFUNCF, rbase, ___, lit, ___) \ - _(FUNCV, rbase, ___, ___, ___) \ - _(IFUNCV, rbase, ___, ___, ___) \ - _(JFUNCV, rbase, ___, lit, ___) \ - _(FUNCC, rbase, ___, ___, ___) \ - _(FUNCCW, rbase, ___, ___, ___) - -/* Bytecode opcode numbers. */ -typedef enum { -#define BCENUM(name, ma, mb, mc, mt) BC_##name, -BCDEF(BCENUM) -#undef BCENUM - BC__MAX -} BCOp; - -LJ_STATIC_ASSERT((int)BC_ISEQV+1 == (int)BC_ISNEV); -LJ_STATIC_ASSERT(((int)BC_ISEQV^1) == (int)BC_ISNEV); -LJ_STATIC_ASSERT(((int)BC_ISEQS^1) == (int)BC_ISNES); -LJ_STATIC_ASSERT(((int)BC_ISEQN^1) == (int)BC_ISNEN); -LJ_STATIC_ASSERT(((int)BC_ISEQP^1) == (int)BC_ISNEP); -LJ_STATIC_ASSERT(((int)BC_ISLT^1) == (int)BC_ISGE); -LJ_STATIC_ASSERT(((int)BC_ISLE^1) == (int)BC_ISGT); -LJ_STATIC_ASSERT(((int)BC_ISLT^3) == (int)BC_ISGT); -LJ_STATIC_ASSERT((int)BC_IST-(int)BC_ISTC == (int)BC_ISF-(int)BC_ISFC); -LJ_STATIC_ASSERT((int)BC_CALLT-(int)BC_CALL == (int)BC_CALLMT-(int)BC_CALLM); -LJ_STATIC_ASSERT((int)BC_CALLMT + 1 == (int)BC_CALLT); -LJ_STATIC_ASSERT((int)BC_RETM + 1 == (int)BC_RET); -LJ_STATIC_ASSERT((int)BC_FORL + 1 == (int)BC_IFORL); -LJ_STATIC_ASSERT((int)BC_FORL + 2 == (int)BC_JFORL); -LJ_STATIC_ASSERT((int)BC_ITERL + 1 == (int)BC_IITERL); -LJ_STATIC_ASSERT((int)BC_ITERL + 2 == (int)BC_JITERL); -LJ_STATIC_ASSERT((int)BC_LOOP + 1 == (int)BC_ILOOP); -LJ_STATIC_ASSERT((int)BC_LOOP + 2 == (int)BC_JLOOP); -LJ_STATIC_ASSERT((int)BC_FUNCF + 1 == (int)BC_IFUNCF); -LJ_STATIC_ASSERT((int)BC_FUNCF + 2 == (int)BC_JFUNCF); -LJ_STATIC_ASSERT((int)BC_FUNCV + 1 == (int)BC_IFUNCV); -LJ_STATIC_ASSERT((int)BC_FUNCV + 2 == (int)BC_JFUNCV); - -/* This solves a circular dependency problem, change as needed. */ -#define FF_next_N 4 - -/* Stack slots used by FORI/FORL, relative to operand A. */ -enum { - FORL_IDX, FORL_STOP, FORL_STEP, FORL_EXT -}; - -/* Bytecode operand modes. ORDER BCMode */ -typedef enum { - BCMnone, BCMdst, BCMbase, BCMvar, BCMrbase, BCMuv, /* Mode A must be <= 7 */ - BCMlit, BCMlits, BCMpri, BCMnum, BCMstr, BCMtab, BCMfunc, BCMjump, BCMcdata, - BCM_max -} BCMode; -#define BCM___ BCMnone - -#define bcmode_a(op) ((BCMode)(lj_bc_mode[op] & 7)) -#define bcmode_b(op) ((BCMode)((lj_bc_mode[op]>>3) & 15)) -#define bcmode_c(op) ((BCMode)((lj_bc_mode[op]>>7) & 15)) -#define bcmode_d(op) bcmode_c(op) -#define bcmode_hasd(op) ((lj_bc_mode[op] & (15<<3)) == (BCMnone<<3)) -#define bcmode_mm(op) ((MMS)(lj_bc_mode[op]>>11)) - -#define BCMODE(name, ma, mb, mc, mm) \ - (BCM##ma|(BCM##mb<<3)|(BCM##mc<<7)|(MM_##mm<<11)), -#define BCMODE_FF 0 - -static LJ_AINLINE int bc_isret(BCOp op) -{ - return (op == BC_RETM || op == BC_RET || op == BC_RET0 || op == BC_RET1); -} - -static LJ_AINLINE int bc_isret_or_tail(BCOp op) -{ - return (op == BC_CALLMT || op == BC_CALLT || bc_isret(op)); -} - -LJ_DATA const uint16_t lj_bc_mode[]; -LJ_DATA const uint16_t lj_bc_ofs[]; - -#endif diff --git a/include/luajit/lj_bcdump.h b/include/luajit/lj_bcdump.h deleted file mode 100644 index 6450c19..0000000 --- a/include/luajit/lj_bcdump.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -** Bytecode dump definitions. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_BCDUMP_H -#define _LJ_BCDUMP_H - -#include "lj_obj.h" -#include "lj_lex.h" - -/* -- Bytecode dump format ------------------------------------------------ */ - -/* -** dump = header proto+ 0U -** header = ESC 'L' 'J' versionB flagsU [namelenU nameB*] -** proto = lengthU pdata -** pdata = phead bcinsW* uvdataH* kgc* knum* [debugB*] -** phead = flagsB numparamsB framesizeB numuvB numkgcU numknU numbcU -** [debuglenU [firstlineU numlineU]] -** kgc = kgctypeU { ktab | (loU hiU) | (rloU rhiU iloU ihiU) | strB* } -** knum = intU0 | (loU1 hiU) -** ktab = narrayU nhashU karray* khash* -** karray = ktabk -** khash = ktabk ktabk -** ktabk = ktabtypeU { intU | (loU hiU) | strB* } -** -** B = 8 bit, H = 16 bit, W = 32 bit, U = ULEB128 of W, U0/U1 = ULEB128 of W+1 -*/ - -/* Bytecode dump header. */ -#define BCDUMP_HEAD1 0x1b -#define BCDUMP_HEAD2 0x4c -#define BCDUMP_HEAD3 0x4a - -/* If you perform *any* kind of private modifications to the bytecode itself -** or to the dump format, you *must* set BCDUMP_VERSION to 0x80 or higher. -*/ -#define BCDUMP_VERSION 2 - -/* Compatibility flags. */ -#define BCDUMP_F_BE 0x01 -#define BCDUMP_F_STRIP 0x02 -#define BCDUMP_F_FFI 0x04 -#define BCDUMP_F_FR2 0x08 - -#define BCDUMP_F_KNOWN (BCDUMP_F_FR2*2-1) - -#define BCDUMP_F_DETERMINISTIC 0x80000000 - -/* Type codes for the GC constants of a prototype. Plus length for strings. */ -enum { - BCDUMP_KGC_CHILD, BCDUMP_KGC_TAB, BCDUMP_KGC_I64, BCDUMP_KGC_U64, - BCDUMP_KGC_COMPLEX, BCDUMP_KGC_STR -}; - -/* Type codes for the keys/values of a constant table. */ -enum { - BCDUMP_KTAB_NIL, BCDUMP_KTAB_FALSE, BCDUMP_KTAB_TRUE, - BCDUMP_KTAB_INT, BCDUMP_KTAB_NUM, BCDUMP_KTAB_STR -}; - -/* -- Bytecode reader/writer ---------------------------------------------- */ - -LJ_FUNC int lj_bcwrite(lua_State *L, GCproto *pt, lua_Writer writer, - void *data, uint32_t flags); -LJ_FUNC GCproto *lj_bcread_proto(LexState *ls); -LJ_FUNC GCproto *lj_bcread(LexState *ls); - -#endif diff --git a/include/luajit/lj_buf.h b/include/luajit/lj_buf.h deleted file mode 100644 index 15a0425..0000000 --- a/include/luajit/lj_buf.h +++ /dev/null @@ -1,198 +0,0 @@ -/* -** Buffer handling. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_BUF_H -#define _LJ_BUF_H - -#include "lj_obj.h" -#include "lj_gc.h" -#include "lj_str.h" - -/* Resizable string buffers. */ - -/* The SBuf struct definition is in lj_obj.h: -** char *w; Write pointer. -** char *e; End pointer. -** char *b; Base pointer. -** MRef L; lua_State, used for buffer resizing. Extension bits in 3 LSB. -*/ - -/* Extended string buffer. */ -typedef struct SBufExt { - SBufHeader; - union { - GCRef cowref; /* Copy-on-write object reference. */ - MRef bsb; /* Borrowed string buffer. */ - }; - char *r; /* Read pointer. */ - GCRef dict_str; /* Serialization string dictionary table. */ - GCRef dict_mt; /* Serialization metatable dictionary table. */ - int depth; /* Remaining recursion depth. */ -} SBufExt; - -#define sbufsz(sb) ((MSize)((sb)->e - (sb)->b)) -#define sbuflen(sb) ((MSize)((sb)->w - (sb)->b)) -#define sbufleft(sb) ((MSize)((sb)->e - (sb)->w)) -#define sbufxlen(sbx) ((MSize)((sbx)->w - (sbx)->r)) -#define sbufxslack(sbx) ((MSize)((sbx)->r - (sbx)->b)) - -#define SBUF_MASK_FLAG (7) -#define SBUF_MASK_L (~(GCSize)SBUF_MASK_FLAG) -#define SBUF_FLAG_EXT 1 /* Extended string buffer. */ -#define SBUF_FLAG_COW 2 /* Copy-on-write buffer. */ -#define SBUF_FLAG_BORROW 4 /* Borrowed string buffer. */ - -#define sbufL(sb) \ - ((lua_State *)(void *)(uintptr_t)(mrefu((sb)->L) & SBUF_MASK_L)) -#define setsbufL(sb, l) (setmref((sb)->L, (l))) -#define setsbufXL(sb, l, flag) \ - (setmrefu((sb)->L, (GCSize)(uintptr_t)(void *)(l) + (flag))) -#define setsbufXL_(sb, l) \ - (setmrefu((sb)->L, (GCSize)(uintptr_t)(void *)(l) | (mrefu((sb)->L) & SBUF_MASK_FLAG))) - -#define sbufflag(sb) (mrefu((sb)->L)) -#define sbufisext(sb) (sbufflag((sb)) & SBUF_FLAG_EXT) -#define sbufiscow(sb) (sbufflag((sb)) & SBUF_FLAG_COW) -#define sbufisborrow(sb) (sbufflag((sb)) & SBUF_FLAG_BORROW) -#define sbufiscoworborrow(sb) (sbufflag((sb)) & (SBUF_FLAG_COW|SBUF_FLAG_BORROW)) -#define sbufX(sb) \ - (lj_assertG_(G(sbufL(sb)), sbufisext(sb), "not an SBufExt"), (SBufExt *)(sb)) -#define setsbufflag(sb, flag) (setmrefu((sb)->L, (flag))) - -#define tvisbuf(o) \ - (LJ_HASBUFFER && tvisudata(o) && udataV(o)->udtype == UDTYPE_BUFFER) -#define bufV(o) check_exp(tvisbuf(o), ((SBufExt *)uddata(udataV(o)))) - -/* Buffer management */ -LJ_FUNC char *LJ_FASTCALL lj_buf_need2(SBuf *sb, MSize sz); -LJ_FUNC char *LJ_FASTCALL lj_buf_more2(SBuf *sb, MSize sz); -LJ_FUNC void LJ_FASTCALL lj_buf_shrink(lua_State *L, SBuf *sb); -LJ_FUNC char * LJ_FASTCALL lj_buf_tmp(lua_State *L, MSize sz); - -static LJ_AINLINE void lj_buf_init(lua_State *L, SBuf *sb) -{ - setsbufL(sb, L); - sb->w = sb->e = sb->b = NULL; -} - -static LJ_AINLINE void lj_buf_reset(SBuf *sb) -{ - sb->w = sb->b; -} - -static LJ_AINLINE SBuf *lj_buf_tmp_(lua_State *L) -{ - SBuf *sb = &G(L)->tmpbuf; - setsbufL(sb, L); - lj_buf_reset(sb); - return sb; -} - -static LJ_AINLINE void lj_buf_free(global_State *g, SBuf *sb) -{ - lj_assertG(!sbufisext(sb), "bad free of SBufExt"); - lj_mem_free(g, sb->b, sbufsz(sb)); -} - -static LJ_AINLINE char *lj_buf_need(SBuf *sb, MSize sz) -{ - if (LJ_UNLIKELY(sz > sbufsz(sb))) - return lj_buf_need2(sb, sz); - return sb->b; -} - -static LJ_AINLINE char *lj_buf_more(SBuf *sb, MSize sz) -{ - if (LJ_UNLIKELY(sz > sbufleft(sb))) - return lj_buf_more2(sb, sz); - return sb->w; -} - -/* Extended buffer management */ -static LJ_AINLINE void lj_bufx_init(lua_State *L, SBufExt *sbx) -{ - memset(sbx, 0, sizeof(SBufExt)); - setsbufXL(sbx, L, SBUF_FLAG_EXT); -} - -static LJ_AINLINE void lj_bufx_set_borrow(lua_State *L, SBufExt *sbx, SBuf *sb) -{ - setsbufXL(sbx, L, SBUF_FLAG_EXT | SBUF_FLAG_BORROW); - setmref(sbx->bsb, sb); - sbx->r = sbx->w = sbx->b = sb->b; - sbx->e = sb->e; -} - -static LJ_AINLINE void lj_bufx_set_cow(lua_State *L, SBufExt *sbx, - const char *p, MSize len) -{ - setsbufXL(sbx, L, SBUF_FLAG_EXT | SBUF_FLAG_COW); - sbx->r = sbx->b = (char *)p; - sbx->w = sbx->e = (char *)p + len; -} - -static LJ_AINLINE void lj_bufx_reset(SBufExt *sbx) -{ - if (sbufiscow(sbx)) { - setmrefu(sbx->L, (mrefu(sbx->L) & ~(GCSize)SBUF_FLAG_COW)); - setgcrefnull(sbx->cowref); - sbx->b = sbx->e = NULL; - } - sbx->r = sbx->w = sbx->b; -} - -static LJ_AINLINE void lj_bufx_free(lua_State *L, SBufExt *sbx) -{ - if (!sbufiscoworborrow(sbx)) lj_mem_free(G(L), sbx->b, sbufsz(sbx)); - setsbufXL(sbx, L, SBUF_FLAG_EXT); - setgcrefnull(sbx->cowref); - sbx->r = sbx->w = sbx->b = sbx->e = NULL; -} - -#if LJ_HASBUFFER && LJ_HASJIT -LJ_FUNC void lj_bufx_set(SBufExt *sbx, const char *p, MSize len, GCobj *o); -#if LJ_HASFFI -LJ_FUNC MSize LJ_FASTCALL lj_bufx_more(SBufExt *sbx, MSize sz); -#endif -#endif - -/* Low-level buffer put operations */ -LJ_FUNC SBuf *lj_buf_putmem(SBuf *sb, const void *q, MSize len); -#if LJ_HASJIT || LJ_HASFFI -LJ_FUNC SBuf * LJ_FASTCALL lj_buf_putchar(SBuf *sb, int c); -#endif -LJ_FUNC SBuf * LJ_FASTCALL lj_buf_putstr(SBuf *sb, GCstr *s); - -static LJ_AINLINE char *lj_buf_wmem(char *p, const void *q, MSize len) -{ - return (char *)memcpy(p, q, len) + len; -} - -static LJ_AINLINE void lj_buf_putb(SBuf *sb, int c) -{ - char *w = lj_buf_more(sb, 1); - *w++ = (char)c; - sb->w = w; -} - -/* High-level buffer put operations */ -LJ_FUNCA SBuf * LJ_FASTCALL lj_buf_putstr_reverse(SBuf *sb, GCstr *s); -LJ_FUNCA SBuf * LJ_FASTCALL lj_buf_putstr_lower(SBuf *sb, GCstr *s); -LJ_FUNCA SBuf * LJ_FASTCALL lj_buf_putstr_upper(SBuf *sb, GCstr *s); -LJ_FUNC SBuf *lj_buf_putstr_rep(SBuf *sb, GCstr *s, int32_t rep); -LJ_FUNC SBuf *lj_buf_puttab(SBuf *sb, GCtab *t, GCstr *sep, - int32_t i, int32_t e); - -/* Miscellaneous buffer operations */ -LJ_FUNCA GCstr * LJ_FASTCALL lj_buf_tostr(SBuf *sb); -LJ_FUNC GCstr *lj_buf_cat2str(lua_State *L, GCstr *s1, GCstr *s2); -LJ_FUNC uint32_t LJ_FASTCALL lj_buf_ruleb128(const char **pp); - -static LJ_AINLINE GCstr *lj_buf_str(lua_State *L, SBuf *sb) -{ - return lj_str_new(L, sb->b, sbuflen(sb)); -} - -#endif diff --git a/include/luajit/lj_carith.h b/include/luajit/lj_carith.h deleted file mode 100644 index 6fad1c6..0000000 --- a/include/luajit/lj_carith.h +++ /dev/null @@ -1,37 +0,0 @@ -/* -** C data arithmetic. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_CARITH_H -#define _LJ_CARITH_H - -#include "lj_obj.h" - -#if LJ_HASFFI - -LJ_FUNC int lj_carith_op(lua_State *L, MMS mm); - -#if LJ_32 -LJ_FUNC uint64_t lj_carith_shl64(uint64_t x, int32_t sh); -LJ_FUNC uint64_t lj_carith_shr64(uint64_t x, int32_t sh); -LJ_FUNC uint64_t lj_carith_sar64(uint64_t x, int32_t sh); -LJ_FUNC uint64_t lj_carith_rol64(uint64_t x, int32_t sh); -LJ_FUNC uint64_t lj_carith_ror64(uint64_t x, int32_t sh); -#endif -LJ_FUNC uint64_t lj_carith_shift64(uint64_t x, int32_t sh, int op); -LJ_FUNC uint64_t lj_carith_check64(lua_State *L, int narg, CTypeID *id); - -#if LJ_32 && LJ_HASJIT -LJ_FUNC int64_t lj_carith_mul64(int64_t x, int64_t k); -#endif -LJ_FUNC uint64_t lj_carith_divu64(uint64_t a, uint64_t b); -LJ_FUNC int64_t lj_carith_divi64(int64_t a, int64_t b); -LJ_FUNC uint64_t lj_carith_modu64(uint64_t a, uint64_t b); -LJ_FUNC int64_t lj_carith_modi64(int64_t a, int64_t b); -LJ_FUNC uint64_t lj_carith_powu64(uint64_t x, uint64_t k); -LJ_FUNC int64_t lj_carith_powi64(int64_t x, int64_t k); - -#endif - -#endif diff --git a/include/luajit/lj_ccall.h b/include/luajit/lj_ccall.h deleted file mode 100644 index 3528fca..0000000 --- a/include/luajit/lj_ccall.h +++ /dev/null @@ -1,201 +0,0 @@ -/* -** FFI C call handling. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_CCALL_H -#define _LJ_CCALL_H - -#include "lj_obj.h" -#include "lj_ctype.h" - -#if LJ_HASFFI - -/* -- C calling conventions ----------------------------------------------- */ - -#if LJ_TARGET_X86ORX64 - -#if LJ_TARGET_X86 -#define CCALL_NARG_GPR 2 /* For fastcall arguments. */ -#define CCALL_NARG_FPR 0 -#define CCALL_NRET_GPR 2 -#define CCALL_NRET_FPR 1 /* For FP results on x87 stack. */ -#define CCALL_ALIGN_STACKARG 0 /* Don't align argument on stack. */ -#elif LJ_ABI_WIN -#define CCALL_NARG_GPR 4 -#define CCALL_NARG_FPR 4 -#define CCALL_NRET_GPR 1 -#define CCALL_NRET_FPR 1 -#define CCALL_SPS_EXTRA 4 -#else -#define CCALL_NARG_GPR 6 -#define CCALL_NARG_FPR 8 -#define CCALL_NRET_GPR 2 -#define CCALL_NRET_FPR 2 -#define CCALL_VECTOR_REG 1 /* Pass vectors in registers. */ -#endif - -#define CCALL_SPS_FREE 1 -#define CCALL_ALIGN_CALLSTATE 16 - -typedef LJ_ALIGN(16) union FPRArg { - double d[2]; - float f[4]; - uint8_t b[16]; - uint16_t s[8]; - int i[4]; - int64_t l[2]; -} FPRArg; - -typedef intptr_t GPRArg; - -#elif LJ_TARGET_ARM - -#define CCALL_NARG_GPR 4 -#define CCALL_NRET_GPR 2 /* For softfp double. */ -#if LJ_ABI_SOFTFP -#define CCALL_NARG_FPR 0 -#define CCALL_NRET_FPR 0 -#else -#define CCALL_NARG_FPR 8 -#define CCALL_NRET_FPR 4 -#endif -#define CCALL_SPS_FREE 0 - -typedef intptr_t GPRArg; -typedef union FPRArg { - double d; - float f[2]; -} FPRArg; - -#elif LJ_TARGET_ARM64 - -#define CCALL_NARG_GPR 8 -#define CCALL_NRET_GPR 2 -#define CCALL_NARG_FPR 8 -#define CCALL_NRET_FPR 4 -#define CCALL_SPS_FREE 0 -#if LJ_TARGET_OSX -#define CCALL_PACK_STACKARG 1 -#endif - -typedef intptr_t GPRArg; -typedef union FPRArg { - double d; - struct { LJ_ENDIAN_LOHI(float f; , float g;) }; - struct { LJ_ENDIAN_LOHI(uint32_t lo; , uint32_t hi;) }; -} FPRArg; - -#elif LJ_TARGET_PPC - -#define CCALL_NARG_GPR 8 -#define CCALL_NARG_FPR (LJ_ABI_SOFTFP ? 0 : 8) -#define CCALL_NRET_GPR 4 /* For complex double. */ -#define CCALL_NRET_FPR (LJ_ABI_SOFTFP ? 0 : 1) -#define CCALL_SPS_EXTRA 4 -#define CCALL_SPS_FREE 0 - -typedef intptr_t GPRArg; -typedef double FPRArg; - -#elif LJ_TARGET_MIPS32 - -#define CCALL_NARG_GPR 4 -#define CCALL_NARG_FPR (LJ_ABI_SOFTFP ? 0 : 2) -#define CCALL_NRET_GPR (LJ_ABI_SOFTFP ? 4 : 2) -#define CCALL_NRET_FPR (LJ_ABI_SOFTFP ? 0 : 2) -#define CCALL_SPS_EXTRA 7 -#define CCALL_SPS_FREE 1 - -typedef intptr_t GPRArg; -typedef union FPRArg { - double d; - struct { LJ_ENDIAN_LOHI(float f; , float g;) }; -} FPRArg; - -#elif LJ_TARGET_MIPS64 - -/* FP args are positional and overlay the GPR array. */ -#define CCALL_NARG_GPR 8 -#define CCALL_NARG_FPR 0 -#define CCALL_NRET_GPR 2 -#define CCALL_NRET_FPR (LJ_ABI_SOFTFP ? 0 : 2) -#define CCALL_SPS_EXTRA 3 -#define CCALL_SPS_FREE 1 - -typedef intptr_t GPRArg; -typedef union FPRArg { - double d; - struct { LJ_ENDIAN_LOHI(float f; , float g;) }; -} FPRArg; - -#else -#error "Missing calling convention definitions for this architecture" -#endif - -#ifndef CCALL_SPS_EXTRA -#define CCALL_SPS_EXTRA 0 -#endif -#ifndef CCALL_VECTOR_REG -#define CCALL_VECTOR_REG 0 -#endif -#ifndef CCALL_ALIGN_STACKARG -#define CCALL_ALIGN_STACKARG 1 -#endif -#ifndef CCALL_PACK_STACKARG -#define CCALL_PACK_STACKARG 0 -#endif -#ifndef CCALL_ALIGN_CALLSTATE -#define CCALL_ALIGN_CALLSTATE 8 -#endif - -#define CCALL_NUM_GPR \ - (CCALL_NARG_GPR > CCALL_NRET_GPR ? CCALL_NARG_GPR : CCALL_NRET_GPR) -#define CCALL_NUM_FPR \ - (CCALL_NARG_FPR > CCALL_NRET_FPR ? CCALL_NARG_FPR : CCALL_NRET_FPR) - -/* Check against constants in lj_ctype.h. */ -LJ_STATIC_ASSERT(CCALL_NUM_GPR <= CCALL_MAX_GPR); -LJ_STATIC_ASSERT(CCALL_NUM_FPR <= CCALL_MAX_FPR); - -#define CCALL_NUM_STACK 31 -#define CCALL_SIZE_STACK (CCALL_NUM_STACK * CTSIZE_PTR) - -/* -- C call state -------------------------------------------------------- */ - -typedef LJ_ALIGN(CCALL_ALIGN_CALLSTATE) struct CCallState { - void (*func)(void); /* Pointer to called function. */ - uint32_t spadj; /* Stack pointer adjustment. */ - uint8_t nsp; /* Number of bytes on stack. */ - uint8_t retref; /* Return value by reference. */ -#if LJ_TARGET_X64 - uint8_t ngpr; /* Number of arguments in GPRs. */ - uint8_t nfpr; /* Number of arguments in FPRs. */ -#elif LJ_TARGET_X86 - uint8_t resx87; /* Result on x87 stack: 1:float, 2:double. */ -#elif LJ_TARGET_ARM64 - void *retp; /* Aggregate return pointer in x8. */ -#elif LJ_TARGET_PPC - uint8_t nfpr; /* Number of arguments in FPRs. */ -#endif -#if LJ_32 - int32_t align1; -#endif -#if CCALL_NUM_FPR - FPRArg fpr[CCALL_NUM_FPR]; /* Arguments/results in FPRs. */ -#endif - GPRArg gpr[CCALL_NUM_GPR]; /* Arguments/results in GPRs. */ - GPRArg stack[CCALL_NUM_STACK]; /* Stack slots. */ -} CCallState; - -/* -- C call handling ----------------------------------------------------- */ - -/* Really belongs to lj_vm.h. */ -LJ_ASMF void LJ_FASTCALL lj_vm_ffi_call(CCallState *cc); - -LJ_FUNC CTypeID lj_ccall_ctid_vararg(CTState *cts, cTValue *o); -LJ_FUNC int lj_ccall_func(lua_State *L, GCcdata *cd); - -#endif - -#endif diff --git a/include/luajit/lj_ccallback.h b/include/luajit/lj_ccallback.h deleted file mode 100644 index 073a69c..0000000 --- a/include/luajit/lj_ccallback.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -** FFI C callback handling. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_CCALLBACK_H -#define _LJ_CCALLBACK_H - -#include "lj_obj.h" -#include "lj_ctype.h" - -#if LJ_HASFFI - -/* Really belongs to lj_vm.h. */ -LJ_ASMF void lj_vm_ffi_callback(void); - -LJ_FUNC MSize lj_ccallback_ptr2slot(CTState *cts, void *p); -LJ_FUNCA lua_State * LJ_FASTCALL lj_ccallback_enter(CTState *cts, void *cf); -LJ_FUNCA void LJ_FASTCALL lj_ccallback_leave(CTState *cts, TValue *o); -LJ_FUNC void *lj_ccallback_new(CTState *cts, CType *ct, GCfunc *fn); -LJ_FUNC void lj_ccallback_mcode_free(CTState *cts); - -#endif - -#endif diff --git a/include/luajit/lj_cconv.h b/include/luajit/lj_cconv.h deleted file mode 100644 index 1e96cd6..0000000 --- a/include/luajit/lj_cconv.h +++ /dev/null @@ -1,71 +0,0 @@ -/* -** C type conversions. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_CCONV_H -#define _LJ_CCONV_H - -#include "lj_obj.h" -#include "lj_ctype.h" - -#if LJ_HASFFI - -/* Compressed C type index. ORDER CCX. */ -enum { - CCX_B, /* Bool. */ - CCX_I, /* Integer. */ - CCX_F, /* Floating-point number. */ - CCX_C, /* Complex. */ - CCX_V, /* Vector. */ - CCX_P, /* Pointer. */ - CCX_A, /* Refarray. */ - CCX_S /* Struct/union. */ -}; - -/* Convert C type info to compressed C type index. ORDER CT. ORDER CCX. */ -static LJ_AINLINE uint32_t cconv_idx(CTInfo info) -{ - uint32_t idx = ((info >> 26) & 15u); /* Dispatch bits. */ - lj_assertX(ctype_type(info) <= CT_MAYCONVERT, - "cannot convert ctype %08x", info); -#if LJ_64 - idx = ((uint32_t)(U64x(f436fff5,fff7f021) >> 4*idx) & 15u); -#else - idx = (((idx < 8 ? 0xfff7f021u : 0xf436fff5) >> 4*(idx & 7u)) & 15u); -#endif - lj_assertX(idx < 8, "cannot convert ctype %08x", info); - return idx; -} - -#define cconv_idx2(dinfo, sinfo) \ - ((cconv_idx((dinfo)) << 3) + cconv_idx((sinfo))) - -#define CCX(dst, src) ((CCX_##dst << 3) + CCX_##src) - -/* Conversion flags. */ -#define CCF_CAST 0x00000001u -#define CCF_FROMTV 0x00000002u -#define CCF_SAME 0x00000004u -#define CCF_IGNQUAL 0x00000008u - -#define CCF_ARG_SHIFT 8 -#define CCF_ARG(n) ((n) << CCF_ARG_SHIFT) -#define CCF_GETARG(f) ((f) >> CCF_ARG_SHIFT) - -LJ_FUNC int lj_cconv_compatptr(CTState *cts, CType *d, CType *s, CTInfo flags); -LJ_FUNC void lj_cconv_ct_ct(CTState *cts, CType *d, CType *s, - uint8_t *dp, uint8_t *sp, CTInfo flags); -LJ_FUNC int lj_cconv_tv_ct(CTState *cts, CType *s, CTypeID sid, - TValue *o, uint8_t *sp); -LJ_FUNC int lj_cconv_tv_bf(CTState *cts, CType *s, TValue *o, uint8_t *sp); -LJ_FUNC void lj_cconv_ct_tv(CTState *cts, CType *d, - uint8_t *dp, TValue *o, CTInfo flags); -LJ_FUNC void lj_cconv_bf_tv(CTState *cts, CType *d, uint8_t *dp, TValue *o); -LJ_FUNC int lj_cconv_multi_init(CTState *cts, CType *d, TValue *o); -LJ_FUNC void lj_cconv_ct_init(CTState *cts, CType *d, CTSize sz, - uint8_t *dp, TValue *o, MSize len); - -#endif - -#endif diff --git a/include/luajit/lj_cdata.h b/include/luajit/lj_cdata.h deleted file mode 100644 index 204c1f8..0000000 --- a/include/luajit/lj_cdata.h +++ /dev/null @@ -1,79 +0,0 @@ -/* -** C data management. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_CDATA_H -#define _LJ_CDATA_H - -#include "lj_obj.h" -#include "lj_gc.h" -#include "lj_ctype.h" - -#if LJ_HASFFI - -/* Get C data pointer. */ -static LJ_AINLINE void *cdata_getptr(void *p, CTSize sz) -{ - if (LJ_64 && sz == 4) { /* Support 32 bit pointers on 64 bit targets. */ - return ((void *)(uintptr_t)*(uint32_t *)p); - } else { - lj_assertX(sz == CTSIZE_PTR, "bad pointer size %d", sz); - return *(void **)p; - } -} - -/* Set C data pointer. */ -static LJ_AINLINE void cdata_setptr(void *p, CTSize sz, const void *v) -{ - if (LJ_64 && sz == 4) { /* Support 32 bit pointers on 64 bit targets. */ - *(uint32_t *)p = (uint32_t)(uintptr_t)v; - } else { - lj_assertX(sz == CTSIZE_PTR, "bad pointer size %d", sz); - *(void **)p = (void *)v; - } -} - -/* Allocate fixed-size C data object. */ -static LJ_AINLINE GCcdata *lj_cdata_new(CTState *cts, CTypeID id, CTSize sz) -{ - GCcdata *cd; -#ifdef LUA_USE_ASSERT - CType *ct = ctype_raw(cts, id); - lj_assertCTS((ctype_hassize(ct->info) ? ct->size : CTSIZE_PTR) == sz, - "inconsistent size of fixed-size cdata alloc"); -#endif - cd = (GCcdata *)lj_mem_newgco(cts->L, sizeof(GCcdata) + sz); - cd->gct = ~LJ_TCDATA; - cd->ctypeid = ctype_check(cts, id); - return cd; -} - -/* Variant which works without a valid CTState. */ -static LJ_AINLINE GCcdata *lj_cdata_new_(lua_State *L, CTypeID id, CTSize sz) -{ - GCcdata *cd = (GCcdata *)lj_mem_newgco(L, sizeof(GCcdata) + sz); - cd->gct = ~LJ_TCDATA; - cd->ctypeid = id; - return cd; -} - -LJ_FUNC GCcdata *lj_cdata_newref(CTState *cts, const void *pp, CTypeID id); -LJ_FUNC GCcdata *lj_cdata_newv(lua_State *L, CTypeID id, CTSize sz, - CTSize align); -LJ_FUNC GCcdata *lj_cdata_newx(CTState *cts, CTypeID id, CTSize sz, - CTInfo info); - -LJ_FUNC void LJ_FASTCALL lj_cdata_free(global_State *g, GCcdata *cd); -LJ_FUNC void lj_cdata_setfin(lua_State *L, GCcdata *cd, GCobj *obj, - uint32_t it); - -LJ_FUNC CType *lj_cdata_index(CTState *cts, GCcdata *cd, cTValue *key, - uint8_t **pp, CTInfo *qual); -LJ_FUNC int lj_cdata_get(CTState *cts, CType *s, TValue *o, uint8_t *sp); -LJ_FUNC void lj_cdata_set(CTState *cts, CType *d, uint8_t *dp, TValue *o, - CTInfo qual); - -#endif - -#endif diff --git a/include/luajit/lj_char.h b/include/luajit/lj_char.h deleted file mode 100644 index c3c86d3..0000000 --- a/include/luajit/lj_char.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -** Character types. -** Donated to the public domain. -*/ - -#ifndef _LJ_CHAR_H -#define _LJ_CHAR_H - -#include "lj_def.h" - -#define LJ_CHAR_CNTRL 0x01 -#define LJ_CHAR_SPACE 0x02 -#define LJ_CHAR_PUNCT 0x04 -#define LJ_CHAR_DIGIT 0x08 -#define LJ_CHAR_XDIGIT 0x10 -#define LJ_CHAR_UPPER 0x20 -#define LJ_CHAR_LOWER 0x40 -#define LJ_CHAR_IDENT 0x80 -#define LJ_CHAR_ALPHA (LJ_CHAR_LOWER|LJ_CHAR_UPPER) -#define LJ_CHAR_ALNUM (LJ_CHAR_ALPHA|LJ_CHAR_DIGIT) -#define LJ_CHAR_GRAPH (LJ_CHAR_ALNUM|LJ_CHAR_PUNCT) - -/* Only pass -1 or 0..255 to these macros. Never pass a signed char! */ -#define lj_char_isa(c, t) ((lj_char_bits+1)[(c)] & t) -#define lj_char_iscntrl(c) lj_char_isa((c), LJ_CHAR_CNTRL) -#define lj_char_isspace(c) lj_char_isa((c), LJ_CHAR_SPACE) -#define lj_char_ispunct(c) lj_char_isa((c), LJ_CHAR_PUNCT) -#define lj_char_isdigit(c) lj_char_isa((c), LJ_CHAR_DIGIT) -#define lj_char_isxdigit(c) lj_char_isa((c), LJ_CHAR_XDIGIT) -#define lj_char_isupper(c) lj_char_isa((c), LJ_CHAR_UPPER) -#define lj_char_islower(c) lj_char_isa((c), LJ_CHAR_LOWER) -#define lj_char_isident(c) lj_char_isa((c), LJ_CHAR_IDENT) -#define lj_char_isalpha(c) lj_char_isa((c), LJ_CHAR_ALPHA) -#define lj_char_isalnum(c) lj_char_isa((c), LJ_CHAR_ALNUM) -#define lj_char_isgraph(c) lj_char_isa((c), LJ_CHAR_GRAPH) - -#define lj_char_toupper(c) ((c) - (lj_char_islower(c) >> 1)) -#define lj_char_tolower(c) ((c) + lj_char_isupper(c)) - -LJ_DATA const uint8_t lj_char_bits[257]; - -#endif diff --git a/include/luajit/lj_clib.h b/include/luajit/lj_clib.h deleted file mode 100644 index e48d0e8..0000000 --- a/include/luajit/lj_clib.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -** FFI C library loader. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_CLIB_H -#define _LJ_CLIB_H - -#include "lj_obj.h" - -#if LJ_HASFFI - -/* Namespace for C library indexing. */ -#define CLNS_INDEX ((1u<env. */ -} CLibrary; - -LJ_FUNC TValue *lj_clib_index(lua_State *L, CLibrary *cl, GCstr *name); -LJ_FUNC void lj_clib_load(lua_State *L, GCtab *mt, GCstr *name, int global); -LJ_FUNC void lj_clib_unload(CLibrary *cl); -LJ_FUNC void lj_clib_default(lua_State *L, GCtab *mt); - -#endif - -#endif diff --git a/include/luajit/lj_cparse.h b/include/luajit/lj_cparse.h deleted file mode 100644 index 63e8851..0000000 --- a/include/luajit/lj_cparse.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -** C declaration parser. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_CPARSE_H -#define _LJ_CPARSE_H - -#include "lj_obj.h" -#include "lj_ctype.h" - -#if LJ_HASFFI - -/* C parser limits. */ -#define CPARSE_MAX_BUF 32768 /* Max. token buffer size. */ -#define CPARSE_MAX_DECLSTACK 100 /* Max. declaration stack depth. */ -#define CPARSE_MAX_DECLDEPTH 20 /* Max. recursive declaration depth. */ -#define CPARSE_MAX_PACKSTACK 7 /* Max. pack pragma stack depth. */ - -/* Flags for C parser mode. */ -#define CPARSE_MODE_MULTI 1 /* Process multiple declarations. */ -#define CPARSE_MODE_ABSTRACT 2 /* Accept abstract declarators. */ -#define CPARSE_MODE_DIRECT 4 /* Accept direct declarators. */ -#define CPARSE_MODE_FIELD 8 /* Accept field width in bits, too. */ -#define CPARSE_MODE_NOIMPLICIT 16 /* Reject implicit declarations. */ -#define CPARSE_MODE_SKIP 32 /* Skip definitions, ignore errors. */ - -typedef int CPChar; /* C parser character. Unsigned ext. from char. */ -typedef int CPToken; /* C parser token. */ - -/* C parser internal value representation. */ -typedef struct CPValue { - union { - int32_t i32; /* Value for CTID_INT32. */ - uint32_t u32; /* Value for CTID_UINT32. */ - }; - CTypeID id; /* C Type ID of the value. */ -} CPValue; - -/* C parser state. */ -typedef struct CPState { - CPChar c; /* Current character. */ - CPToken tok; /* Current token. */ - CPValue val; /* Token value. */ - GCstr *str; /* Interned string of identifier/keyword. */ - CType *ct; /* C type table entry. */ - const char *p; /* Current position in input buffer. */ - SBuf sb; /* String buffer for tokens. */ - lua_State *L; /* Lua state. */ - CTState *cts; /* C type state. */ - TValue *param; /* C type parameters. */ - const char *srcname; /* Current source name. */ - BCLine linenumber; /* Input line counter. */ - int depth; /* Recursive declaration depth. */ - uint32_t tmask; /* Type mask for next identifier. */ - uint32_t mode; /* C parser mode. */ - uint8_t packstack[CPARSE_MAX_PACKSTACK]; /* Stack for pack pragmas. */ - uint8_t curpack; /* Current position in pack pragma stack. */ -} CPState; - -LJ_FUNC int lj_cparse(CPState *cp); - -LJ_FUNC int lj_cparse_case(GCstr *str, const char *match); - -#endif - -#endif diff --git a/include/luajit/lj_crecord.h b/include/luajit/lj_crecord.h deleted file mode 100644 index 898365d..0000000 --- a/include/luajit/lj_crecord.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -** Trace recorder for C data operations. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_CRECORD_H -#define _LJ_CRECORD_H - -#include "lj_obj.h" -#include "lj_jit.h" -#include "lj_ffrecord.h" - -#if LJ_HASJIT && LJ_HASFFI -LJ_FUNC void LJ_FASTCALL recff_cdata_index(jit_State *J, RecordFFData *rd); -LJ_FUNC void LJ_FASTCALL recff_cdata_call(jit_State *J, RecordFFData *rd); -LJ_FUNC void LJ_FASTCALL recff_cdata_arith(jit_State *J, RecordFFData *rd); -LJ_FUNC void LJ_FASTCALL recff_clib_index(jit_State *J, RecordFFData *rd); -LJ_FUNC void LJ_FASTCALL recff_ffi_new(jit_State *J, RecordFFData *rd); -LJ_FUNC void LJ_FASTCALL recff_ffi_errno(jit_State *J, RecordFFData *rd); -LJ_FUNC void LJ_FASTCALL recff_ffi_string(jit_State *J, RecordFFData *rd); -LJ_FUNC void LJ_FASTCALL recff_ffi_copy(jit_State *J, RecordFFData *rd); -LJ_FUNC void LJ_FASTCALL recff_ffi_fill(jit_State *J, RecordFFData *rd); -LJ_FUNC void LJ_FASTCALL recff_ffi_typeof(jit_State *J, RecordFFData *rd); -LJ_FUNC void LJ_FASTCALL recff_ffi_istype(jit_State *J, RecordFFData *rd); -LJ_FUNC void LJ_FASTCALL recff_ffi_abi(jit_State *J, RecordFFData *rd); -LJ_FUNC void LJ_FASTCALL recff_ffi_xof(jit_State *J, RecordFFData *rd); -LJ_FUNC void LJ_FASTCALL recff_ffi_gc(jit_State *J, RecordFFData *rd); - -LJ_FUNC void LJ_FASTCALL recff_bit64_tobit(jit_State *J, RecordFFData *rd); -LJ_FUNC int LJ_FASTCALL recff_bit64_unary(jit_State *J, RecordFFData *rd); -LJ_FUNC int LJ_FASTCALL recff_bit64_nary(jit_State *J, RecordFFData *rd); -LJ_FUNC int LJ_FASTCALL recff_bit64_shift(jit_State *J, RecordFFData *rd); -LJ_FUNC TRef recff_bit64_tohex(jit_State *J, RecordFFData *rd, TRef hdr); - -LJ_FUNC void LJ_FASTCALL lj_crecord_tonumber(jit_State *J, RecordFFData *rd); -LJ_FUNC TRef lj_crecord_loadiu64(jit_State *J, TRef tr, cTValue *o); -#if LJ_HASBUFFER -LJ_FUNC TRef lj_crecord_topcvoid(jit_State *J, TRef tr, cTValue *o); -LJ_FUNC TRef lj_crecord_topuint8(jit_State *J, TRef tr); -#endif -#endif - -#endif diff --git a/include/luajit/lj_ctype.h b/include/luajit/lj_ctype.h deleted file mode 100644 index 18db299..0000000 --- a/include/luajit/lj_ctype.h +++ /dev/null @@ -1,485 +0,0 @@ -/* -** C type management. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_CTYPE_H -#define _LJ_CTYPE_H - -#include "lj_obj.h" -#include "lj_gc.h" - -#if LJ_HASFFI - -/* -- C type definitions -------------------------------------------------- */ - -/* C type numbers. Highest 4 bits of C type info. ORDER CT. */ -enum { - /* Externally visible types. */ - CT_NUM, /* Integer or floating-point numbers. */ - CT_STRUCT, /* Struct or union. */ - CT_PTR, /* Pointer or reference. */ - CT_ARRAY, /* Array or complex type. */ - CT_MAYCONVERT = CT_ARRAY, - CT_VOID, /* Void type. */ - CT_ENUM, /* Enumeration. */ - CT_HASSIZE = CT_ENUM, /* Last type where ct->size holds the actual size. */ - CT_FUNC, /* Function. */ - CT_TYPEDEF, /* Typedef. */ - CT_ATTRIB, /* Miscellaneous attributes. */ - /* Internal element types. */ - CT_FIELD, /* Struct/union field or function parameter. */ - CT_BITFIELD, /* Struct/union bitfield. */ - CT_CONSTVAL, /* Constant value. */ - CT_EXTERN, /* External reference. */ - CT_KW /* Keyword. */ -}; - -LJ_STATIC_ASSERT(((int)CT_PTR & (int)CT_ARRAY) == CT_PTR); -LJ_STATIC_ASSERT(((int)CT_STRUCT & (int)CT_ARRAY) == CT_STRUCT); - -/* -** ---------- info ------------ -** |type flags... A cid | size | sib | next | name | -** +----------------------------+--------+-------+-------+-------+-- -** |NUM BFcvUL.. A | size | | type | | -** |STRUCT ..cvU..V A | size | field | name? | name? | -** |PTR ..cvR... A cid | size | | type | | -** |ARRAY VCcv...V A cid | size | | type | | -** |VOID ..cv.... A | size | | type | | -** |ENUM A cid | size | const | name? | name? | -** |FUNC ....VS.. cc cid | nargs | field | name? | name? | -** |TYPEDEF cid | | | name | name | -** |ATTRIB attrnum cid | attr | sib? | type? | | -** |FIELD cid | offset | field | | name? | -** |BITFIELD B.cvU csz bsz pos | offset | field | | name? | -** |CONSTVAL c cid | value | const | name | name | -** |EXTERN cid | | sib? | name | name | -** |KW tok | size | | name | name | -** +----------------------------+--------+-------+-------+-------+-- -** ^^ ^^--- bits used for C type conversion dispatch -*/ - -/* C type info flags. TFFArrrr */ -#define CTF_BOOL 0x08000000u /* Boolean: NUM, BITFIELD. */ -#define CTF_FP 0x04000000u /* Floating-point: NUM. */ -#define CTF_CONST 0x02000000u /* Const qualifier. */ -#define CTF_VOLATILE 0x01000000u /* Volatile qualifier. */ -#define CTF_UNSIGNED 0x00800000u /* Unsigned: NUM, BITFIELD. */ -#define CTF_LONG 0x00400000u /* Long: NUM. */ -#define CTF_VLA 0x00100000u /* Variable-length: ARRAY, STRUCT. */ -#define CTF_REF 0x00800000u /* Reference: PTR. */ -#define CTF_VECTOR 0x08000000u /* Vector: ARRAY. */ -#define CTF_COMPLEX 0x04000000u /* Complex: ARRAY. */ -#define CTF_UNION 0x00800000u /* Union: STRUCT. */ -#define CTF_VARARG 0x00800000u /* Vararg: FUNC. */ -#define CTF_SSEREGPARM 0x00400000u /* SSE register parameters: FUNC. */ - -#define CTF_QUAL (CTF_CONST|CTF_VOLATILE) -#define CTF_ALIGN (CTMASK_ALIGN< 0 ? CTF_UNSIGNED : 0) - -/* Flags used in parser. .F.Ammvf cp->attr */ -#define CTFP_ALIGNED 0x00000001u /* cp->attr + ALIGN */ -#define CTFP_PACKED 0x00000002u /* cp->attr */ -/* ...C...f cp->fattr */ -#define CTFP_CCONV 0x00000001u /* cp->fattr + CCONV/[SSE]REGPARM */ - -/* C type info bitfields. */ -#define CTMASK_CID 0x0000ffffu /* Max. 65536 type IDs. */ -#define CTMASK_NUM 0xf0000000u /* Max. 16 type numbers. */ -#define CTSHIFT_NUM 28 -#define CTMASK_ALIGN 15 /* Max. alignment is 2^15. */ -#define CTSHIFT_ALIGN 16 -#define CTMASK_ATTRIB 255 /* Max. 256 attributes. */ -#define CTSHIFT_ATTRIB 16 -#define CTMASK_CCONV 3 /* Max. 4 calling conventions. */ -#define CTSHIFT_CCONV 16 -#define CTMASK_REGPARM 3 /* Max. 0-3 regparms. */ -#define CTSHIFT_REGPARM 18 -/* Bitfields only used in parser. */ -#define CTMASK_VSIZEP 15 /* Max. vector size is 2^15. */ -#define CTSHIFT_VSIZEP 4 -#define CTMASK_MSIZEP 255 /* Max. type size (via mode) is 128. */ -#define CTSHIFT_MSIZEP 8 - -/* Info bits for BITFIELD. Max. size of bitfield is 64 bits. */ -#define CTBSZ_MAX 32 /* Max. size of bitfield is 32 bit. */ -#define CTBSZ_FIELD 127 /* Temp. marker for regular field. */ -#define CTMASK_BITPOS 127 -#define CTMASK_BITBSZ 127 -#define CTMASK_BITCSZ 127 -#define CTSHIFT_BITPOS 0 -#define CTSHIFT_BITBSZ 8 -#define CTSHIFT_BITCSZ 16 - -#define CTF_INSERT(info, field, val) \ - info = (info & ~(CTMASK_##field<> CTSHIFT_NUM) -#define ctype_cid(info) ((CTypeID)((info) & CTMASK_CID)) -#define ctype_align(info) (((info) >> CTSHIFT_ALIGN) & CTMASK_ALIGN) -#define ctype_attrib(info) (((info) >> CTSHIFT_ATTRIB) & CTMASK_ATTRIB) -#define ctype_bitpos(info) (((info) >> CTSHIFT_BITPOS) & CTMASK_BITPOS) -#define ctype_bitbsz(info) (((info) >> CTSHIFT_BITBSZ) & CTMASK_BITBSZ) -#define ctype_bitcsz(info) (((info) >> CTSHIFT_BITCSZ) & CTMASK_BITCSZ) -#define ctype_vsizeP(info) (((info) >> CTSHIFT_VSIZEP) & CTMASK_VSIZEP) -#define ctype_msizeP(info) (((info) >> CTSHIFT_MSIZEP) & CTMASK_MSIZEP) -#define ctype_cconv(info) (((info) >> CTSHIFT_CCONV) & CTMASK_CCONV) - -/* Simple type checks. */ -#define ctype_isnum(info) (ctype_type((info)) == CT_NUM) -#define ctype_isvoid(info) (ctype_type((info)) == CT_VOID) -#define ctype_isptr(info) (ctype_type((info)) == CT_PTR) -#define ctype_isarray(info) (ctype_type((info)) == CT_ARRAY) -#define ctype_isstruct(info) (ctype_type((info)) == CT_STRUCT) -#define ctype_isfunc(info) (ctype_type((info)) == CT_FUNC) -#define ctype_isenum(info) (ctype_type((info)) == CT_ENUM) -#define ctype_istypedef(info) (ctype_type((info)) == CT_TYPEDEF) -#define ctype_isattrib(info) (ctype_type((info)) == CT_ATTRIB) -#define ctype_isfield(info) (ctype_type((info)) == CT_FIELD) -#define ctype_isbitfield(info) (ctype_type((info)) == CT_BITFIELD) -#define ctype_isconstval(info) (ctype_type((info)) == CT_CONSTVAL) -#define ctype_isextern(info) (ctype_type((info)) == CT_EXTERN) -#define ctype_hassize(info) (ctype_type((info)) <= CT_HASSIZE) - -/* Combined type and flag checks. */ -#define ctype_isinteger(info) \ - (((info) & (CTMASK_NUM|CTF_BOOL|CTF_FP)) == CTINFO(CT_NUM, 0)) -#define ctype_isinteger_or_bool(info) \ - (((info) & (CTMASK_NUM|CTF_FP)) == CTINFO(CT_NUM, 0)) -#define ctype_isbool(info) \ - (((info) & (CTMASK_NUM|CTF_BOOL)) == CTINFO(CT_NUM, CTF_BOOL)) -#define ctype_isfp(info) \ - (((info) & (CTMASK_NUM|CTF_FP)) == CTINFO(CT_NUM, CTF_FP)) - -#define ctype_ispointer(info) \ - ((ctype_type(info) >> 1) == (CT_PTR >> 1)) /* Pointer or array. */ -#define ctype_isref(info) \ - (((info) & (CTMASK_NUM|CTF_REF)) == CTINFO(CT_PTR, CTF_REF)) - -#define ctype_isrefarray(info) \ - (((info) & (CTMASK_NUM|CTF_VECTOR|CTF_COMPLEX)) == CTINFO(CT_ARRAY, 0)) -#define ctype_isvector(info) \ - (((info) & (CTMASK_NUM|CTF_VECTOR)) == CTINFO(CT_ARRAY, CTF_VECTOR)) -#define ctype_iscomplex(info) \ - (((info) & (CTMASK_NUM|CTF_COMPLEX)) == CTINFO(CT_ARRAY, CTF_COMPLEX)) - -#define ctype_isvltype(info) \ - (((info) & ((CTMASK_NUM|CTF_VLA) - (2u<g, (c), __VA_ARGS__)) -#else -#define lj_assertCTS(c, ...) ((void)cts) -#endif - -/* -- Predefined types ---------------------------------------------------- */ - -/* Target-dependent types. */ -#if LJ_TARGET_PPC -#define CTTYDEFP(_) \ - _(LINT32, 4, CT_NUM, CTF_LONG|CTALIGN(2)) -#else -#define CTTYDEFP(_) -#endif - -#define CTF_LONG_IF8 (CTF_LONG * (sizeof(long) == 8)) - -/* Common types. */ -#define CTTYDEF(_) \ - _(NONE, 0, CT_ATTRIB, CTATTRIB(CTA_BAD)) \ - _(VOID, -1, CT_VOID, CTALIGN(0)) \ - _(CVOID, -1, CT_VOID, CTF_CONST|CTALIGN(0)) \ - _(BOOL, 1, CT_NUM, CTF_BOOL|CTF_UNSIGNED|CTALIGN(0)) \ - _(CCHAR, 1, CT_NUM, CTF_CONST|CTF_UCHAR|CTALIGN(0)) \ - _(INT8, 1, CT_NUM, CTALIGN(0)) \ - _(UINT8, 1, CT_NUM, CTF_UNSIGNED|CTALIGN(0)) \ - _(INT16, 2, CT_NUM, CTALIGN(1)) \ - _(UINT16, 2, CT_NUM, CTF_UNSIGNED|CTALIGN(1)) \ - _(INT32, 4, CT_NUM, CTALIGN(2)) \ - _(UINT32, 4, CT_NUM, CTF_UNSIGNED|CTALIGN(2)) \ - _(INT64, 8, CT_NUM, CTF_LONG_IF8|CTALIGN(3)) \ - _(UINT64, 8, CT_NUM, CTF_UNSIGNED|CTF_LONG_IF8|CTALIGN(3)) \ - _(INT128, 16, CT_NUM, CTALIGN(4)) \ - _(UINT128, 16, CT_NUM, CTF_UNSIGNED|CTALIGN(4)) \ - _(FLOAT, 4, CT_NUM, CTF_FP|CTALIGN(2)) \ - _(DOUBLE, 8, CT_NUM, CTF_FP|CTALIGN(3)) \ - _(COMPLEX_FLOAT, 8, CT_ARRAY, CTF_COMPLEX|CTALIGN(2)|CTID_FLOAT) \ - _(COMPLEX_DOUBLE, 16, CT_ARRAY, CTF_COMPLEX|CTALIGN(3)|CTID_DOUBLE) \ - _(P_VOID, CTSIZE_PTR, CT_PTR, CTALIGN_PTR|CTID_VOID) \ - _(P_CVOID, CTSIZE_PTR, CT_PTR, CTALIGN_PTR|CTID_CVOID) \ - _(P_CCHAR, CTSIZE_PTR, CT_PTR, CTALIGN_PTR|CTID_CCHAR) \ - _(P_UINT8, CTSIZE_PTR, CT_PTR, CTALIGN_PTR|CTID_UINT8) \ - _(A_CCHAR, -1, CT_ARRAY, CTF_CONST|CTALIGN(0)|CTID_CCHAR) \ - _(CTYPEID, 4, CT_ENUM, CTALIGN(2)|CTID_INT32) \ - CTTYDEFP(_) \ - /* End of type list. */ - -/* Public predefined type IDs. */ -enum { -#define CTTYIDDEF(id, sz, ct, info) CTID_##id, -CTTYDEF(CTTYIDDEF) -#undef CTTYIDDEF - /* Predefined typedefs and keywords follow. */ - CTID_MAX = 65536 -}; - -/* Target-dependent type IDs. */ -#if LJ_64 -#define CTID_INT_PSZ CTID_INT64 -#define CTID_UINT_PSZ CTID_UINT64 -#else -#define CTID_INT_PSZ CTID_INT32 -#define CTID_UINT_PSZ CTID_UINT32 -#endif - -#if LJ_ABI_WIN -#define CTID_WCHAR CTID_UINT16 -#elif LJ_TARGET_PPC -#define CTID_WCHAR CTID_LINT32 -#else -#define CTID_WCHAR CTID_INT32 -#endif - -/* -- C tokens and keywords ----------------------------------------------- */ - -/* C lexer keywords. */ -#define CTOKDEF(_) \ - _(IDENT, "") _(STRING, "") \ - _(INTEGER, "") _(EOF, "") \ - _(OROR, "||") _(ANDAND, "&&") _(EQ, "==") _(NE, "!=") \ - _(LE, "<=") _(GE, ">=") _(SHL, "<<") _(SHR, ">>") _(DEREF, "->") - -/* Simple declaration specifiers. */ -#define CDSDEF(_) \ - _(VOID) _(BOOL) _(CHAR) _(INT) _(FP) \ - _(LONG) _(LONGLONG) _(SHORT) _(COMPLEX) _(SIGNED) _(UNSIGNED) \ - _(CONST) _(VOLATILE) _(RESTRICT) _(INLINE) \ - _(TYPEDEF) _(EXTERN) _(STATIC) _(AUTO) _(REGISTER) - -/* C keywords. */ -#define CKWDEF(_) \ - CDSDEF(_) _(EXTENSION) _(ASM) _(ATTRIBUTE) \ - _(DECLSPEC) _(CCDECL) _(PTRSZ) \ - _(STRUCT) _(UNION) _(ENUM) \ - _(SIZEOF) _(ALIGNOF) - -/* C token numbers. */ -enum { - CTOK_OFS = 255, -#define CTOKNUM(name, sym) CTOK_##name, -#define CKWNUM(name) CTOK_##name, -CTOKDEF(CTOKNUM) -CKWDEF(CKWNUM) -#undef CTOKNUM -#undef CKWNUM - CTOK_FIRSTDECL = CTOK_VOID, - CTOK_FIRSTSCL = CTOK_TYPEDEF, - CTOK_LASTDECLFLAG = CTOK_REGISTER, - CTOK_LASTDECL = CTOK_ENUM -}; - -/* Declaration specifier flags. */ -enum { -#define CDSFLAG(name) CDF_##name = (1u << (CTOK_##name - CTOK_FIRSTDECL)), -CDSDEF(CDSFLAG) -#undef CDSFLAG - CDF__END -}; - -#define CDF_SCL (CDF_TYPEDEF|CDF_EXTERN|CDF_STATIC|CDF_AUTO|CDF_REGISTER) - -/* -- C type management --------------------------------------------------- */ - -#define ctype_ctsG(g) (mref((g)->ctype_state, CTState)) - -/* Get C type state. */ -static LJ_AINLINE CTState *ctype_cts(lua_State *L) -{ - CTState *cts = ctype_ctsG(G(L)); - cts->L = L; /* Save L for errors and allocations. */ - return cts; -} - -/* Load FFI library on-demand. */ -#define ctype_loadffi(L) \ - do { \ - if (!ctype_ctsG(G(L))) { \ - ptrdiff_t oldtop = (char *)L->top - mref(L->stack, char); \ - luaopen_ffi(L); \ - L->top = (TValue *)(mref(L->stack, char) + oldtop); \ - } \ - } while (0) - -/* Save and restore state of C type table. */ -#define LJ_CTYPE_SAVE(cts) CTState savects_ = *(cts) -#define LJ_CTYPE_RESTORE(cts) \ - ((cts)->top = savects_.top, \ - memcpy((cts)->hash, savects_.hash, sizeof(savects_.hash))) - -/* Check C type ID for validity when assertions are enabled. */ -static LJ_AINLINE CTypeID ctype_check(CTState *cts, CTypeID id) -{ - UNUSED(cts); - lj_assertCTS(id > 0 && id < cts->top, "bad CTID %d", id); - return id; -} - -/* Get C type for C type ID. */ -static LJ_AINLINE CType *ctype_get(CTState *cts, CTypeID id) -{ - return &cts->tab[ctype_check(cts, id)]; -} - -/* Get C type ID for a C type. */ -#define ctype_typeid(cts, ct) ((CTypeID)((ct) - (cts)->tab)) - -/* Get child C type. */ -static LJ_AINLINE CType *ctype_child(CTState *cts, CType *ct) -{ - lj_assertCTS(!(ctype_isvoid(ct->info) || ctype_isstruct(ct->info) || - ctype_isbitfield(ct->info)), - "ctype %08x has no children", ct->info); - return ctype_get(cts, ctype_cid(ct->info)); -} - -/* Get raw type for a C type ID. */ -static LJ_AINLINE CType *ctype_raw(CTState *cts, CTypeID id) -{ - CType *ct = ctype_get(cts, id); - while (ctype_isattrib(ct->info)) ct = ctype_child(cts, ct); - return ct; -} - -/* Get raw type of the child of a C type. */ -static LJ_AINLINE CType *ctype_rawchild(CTState *cts, CType *ct) -{ - do { ct = ctype_child(cts, ct); } while (ctype_isattrib(ct->info)); - return ct; -} - -/* Set the name of a C type table element. */ -static LJ_AINLINE void ctype_setname(CType *ct, GCstr *s) -{ - /* NOBARRIER: mark string as fixed -- the C type table is never collected. */ - fixstring(s); - setgcref(ct->name, obj2gco(s)); -} - -LJ_FUNC CTypeID lj_ctype_new(CTState *cts, CType **ctp); -LJ_FUNC CTypeID lj_ctype_intern(CTState *cts, CTInfo info, CTSize size); -LJ_FUNC void lj_ctype_addname(CTState *cts, CType *ct, CTypeID id); -LJ_FUNC CTypeID lj_ctype_getname(CTState *cts, CType **ctp, GCstr *name, - uint32_t tmask); -LJ_FUNC CType *lj_ctype_getfieldq(CTState *cts, CType *ct, GCstr *name, - CTSize *ofs, CTInfo *qual); -#define lj_ctype_getfield(cts, ct, name, ofs) \ - lj_ctype_getfieldq((cts), (ct), (name), (ofs), NULL) -LJ_FUNC CType *lj_ctype_rawref(CTState *cts, CTypeID id); -LJ_FUNC CTSize lj_ctype_size(CTState *cts, CTypeID id); -LJ_FUNC CTSize lj_ctype_vlsize(CTState *cts, CType *ct, CTSize nelem); -LJ_FUNC CTInfo lj_ctype_info(CTState *cts, CTypeID id, CTSize *szp); -LJ_FUNC CTInfo lj_ctype_info_raw(CTState *cts, CTypeID id, CTSize *szp); -LJ_FUNC cTValue *lj_ctype_meta(CTState *cts, CTypeID id, MMS mm); -LJ_FUNC GCstr *lj_ctype_repr(lua_State *L, CTypeID id, GCstr *name); -LJ_FUNC GCstr *lj_ctype_repr_int64(lua_State *L, uint64_t n, int isunsigned); -LJ_FUNC GCstr *lj_ctype_repr_complex(lua_State *L, void *sp, CTSize size); -LJ_FUNC CTState *lj_ctype_init(lua_State *L); -LJ_FUNC void lj_ctype_initfin(lua_State *L); -LJ_FUNC void lj_ctype_freestate(global_State *g); - -#endif - -#endif diff --git a/include/luajit/lj_debug.h b/include/luajit/lj_debug.h deleted file mode 100644 index 8b1b769..0000000 --- a/include/luajit/lj_debug.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -** Debugging and introspection. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_DEBUG_H -#define _LJ_DEBUG_H - -#include "lj_obj.h" - -typedef struct lj_Debug { - /* Common fields. Must be in the same order as in lua.h. */ - int event; - const char *name; - const char *namewhat; - const char *what; - const char *source; - int currentline; - int nups; - int linedefined; - int lastlinedefined; - char short_src[LUA_IDSIZE]; - int i_ci; - /* Extended fields. Only valid if lj_debug_getinfo() is called with ext = 1.*/ - int nparams; - int isvararg; -} lj_Debug; - -LJ_FUNC cTValue *lj_debug_frame(lua_State *L, int level, int *size); -LJ_FUNC BCLine LJ_FASTCALL lj_debug_line(GCproto *pt, BCPos pc); -LJ_FUNC const char *lj_debug_uvname(GCproto *pt, uint32_t idx); -LJ_FUNC const char *lj_debug_uvnamev(cTValue *o, uint32_t idx, TValue **tvp, - GCobj **op); -LJ_FUNC const char *lj_debug_slotname(GCproto *pt, const BCIns *pc, - BCReg slot, const char **name); -LJ_FUNC const char *lj_debug_funcname(lua_State *L, cTValue *frame, - const char **name); -LJ_FUNC void lj_debug_shortname(char *out, GCstr *str, BCLine line); -LJ_FUNC void lj_debug_addloc(lua_State *L, const char *msg, - cTValue *frame, cTValue *nextframe); -LJ_FUNC void lj_debug_pushloc(lua_State *L, GCproto *pt, BCPos pc); -LJ_FUNC int lj_debug_getinfo(lua_State *L, const char *what, lj_Debug *ar, - int ext); -#if LJ_HASPROFILE -LJ_FUNC void lj_debug_dumpstack(lua_State *L, SBuf *sb, const char *fmt, - int depth); -#endif - -/* Fixed internal variable names. */ -#define VARNAMEDEF(_) \ - _(FOR_IDX, "(for index)") \ - _(FOR_STOP, "(for limit)") \ - _(FOR_STEP, "(for step)") \ - _(FOR_GEN, "(for generator)") \ - _(FOR_STATE, "(for state)") \ - _(FOR_CTL, "(for control)") - -enum { - VARNAME_END, -#define VARNAMEENUM(name, str) VARNAME_##name, - VARNAMEDEF(VARNAMEENUM) -#undef VARNAMEENUM - VARNAME__MAX -}; - -#endif diff --git a/include/luajit/lj_def.h b/include/luajit/lj_def.h deleted file mode 100644 index 7785291..0000000 --- a/include/luajit/lj_def.h +++ /dev/null @@ -1,394 +0,0 @@ -/* -** LuaJIT common internal definitions. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_DEF_H -#define _LJ_DEF_H - -#include "lua.h" - -#if defined(_MSC_VER) && (_MSC_VER < 1700) -/* Old MSVC is stuck in the last century and doesn't have C99's stdint.h. */ -typedef __int8 int8_t; -typedef __int16 int16_t; -typedef __int32 int32_t; -typedef __int64 int64_t; -typedef unsigned __int8 uint8_t; -typedef unsigned __int16 uint16_t; -typedef unsigned __int32 uint32_t; -typedef unsigned __int64 uint64_t; -#ifdef _WIN64 -typedef __int64 intptr_t; -typedef unsigned __int64 uintptr_t; -#else -typedef __int32 intptr_t; -typedef unsigned __int32 uintptr_t; -#endif -#elif defined(__symbian__) -/* Cough. */ -typedef signed char int8_t; -typedef short int int16_t; -typedef int int32_t; -typedef long long int64_t; -typedef unsigned char uint8_t; -typedef unsigned short int uint16_t; -typedef unsigned int uint32_t; -typedef unsigned long long uint64_t; -typedef int intptr_t; -typedef unsigned int uintptr_t; -#else -#include -#endif - -/* Needed everywhere. */ -#include -#include - -/* Various VM limits. */ -#define LJ_MAX_MEM32 0x7fffff00 /* Max. 32 bit memory allocation. */ -#define LJ_MAX_MEM64 ((uint64_t)1<<47) /* Max. 64 bit memory allocation. */ -/* Max. total memory allocation. */ -#define LJ_MAX_MEM (LJ_GC64 ? LJ_MAX_MEM64 : LJ_MAX_MEM32) -#define LJ_MAX_ALLOC LJ_MAX_MEM /* Max. individual allocation length. */ -#define LJ_MAX_STR LJ_MAX_MEM32 /* Max. string length. */ -#define LJ_MAX_BUF LJ_MAX_MEM32 /* Max. buffer length. */ -#define LJ_MAX_UDATA LJ_MAX_MEM32 /* Max. userdata length. */ - -#define LJ_MAX_STRTAB (1<<26) /* Max. string table size. */ -#define LJ_MAX_HBITS 26 /* Max. hash bits. */ -#define LJ_MAX_ABITS 28 /* Max. bits of array key. */ -#define LJ_MAX_ASIZE ((1<<(LJ_MAX_ABITS-1))+1) /* Max. array part size. */ -#define LJ_MAX_COLOSIZE 16 /* Max. elems for colocated array. */ - -#define LJ_MAX_LINE LJ_MAX_MEM32 /* Max. source code line number. */ -#define LJ_MAX_XLEVEL 200 /* Max. syntactic nesting level. */ -#define LJ_MAX_BCINS (1<<26) /* Max. # of bytecode instructions. */ -#define LJ_MAX_SLOTS 250 /* Max. # of slots in a Lua func. */ -#define LJ_MAX_LOCVAR 200 /* Max. # of local variables. */ -#define LJ_MAX_UPVAL 60 /* Max. # of upvalues. */ - -#define LJ_MAX_IDXCHAIN 100 /* __index/__newindex chain limit. */ -#define LJ_STACK_EXTRA (5+3*LJ_FR2) /* Extra stack space (metamethods). */ - -#define LJ_NUM_CBPAGE 1 /* Number of FFI callback pages. */ - -/* Minimum table/buffer sizes. */ -#define LJ_MIN_GLOBAL 6 /* Min. global table size (hbits). */ -#define LJ_MIN_REGISTRY 2 /* Min. registry size (hbits). */ -#define LJ_MIN_STRTAB 256 /* Min. string table size (pow2). */ -#define LJ_MIN_SBUF 32 /* Min. string buffer length. */ -#define LJ_MIN_VECSZ 8 /* Min. size for growable vectors. */ -#define LJ_MIN_IRSZ 32 /* Min. size for growable IR. */ - -/* JIT compiler limits. */ -#define LJ_MAX_JSLOTS 250 /* Max. # of stack slots for a trace. */ -#define LJ_MAX_PHI 64 /* Max. # of PHIs for a loop. */ -#define LJ_MAX_EXITSTUBGR 16 /* Max. # of exit stub groups. */ - -/* Various macros. */ -#ifndef UNUSED -#define UNUSED(x) ((void)(x)) /* to avoid warnings */ -#endif - -#define U64x(hi, lo) (((uint64_t)0x##hi << 32) + (uint64_t)0x##lo) -#define i32ptr(p) ((int32_t)(intptr_t)(void *)(p)) -#define u32ptr(p) ((uint32_t)(intptr_t)(void *)(p)) -#define i64ptr(p) ((int64_t)(intptr_t)(void *)(p)) -#define u64ptr(p) ((uint64_t)(intptr_t)(void *)(p)) -#define igcptr(p) (LJ_GC64 ? i64ptr(p) : i32ptr(p)) - -#define checki8(x) ((x) == (int32_t)(int8_t)(x)) -#define checku8(x) ((x) == (int32_t)(uint8_t)(x)) -#define checki16(x) ((x) == (int32_t)(int16_t)(x)) -#define checku16(x) ((x) == (int32_t)(uint16_t)(x)) -#define checki32(x) ((x) == (int32_t)(x)) -#define checku32(x) ((x) == (uint32_t)(x)) -#define checkptr31(x) (((uint64_t)(uintptr_t)(x) >> 31) == 0) -#define checkptr32(x) ((uintptr_t)(x) == (uint32_t)(uintptr_t)(x)) -#define checkptr47(x) (((uint64_t)(uintptr_t)(x) >> 47) == 0) -#define checkptrGC(x) (LJ_GC64 ? checkptr47((x)) : LJ_64 ? checkptr31((x)) :1) - -/* Every half-decent C compiler transforms this into a rotate instruction. */ -#define lj_rol(x, n) (((x)<<(n)) | ((x)>>(-(int)(n)&(8*sizeof(x)-1)))) -#define lj_ror(x, n) (((x)<<(-(int)(n)&(8*sizeof(x)-1))) | ((x)>>(n))) - -/* A really naive Bloom filter. But sufficient for our needs. */ -typedef uintptr_t BloomFilter; -#define BLOOM_MASK (8*sizeof(BloomFilter) - 1) -#define bloombit(x) ((uintptr_t)1 << ((x) & BLOOM_MASK)) -#define bloomset(b, x) ((b) |= bloombit((x))) -#define bloomtest(b, x) ((b) & bloombit((x))) - -#if defined(__GNUC__) || defined(__clang__) || defined(__psp2__) - -#define LJ_NORET __attribute__((noreturn)) -#define LJ_ALIGN(n) __attribute__((aligned(n))) -#define LJ_INLINE inline -#define LJ_AINLINE inline __attribute__((always_inline)) -#define LJ_NOINLINE __attribute__((noinline)) -#define LJ_CONSTF __attribute__((nothrow,const)) - -#if defined(__ELF__) || defined(__MACH__) || defined(__psp2__) -#if !((defined(__sun__) && defined(__svr4__)) || defined(__CELLOS_LV2__)) -#define LJ_NOAPI extern __attribute__((visibility("hidden"))) -#endif -#endif - -/* Note: it's only beneficial to use fastcall on x86 and then only for up to -** two non-FP args. The amalgamated compile covers all LJ_FUNC cases. Only -** indirect calls and related tail-called C functions are marked as fastcall. -*/ -#if defined(__i386__) -#define LJ_FASTCALL __attribute__((fastcall)) -#endif - -#define LJ_LIKELY(x) __builtin_expect(!!(x), 1) -#define LJ_UNLIKELY(x) __builtin_expect(!!(x), 0) - -#define lj_ffs(x) ((uint32_t)__builtin_ctz(x)) -#define lj_fls(x) ((uint32_t)(__builtin_clz(x)^31)) -#define lj_ffs64(x) ((uint32_t)__builtin_ctzll(x)) -#define lj_fls64(x) ((uint32_t)(__builtin_clzll(x)^63)) - -#if defined(__arm__) -static LJ_AINLINE uint32_t lj_bswap(uint32_t x) -{ -#if defined(__psp2__) - return __builtin_rev(x); -#else - uint32_t r; -#if __ARM_ARCH_6__ || __ARM_ARCH_6J__ || __ARM_ARCH_6T2__ || __ARM_ARCH_6Z__ ||\ - __ARM_ARCH_6ZK__ || __ARM_ARCH_7__ || __ARM_ARCH_7A__ || __ARM_ARCH_7R__ - __asm__("rev %0, %1" : "=r" (r) : "r" (x)); - return r; -#else -#ifdef __thumb__ - r = x ^ lj_ror(x, 16); -#else - __asm__("eor %0, %1, %1, ror #16" : "=r" (r) : "r" (x)); -#endif - return ((r & 0xff00ffffu) >> 8) ^ lj_ror(x, 8); -#endif -#endif -} - -static LJ_AINLINE uint64_t lj_bswap64(uint64_t x) -{ - return ((uint64_t)lj_bswap((uint32_t)x)<<32) | lj_bswap((uint32_t)(x>>32)); -} -#elif (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3) || __clang__ -static LJ_AINLINE uint32_t lj_bswap(uint32_t x) -{ - return (uint32_t)__builtin_bswap32((int32_t)x); -} - -static LJ_AINLINE uint64_t lj_bswap64(uint64_t x) -{ - return (uint64_t)__builtin_bswap64((int64_t)x); -} -#elif defined(__i386__) || defined(__x86_64__) -static LJ_AINLINE uint32_t lj_bswap(uint32_t x) -{ - uint32_t r; __asm__("bswap %0" : "=r" (r) : "0" (x)); return r; -} - -#if defined(__i386__) -static LJ_AINLINE uint64_t lj_bswap64(uint64_t x) -{ - return ((uint64_t)lj_bswap((uint32_t)x)<<32) | lj_bswap((uint32_t)(x>>32)); -} -#else -static LJ_AINLINE uint64_t lj_bswap64(uint64_t x) -{ - uint64_t r; __asm__("bswap %0" : "=r" (r) : "0" (x)); return r; -} -#endif -#else -static LJ_AINLINE uint32_t lj_bswap(uint32_t x) -{ - return (x << 24) | ((x & 0xff00) << 8) | ((x >> 8) & 0xff00) | (x >> 24); -} - -static LJ_AINLINE uint64_t lj_bswap64(uint64_t x) -{ - return (uint64_t)lj_bswap((uint32_t)(x >> 32)) | - ((uint64_t)lj_bswap((uint32_t)x) << 32); -} -#endif - -typedef union __attribute__((packed)) Unaligned16 { - uint16_t u; - uint8_t b[2]; -} Unaligned16; - -typedef union __attribute__((packed)) Unaligned32 { - uint32_t u; - uint8_t b[4]; -} Unaligned32; - -/* Unaligned load of uint16_t. */ -static LJ_AINLINE uint16_t lj_getu16(const void *p) -{ - return ((const Unaligned16 *)p)->u; -} - -/* Unaligned load of uint32_t. */ -static LJ_AINLINE uint32_t lj_getu32(const void *p) -{ - return ((const Unaligned32 *)p)->u; -} - -#elif defined(_MSC_VER) - -#define LJ_NORET __declspec(noreturn) -#define LJ_ALIGN(n) __declspec(align(n)) -#define LJ_INLINE __inline -#define LJ_AINLINE __forceinline -#define LJ_NOINLINE __declspec(noinline) -#define LJ_CONSTF __declspec(noalias) -#if defined(_M_IX86) -#define LJ_FASTCALL __fastcall -#endif - -#ifdef _M_PPC -unsigned int _CountLeadingZeros(long); -#pragma intrinsic(_CountLeadingZeros) -static LJ_AINLINE uint32_t lj_fls(uint32_t x) -{ - return _CountLeadingZeros(x) ^ 31; -} -#else -unsigned char _BitScanForward(unsigned long *, unsigned long); -unsigned char _BitScanReverse(unsigned long *, unsigned long); -#pragma intrinsic(_BitScanForward) -#pragma intrinsic(_BitScanReverse) - -static LJ_AINLINE uint32_t lj_ffs(uint32_t x) -{ - unsigned long r; _BitScanForward(&r, x); return (uint32_t)r; -} - -static LJ_AINLINE uint32_t lj_fls(uint32_t x) -{ - unsigned long r; _BitScanReverse(&r, x); return (uint32_t)r; -} - -#if defined(_M_X64) || defined(_M_ARM64) -unsigned char _BitScanForward64(unsigned long *, uint64_t); -unsigned char _BitScanReverse64(unsigned long *, uint64_t); -#pragma intrinsic(_BitScanForward64) -#pragma intrinsic(_BitScanReverse64) - -static LJ_AINLINE uint32_t lj_ffs64(uint64_t x) -{ - unsigned long r; _BitScanForward64(&r, x); return (uint32_t)r; -} - -static LJ_AINLINE uint32_t lj_fls64(uint64_t x) -{ - unsigned long r; _BitScanReverse64(&r, x); return (uint32_t)r; -} -#endif -#endif - -unsigned long _byteswap_ulong(unsigned long); -uint64_t _byteswap_uint64(uint64_t); -#define lj_bswap(x) (_byteswap_ulong((x))) -#define lj_bswap64(x) (_byteswap_uint64((x))) - -#if defined(_M_PPC) && defined(LUAJIT_NO_UNALIGNED) -/* -** Replacement for unaligned loads on Xbox 360. Disabled by default since it's -** usually more costly than the occasional stall when crossing a cache-line. -*/ -static LJ_AINLINE uint16_t lj_getu16(const void *v) -{ - const uint8_t *p = (const uint8_t *)v; - return (uint16_t)((p[0]<<8) | p[1]); -} -static LJ_AINLINE uint32_t lj_getu32(const void *v) -{ - const uint8_t *p = (const uint8_t *)v; - return (uint32_t)((p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3]); -} -#else -/* Unaligned loads are generally ok on x86/x64. */ -#define lj_getu16(p) (*(uint16_t *)(p)) -#define lj_getu32(p) (*(uint32_t *)(p)) -#endif - -#else -#error "missing defines for your compiler" -#endif - -/* Optional defines. */ -#ifndef LJ_FASTCALL -#define LJ_FASTCALL -#endif -#ifndef LJ_NORET -#define LJ_NORET -#endif -#ifndef LJ_NOAPI -#define LJ_NOAPI extern -#endif -#ifndef LJ_LIKELY -#define LJ_LIKELY(x) (x) -#define LJ_UNLIKELY(x) (x) -#endif - -/* Attributes for internal functions. */ -#define LJ_DATA LJ_NOAPI -#define LJ_DATADEF -#define LJ_ASMF LJ_NOAPI -#define LJ_FUNCA LJ_NOAPI -#if defined(ljamalg_c) -#define LJ_FUNC static -#else -#define LJ_FUNC LJ_NOAPI -#endif -#define LJ_FUNC_NORET LJ_FUNC LJ_NORET -#define LJ_FUNCA_NORET LJ_FUNCA LJ_NORET -#define LJ_ASMF_NORET LJ_ASMF LJ_NORET - -/* Internal assertions. */ -#if defined(LUA_USE_ASSERT) || defined(LUA_USE_APICHECK) -#define lj_assert_check(g, c, ...) \ - ((c) ? (void)0 : \ - (lj_assert_fail((g), __FILE__, __LINE__, __func__, __VA_ARGS__), 0)) -#define lj_checkapi(c, ...) lj_assert_check(G(L), (c), __VA_ARGS__) -#else -#define lj_checkapi(c, ...) ((void)L) -#endif - -#ifdef LUA_USE_ASSERT -#define lj_assertG_(g, c, ...) lj_assert_check((g), (c), __VA_ARGS__) -#define lj_assertG(c, ...) lj_assert_check(g, (c), __VA_ARGS__) -#define lj_assertL(c, ...) lj_assert_check(G(L), (c), __VA_ARGS__) -#define lj_assertX(c, ...) lj_assert_check(NULL, (c), __VA_ARGS__) -#define check_exp(c, e) (lj_assertX((c), #c), (e)) -#else -#define lj_assertG_(g, c, ...) ((void)0) -#define lj_assertG(c, ...) ((void)g) -#define lj_assertL(c, ...) ((void)L) -#define lj_assertX(c, ...) ((void)0) -#define check_exp(c, e) (e) -#endif - -/* Static assertions. */ -#define LJ_ASSERT_NAME2(name, line) name ## line -#define LJ_ASSERT_NAME(line) LJ_ASSERT_NAME2(lj_assert_, line) -#ifdef __COUNTER__ -#define LJ_STATIC_ASSERT(cond) \ - extern void LJ_ASSERT_NAME(__COUNTER__)(int STATIC_ASSERTION_FAILED[(cond)?1:-1]) -#else -#define LJ_STATIC_ASSERT(cond) \ - extern void LJ_ASSERT_NAME(__LINE__)(int STATIC_ASSERTION_FAILED[(cond)?1:-1]) -#endif - -/* PRNG state. Need this here, details in lj_prng.h. */ -typedef struct PRNGState { - uint64_t u[4]; -} PRNGState; - -#endif diff --git a/include/luajit/lj_dispatch.h b/include/luajit/lj_dispatch.h deleted file mode 100644 index b1ccff7..0000000 --- a/include/luajit/lj_dispatch.h +++ /dev/null @@ -1,164 +0,0 @@ -/* -** Instruction dispatch handling. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_DISPATCH_H -#define _LJ_DISPATCH_H - -#include "lj_obj.h" -#include "lj_bc.h" -#if LJ_HASJIT -#include "lj_jit.h" -#endif - -#if LJ_TARGET_MIPS -/* Need our own global offset table for the dreaded MIPS calling conventions. */ - -#ifndef _LJ_VM_H -LJ_ASMF int32_t LJ_FASTCALL lj_vm_modi(int32_t a, int32_t b); -#endif - -#if LJ_SOFTFP -#ifndef _LJ_IRCALL_H -extern double __adddf3(double a, double b); -extern double __subdf3(double a, double b); -extern double __muldf3(double a, double b); -extern double __divdf3(double a, double b); -#endif -#define SFGOTDEF(_) _(sqrt) _(__adddf3) _(__subdf3) _(__muldf3) _(__divdf3) -#else -#define SFGOTDEF(_) -#endif -#if LJ_HASJIT -#define JITGOTDEF(_) _(lj_err_trace) _(lj_trace_exit) _(lj_trace_hot) -#else -#define JITGOTDEF(_) -#endif -#if LJ_HASFFI -#define FFIGOTDEF(_) \ - _(lj_meta_equal_cd) _(lj_ccallback_enter) _(lj_ccallback_leave) -#else -#define FFIGOTDEF(_) -#endif -#define GOTDEF(_) \ - _(floor) _(ceil) _(trunc) _(log) _(log10) _(exp) _(sin) _(cos) _(tan) \ - _(asin) _(acos) _(atan) _(sinh) _(cosh) _(tanh) _(frexp) _(modf) _(atan2) \ - _(pow) _(fmod) _(ldexp) _(lj_vm_modi) \ - _(lj_dispatch_call) _(lj_dispatch_ins) _(lj_dispatch_stitch) \ - _(lj_dispatch_profile) _(lj_err_throw) \ - _(lj_ffh_coroutine_wrap_err) _(lj_func_closeuv) _(lj_func_newL_gc) \ - _(lj_gc_barrieruv) _(lj_gc_step) _(lj_gc_step_fixtop) _(lj_meta_arith) \ - _(lj_meta_call) _(lj_meta_cat) _(lj_meta_comp) _(lj_meta_equal) \ - _(lj_meta_for) _(lj_meta_istype) _(lj_meta_len) _(lj_meta_tget) \ - _(lj_meta_tset) _(lj_state_growstack) _(lj_strfmt_number) \ - _(lj_str_new) _(lj_tab_dup) _(lj_tab_get) _(lj_tab_getinth) _(lj_tab_len) \ - _(lj_tab_new) _(lj_tab_newkey) _(lj_tab_next) _(lj_tab_reasize) \ - _(lj_tab_setinth) _(lj_buf_putstr_reverse) _(lj_buf_putstr_lower) \ - _(lj_buf_putstr_upper) _(lj_buf_tostr) \ - JITGOTDEF(_) FFIGOTDEF(_) SFGOTDEF(_) - -enum { -#define GOTENUM(name) LJ_GOT_##name, -GOTDEF(GOTENUM) -#undef GOTENUM - LJ_GOT__MAX -}; -#endif - -/* Type of hot counter. Must match the code in the assembler VM. */ -/* 16 bits are sufficient. Only 0.0015% overhead with maximum slot penalty. */ -typedef uint16_t HotCount; - -/* Number of hot counter hash table entries (must be a power of two). */ -#define HOTCOUNT_SIZE 64 -#define HOTCOUNT_PCMASK ((HOTCOUNT_SIZE-1)*sizeof(HotCount)) - -/* Hotcount decrements. */ -#define HOTCOUNT_LOOP 2 -#define HOTCOUNT_CALL 1 - -/* This solves a circular dependency problem -- bump as needed. Sigh. */ -#define GG_NUM_ASMFF 57 - -#define GG_LEN_DDISP (BC__MAX + GG_NUM_ASMFF) -#define GG_LEN_SDISP BC_FUNCF -#define GG_LEN_DISP (GG_LEN_DDISP + GG_LEN_SDISP) - -/* Global state, main thread and extra fields are allocated together. */ -typedef struct GG_State { - lua_State L; /* Main thread. */ - global_State g; /* Global state. */ -#if LJ_TARGET_ARM && !LJ_TARGET_NX - /* Make g reachable via K12 encoded DISPATCH-relative addressing. */ - uint8_t align1[(16-sizeof(global_State))&15]; -#endif -#if LJ_TARGET_MIPS - ASMFunction got[LJ_GOT__MAX]; /* Global offset table. */ -#endif -#if LJ_HASJIT - jit_State J; /* JIT state. */ - HotCount hotcount[HOTCOUNT_SIZE]; /* Hot counters. */ -#if LJ_TARGET_ARM && !LJ_TARGET_NX - /* Ditto for J. */ - uint8_t align2[(16-sizeof(jit_State)-sizeof(HotCount)*HOTCOUNT_SIZE)&15]; -#endif -#endif - ASMFunction dispatch[GG_LEN_DISP]; /* Instruction dispatch tables. */ - BCIns bcff[GG_NUM_ASMFF]; /* Bytecode for ASM fast functions. */ -} GG_State; - -#define GG_OFS(field) ((int)offsetof(GG_State, field)) -#define G2GG(gl) ((GG_State *)((char *)(gl) - GG_OFS(g))) -#define J2GG(j) ((GG_State *)((char *)(j) - GG_OFS(J))) -#define L2GG(L) (G2GG(G(L))) -#define J2G(J) (&J2GG(J)->g) -#define G2J(gl) (&G2GG(gl)->J) -#define L2J(L) (&L2GG(L)->J) -#define GG_G2J (GG_OFS(J) - GG_OFS(g)) -#define GG_G2DISP (GG_OFS(dispatch) - GG_OFS(g)) -#define GG_DISP2G (GG_OFS(g) - GG_OFS(dispatch)) -#define GG_DISP2J (GG_OFS(J) - GG_OFS(dispatch)) -#define GG_DISP2HOT (GG_OFS(hotcount) - GG_OFS(dispatch)) -#define GG_DISP2STATIC (GG_LEN_DDISP*(int)sizeof(ASMFunction)) - -#define hotcount_get(gg, pc) \ - (gg)->hotcount[(u32ptr(pc)>>2) & (HOTCOUNT_SIZE-1)] -#define hotcount_set(gg, pc, val) \ - (hotcount_get((gg), (pc)) = (HotCount)(val)) - -/* Dispatch table management. */ -LJ_FUNC void lj_dispatch_init(GG_State *GG); -#if LJ_HASJIT -LJ_FUNC void lj_dispatch_init_hotcount(global_State *g); -#endif -LJ_FUNC void lj_dispatch_update(global_State *g); - -/* Instruction dispatch callback for hooks or when recording. */ -LJ_FUNCA void LJ_FASTCALL lj_dispatch_ins(lua_State *L, const BCIns *pc); -LJ_FUNCA ASMFunction LJ_FASTCALL lj_dispatch_call(lua_State *L, const BCIns*pc); -#if LJ_HASJIT -LJ_FUNCA void LJ_FASTCALL lj_dispatch_stitch(jit_State *J, const BCIns *pc); -#endif -#if LJ_HASPROFILE -LJ_FUNCA void LJ_FASTCALL lj_dispatch_profile(lua_State *L, const BCIns *pc); -#endif - -#if LJ_HASFFI && !defined(_BUILDVM_H) -/* Save/restore errno and GetLastError() around hooks, exits and recording. */ -#include -#if LJ_TARGET_WINDOWS -#define WIN32_LEAN_AND_MEAN -#include -#define ERRNO_SAVE int olderr = errno; DWORD oldwerr = GetLastError(); -#define ERRNO_RESTORE errno = olderr; SetLastError(oldwerr); -#else -#define ERRNO_SAVE int olderr = errno; -#define ERRNO_RESTORE errno = olderr; -#endif -#else -#define ERRNO_SAVE -#define ERRNO_RESTORE -#endif - -#endif diff --git a/include/luajit/lj_emit_arm.h b/include/luajit/lj_emit_arm.h deleted file mode 100644 index 3e1eb64..0000000 --- a/include/luajit/lj_emit_arm.h +++ /dev/null @@ -1,366 +0,0 @@ -/* -** ARM instruction emitter. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -/* -- Constant encoding --------------------------------------------------- */ - -static uint8_t emit_invai[16] = { - /* AND */ (ARMI_AND^ARMI_BIC) >> 21, - /* EOR */ 0, - /* SUB */ (ARMI_SUB^ARMI_ADD) >> 21, - /* RSB */ 0, - /* ADD */ (ARMI_ADD^ARMI_SUB) >> 21, - /* ADC */ (ARMI_ADC^ARMI_SBC) >> 21, - /* SBC */ (ARMI_SBC^ARMI_ADC) >> 21, - /* RSC */ 0, - /* TST */ 0, - /* TEQ */ 0, - /* CMP */ (ARMI_CMP^ARMI_CMN) >> 21, - /* CMN */ (ARMI_CMN^ARMI_CMP) >> 21, - /* ORR */ 0, - /* MOV */ (ARMI_MOV^ARMI_MVN) >> 21, - /* BIC */ (ARMI_BIC^ARMI_AND) >> 21, - /* MVN */ (ARMI_MVN^ARMI_MOV) >> 21 -}; - -/* Encode constant in K12 format for data processing instructions. */ -static uint32_t emit_isk12(ARMIns ai, int32_t n) -{ - uint32_t invai, i, m = (uint32_t)n; - /* K12: unsigned 8 bit value, rotated in steps of two bits. */ - for (i = 0; i < 4096; i += 256, m = lj_rol(m, 2)) - if (m <= 255) return ARMI_K12|m|i; - /* Otherwise try negation/complement with the inverse instruction. */ - invai = emit_invai[((ai >> 21) & 15)]; - if (!invai) return 0; /* Failed. No inverse instruction. */ - m = ~(uint32_t)n; - if (invai == ((ARMI_SUB^ARMI_ADD) >> 21) || - invai == (ARMI_CMP^ARMI_CMN) >> 21) m++; - for (i = 0; i < 4096; i += 256, m = lj_rol(m, 2)) - if (m <= 255) return ARMI_K12|(invai<<21)|m|i; - return 0; /* Failed. */ -} - -/* -- Emit basic instructions --------------------------------------------- */ - -static void emit_dnm(ASMState *as, ARMIns ai, Reg rd, Reg rn, Reg rm) -{ - *--as->mcp = ai | ARMF_D(rd) | ARMF_N(rn) | ARMF_M(rm); -} - -static void emit_dm(ASMState *as, ARMIns ai, Reg rd, Reg rm) -{ - *--as->mcp = ai | ARMF_D(rd) | ARMF_M(rm); -} - -static void emit_dn(ASMState *as, ARMIns ai, Reg rd, Reg rn) -{ - *--as->mcp = ai | ARMF_D(rd) | ARMF_N(rn); -} - -static void emit_nm(ASMState *as, ARMIns ai, Reg rn, Reg rm) -{ - *--as->mcp = ai | ARMF_N(rn) | ARMF_M(rm); -} - -static void emit_d(ASMState *as, ARMIns ai, Reg rd) -{ - *--as->mcp = ai | ARMF_D(rd); -} - -static void emit_n(ASMState *as, ARMIns ai, Reg rn) -{ - *--as->mcp = ai | ARMF_N(rn); -} - -static void emit_m(ASMState *as, ARMIns ai, Reg rm) -{ - *--as->mcp = ai | ARMF_M(rm); -} - -static void emit_lsox(ASMState *as, ARMIns ai, Reg rd, Reg rn, int32_t ofs) -{ - lj_assertA(ofs >= -255 && ofs <= 255, - "load/store offset %d out of range", ofs); - if (ofs < 0) ofs = -ofs; else ai |= ARMI_LS_U; - *--as->mcp = ai | ARMI_LS_P | ARMI_LSX_I | ARMF_D(rd) | ARMF_N(rn) | - ((ofs & 0xf0) << 4) | (ofs & 0x0f); -} - -static void emit_lso(ASMState *as, ARMIns ai, Reg rd, Reg rn, int32_t ofs) -{ - lj_assertA(ofs >= -4095 && ofs <= 4095, - "load/store offset %d out of range", ofs); - /* Combine LDR/STR pairs to LDRD/STRD. */ - if (*as->mcp == (ai|ARMI_LS_P|ARMI_LS_U|ARMF_D(rd^1)|ARMF_N(rn)|(ofs^4)) && - (ai & ~(ARMI_LDR^ARMI_STR)) == ARMI_STR && rd != rn && - (uint32_t)ofs <= 252 && !(ofs & 3) && !((rd ^ (ofs >>2)) & 1) && - as->mcp != as->mcloop) { - as->mcp++; - emit_lsox(as, ai == ARMI_LDR ? ARMI_LDRD : ARMI_STRD, rd&~1, rn, ofs&~4); - return; - } - if (ofs < 0) ofs = -ofs; else ai |= ARMI_LS_U; - *--as->mcp = ai | ARMI_LS_P | ARMF_D(rd) | ARMF_N(rn) | ofs; -} - -#if !LJ_SOFTFP -static void emit_vlso(ASMState *as, ARMIns ai, Reg rd, Reg rn, int32_t ofs) -{ - lj_assertA(ofs >= -1020 && ofs <= 1020 && (ofs&3) == 0, - "load/store offset %d out of range", ofs); - if (ofs < 0) ofs = -ofs; else ai |= ARMI_LS_U; - *--as->mcp = ai | ARMI_LS_P | ARMF_D(rd & 15) | ARMF_N(rn) | (ofs >> 2); -} -#endif - -/* -- Emit loads/stores --------------------------------------------------- */ - -/* Prefer spills of BASE/L. */ -#define emit_canremat(ref) ((ref) < ASMREF_L) - -/* Try to find a one step delta relative to another constant. */ -static int emit_kdelta1(ASMState *as, Reg d, int32_t i) -{ - RegSet work = ~as->freeset & RSET_GPR; - while (work) { - Reg r = rset_picktop(work); - IRRef ref = regcost_ref(as->cost[r]); - lj_assertA(r != d, "dest reg not free"); - if (emit_canremat(ref)) { - int32_t delta = i - (ra_iskref(ref) ? ra_krefk(as, ref) : IR(ref)->i); - uint32_t k = emit_isk12(ARMI_ADD, delta); - if (k) { - if (k == ARMI_K12) - emit_dm(as, ARMI_MOV, d, r); - else - emit_dn(as, ARMI_ADD^k, d, r); - return 1; - } - } - rset_clear(work, r); - } - return 0; /* Failed. */ -} - -/* Try to find a two step delta relative to another constant. */ -static int emit_kdelta2(ASMState *as, Reg rd, int32_t i) -{ - RegSet work = ~as->freeset & RSET_GPR; - while (work) { - Reg r = rset_picktop(work); - IRRef ref = regcost_ref(as->cost[r]); - lj_assertA(r != rd, "dest reg %d not free", rd); - if (emit_canremat(ref)) { - int32_t other = ra_iskref(ref) ? ra_krefk(as, ref) : IR(ref)->i; - if (other) { - int32_t delta = i - other; - uint32_t sh, inv = 0, k2, k; - if (delta < 0) { delta = (int32_t)(~(uint32_t)delta+1u); inv = ARMI_ADD^ARMI_SUB; } - sh = lj_ffs(delta) & ~1; - k2 = emit_isk12(0, delta & (255 << sh)); - k = emit_isk12(0, delta & ~(255 << sh)); - if (k) { - emit_dn(as, ARMI_ADD^k2^inv, rd, rd); - emit_dn(as, ARMI_ADD^k^inv, rd, r); - return 1; - } - } - } - rset_clear(work, r); - } - return 0; /* Failed. */ -} - -#define emit_movw_k(k) \ - (ARMI_MOVW | ((k) & 0x0fffu) | (((k) & 0xf000u) << 4)) -#define emit_movt_k(k) \ - (ARMI_MOVT | (((k) >> 16) & 0x0fffu) | ((((k) >> 16) & 0xf000u) << 4)) - -/* Load a 32 bit constant into a GPR. */ -static void emit_loadi(ASMState *as, Reg rd, int32_t i) -{ - uint32_t k = emit_isk12(ARMI_MOV, i); - lj_assertA(rset_test(as->freeset, rd) || rd == RID_TMP, - "dest reg %d not free", rd); - if (k) { - /* Standard K12 constant. */ - emit_d(as, ARMI_MOV^k, rd); - } else if ((as->flags & JIT_F_ARMV6T2) && (uint32_t)i < 0x00010000u) { - /* 16 bit loword constant for ARMv6T2. */ - emit_d(as, emit_movw_k(i), rd); - } else if (emit_kdelta1(as, rd, i)) { - /* One step delta relative to another constant. */ - } else if ((as->flags & JIT_F_ARMV6T2)) { - /* 32 bit hiword/loword constant for ARMv6T2. */ - emit_d(as, emit_movt_k(i), rd); - emit_d(as, emit_movw_k(i), rd); - } else if (emit_kdelta2(as, rd, i)) { - /* Two step delta relative to another constant. */ - } else { - /* Otherwise construct the constant with up to 4 instructions. */ - /* NYI: use mvn+bic, use pc-relative loads. */ - for (;;) { - uint32_t sh = lj_ffs(i) & ~1; - int32_t m = i & (255 << sh); - i &= ~(255 << sh); - if (i == 0) { - emit_d(as, ARMI_MOV ^ emit_isk12(0, m), rd); - break; - } - emit_dn(as, ARMI_ORR ^ emit_isk12(0, m), rd, rd); - } - } -} - -#define emit_loada(as, rd, addr) emit_loadi(as, (rd), i32ptr((addr))) - -static Reg ra_allock(ASMState *as, intptr_t k, RegSet allow); - -/* Get/set from constant pointer. */ -static void emit_lsptr(ASMState *as, ARMIns ai, Reg r, void *p) -{ - int32_t i = i32ptr(p); - emit_lso(as, ai, r, ra_allock(as, (i & ~4095), rset_exclude(RSET_GPR, r)), - (i & 4095)); -} - -#if !LJ_SOFTFP -/* Load a number constant into an FPR. */ -static void emit_loadk64(ASMState *as, Reg r, IRIns *ir) -{ - cTValue *tv = ir_knum(ir); - int32_t i; - if ((as->flags & JIT_F_VFPV3) && !tv->u32.lo) { - uint32_t hi = tv->u32.hi; - uint32_t b = ((hi >> 22) & 0x1ff); - if (!(hi & 0xffff) && (b == 0x100 || b == 0x0ff)) { - *--as->mcp = ARMI_VMOVI_D | ARMF_D(r & 15) | - ((tv->u32.hi >> 12) & 0x00080000) | - ((tv->u32.hi >> 4) & 0x00070000) | - ((tv->u32.hi >> 16) & 0x0000000f); - return; - } - } - i = i32ptr(tv); - emit_vlso(as, ARMI_VLDR_D, r, - ra_allock(as, (i & ~1020), RSET_GPR), (i & 1020)); -} -#endif - -/* Get/set global_State fields. */ -#define emit_getgl(as, r, field) \ - emit_lsptr(as, ARMI_LDR, (r), (void *)&J2G(as->J)->field) -#define emit_setgl(as, r, field) \ - emit_lsptr(as, ARMI_STR, (r), (void *)&J2G(as->J)->field) - -/* Trace number is determined from pc of exit instruction. */ -#define emit_setvmstate(as, i) UNUSED(i) - -/* -- Emit control-flow instructions -------------------------------------- */ - -/* Label for internal jumps. */ -typedef MCode *MCLabel; - -/* Return label pointing to current PC. */ -#define emit_label(as) ((as)->mcp) - -static void emit_branch(ASMState *as, ARMIns ai, MCode *target) -{ - MCode *p = as->mcp; - ptrdiff_t delta = (target - p) - 1; - lj_assertA(((delta + 0x00800000) >> 24) == 0, "branch target out of range"); - *--p = ai | ((uint32_t)delta & 0x00ffffffu); - as->mcp = p; -} - -#define emit_jmp(as, target) emit_branch(as, ARMI_B, (target)) - -static void emit_call(ASMState *as, void *target) -{ - MCode *p = --as->mcp; - ptrdiff_t delta = ((char *)target - (char *)p) - 8; - if ((((delta>>2) + 0x00800000) >> 24) == 0) { - if ((delta & 1)) - *p = ARMI_BLX | ((uint32_t)(delta>>2) & 0x00ffffffu) | ((delta&2) << 23); - else - *p = ARMI_BL | ((uint32_t)(delta>>2) & 0x00ffffffu); - } else { /* Target out of range: need indirect call. But don't use R0-R3. */ - Reg r = ra_allock(as, i32ptr(target), RSET_RANGE(RID_R4, RID_R12+1)); - *p = ARMI_BLXr | ARMF_M(r); - } -} - -/* -- Emit generic operations --------------------------------------------- */ - -/* Generic move between two regs. */ -static void emit_movrr(ASMState *as, IRIns *ir, Reg dst, Reg src) -{ -#if LJ_SOFTFP - lj_assertA(!irt_isnum(ir->t), "unexpected FP op"); UNUSED(ir); -#else - if (dst >= RID_MAX_GPR) { - emit_dm(as, irt_isnum(ir->t) ? ARMI_VMOV_D : ARMI_VMOV_S, - (dst & 15), (src & 15)); - return; - } -#endif - if (as->mcp != as->mcloop) { /* Swap early registers for loads/stores. */ - MCode ins = *as->mcp, swp = (src^dst); - if ((ins & 0x0c000000) == 0x04000000 && (ins & 0x02000010) != 0x02000010) { - if (!((ins ^ (dst << 16)) & 0x000f0000)) - *as->mcp = ins ^ (swp << 16); /* Swap N in load/store. */ - if (!(ins & 0x00100000) && !((ins ^ (dst << 12)) & 0x0000f000)) - *as->mcp = ins ^ (swp << 12); /* Swap D in store. */ - } - } - emit_dm(as, ARMI_MOV, dst, src); -} - -/* Generic load of register with base and (small) offset address. */ -static void emit_loadofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs) -{ -#if LJ_SOFTFP - lj_assertA(!irt_isnum(ir->t), "unexpected FP op"); UNUSED(ir); -#else - if (r >= RID_MAX_GPR) - emit_vlso(as, irt_isnum(ir->t) ? ARMI_VLDR_D : ARMI_VLDR_S, r, base, ofs); - else -#endif - emit_lso(as, ARMI_LDR, r, base, ofs); -} - -/* Generic store of register with base and (small) offset address. */ -static void emit_storeofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs) -{ -#if LJ_SOFTFP - lj_assertA(!irt_isnum(ir->t), "unexpected FP op"); UNUSED(ir); -#else - if (r >= RID_MAX_GPR) - emit_vlso(as, irt_isnum(ir->t) ? ARMI_VSTR_D : ARMI_VSTR_S, r, base, ofs); - else -#endif - emit_lso(as, ARMI_STR, r, base, ofs); -} - -/* Emit an arithmetic/logic operation with a constant operand. */ -static void emit_opk(ASMState *as, ARMIns ai, Reg dest, Reg src, - int32_t i, RegSet allow) -{ - uint32_t k = emit_isk12(ai, i); - if (k) - emit_dn(as, ai^k, dest, src); - else - emit_dnm(as, ai, dest, src, ra_allock(as, i, allow)); -} - -/* Add offset to pointer. */ -static void emit_addptr(ASMState *as, Reg r, int32_t ofs) -{ - if (ofs) - emit_opk(as, ARMI_ADD, r, r, ofs, rset_exclude(RSET_GPR, r)); -} - -#define emit_spsub(as, ofs) emit_addptr(as, RID_SP, -(ofs)) - diff --git a/include/luajit/lj_emit_arm64.h b/include/luajit/lj_emit_arm64.h deleted file mode 100644 index a8be741..0000000 --- a/include/luajit/lj_emit_arm64.h +++ /dev/null @@ -1,480 +0,0 @@ -/* -** ARM64 instruction emitter. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -** -** Contributed by Djordje Kovacevic and Stefan Pejic from RT-RK.com. -** Sponsored by Cisco Systems, Inc. -*/ - -/* -- Constant encoding --------------------------------------------------- */ - -static uint64_t get_k64val(ASMState *as, IRRef ref) -{ - IRIns *ir = IR(ref); - if (ir->o == IR_KINT64) { - return ir_kint64(ir)->u64; - } else if (ir->o == IR_KGC) { - return (uint64_t)ir_kgc(ir); - } else if (ir->o == IR_KPTR || ir->o == IR_KKPTR) { - return (uint64_t)ir_kptr(ir); - } else { - lj_assertA(ir->o == IR_KINT || ir->o == IR_KNULL, - "bad 64 bit const IR op %d", ir->o); - return (uint32_t)ir->i; /* Zero-extended. */ - } -} - -/* Encode constant in K12 format for data processing instructions. */ -static uint32_t emit_isk12(int64_t n) -{ - uint64_t k = n < 0 ? ~(uint64_t)n+1u : (uint64_t)n; - uint32_t m = n < 0 ? 0x40000000 : 0; - if (k < 0x1000) { - return (uint32_t)(A64I_K12|m|A64F_U12(k)); - } else if ((k & 0xfff000) == k) { - return (uint32_t)(A64I_K12|m|0x400000|A64F_U12(k>>12)); - } - return 0; -} - -#define emit_clz64(n) (lj_fls64(n)^63) -#define emit_ctz64(n) lj_ffs64(n) - -/* Encode constant in K13 format for logical data processing instructions. */ -static uint32_t emit_isk13(uint64_t n, int is64) -{ - /* Thanks to: https://dougallj.wordpress.com/2021/10/30/ */ - int rot, ones, size, immr, imms; - if (!is64) n = ((uint64_t)n << 32) | (uint32_t)n; - if ((n+1u) <= 1u) return 0; /* Neither all-zero nor all-ones are allowed. */ - rot = (n & (n+1u)) ? emit_ctz64(n & (n+1u)) : 64; - n = lj_ror(n, rot & 63); - ones = emit_ctz64(~n); - size = emit_clz64(n) + ones; - if (lj_ror(n, size & 63) != n) return 0; /* Non-repeating? */ - immr = -rot & (size - 1); - imms = (-(size << 1) | (ones - 1)) & 63; - return A64I_K13 | A64F_IMMR(immr | (size & 64)) | A64F_IMMS(imms); -} - -static uint32_t emit_isfpk64(uint64_t n) -{ - uint64_t etop9 = ((n >> 54) & 0x1ff); - if ((n << 16) == 0 && (etop9 == 0x100 || etop9 == 0x0ff)) { - return (uint32_t)(((n >> 48) & 0x7f) | ((n >> 56) & 0x80)); - } - return ~0u; -} - -static uint32_t emit_isfpmovi(uint64_t n) -{ - /* Is every byte either 0x00 or 0xff? */ - if ((n & U64x(01010101,01010101)) * 0xff != n) return 0; - /* Form 8-bit value by taking one bit from each byte. */ - n &= U64x(80402010,08040201); - n = (n * U64x(01010101,01010101)) >> 56; - /* Split into the format expected by movi. */ - return ((n & 0xe0) << 6) | 0x700 | (n & 0x1f); -} - -/* -- Emit basic instructions --------------------------------------------- */ - -static void emit_dnma(ASMState *as, A64Ins ai, Reg rd, Reg rn, Reg rm, Reg ra) -{ - *--as->mcp = ai | A64F_D(rd) | A64F_N(rn) | A64F_M(rm) | A64F_A(ra); -} - -static void emit_dnm(ASMState *as, A64Ins ai, Reg rd, Reg rn, Reg rm) -{ - *--as->mcp = ai | A64F_D(rd) | A64F_N(rn) | A64F_M(rm); -} - -static void emit_dm(ASMState *as, A64Ins ai, Reg rd, Reg rm) -{ - *--as->mcp = ai | A64F_D(rd) | A64F_M(rm); -} - -static void emit_dn(ASMState *as, A64Ins ai, Reg rd, Reg rn) -{ - *--as->mcp = ai | A64F_D(rd) | A64F_N(rn); -} - -static void emit_nm(ASMState *as, A64Ins ai, Reg rn, Reg rm) -{ - *--as->mcp = ai | A64F_N(rn) | A64F_M(rm); -} - -static void emit_d(ASMState *as, A64Ins ai, Reg rd) -{ - *--as->mcp = ai | A64F_D(rd); -} - -static void emit_dl(ASMState *as, A64Ins ai, Reg rd, uint32_t l) -{ - *--as->mcp = ai | A64F_D(rd) | A64F_S19(l >> 2); -} - -static void emit_n(ASMState *as, A64Ins ai, Reg rn) -{ - *--as->mcp = ai | A64F_N(rn); -} - -static int emit_checkofs(A64Ins ai, int64_t ofs) -{ - int scale = (ai >> 30) & 3; - if (ofs < 0 || (ofs & ((1<= -256 && ofs <= 255) ? -1 : 0; - } else { - return (ofs < (4096<= 0) { - return ai | A64F_U12(ofs>>sc); /* Subsequent lj_ror checks ofs. */ - } else if (ofs >= -256) { - return (ai^A64I_LS_U) | A64F_S9(ofs & 0x1ff); - } else { - return A64F_D(31); /* Will mismatch prev. */ - } -} - -static void emit_lso(ASMState *as, A64Ins ai, Reg rd, Reg rn, int64_t ofs64) -{ - int ot = emit_checkofs(ai, ofs64), sc = (ai >> 30) & 3, ofs = (int)ofs64; - lj_assertA(ot, "load/store offset %d out of range", ofs); - /* Combine LDR/STR pairs to LDP/STP. */ - if ((sc == 2 || sc == 3) && - (!(ai & 0x400000) || rd != rn) && - as->mcp != as->mcloop) { - uint32_t prev = *as->mcp & ~A64F_D(31); - int ofsm = ofs - (1<mcp & 31)); - } else if (prev == emit_lso_pair_candidate(ai | A64F_N(rn), ofsp, sc)) { - aip = (A64F_D(rd) | A64F_A(*as->mcp & 31)); - ofsm = ofs; - } else { - goto nopair; - } - if (lj_ror((unsigned int)ofsm + (64u<mcp = aip | A64F_N(rn) | (((ofsm >> sc) & 0x7f) << 15) | - (ai ^ ((ai == A64I_LDRx || ai == A64I_STRx) ? 0x50000000 : 0x90000000)); - return; - } - } -nopair: - if (ot == 1) - *--as->mcp = ai | A64F_D(rd) | A64F_N(rn) | A64F_U12(ofs >> sc); - else - *--as->mcp = (ai^A64I_LS_U) | A64F_D(rd) | A64F_N(rn) | A64F_S9(ofs & 0x1ff); -} - -/* -- Emit loads/stores --------------------------------------------------- */ - -/* Prefer rematerialization of BASE/L from global_State over spills. */ -#define emit_canremat(ref) ((ref) <= REF_BASE) - -/* Try to find a one-step delta relative to other consts. */ -static int emit_kdelta(ASMState *as, Reg rd, uint64_t k, int is64) -{ - RegSet work = (~as->freeset & RSET_GPR) | RID2RSET(RID_GL); - while (work) { - Reg r = rset_picktop(work); - IRRef ref = regcost_ref(as->cost[r]); - lj_assertA(r != rd, "dest reg %d not free", rd); - if (ref < REF_TRUE) { - uint64_t kx = ra_iskref(ref) ? (uint64_t)ra_krefk(as, ref) : - get_k64val(as, ref); - int64_t delta = (int64_t)(k - kx); - if (!is64) delta = (int64_t)(int32_t)delta; /* Sign-extend. */ - if (delta == 0) { - emit_dm(as, is64|A64I_MOVw, rd, r); - return 1; - } else { - uint32_t k12 = emit_isk12(delta < 0 ? (int64_t)(~(uint64_t)delta+1u) : delta); - if (k12) { - emit_dn(as, (delta < 0 ? A64I_SUBw : A64I_ADDw)^is64^k12, rd, r); - return 1; - } - /* Do other ops or multi-step deltas pay off? Probably not. - ** E.g. XOR rarely helps with pointer consts. - */ - } - } - rset_clear(work, r); - } - return 0; /* Failed. */ -} - -#define glofs(as, k) \ - ((intptr_t)((uintptr_t)(k) - (uintptr_t)&J2GG(as->J)->g)) -#define mcpofs(as, k) \ - ((intptr_t)((uintptr_t)(k) - (uintptr_t)(as->mcp - 1))) -#define checkmcpofs(as, k) \ - (A64F_S_OK(mcpofs(as, k)>>2, 19)) - -/* Try to form a const as ADR or ADRP or ADRP + ADD. */ -static int emit_kadrp(ASMState *as, Reg rd, uint64_t k) -{ - A64Ins ai = A64I_ADR; - int64_t ofs = mcpofs(as, k); - if (!A64F_S_OK((uint64_t)ofs, 21)) { - uint64_t kpage = k & ~0xfffull; - MCode *adrp = as->mcp - 1 - (k != kpage); - ofs = (int64_t)(kpage - ((uint64_t)adrp & ~0xfffull)) >> 12; - if (!A64F_S_OK(ofs, 21)) - return 0; /* Failed. */ - if (k != kpage) - emit_dn(as, (A64I_ADDx^A64I_K12)|A64F_U12(k - kpage), rd, rd); - ai = A64I_ADRP; - } - emit_dl(as, ai|(((uint32_t)ofs&3)<<29), rd, ofs); - return 1; -} - -static void emit_loadk(ASMState *as, Reg rd, uint64_t u64) -{ - int zeros = 0, ones = 0, neg, lshift = 0; - int is64 = (u64 >> 32) ? A64I_X : 0, i = is64 ? 4 : 2; - /* Count non-homogeneous 16 bit fragments. */ - while (--i >= 0) { - uint32_t frag = (u64 >> i*16) & 0xffff; - zeros += (frag != 0); - ones += (frag != 0xffff); - } - neg = ones < zeros; /* Use MOVN if it pays off. */ - if ((neg ? ones : zeros) > 1) { /* Need 2+ ins. Try 1 ins encodings. */ - uint32_t k13 = emit_isk13(u64, is64); - if (k13) { - emit_dn(as, (is64|A64I_ORRw)^k13, rd, RID_ZERO); - return; - } - if (emit_kdelta(as, rd, u64, is64)) { - return; - } - if (emit_kadrp(as, rd, u64)) { /* Either 1 or 2 ins. */ - return; - } - } - if (neg) { - u64 = ~u64; - if (!is64) u64 = (uint32_t)u64; - } - if (u64) { - /* Find first/last fragment to be filled. */ - int shift = (63-emit_clz64(u64)) & ~15; - lshift = emit_ctz64(u64) & ~15; - for (; shift > lshift; shift -= 16) { - uint32_t frag = (u64 >> shift) & 0xffff; - if (frag == 0) continue; /* Will be correctly filled by MOVN/MOVZ. */ - if (neg) frag ^= 0xffff; /* MOVK requires the original value. */ - emit_d(as, is64 | A64I_MOVKw | A64F_U16(frag) | A64F_LSL16(shift), rd); - } - } - /* But MOVN needs an inverted value. */ - emit_d(as, is64 | (neg ? A64I_MOVNw : A64I_MOVZw) | - A64F_U16((u64 >> lshift) & 0xffff) | A64F_LSL16(lshift), rd); -} - -/* Load a 32 bit constant into a GPR. */ -#define emit_loadi(as, rd, i) emit_loadk(as, rd, (uint32_t)i) - -/* Load a 64 bit constant into a GPR. */ -#define emit_loadu64(as, rd, i) emit_loadk(as, rd, i) - -static Reg ra_allock(ASMState *as, intptr_t k, RegSet allow); - -/* Get/set from constant pointer. */ -static void emit_lsptr(ASMState *as, A64Ins ai, Reg r, void *p) -{ - Reg base = RID_GL; - int64_t ofs = glofs(as, p); - if (emit_checkofs(ai, ofs)) { - /* GL + offset, might subsequently fuse to LDP/STP. */ - } else if (ai == A64I_LDRx && checkmcpofs(as, p)) { - /* IP + offset is cheaper than allock, but address must be in range. */ - emit_dl(as, A64I_LDRLx, r, mcpofs(as, p)); - return; - } else { /* Split up into base reg + offset. */ - int64_t i64 = i64ptr(p); - base = ra_allock(as, (i64 & ~0x7fffull), rset_exclude(RSET_GPR, r)); - ofs = i64 & 0x7fffull; - } - emit_lso(as, ai, r, base, ofs); -} - -/* Load 64 bit IR constant into register. */ -static void emit_loadk64(ASMState *as, Reg r, IRIns *ir) -{ - const uint64_t *k = &ir_k64(ir)->u64; - int64_t ofs; - if (r >= RID_MAX_GPR) { - uint32_t fpk = emit_isfpk64(*k); - if (fpk != ~0u) { - emit_d(as, A64I_FMOV_DI | A64F_FP8(fpk), (r & 31)); - return; - } else if ((fpk = emit_isfpmovi(*k))) { - emit_d(as, A64I_MOVI_DI | (fpk << 5), (r & 31)); - return; - } - } - ofs = glofs(as, k); - if (emit_checkofs(A64I_LDRx, ofs)) { - emit_lso(as, r >= RID_MAX_GPR ? A64I_LDRd : A64I_LDRx, - (r & 31), RID_GL, ofs); - } else if (checkmcpofs(as, k)) { - emit_dl(as, r >= RID_MAX_GPR ? A64I_LDRLd : A64I_LDRLx, - (r & 31), mcpofs(as, k)); - } else { - if (r >= RID_MAX_GPR) { - emit_dn(as, A64I_FMOV_D_R, (r & 31), RID_TMP); - r = RID_TMP; - } - emit_loadu64(as, r, *k); - } -} - -/* Get/set global_State fields. */ -#define emit_getgl(as, r, field) \ - emit_lsptr(as, A64I_LDRx, (r), (void *)&J2G(as->J)->field) -#define emit_setgl(as, r, field) \ - emit_lsptr(as, A64I_STRx, (r), (void *)&J2G(as->J)->field) - -/* Trace number is determined from pc of exit instruction. */ -#define emit_setvmstate(as, i) UNUSED(i) - -/* -- Emit control-flow instructions -------------------------------------- */ - -/* Label for internal jumps. */ -typedef MCode *MCLabel; - -/* Return label pointing to current PC. */ -#define emit_label(as) ((as)->mcp) - -static void emit_cond_branch(ASMState *as, A64CC cond, MCode *target) -{ - MCode *p = --as->mcp; - ptrdiff_t delta = target - p; - lj_assertA(A64F_S_OK(delta, 19), "branch target out of range"); - *p = A64I_BCC | A64F_S19(delta) | cond; -} - -static void emit_branch(ASMState *as, A64Ins ai, MCode *target) -{ - MCode *p = --as->mcp; - ptrdiff_t delta = target - p; - lj_assertA(A64F_S_OK(delta, 26), "branch target out of range"); - *p = ai | A64F_S26(delta); -} - -static void emit_tnb(ASMState *as, A64Ins ai, Reg r, uint32_t bit, MCode *target) -{ - MCode *p = --as->mcp; - ptrdiff_t delta = target - p; - lj_assertA(bit < 63, "bit number out of range"); - lj_assertA(A64F_S_OK(delta, 14), "branch target out of range"); - if (bit > 31) ai |= A64I_X; - *p = ai | A64F_BIT(bit & 31) | A64F_S14(delta) | r; -} - -static void emit_cnb(ASMState *as, A64Ins ai, Reg r, MCode *target) -{ - MCode *p = --as->mcp; - ptrdiff_t delta = target - p; - lj_assertA(A64F_S_OK(delta, 19), "branch target out of range"); - *p = ai | A64F_S19(delta) | r; -} - -#define emit_jmp(as, target) emit_branch(as, A64I_B, (target)) - -static void emit_call(ASMState *as, ASMFunction target) -{ - MCode *p = --as->mcp; -#if LJ_ABI_PAUTH - char *targetp = ptrauth_auth_data((char *)target, - ptrauth_key_function_pointer, 0); -#else - char *targetp = (char *)target; -#endif - ptrdiff_t delta = targetp - (char *)p; - if (A64F_S_OK(delta>>2, 26)) { - *p = A64I_BL | A64F_S26(delta>>2); - } else { /* Target out of range: need indirect call. But don't use R0-R7. */ - Reg r = ra_allock(as, i64ptr(target), - RSET_RANGE(RID_X8, RID_MAX_GPR)-RSET_FIXED); - *p = A64I_BLR_AUTH | A64F_N(r); - } -} - -#if LJ_ABI_BRANCH_TRACK -static void emit_branch_track(ASMState *as) -{ - *--as->mcp = A64I_BTI_J; -} -#endif - -/* -- Emit generic operations --------------------------------------------- */ - -/* Generic move between two regs. */ -static void emit_movrr(ASMState *as, IRIns *ir, Reg dst, Reg src) -{ - if (dst >= RID_MAX_GPR) { - emit_dn(as, irt_isnum(ir->t) ? A64I_FMOV_D : A64I_FMOV_S, - (dst & 31), (src & 31)); - return; - } - if (as->mcp != as->mcloop) { /* Swap early registers for loads/stores. */ - MCode ins = *as->mcp, swp = (src^dst); - if ((ins & 0xbf800000) == 0xb9000000) { - if (!((ins ^ (dst << 5)) & 0x000003e0)) - *as->mcp = ins ^ (swp << 5); /* Swap N in load/store. */ - if (!(ins & 0x00400000) && !((ins ^ dst) & 0x0000001f)) - *as->mcp = ins ^ swp; /* Swap D in store. */ - } - } - emit_dm(as, A64I_MOVx, dst, src); -} - -/* Generic load of register with base and (small) offset address. */ -static void emit_loadofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs) -{ - if (r >= RID_MAX_GPR) - emit_lso(as, irt_isnum(ir->t) ? A64I_LDRd : A64I_LDRs, (r & 31), base, ofs); - else - emit_lso(as, irt_is64(ir->t) ? A64I_LDRx : A64I_LDRw, r, base, ofs); -} - -/* Generic store of register with base and (small) offset address. */ -static void emit_storeofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs) -{ - if (r >= RID_MAX_GPR) - emit_lso(as, irt_isnum(ir->t) ? A64I_STRd : A64I_STRs, (r & 31), base, ofs); - else - emit_lso(as, irt_is64(ir->t) ? A64I_STRx : A64I_STRw, r, base, ofs); -} - -/* Emit an arithmetic operation with a constant operand. */ -static void emit_opk(ASMState *as, A64Ins ai, Reg dest, Reg src, - int32_t i, RegSet allow) -{ - uint32_t k = emit_isk12(i); - if (k) - emit_dn(as, ai^k, dest, src); - else - emit_dnm(as, ai, dest, src, ra_allock(as, i, allow)); -} - -/* Add offset to pointer. */ -static void emit_addptr(ASMState *as, Reg r, int32_t ofs) -{ - if (ofs) - emit_opk(as, ofs < 0 ? A64I_SUBx : A64I_ADDx, r, r, - ofs < 0 ? (int32_t)(~(uint32_t)ofs+1u) : ofs, - rset_exclude(RSET_GPR, r)); -} - -#define emit_spsub(as, ofs) emit_addptr(as, RID_SP, -(ofs)) - diff --git a/include/luajit/lj_emit_mips.h b/include/luajit/lj_emit_mips.h deleted file mode 100644 index d65b1c5..0000000 --- a/include/luajit/lj_emit_mips.h +++ /dev/null @@ -1,313 +0,0 @@ -/* -** MIPS instruction emitter. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#if LJ_64 -static intptr_t get_k64val(ASMState *as, IRRef ref) -{ - IRIns *ir = IR(ref); - if (ir->o == IR_KINT64) { - return (intptr_t)ir_kint64(ir)->u64; - } else if (ir->o == IR_KGC) { - return (intptr_t)ir_kgc(ir); - } else if (ir->o == IR_KPTR || ir->o == IR_KKPTR) { - return (intptr_t)ir_kptr(ir); - } else if (LJ_SOFTFP && ir->o == IR_KNUM) { - return (intptr_t)ir_knum(ir)->u64; - } else { - lj_assertA(ir->o == IR_KINT || ir->o == IR_KNULL, - "bad 64 bit const IR op %d", ir->o); - return ir->i; /* Sign-extended. */ - } -} -#endif - -#if LJ_64 -#define get_kval(as, ref) get_k64val(as, ref) -#else -#define get_kval(as, ref) (IR((ref))->i) -#endif - -/* -- Emit basic instructions --------------------------------------------- */ - -static void emit_dst(ASMState *as, MIPSIns mi, Reg rd, Reg rs, Reg rt) -{ - *--as->mcp = mi | MIPSF_D(rd) | MIPSF_S(rs) | MIPSF_T(rt); -} - -static void emit_dta(ASMState *as, MIPSIns mi, Reg rd, Reg rt, uint32_t a) -{ - *--as->mcp = mi | MIPSF_D(rd) | MIPSF_T(rt) | MIPSF_A(a); -} - -#define emit_ds(as, mi, rd, rs) emit_dst(as, (mi), (rd), (rs), 0) -#define emit_tg(as, mi, rt, rg) emit_dst(as, (mi), (rg)&31, 0, (rt)) - -static void emit_tsi(ASMState *as, MIPSIns mi, Reg rt, Reg rs, int32_t i) -{ - *--as->mcp = mi | MIPSF_T(rt) | MIPSF_S(rs) | (i & 0xffff); -} - -#define emit_ti(as, mi, rt, i) emit_tsi(as, (mi), (rt), 0, (i)) -#define emit_hsi(as, mi, rh, rs, i) emit_tsi(as, (mi), (rh) & 31, (rs), (i)) - -static void emit_fgh(ASMState *as, MIPSIns mi, Reg rf, Reg rg, Reg rh) -{ - *--as->mcp = mi | MIPSF_F(rf&31) | MIPSF_G(rg&31) | MIPSF_H(rh&31); -} - -#define emit_fg(as, mi, rf, rg) emit_fgh(as, (mi), (rf), (rg), 0) - -static void emit_rotr(ASMState *as, Reg dest, Reg src, Reg tmp, uint32_t shift) -{ - if (LJ_64 || (as->flags & JIT_F_MIPSXXR2)) { - emit_dta(as, MIPSI_ROTR, dest, src, shift); - } else { - emit_dst(as, MIPSI_OR, dest, dest, tmp); - emit_dta(as, MIPSI_SLL, dest, src, (-shift)&31); - emit_dta(as, MIPSI_SRL, tmp, src, shift); - } -} - -#if LJ_64 || LJ_HASBUFFER -static void emit_tsml(ASMState *as, MIPSIns mi, Reg rt, Reg rs, uint32_t msb, - uint32_t lsb) -{ - *--as->mcp = mi | MIPSF_T(rt) | MIPSF_S(rs) | MIPSF_M(msb) | MIPSF_L(lsb); -} -#endif - -/* -- Emit loads/stores --------------------------------------------------- */ - -#define jglofs(as, k) \ - (((uintptr_t)(k) - (uintptr_t)J2G(as->J) - 32768) & 0xffff) - -/* Prefer rematerialization of BASE/L from global_State over spills. */ -#define emit_canremat(ref) ((ref) <= REF_BASE) - -/* Try to find a one step delta relative to another constant. */ -static int emit_kdelta1(ASMState *as, Reg rd, intptr_t i) -{ - RegSet work = ~as->freeset & RSET_GPR; - while (work) { - Reg r = rset_picktop(work); - IRRef ref = regcost_ref(as->cost[r]); - lj_assertA(r != rd, "dest reg %d not free", rd); - if (ref < ASMREF_L) { - intptr_t delta = (intptr_t)((uintptr_t)i - - (uintptr_t)(ra_iskref(ref) ? ra_krefk(as, ref) : get_kval(as, ref))); - if (checki16(delta)) { - emit_tsi(as, MIPSI_AADDIU, rd, r, delta); - return 1; - } - } - rset_clear(work, r); - } - return 0; /* Failed. */ -} - -/* Load a 32 bit constant into a GPR. */ -static void emit_loadi(ASMState *as, Reg r, int32_t i) -{ - if (checki16(i)) { - emit_ti(as, MIPSI_LI, r, i); - } else { - if ((i & 0xffff)) { - intptr_t jgl = (intptr_t)(void *)J2G(as->J); - if ((uintptr_t)(i-jgl) < 65536) { - emit_tsi(as, MIPSI_ADDIU, r, RID_JGL, i-jgl-32768); - return; - } else if (emit_kdelta1(as, r, i)) { - return; - } else if ((i >> 16) == 0) { - emit_tsi(as, MIPSI_ORI, r, RID_ZERO, i); - return; - } - emit_tsi(as, MIPSI_ORI, r, r, i); - } - emit_ti(as, MIPSI_LUI, r, (i >> 16)); - } -} - -#if LJ_64 -/* Load a 64 bit constant into a GPR. */ -static void emit_loadu64(ASMState *as, Reg r, uint64_t u64) -{ - if (checki32((int64_t)u64)) { - emit_loadi(as, r, (int32_t)u64); - } else { - uint64_t delta = u64 - (uint64_t)(void *)J2G(as->J); - if (delta < 65536) { - emit_tsi(as, MIPSI_DADDIU, r, RID_JGL, (int32_t)(delta-32768)); - } else if (emit_kdelta1(as, r, (intptr_t)u64)) { - return; - } else { - /* TODO MIPSR6: Use DAHI & DATI. Caveat: sign-extension. */ - if ((u64 & 0xffff)) { - emit_tsi(as, MIPSI_ORI, r, r, u64 & 0xffff); - } - if (((u64 >> 16) & 0xffff)) { - emit_dta(as, MIPSI_DSLL, r, r, 16); - emit_tsi(as, MIPSI_ORI, r, r, (u64 >> 16) & 0xffff); - emit_dta(as, MIPSI_DSLL, r, r, 16); - } else { - emit_dta(as, MIPSI_DSLL32, r, r, 0); - } - emit_loadi(as, r, (int32_t)(u64 >> 32)); - } - /* TODO: There are probably more optimization opportunities. */ - } -} - -#define emit_loada(as, r, addr) emit_loadu64(as, (r), u64ptr((addr))) -#else -#define emit_loada(as, r, addr) emit_loadi(as, (r), i32ptr((addr))) -#endif - -static Reg ra_allock(ASMState *as, intptr_t k, RegSet allow); -static void ra_allockreg(ASMState *as, intptr_t k, Reg r); - -/* Get/set from constant pointer. */ -static void emit_lsptr(ASMState *as, MIPSIns mi, Reg r, void *p, RegSet allow) -{ - intptr_t jgl = (intptr_t)(J2G(as->J)); - intptr_t i = (intptr_t)(p); - Reg base; - if ((uint32_t)(i-jgl) < 65536) { - i = i-jgl-32768; - base = RID_JGL; - } else { - base = ra_allock(as, i-(int16_t)i, allow); - } - emit_tsi(as, mi, r, base, i); -} - -#if LJ_64 -static void emit_loadk64(ASMState *as, Reg r, IRIns *ir) -{ - const uint64_t *k = &ir_k64(ir)->u64; - Reg r64 = r; - if (rset_test(RSET_FPR, r)) { - r64 = RID_TMP; - emit_tg(as, MIPSI_DMTC1, r64, r); - } - if ((uint32_t)((intptr_t)k-(intptr_t)J2G(as->J)) < 65536) - emit_lsptr(as, MIPSI_LD, r64, (void *)k, 0); - else - emit_loadu64(as, r64, *k); -} -#else -#define emit_loadk64(as, r, ir) \ - emit_lsptr(as, MIPSI_LDC1, ((r) & 31), (void *)&ir_knum((ir))->u64, RSET_GPR) -#endif - -/* Get/set global_State fields. */ -static void emit_lsglptr(ASMState *as, MIPSIns mi, Reg r, int32_t ofs) -{ - emit_tsi(as, mi, r, RID_JGL, ofs-32768); -} - -#define emit_getgl(as, r, field) \ - emit_lsglptr(as, MIPSI_AL, (r), (int32_t)offsetof(global_State, field)) -#define emit_setgl(as, r, field) \ - emit_lsglptr(as, MIPSI_AS, (r), (int32_t)offsetof(global_State, field)) - -/* Trace number is determined from per-trace exit stubs. */ -#define emit_setvmstate(as, i) UNUSED(i) - -/* -- Emit control-flow instructions -------------------------------------- */ - -/* Label for internal jumps. */ -typedef MCode *MCLabel; - -/* Return label pointing to current PC. */ -#define emit_label(as) ((as)->mcp) - -static void emit_branch(ASMState *as, MIPSIns mi, Reg rs, Reg rt, MCode *target) -{ - MCode *p = as->mcp; - ptrdiff_t delta = target - p; - lj_assertA(((delta + 0x8000) >> 16) == 0, "branch target out of range"); - *--p = mi | MIPSF_S(rs) | MIPSF_T(rt) | ((uint32_t)delta & 0xffffu); - as->mcp = p; -} - -static void emit_jmp(ASMState *as, MCode *target) -{ - *--as->mcp = MIPSI_NOP; - emit_branch(as, MIPSI_B, RID_ZERO, RID_ZERO, (target)); -} - -static void emit_call(ASMState *as, void *target, int needcfa) -{ - MCode *p = as->mcp; -#if LJ_TARGET_MIPSR6 - ptrdiff_t delta = (char *)target - (char *)p; - if ((((delta>>2) + 0x02000000) >> 26) == 0) { /* Try compact call first. */ - *--p = MIPSI_BALC | (((uintptr_t)delta >>2) & 0x03ffffffu); - as->mcp = p; - return; - } -#endif - *--p = MIPSI_NOP; /* Delay slot. */ - if ((((uintptr_t)target ^ (uintptr_t)p) >> 28) == 0) { -#if !LJ_TARGET_MIPSR6 - *--p = (((uintptr_t)target & 1) ? MIPSI_JALX : MIPSI_JAL) | - (((uintptr_t)target >>2) & 0x03ffffffu); -#else - *--p = MIPSI_JAL | (((uintptr_t)target >>2) & 0x03ffffffu); -#endif - } else { /* Target out of range: need indirect call. */ - *--p = MIPSI_JALR | MIPSF_S(RID_CFUNCADDR); - needcfa = 1; - } - as->mcp = p; - if (needcfa) ra_allockreg(as, (intptr_t)target, RID_CFUNCADDR); -} - -/* -- Emit generic operations --------------------------------------------- */ - -#define emit_move(as, dst, src) \ - emit_ds(as, MIPSI_MOVE, (dst), (src)) - -/* Generic move between two regs. */ -static void emit_movrr(ASMState *as, IRIns *ir, Reg dst, Reg src) -{ - if (dst < RID_MAX_GPR) - emit_move(as, dst, src); - else - emit_fg(as, irt_isnum(ir->t) ? MIPSI_MOV_D : MIPSI_MOV_S, dst, src); -} - -/* Generic load of register with base and (small) offset address. */ -static void emit_loadofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs) -{ - if (r < RID_MAX_GPR) - emit_tsi(as, irt_is64(ir->t) ? MIPSI_LD : MIPSI_LW, r, base, ofs); - else - emit_tsi(as, irt_isnum(ir->t) ? MIPSI_LDC1 : MIPSI_LWC1, - (r & 31), base, ofs); -} - -/* Generic store of register with base and (small) offset address. */ -static void emit_storeofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs) -{ - if (r < RID_MAX_GPR) - emit_tsi(as, irt_is64(ir->t) ? MIPSI_SD : MIPSI_SW, r, base, ofs); - else - emit_tsi(as, irt_isnum(ir->t) ? MIPSI_SDC1 : MIPSI_SWC1, - (r&31), base, ofs); -} - -/* Add offset to pointer. */ -static void emit_addptr(ASMState *as, Reg r, int32_t ofs) -{ - if (ofs) { - lj_assertA(checki16(ofs), "offset %d out of range", ofs); - emit_tsi(as, MIPSI_AADDIU, r, r, ofs); - } -} - -#define emit_spsub(as, ofs) emit_addptr(as, RID_SP, -(ofs)) - diff --git a/include/luajit/lj_emit_ppc.h b/include/luajit/lj_emit_ppc.h deleted file mode 100644 index 56928e4..0000000 --- a/include/luajit/lj_emit_ppc.h +++ /dev/null @@ -1,241 +0,0 @@ -/* -** PPC instruction emitter. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -/* -- Emit basic instructions --------------------------------------------- */ - -static void emit_tab(ASMState *as, PPCIns pi, Reg rt, Reg ra, Reg rb) -{ - *--as->mcp = pi | PPCF_T(rt) | PPCF_A(ra) | PPCF_B(rb); -} - -#define emit_asb(as, pi, ra, rs, rb) emit_tab(as, (pi), (rs), (ra), (rb)) -#define emit_as(as, pi, ra, rs) emit_tab(as, (pi), (rs), (ra), 0) -#define emit_ab(as, pi, ra, rb) emit_tab(as, (pi), 0, (ra), (rb)) - -static void emit_tai(ASMState *as, PPCIns pi, Reg rt, Reg ra, int32_t i) -{ - *--as->mcp = pi | PPCF_T(rt) | PPCF_A(ra) | (i & 0xffff); -} - -#define emit_ti(as, pi, rt, i) emit_tai(as, (pi), (rt), 0, (i)) -#define emit_ai(as, pi, ra, i) emit_tai(as, (pi), 0, (ra), (i)) -#define emit_asi(as, pi, ra, rs, i) emit_tai(as, (pi), (rs), (ra), (i)) - -#define emit_fab(as, pi, rf, ra, rb) \ - emit_tab(as, (pi), (rf)&31, (ra)&31, (rb)&31) -#define emit_fb(as, pi, rf, rb) emit_tab(as, (pi), (rf)&31, 0, (rb)&31) -#define emit_fac(as, pi, rf, ra, rc) \ - emit_tab(as, (pi) | PPCF_C((rc) & 31), (rf)&31, (ra)&31, 0) -#define emit_facb(as, pi, rf, ra, rc, rb) \ - emit_tab(as, (pi) | PPCF_C((rc) & 31), (rf)&31, (ra)&31, (rb)&31) -#define emit_fai(as, pi, rf, ra, i) emit_tai(as, (pi), (rf)&31, (ra), (i)) - -static void emit_rot(ASMState *as, PPCIns pi, Reg ra, Reg rs, - int32_t n, int32_t b, int32_t e) -{ - *--as->mcp = pi | PPCF_T(rs) | PPCF_A(ra) | PPCF_B(n) | - PPCF_MB(b) | PPCF_ME(e); -} - -static void emit_slwi(ASMState *as, Reg ra, Reg rs, int32_t n) -{ - lj_assertA(n >= 0 && n < 32, "shift out or range"); - emit_rot(as, PPCI_RLWINM, ra, rs, n, 0, 31-n); -} - -static void emit_rotlwi(ASMState *as, Reg ra, Reg rs, int32_t n) -{ - lj_assertA(n >= 0 && n < 32, "shift out or range"); - emit_rot(as, PPCI_RLWINM, ra, rs, n, 0, 31); -} - -/* -- Emit loads/stores --------------------------------------------------- */ - -#define jglofs(as, k) \ - (((uintptr_t)(k) - (uintptr_t)J2G(as->J) - 32768) & 0xffff) - -/* Prefer rematerialization of BASE/L from global_State over spills. */ -#define emit_canremat(ref) ((ref) <= REF_BASE) - -/* Try to find a one step delta relative to another constant. */ -static int emit_kdelta1(ASMState *as, Reg rd, int32_t i) -{ - RegSet work = ~as->freeset & RSET_GPR; - while (work) { - Reg r = rset_picktop(work); - IRRef ref = regcost_ref(as->cost[r]); - lj_assertA(r != rd, "dest reg %d not free", rd); - if (ref < ASMREF_L) { - int32_t delta = i - (ra_iskref(ref) ? ra_krefk(as, ref) : IR(ref)->i); - if (checki16(delta)) { - emit_tai(as, PPCI_ADDI, rd, r, delta); - return 1; - } - } - rset_clear(work, r); - } - return 0; /* Failed. */ -} - -/* Load a 32 bit constant into a GPR. */ -static void emit_loadi(ASMState *as, Reg r, int32_t i) -{ - if (checki16(i)) { - emit_ti(as, PPCI_LI, r, i); - } else { - if ((i & 0xffff)) { - int32_t jgl = i32ptr(J2G(as->J)); - if ((uint32_t)(i-jgl) < 65536) { - emit_tai(as, PPCI_ADDI, r, RID_JGL, i-jgl-32768); - return; - } else if (emit_kdelta1(as, r, i)) { - return; - } - emit_asi(as, PPCI_ORI, r, r, i); - } - emit_ti(as, PPCI_LIS, r, (i >> 16)); - } -} - -#define emit_loada(as, r, addr) emit_loadi(as, (r), i32ptr((addr))) - -static Reg ra_allock(ASMState *as, intptr_t k, RegSet allow); - -/* Get/set from constant pointer. */ -static void emit_lsptr(ASMState *as, PPCIns pi, Reg r, void *p, RegSet allow) -{ - int32_t jgl = i32ptr(J2G(as->J)); - int32_t i = i32ptr(p); - Reg base; - if ((uint32_t)(i-jgl) < 65536) { - i = i-jgl-32768; - base = RID_JGL; - } else { - base = ra_allock(as, i-(int16_t)i, allow); - } - emit_tai(as, pi, r, base, i); -} - -#define emit_loadk64(as, r, ir) \ - emit_lsptr(as, PPCI_LFD, ((r) & 31), (void *)&ir_knum((ir))->u64, RSET_GPR) - -/* Get/set global_State fields. */ -static void emit_lsglptr(ASMState *as, PPCIns pi, Reg r, int32_t ofs) -{ - emit_tai(as, pi, r, RID_JGL, ofs-32768); -} - -#define emit_getgl(as, r, field) \ - emit_lsglptr(as, PPCI_LWZ, (r), (int32_t)offsetof(global_State, field)) -#define emit_setgl(as, r, field) \ - emit_lsglptr(as, PPCI_STW, (r), (int32_t)offsetof(global_State, field)) - -/* Trace number is determined from per-trace exit stubs. */ -#define emit_setvmstate(as, i) UNUSED(i) - -/* -- Emit control-flow instructions -------------------------------------- */ - -/* Label for internal jumps. */ -typedef MCode *MCLabel; - -/* Return label pointing to current PC. */ -#define emit_label(as) ((as)->mcp) - -static void emit_condbranch(ASMState *as, PPCIns pi, PPCCC cc, MCode *target) -{ - MCode *p = --as->mcp; - ptrdiff_t delta = (char *)target - (char *)p; - lj_assertA(((delta + 0x8000) >> 16) == 0, "branch target out of range"); - pi ^= (delta & 0x8000) * (PPCF_Y/0x8000); - *p = pi | PPCF_CC(cc) | ((uint32_t)delta & 0xffffu); -} - -static void emit_jmp(ASMState *as, MCode *target) -{ - MCode *p = --as->mcp; - ptrdiff_t delta = (char *)target - (char *)p; - *p = PPCI_B | (delta & 0x03fffffcu); -} - -static void emit_call(ASMState *as, void *target) -{ - MCode *p = --as->mcp; - ptrdiff_t delta = (char *)target - (char *)p; - if ((((delta>>2) + 0x00800000) >> 24) == 0) { - *p = PPCI_BL | (delta & 0x03fffffcu); - } else { /* Target out of range: need indirect call. Don't use arg reg. */ - RegSet allow = RSET_GPR & ~RSET_RANGE(RID_R0, REGARG_LASTGPR+1); - Reg r = ra_allock(as, i32ptr(target), allow); - *p = PPCI_BCTRL; - p[-1] = PPCI_MTCTR | PPCF_T(r); - as->mcp = p-1; - } -} - -/* -- Emit generic operations --------------------------------------------- */ - -#define emit_mr(as, dst, src) \ - emit_asb(as, PPCI_MR, (dst), (src), (src)) - -/* Generic move between two regs. */ -static void emit_movrr(ASMState *as, IRIns *ir, Reg dst, Reg src) -{ - UNUSED(ir); - if (dst < RID_MAX_GPR) - emit_mr(as, dst, src); - else - emit_fb(as, PPCI_FMR, dst, src); -} - -/* Generic load of register with base and (small) offset address. */ -static void emit_loadofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs) -{ - if (r < RID_MAX_GPR) - emit_tai(as, PPCI_LWZ, r, base, ofs); - else - emit_fai(as, irt_isnum(ir->t) ? PPCI_LFD : PPCI_LFS, r, base, ofs); -} - -/* Generic store of register with base and (small) offset address. */ -static void emit_storeofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs) -{ - if (r < RID_MAX_GPR) - emit_tai(as, PPCI_STW, r, base, ofs); - else - emit_fai(as, irt_isnum(ir->t) ? PPCI_STFD : PPCI_STFS, r, base, ofs); -} - -/* Emit a compare (for equality) with a constant operand. */ -static void emit_cmpi(ASMState *as, Reg r, int32_t k) -{ - if (checki16(k)) { - emit_ai(as, PPCI_CMPWI, r, k); - } else if (checku16(k)) { - emit_ai(as, PPCI_CMPLWI, r, k); - } else { - emit_ai(as, PPCI_CMPLWI, RID_TMP, k); - emit_asi(as, PPCI_XORIS, RID_TMP, r, (k >> 16)); - } -} - -/* Add offset to pointer. */ -static void emit_addptr(ASMState *as, Reg r, int32_t ofs) -{ - if (ofs) { - emit_tai(as, PPCI_ADDI, r, r, ofs); - if (!checki16(ofs)) - emit_tai(as, PPCI_ADDIS, r, r, (ofs + 32768) >> 16); - } -} - -static void emit_spsub(ASMState *as, int32_t ofs) -{ - if (ofs) { - emit_tai(as, PPCI_STWU, RID_TMP, RID_SP, -ofs); - emit_tai(as, PPCI_ADDI, RID_TMP, RID_SP, - CFRAME_SIZE + (as->parent ? as->parent->spadjust : 0)); - } -} - diff --git a/include/luajit/lj_emit_x86.h b/include/luajit/lj_emit_x86.h deleted file mode 100644 index 858fe75..0000000 --- a/include/luajit/lj_emit_x86.h +++ /dev/null @@ -1,590 +0,0 @@ -/* -** x86/x64 instruction emitter. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -/* -- Emit basic instructions --------------------------------------------- */ - -#define MODRM(mode, r1, r2) ((MCode)((mode)+(((r1)&7)<<3)+((r2)&7))) - -#if LJ_64 -#define REXRB(p, rr, rb) \ - { MCode rex = 0x40 + (((rr)>>1)&4) + (((rb)>>3)&1); \ - if (rex != 0x40) *--(p) = rex; } -#define FORCE_REX 0x200 -#define REX_64 (FORCE_REX|0x080000) -#define VEX_64 0x800000 -#else -#define REXRB(p, rr, rb) ((void)0) -#define FORCE_REX 0 -#define REX_64 0 -#define VEX_64 0 -#endif -#if LJ_GC64 -#define REX_GC64 REX_64 -#else -#define REX_GC64 0 -#endif - -#define emit_i8(as, i) (*--as->mcp = (MCode)(i)) -#define emit_i32(as, i) (*(int32_t *)(as->mcp-4) = (i), as->mcp -= 4) -#define emit_u32(as, u) (*(uint32_t *)(as->mcp-4) = (u), as->mcp -= 4) - -#define emit_x87op(as, xo) \ - (*(uint16_t *)(as->mcp-2) = (uint16_t)(xo), as->mcp -= 2) - -/* op */ -static LJ_AINLINE MCode *emit_op(x86Op xo, Reg rr, Reg rb, Reg rx, - MCode *p, int delta) -{ - int n = (int8_t)xo; - if (n == -60) { /* VEX-encoded instruction */ -#if LJ_64 - xo ^= (((rr>>1)&4)+((rx>>2)&2)+((rb>>3)&1))<<13; -#endif - *(uint32_t *)(p+delta-5) = (uint32_t)xo; - return p+delta-5; - } -#if defined(__GNUC__) || defined(__clang__) - if (__builtin_constant_p(xo) && n == -2) - p[delta-2] = (MCode)(xo >> 24); - else if (__builtin_constant_p(xo) && n == -3) - *(uint16_t *)(p+delta-3) = (uint16_t)(xo >> 16); - else -#endif - *(uint32_t *)(p+delta-5) = (uint32_t)xo; - p += n + delta; -#if LJ_64 - { - uint32_t rex = 0x40 + ((rr>>1)&(4+(FORCE_REX>>1)))+((rx>>2)&2)+((rb>>3)&1); - if (rex != 0x40) { - rex |= (rr >> 16); - if (n == -4) { *p = (MCode)rex; rex = (MCode)(xo >> 8); } - else if ((xo & 0xffffff) == 0x6600fd) { *p = (MCode)rex; rex = 0x66; } - *--p = (MCode)rex; - } - } -#else - UNUSED(rr); UNUSED(rb); UNUSED(rx); -#endif - return p; -} - -#if LJ_ABI_BRANCH_TRACK -static void emit_branch_track(ASMState *as) -{ - emit_u32(as, XI_ENDBR64); -} -#endif - -/* op + modrm */ -#define emit_opm(xo, mode, rr, rb, p, delta) \ - (p[(delta)-1] = MODRM((mode), (rr), (rb)), \ - emit_op((xo), (rr), (rb), 0, (p), (delta))) - -/* op + modrm + sib */ -#define emit_opmx(xo, mode, scale, rr, rb, rx, p) \ - (p[-1] = MODRM((scale), (rx), (rb)), \ - p[-2] = MODRM((mode), (rr), RID_ESP), \ - emit_op((xo), (rr), (rb), (rx), (p), -1)) - -/* op r1, r2 */ -static void emit_rr(ASMState *as, x86Op xo, Reg r1, Reg r2) -{ - MCode *p = as->mcp; - as->mcp = emit_opm(xo, XM_REG, r1, r2, p, 0); -} - -#if LJ_64 && defined(LUA_USE_ASSERT) -/* [addr] is sign-extended in x64 and must be in lower 2G (not 4G). */ -static int32_t ptr2addr(const void *p) -{ - lj_assertX((uintptr_t)p < (uintptr_t)0x80000000, "pointer outside 2G range"); - return i32ptr(p); -} -#else -#define ptr2addr(p) (i32ptr((p))) -#endif - -/* op r, [base+ofs] */ -static void emit_rmro(ASMState *as, x86Op xo, Reg rr, Reg rb, int32_t ofs) -{ - MCode *p = as->mcp; - x86Mode mode; - if (ra_hasreg(rb)) { - if (LJ_GC64 && rb == RID_RIP) { - mode = XM_OFS0; - p -= 4; - *(int32_t *)p = ofs; - } else if (ofs == 0 && (rb&7) != RID_EBP) { - mode = XM_OFS0; - } else if (checki8(ofs)) { - *--p = (MCode)ofs; - mode = XM_OFS8; - } else { - p -= 4; - *(int32_t *)p = ofs; - mode = XM_OFS32; - } - if ((rb&7) == RID_ESP) - *--p = MODRM(XM_SCALE1, RID_ESP, RID_ESP); - } else { - *(int32_t *)(p-4) = ofs; -#if LJ_64 - p[-5] = MODRM(XM_SCALE1, RID_ESP, RID_EBP); - p -= 5; - rb = RID_ESP; -#else - p -= 4; - rb = RID_EBP; -#endif - mode = XM_OFS0; - } - as->mcp = emit_opm(xo, mode, rr, rb, p, 0); -} - -/* op r, [base+idx*scale+ofs] */ -static void emit_rmrxo(ASMState *as, x86Op xo, Reg rr, Reg rb, Reg rx, - x86Mode scale, int32_t ofs) -{ - MCode *p = as->mcp; - x86Mode mode; - if (ofs == 0 && (rb&7) != RID_EBP) { - mode = XM_OFS0; - } else if (checki8(ofs)) { - mode = XM_OFS8; - *--p = (MCode)ofs; - } else { - mode = XM_OFS32; - p -= 4; - *(int32_t *)p = ofs; - } - as->mcp = emit_opmx(xo, mode, scale, rr, rb, rx, p); -} - -/* op r, i */ -static void emit_gri(ASMState *as, x86Group xg, Reg rb, int32_t i) -{ - MCode *p = as->mcp; - x86Op xo; - if (checki8(i)) { - *--p = (MCode)i; - xo = XG_TOXOi8(xg); - } else { - p -= 4; - *(int32_t *)p = i; - xo = XG_TOXOi(xg); - } - as->mcp = emit_opm(xo, XM_REG, (Reg)(xg & 7) | (rb & REX_64), rb, p, 0); -} - -/* op [base+ofs], i */ -static void emit_gmroi(ASMState *as, x86Group xg, Reg rb, int32_t ofs, - int32_t i) -{ - x86Op xo; - if (checki8(i)) { - emit_i8(as, i); - xo = XG_TOXOi8(xg); - } else { - emit_i32(as, i); - xo = XG_TOXOi(xg); - } - emit_rmro(as, xo, (Reg)(xg & 7), rb, ofs); -} - -#define emit_shifti(as, xg, r, i) \ - (emit_i8(as, (i)), emit_rr(as, XO_SHIFTi, (Reg)(xg), (r))) - -/* op r, rm/mrm */ -static void emit_mrm(ASMState *as, x86Op xo, Reg rr, Reg rb) -{ - MCode *p = as->mcp; - x86Mode mode = XM_REG; - if (rb == RID_MRM) { - rb = as->mrm.base; - if (rb == RID_NONE) { - rb = RID_EBP; - mode = XM_OFS0; - p -= 4; - *(int32_t *)p = as->mrm.ofs; - if (as->mrm.idx != RID_NONE) - goto mrmidx; -#if LJ_64 - *--p = MODRM(XM_SCALE1, RID_ESP, RID_EBP); - rb = RID_ESP; -#endif - } else if (LJ_GC64 && rb == RID_RIP) { - lj_assertA(as->mrm.idx == RID_NONE, "RIP-rel mrm cannot have index"); - mode = XM_OFS0; - p -= 4; - *(int32_t *)p = as->mrm.ofs; - } else { - if (as->mrm.ofs == 0 && (rb&7) != RID_EBP) { - mode = XM_OFS0; - } else if (checki8(as->mrm.ofs)) { - *--p = (MCode)as->mrm.ofs; - mode = XM_OFS8; - } else { - p -= 4; - *(int32_t *)p = as->mrm.ofs; - mode = XM_OFS32; - } - if (as->mrm.idx != RID_NONE) { - mrmidx: - as->mcp = emit_opmx(xo, mode, as->mrm.scale, rr, rb, as->mrm.idx, p); - return; - } - if ((rb&7) == RID_ESP) - *--p = MODRM(XM_SCALE1, RID_ESP, RID_ESP); - } - } - as->mcp = emit_opm(xo, mode, rr, rb, p, 0); -} - -/* op rm/mrm, i */ -static void emit_gmrmi(ASMState *as, x86Group xg, Reg rb, int32_t i) -{ - x86Op xo; - if (checki8(i)) { - emit_i8(as, i); - xo = XG_TOXOi8(xg); - } else { - emit_i32(as, i); - xo = XG_TOXOi(xg); - } - emit_mrm(as, xo, (Reg)(xg & 7) | (rb & REX_64), (rb & ~REX_64)); -} - -/* -- Emit loads/stores --------------------------------------------------- */ - -/* mov [base+ofs], i */ -static void emit_movmroi(ASMState *as, Reg base, int32_t ofs, int32_t i) -{ - emit_i32(as, i); - emit_rmro(as, XO_MOVmi, 0, base, ofs); -} - -/* mov [base+ofs], r */ -#define emit_movtomro(as, r, base, ofs) \ - emit_rmro(as, XO_MOVto, (r), (base), (ofs)) - -/* Get/set global_State fields. */ -#define emit_opgl(as, xo, r, field) \ - emit_rma(as, (xo), (r), (void *)&J2G(as->J)->field) -#define emit_getgl(as, r, field) emit_opgl(as, XO_MOV, (r)|REX_GC64, field) -#define emit_setgl(as, r, field) emit_opgl(as, XO_MOVto, (r)|REX_GC64, field) - -#define emit_setvmstate(as, i) \ - (emit_i32(as, i), emit_opgl(as, XO_MOVmi, 0, vmstate)) - -/* mov r, i / xor r, r */ -static void emit_loadi(ASMState *as, Reg r, int32_t i) -{ - /* XOR r,r is shorter, but modifies the flags. This is bad for HIOP/jcc. */ - if (i == 0 && !(LJ_32 && (IR(as->curins)->o == IR_HIOP || - (as->curins+1 < as->T->nins && - IR(as->curins+1)->o == IR_HIOP))) && - !((*as->mcp == 0x0f && (as->mcp[1] & 0xf0) == XI_JCCn) || - (*as->mcp & 0xf0) == XI_JCCs)) { - emit_rr(as, XO_ARITH(XOg_XOR), r, r); - } else { - MCode *p = as->mcp; - *(int32_t *)(p-4) = i; - p[-5] = (MCode)(XI_MOVri+(r&7)); - p -= 5; - REXRB(p, 0, r); - as->mcp = p; - } -} - -#if LJ_GC64 -#define dispofs(as, k) \ - ((intptr_t)((uintptr_t)(k) - (uintptr_t)J2GG(as->J)->dispatch)) -#define mcpofs(as, k) \ - ((intptr_t)((uintptr_t)(k) - (uintptr_t)as->mcp)) -#define mctopofs(as, k) \ - ((intptr_t)((uintptr_t)(k) - (uintptr_t)as->mctop)) -/* mov r, addr */ -#define emit_loada(as, r, addr) \ - emit_loadu64(as, (r), (uintptr_t)(addr)) -#else -/* mov r, addr */ -#define emit_loada(as, r, addr) \ - emit_loadi(as, (r), ptr2addr((addr))) -#endif - -#if LJ_64 -/* mov r, imm64 or shorter 32 bit extended load. */ -static void emit_loadu64(ASMState *as, Reg r, uint64_t u64) -{ - if (checku32(u64)) { /* 32 bit load clears upper 32 bits. */ - emit_loadi(as, r, (int32_t)u64); - } else if (checki32((int64_t)u64)) { /* Sign-extended 32 bit load. */ - MCode *p = as->mcp; - *(int32_t *)(p-4) = (int32_t)u64; - as->mcp = emit_opm(XO_MOVmi, XM_REG, REX_64, r, p, -4); -#if LJ_GC64 - } else if (checki32(dispofs(as, u64))) { - emit_rmro(as, XO_LEA, r|REX_64, RID_DISPATCH, (int32_t)dispofs(as, u64)); - } else if (checki32(mcpofs(as, u64)) && checki32(mctopofs(as, u64))) { - /* Since as->realign assumes the code size doesn't change, check - ** RIP-relative addressing reachability for both as->mcp and as->mctop. - */ - emit_rmro(as, XO_LEA, r|REX_64, RID_RIP, (int32_t)mcpofs(as, u64)); -#endif - } else { /* Full-size 64 bit load. */ - MCode *p = as->mcp; - *(uint64_t *)(p-8) = u64; - p[-9] = (MCode)(XI_MOVri+(r&7)); - p[-10] = 0x48 + ((r>>3)&1); - p -= 10; - as->mcp = p; - } -} -#endif - -/* op r, [addr] */ -static void emit_rma(ASMState *as, x86Op xo, Reg rr, const void *addr) -{ -#if LJ_GC64 - if (checki32(dispofs(as, addr))) { - emit_rmro(as, xo, rr, RID_DISPATCH, (int32_t)dispofs(as, addr)); - } else if (checki32(mcpofs(as, addr)) && checki32(mctopofs(as, addr))) { - emit_rmro(as, xo, rr, RID_RIP, (int32_t)mcpofs(as, addr)); - } else if (!checki32((intptr_t)addr)) { - Reg ra = (rr & 15); - if (xo != XO_MOV) { - /* We can't allocate a register here. Use and restore DISPATCH. Ugly. */ - uint64_t dispaddr = (uintptr_t)J2GG(as->J)->dispatch; - uint8_t i8 = xo == XO_GROUP3b ? *as->mcp++ : 0; - ra = RID_DISPATCH; - if (checku32(dispaddr)) { - emit_loadi(as, ra, (int32_t)dispaddr); - } else { /* Full-size 64 bit load. */ - MCode *p = as->mcp; - *(uint64_t *)(p-8) = dispaddr; - p[-9] = (MCode)(XI_MOVri+(ra&7)); - p[-10] = 0x48 + ((ra>>3)&1); - p -= 10; - as->mcp = p; - } - if (xo == XO_GROUP3b) emit_i8(as, i8); - } - emit_rmro(as, xo, rr, ra, 0); - emit_loadu64(as, ra, (uintptr_t)addr); - } else -#endif - { - MCode *p = as->mcp; - *(int32_t *)(p-4) = ptr2addr(addr); -#if LJ_64 - p[-5] = MODRM(XM_SCALE1, RID_ESP, RID_EBP); - as->mcp = emit_opm(xo, XM_OFS0, rr, RID_ESP, p, -5); -#else - as->mcp = emit_opm(xo, XM_OFS0, rr, RID_EBP, p, -4); -#endif - } -} - -/* Load 64 bit IR constant into register. */ -static void emit_loadk64(ASMState *as, Reg r, IRIns *ir) -{ - Reg r64; - x86Op xo; - const uint64_t *k = &ir_k64(ir)->u64; - if (rset_test(RSET_FPR, r)) { - r64 = r; - xo = XO_MOVSD; - } else { - r64 = r | REX_64; - xo = XO_MOV; - } - if (*k == 0) { - emit_rr(as, rset_test(RSET_FPR, r) ? XO_XORPS : XO_ARITH(XOg_XOR), r, r); -#if LJ_GC64 - } else if (checki32((intptr_t)k) || checki32(dispofs(as, k)) || - (checki32(mcpofs(as, k)) && checki32(mctopofs(as, k)))) { - emit_rma(as, xo, r64, k); - } else { - if (ir->i) { - lj_assertA(*k == *(uint64_t*)(as->mctop - ir->i), - "bad interned 64 bit constant"); - } else if (as->curins <= as->stopins && rset_test(RSET_GPR, r)) { - emit_loadu64(as, r, *k); - return; - } else { - /* If all else fails, add the FP constant at the MCode area bottom. */ - while ((uintptr_t)as->mcbot & 7) *as->mcbot++ = XI_INT3; - *(uint64_t *)as->mcbot = *k; - ir->i = (int32_t)(as->mctop - as->mcbot); - as->mcbot += 8; - as->mclim = as->mcbot + MCLIM_REDZONE; - lj_mcode_commitbot(as->J, as->mcbot); - } - emit_rmro(as, xo, r64, RID_RIP, (int32_t)mcpofs(as, as->mctop - ir->i)); -#else - } else { - emit_rma(as, xo, r64, k); -#endif - } -} - -/* -- Emit control-flow instructions -------------------------------------- */ - -/* Label for short jumps. */ -typedef MCode *MCLabel; - -#if LJ_32 && LJ_HASFFI -/* jmp short target */ -static void emit_sjmp(ASMState *as, MCLabel target) -{ - MCode *p = as->mcp; - ptrdiff_t delta = target - p; - lj_assertA(delta == (int8_t)delta, "short jump target out of range"); - p[-1] = (MCode)(int8_t)delta; - p[-2] = XI_JMPs; - as->mcp = p - 2; -} -#endif - -/* jcc short target */ -static void emit_sjcc(ASMState *as, int cc, MCLabel target) -{ - MCode *p = as->mcp; - ptrdiff_t delta = target - p; - lj_assertA(delta == (int8_t)delta, "short jump target out of range"); - p[-1] = (MCode)(int8_t)delta; - p[-2] = (MCode)(XI_JCCs+(cc&15)); - as->mcp = p - 2; -} - -/* jcc short (pending target) */ -static MCLabel emit_sjcc_label(ASMState *as, int cc) -{ - MCode *p = as->mcp; - p[-1] = 0; - p[-2] = (MCode)(XI_JCCs+(cc&15)); - as->mcp = p - 2; - return p; -} - -/* Fixup jcc short target. */ -static void emit_sfixup(ASMState *as, MCLabel source) -{ - source[-1] = (MCode)(as->mcp-source); -} - -/* Return label pointing to current PC. */ -#define emit_label(as) ((as)->mcp) - -/* Check if two adresses are in relative jump range. */ -static LJ_AINLINE int jmprel_ok(MCode *a, MCode *b) -{ -#if LJ_64 - return a - b == (int32_t)(a - b); -#else - UNUSED(a); UNUSED(b); - return 1; -#endif -} - -/* Compute relative 32 bit offset for jump and call instructions. */ -static LJ_AINLINE int32_t jmprel(jit_State *J, MCode *p, MCode *target) -{ - ptrdiff_t delta = target - p; - UNUSED(J); - lj_assertJ(delta == (int32_t)delta, "jump target out of range"); - return (int32_t)delta; -} - -/* jcc target */ -static void emit_jcc(ASMState *as, int cc, MCode *target) -{ - MCode *p = as->mcp; - *(int32_t *)(p-4) = jmprel(as->J, p, target); - p[-5] = (MCode)(XI_JCCn+(cc&15)); - p[-6] = 0x0f; - as->mcp = p - 6; -} - -/* jmp target */ -static void emit_jmp(ASMState *as, MCode *target) -{ - MCode *p = as->mcp; - *(int32_t *)(p-4) = jmprel(as->J, p, target); - p[-5] = XI_JMP; - as->mcp = p - 5; -} - -/* call target */ -static void emit_call_(ASMState *as, MCode *target) -{ - MCode *p = as->mcp; -#if LJ_64 - if (!jmprel_ok(target, p)) { - /* Assumes RID_RET is never an argument to calls and always clobbered. */ - emit_rr(as, XO_GROUP5, XOg_CALL, RID_RET); - emit_loadu64(as, RID_RET, (uint64_t)target); - return; - } -#endif - *(int32_t *)(p-4) = jmprel(as->J, p, target); - p[-5] = XI_CALL; - as->mcp = p - 5; -} - -#define emit_call(as, f) emit_call_(as, (MCode *)(void *)(f)) - -/* -- Emit generic operations --------------------------------------------- */ - -/* Use 64 bit operations to handle 64 bit IR types. */ -#if LJ_64 -#define REX_64IR(ir, r) ((r) + (irt_is64((ir)->t) ? REX_64 : 0)) -#define VEX_64IR(ir, r) ((r) + (irt_is64((ir)->t) ? VEX_64 : 0)) -#else -#define REX_64IR(ir, r) (r) -#define VEX_64IR(ir, r) (r) -#endif - -/* Generic move between two regs. */ -static void emit_movrr(ASMState *as, IRIns *ir, Reg dst, Reg src) -{ - UNUSED(ir); - if (dst < RID_MAX_GPR) - emit_rr(as, XO_MOV, REX_64IR(ir, dst), src); - else - emit_rr(as, XO_MOVAPS, dst, src); -} - -/* Generic load of register with base and (small) offset address. */ -static void emit_loadofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs) -{ - if (r < RID_MAX_GPR) - emit_rmro(as, XO_MOV, REX_64IR(ir, r), base, ofs); - else - emit_rmro(as, irt_isnum(ir->t) ? XO_MOVSD : XO_MOVSS, r, base, ofs); -} - -/* Generic store of register with base and (small) offset address. */ -static void emit_storeofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs) -{ - if (r < RID_MAX_GPR) - emit_rmro(as, XO_MOVto, REX_64IR(ir, r), base, ofs); - else - emit_rmro(as, irt_isnum(ir->t) ? XO_MOVSDto : XO_MOVSSto, r, base, ofs); -} - -/* Add offset to pointer. */ -static void emit_addptr(ASMState *as, Reg r, int32_t ofs) -{ - if (ofs) { - emit_gri(as, XG_ARITHi(XOg_ADD), r|REX_GC64, ofs); - } -} - -#define emit_spsub(as, ofs) emit_addptr(as, RID_ESP|REX_64, -(ofs)) - -/* Prefer rematerialization of BASE/L from global_State over spills. */ -#define emit_canremat(ref) ((ref) <= REF_BASE) - diff --git a/include/luajit/lj_err.h b/include/luajit/lj_err.h deleted file mode 100644 index 0cb945b..0000000 --- a/include/luajit/lj_err.h +++ /dev/null @@ -1,59 +0,0 @@ -/* -** Error handling. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_ERR_H -#define _LJ_ERR_H - -#include - -#include "lj_obj.h" - -typedef enum { -#define ERRDEF(name, msg) \ - LJ_ERR_##name, LJ_ERR_##name##_ = LJ_ERR_##name + sizeof(msg)-1, -#include "lj_errmsg.h" - LJ_ERR__MAX -} ErrMsg; - -LJ_DATA const char *lj_err_allmsg; -#define err2msg(em) (lj_err_allmsg+(int)(em)) - -LJ_FUNC GCstr *lj_err_str(lua_State *L, ErrMsg em); -LJ_FUNCA_NORET void LJ_FASTCALL lj_err_throw(lua_State *L, int errcode); -LJ_FUNC_NORET void lj_err_mem(lua_State *L); -LJ_FUNC_NORET void LJ_FASTCALL lj_err_stkov(lua_State *L); -LJ_FUNC_NORET void LJ_FASTCALL lj_err_run(lua_State *L); -#if LJ_HASJIT -LJ_FUNCA_NORET void LJ_FASTCALL lj_err_trace(lua_State *L, int errcode); -#endif -LJ_FUNC_NORET void lj_err_msg(lua_State *L, ErrMsg em); -LJ_FUNC_NORET void lj_err_lex(lua_State *L, GCstr *src, const char *tok, - BCLine line, ErrMsg em, va_list argp); -LJ_FUNC_NORET void lj_err_optype(lua_State *L, cTValue *o, ErrMsg opm); -LJ_FUNC_NORET void lj_err_comp(lua_State *L, cTValue *o1, cTValue *o2); -LJ_FUNC_NORET void lj_err_optype_call(lua_State *L, TValue *o); -LJ_FUNC_NORET void lj_err_callermsg(lua_State *L, const char *msg); -LJ_FUNC_NORET void lj_err_callerv(lua_State *L, ErrMsg em, ...); -LJ_FUNC_NORET void lj_err_caller(lua_State *L, ErrMsg em); -LJ_FUNC_NORET void lj_err_arg(lua_State *L, int narg, ErrMsg em); -LJ_FUNC_NORET void lj_err_argv(lua_State *L, int narg, ErrMsg em, ...); -LJ_FUNC_NORET void lj_err_argtype(lua_State *L, int narg, const char *xname); -LJ_FUNC_NORET void lj_err_argt(lua_State *L, int narg, int tt); - -#if LJ_UNWIND_JIT && !LJ_ABI_WIN -LJ_FUNC uint8_t *lj_err_register_mcode(void *base, size_t sz, uint8_t *info); -LJ_FUNC void lj_err_deregister_mcode(void *base, size_t sz, uint8_t *info); -#else -#define lj_err_register_mcode(base, sz, info) (info) -#define lj_err_deregister_mcode(base, sz, info) UNUSED(base) -#endif - -#if LJ_UNWIND_EXT && !LJ_ABI_WIN && defined(LUA_USE_ASSERT) -LJ_FUNC void lj_err_verify(void); -#else -#define lj_err_verify() ((void)0) -#endif - -#endif diff --git a/include/luajit/lj_errmsg.h b/include/luajit/lj_errmsg.h deleted file mode 100644 index 045d025..0000000 --- a/include/luajit/lj_errmsg.h +++ /dev/null @@ -1,201 +0,0 @@ -/* -** VM error messages. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -/* This file may be included multiple times with different ERRDEF macros. */ - -/* Basic error handling. */ -ERRDEF(ERRMEM, "not enough memory") -ERRDEF(ERRERR, "error in error handling") -ERRDEF(ERRCPP, "C++ exception") - -/* Allocations. */ -ERRDEF(STROV, "string length overflow") -ERRDEF(UDATAOV, "userdata length overflow") -ERRDEF(STKOV, "stack overflow") -ERRDEF(STKOVM, "stack overflow (%s)") -ERRDEF(TABOV, "table overflow") - -/* Table indexing. */ -ERRDEF(NANIDX, "table index is NaN") -ERRDEF(NILIDX, "table index is nil") -ERRDEF(NEXTIDX, "invalid key to " LUA_QL("next")) - -/* Metamethod resolving. */ -ERRDEF(BADCALL, "attempt to call a %s value") -ERRDEF(BADOPRT, "attempt to %s %s " LUA_QS " (a %s value)") -ERRDEF(BADOPRV, "attempt to %s a %s value") -ERRDEF(BADCMPT, "attempt to compare %s with %s") -ERRDEF(BADCMPV, "attempt to compare two %s values") -ERRDEF(GETLOOP, "loop in gettable") -ERRDEF(SETLOOP, "loop in settable") -ERRDEF(OPCALL, "call") -ERRDEF(OPINDEX, "index") -ERRDEF(OPARITH, "perform arithmetic on") -ERRDEF(OPCAT, "concatenate") -ERRDEF(OPLEN, "get length of") - -/* Type checks. */ -ERRDEF(BADSELF, "calling " LUA_QS " on bad self (%s)") -ERRDEF(BADARG, "bad argument #%d to " LUA_QS " (%s)") -ERRDEF(BADTYPE, "%s expected, got %s") -ERRDEF(BADVAL, "invalid value") -ERRDEF(NOVAL, "value expected") -ERRDEF(NOCORO, "coroutine expected") -ERRDEF(NOTABN, "nil or table expected") -ERRDEF(NOLFUNC, "Lua function expected") -ERRDEF(NOFUNCL, "function or level expected") -ERRDEF(NOSFT, "string/function/table expected") -ERRDEF(NOPROXY, "boolean or proxy expected") -ERRDEF(FORINIT, LUA_QL("for") " initial value must be a number") -ERRDEF(FORLIM, LUA_QL("for") " limit must be a number") -ERRDEF(FORSTEP, LUA_QL("for") " step must be a number") - -/* C API checks. */ -ERRDEF(NOENV, "no calling environment") -ERRDEF(CYIELD, "attempt to yield across C-call boundary") -ERRDEF(BADLU, "bad light userdata pointer") -ERRDEF(NOGCMM, "bad action while in __gc metamethod") -#if LJ_TARGET_WINDOWS -ERRDEF(BADFPU, "bad FPU precision (use D3DCREATE_FPU_PRESERVE with DirectX)") -#endif - -/* Standard library function errors. */ -ERRDEF(ASSERT, "assertion failed!") -ERRDEF(PROTMT, "cannot change a protected metatable") -ERRDEF(UNPACK, "too many results to unpack") -ERRDEF(RDRSTR, "reader function must return a string") -ERRDEF(PRTOSTR, LUA_QL("tostring") " must return a string to " LUA_QL("print")) -ERRDEF(NUMRNG, "number out of range") -ERRDEF(IDXRNG, "index out of range") -ERRDEF(BASERNG, "base out of range") -ERRDEF(LVLRNG, "level out of range") -ERRDEF(INVLVL, "invalid level") -ERRDEF(INVOPT, "invalid option") -ERRDEF(INVOPTM, "invalid option " LUA_QS) -ERRDEF(INVFMT, "invalid format") -ERRDEF(SETFENV, LUA_QL("setfenv") " cannot change environment of given object") -ERRDEF(CORUN, "cannot resume running coroutine") -ERRDEF(CODEAD, "cannot resume dead coroutine") -ERRDEF(COSUSP, "cannot resume non-suspended coroutine") -ERRDEF(PRNGSD, "PRNG seeding failed") -ERRDEF(TABINS, "wrong number of arguments to " LUA_QL("insert")) -ERRDEF(TABCAT, "invalid value (%s) at index %d in table for " LUA_QL("concat")) -ERRDEF(TABSORT, "invalid order function for sorting") -ERRDEF(IOCLFL, "attempt to use a closed file") -ERRDEF(IOSTDCL, "standard file is closed") -ERRDEF(OSUNIQF, "unable to generate a unique filename") -ERRDEF(OSDATEF, "field " LUA_QS " missing in date table") -ERRDEF(STRDUMP, "unable to dump given function") -ERRDEF(STRSLC, "string slice too long") -ERRDEF(STRPATB, "missing " LUA_QL("[") " after " LUA_QL("%f") " in pattern") -ERRDEF(STRPATC, "invalid pattern capture") -ERRDEF(STRPATE, "malformed pattern (ends with " LUA_QL("%") ")") -ERRDEF(STRPATM, "malformed pattern (missing " LUA_QL("]") ")") -ERRDEF(STRPATU, "unbalanced pattern") -ERRDEF(STRPATX, "pattern too complex") -ERRDEF(STRCAPI, "invalid capture index") -ERRDEF(STRCAPN, "too many captures") -ERRDEF(STRCAPU, "unfinished capture") -ERRDEF(STRFMT, "invalid option " LUA_QS " to " LUA_QL("format")) -ERRDEF(STRGSRV, "invalid replacement value (a %s)") -ERRDEF(BADMODN, "name conflict for module " LUA_QS) -#if LJ_HASJIT -ERRDEF(JITPROT, "runtime code generation failed, restricted kernel?") -ERRDEF(NOJIT, "JIT compiler disabled") -#elif defined(LJ_ARCH_NOJIT) -ERRDEF(NOJIT, "no JIT compiler for this architecture (yet)") -#else -ERRDEF(NOJIT, "JIT compiler permanently disabled by build option") -#endif -ERRDEF(JITOPT, "unknown or malformed optimization flag " LUA_QS) - -/* Lexer/parser errors. */ -ERRDEF(XMODE, "attempt to load chunk with wrong mode") -ERRDEF(XNEAR, "%s near " LUA_QS) -ERRDEF(XLINES, "chunk has too many lines") -ERRDEF(XLEVELS, "chunk has too many syntax levels") -ERRDEF(XNUMBER, "malformed number") -ERRDEF(XLSTR, "unfinished long string") -ERRDEF(XLCOM, "unfinished long comment") -ERRDEF(XSTR, "unfinished string") -ERRDEF(XESC, "invalid escape sequence") -ERRDEF(XLDELIM, "invalid long string delimiter") -ERRDEF(XTOKEN, LUA_QS " expected") -ERRDEF(XJUMP, "control structure too long") -ERRDEF(XSLOTS, "function or expression too complex") -ERRDEF(XLIMC, "chunk has more than %d local variables") -ERRDEF(XLIMM, "main function has more than %d %s") -ERRDEF(XLIMF, "function at line %d has more than %d %s") -ERRDEF(XMATCH, LUA_QS " expected (to close " LUA_QS " at line %d)") -ERRDEF(XFIXUP, "function too long for return fixup") -ERRDEF(XPARAM, " or " LUA_QL("...") " expected") -#if !LJ_52 -ERRDEF(XAMBIG, "ambiguous syntax (function call x new statement)") -#endif -ERRDEF(XFUNARG, "function arguments expected") -ERRDEF(XSYMBOL, "unexpected symbol") -ERRDEF(XDOTS, "cannot use " LUA_QL("...") " outside a vararg function") -ERRDEF(XSYNTAX, "syntax error") -ERRDEF(XFOR, LUA_QL("=") " or " LUA_QL("in") " expected") -ERRDEF(XBREAK, "no loop to break") -ERRDEF(XLUNDEF, "undefined label " LUA_QS) -ERRDEF(XLDUP, "duplicate label " LUA_QS) -ERRDEF(XGSCOPE, " jumps into the scope of local " LUA_QS) - -/* Bytecode reader errors. */ -ERRDEF(BCFMT, "cannot load incompatible bytecode") -ERRDEF(BCBAD, "cannot load malformed bytecode") - -#if LJ_HASFFI -/* FFI errors. */ -ERRDEF(FFI_INVTYPE, "invalid C type") -ERRDEF(FFI_INVSIZE, "size of C type is unknown or too large") -ERRDEF(FFI_BADSCL, "bad storage class") -ERRDEF(FFI_DECLSPEC, "declaration specifier expected") -ERRDEF(FFI_BADTAG, "undeclared or implicit tag " LUA_QS) -ERRDEF(FFI_REDEF, "attempt to redefine " LUA_QS) -ERRDEF(FFI_NUMPARAM, "wrong number of type parameters") -ERRDEF(FFI_INITOV, "too many initializers for " LUA_QS) -ERRDEF(FFI_BADCONV, "cannot convert " LUA_QS " to " LUA_QS) -ERRDEF(FFI_BADLEN, "attempt to get length of " LUA_QS) -ERRDEF(FFI_BADCONCAT, "attempt to concatenate " LUA_QS " and " LUA_QS) -ERRDEF(FFI_BADARITH, "attempt to perform arithmetic on " LUA_QS " and " LUA_QS) -ERRDEF(FFI_BADCOMP, "attempt to compare " LUA_QS " with " LUA_QS) -ERRDEF(FFI_BADCALL, LUA_QS " is not callable") -ERRDEF(FFI_NUMARG, "wrong number of arguments for function call") -ERRDEF(FFI_BADMEMBER, LUA_QS " has no member named " LUA_QS) -ERRDEF(FFI_BADIDX, LUA_QS " cannot be indexed") -ERRDEF(FFI_BADIDXW, LUA_QS " cannot be indexed with " LUA_QS) -ERRDEF(FFI_BADMM, LUA_QS " has no " LUA_QS " metamethod") -ERRDEF(FFI_WRCONST, "attempt to write to constant location") -ERRDEF(FFI_NODECL, "missing declaration for symbol " LUA_QS) -ERRDEF(FFI_BADCBACK, "bad callback") -#if LJ_OS_NOJIT -ERRDEF(FFI_CBACKOV, "no support for callbacks on this OS") -#else -ERRDEF(FFI_CBACKOV, "too many callbacks") -#endif -ERRDEF(FFI_NYIPACKBIT, "NYI: packed bit fields") -ERRDEF(FFI_NYICALL, "NYI: cannot call this C function (yet)") -#endif - -#if LJ_HASBUFFER -/* String buffer errors. */ -ERRDEF(BUFFER_SELF, "cannot put buffer into itself") -ERRDEF(BUFFER_BADOPT, "bad options table") -ERRDEF(BUFFER_BADENC, "cannot serialize " LUA_QS) -ERRDEF(BUFFER_BADDEC, "cannot deserialize tag 0x%02x") -ERRDEF(BUFFER_BADDICTX, "cannot deserialize dictionary index %d") -ERRDEF(BUFFER_DEPTH, "too deep to serialize") -ERRDEF(BUFFER_DUPKEY, "duplicate table key") -ERRDEF(BUFFER_EOB, "unexpected end of buffer") -ERRDEF(BUFFER_LEFTOV, "left-over data in buffer") -#endif - -#undef ERRDEF - -/* Detecting unused error messages: - awk -F, '/^ERRDEF/ { gsub(/ERRDEF./, ""); printf "grep -q LJ_ERR_%s *.[ch] || echo %s\n", $1, $1}' lj_errmsg.h | sh -*/ diff --git a/include/luajit/lj_ff.h b/include/luajit/lj_ff.h deleted file mode 100644 index 301df0e..0000000 --- a/include/luajit/lj_ff.h +++ /dev/null @@ -1,18 +0,0 @@ -/* -** Fast function IDs. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_FF_H -#define _LJ_FF_H - -/* Fast function ID. */ -typedef enum { - FF_LUA_ = FF_LUA, /* Lua function (must be 0). */ - FF_C_ = FF_C, /* Regular C function (must be 1). */ -#define FFDEF(name) FF_##name, -#include "lj_ffdef.h" - FF__MAX -} FastFunc; - -#endif diff --git a/include/luajit/lj_ffrecord.h b/include/luajit/lj_ffrecord.h deleted file mode 100644 index 6ac9f0e..0000000 --- a/include/luajit/lj_ffrecord.h +++ /dev/null @@ -1,24 +0,0 @@ -/* -** Fast function call recorder. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_FFRECORD_H -#define _LJ_FFRECORD_H - -#include "lj_obj.h" -#include "lj_jit.h" - -#if LJ_HASJIT -/* Data used by handlers to record a fast function. */ -typedef struct RecordFFData { - TValue *argv; /* Runtime argument values. */ - ptrdiff_t nres; /* Number of returned results (defaults to 1). */ - uint32_t data; /* Per-ffid auxiliary data (opcode, literal etc.). */ -} RecordFFData; - -LJ_FUNC int32_t lj_ffrecord_select_mode(jit_State *J, TRef tr, TValue *tv); -LJ_FUNC void lj_ffrecord_func(jit_State *J); -#endif - -#endif diff --git a/include/luajit/lj_frame.h b/include/luajit/lj_frame.h deleted file mode 100644 index a7e07d8..0000000 --- a/include/luajit/lj_frame.h +++ /dev/null @@ -1,297 +0,0 @@ -/* -** Stack frames. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_FRAME_H -#define _LJ_FRAME_H - -#include "lj_obj.h" -#include "lj_bc.h" - -/* -- Lua stack frame ----------------------------------------------------- */ - -/* Frame type markers in LSB of PC (4-byte aligned) or delta (8-byte aligned: -** -** PC 00 Lua frame -** delta 001 C frame -** delta 010 Continuation frame -** delta 011 Lua vararg frame -** delta 101 cpcall() frame -** delta 110 ff pcall() frame -** delta 111 ff pcall() frame with active hook -*/ -enum { - FRAME_LUA, FRAME_C, FRAME_CONT, FRAME_VARG, - FRAME_LUAP, FRAME_CP, FRAME_PCALL, FRAME_PCALLH -}; -#define FRAME_TYPE 3 -#define FRAME_P 4 -#define FRAME_TYPEP (FRAME_TYPE|FRAME_P) - -/* Macros to access and modify Lua frames. */ -#if LJ_FR2 -/* Two-slot frame info, required for 64 bit PC/GCRef: -** -** base-2 base-1 | base base+1 ... -** [func PC/delta/ft] | [slots ...] -** ^-- frame | ^-- base ^-- top -** -** Continuation frames: -** -** base-4 base-3 base-2 base-1 | base base+1 ... -** [cont PC ] [func PC/delta/ft] | [slots ...] -** ^-- frame | ^-- base ^-- top -*/ -#define frame_gc(f) (gcval((f)-1)) -#define frame_ftsz(f) ((ptrdiff_t)(f)->ftsz) -#define frame_pc(f) ((const BCIns *)frame_ftsz(f)) -#define setframe_gc(f, p, tp) (setgcVraw((f), (p), (tp))) -#define setframe_ftsz(f, sz) ((f)->ftsz = (sz)) -#define setframe_pc(f, pc) ((f)->ftsz = (int64_t)(intptr_t)(pc)) -#else -/* One-slot frame info, sufficient for 32 bit PC/GCRef: -** -** base-1 | base base+1 ... -** lo hi | -** [func | PC/delta/ft] | [slots ...] -** ^-- frame | ^-- base ^-- top -** -** Continuation frames: -** -** base-2 base-1 | base base+1 ... -** lo hi lo hi | -** [cont | PC] [func | PC/delta/ft] | [slots ...] -** ^-- frame | ^-- base ^-- top -*/ -#define frame_gc(f) (gcref((f)->fr.func)) -#define frame_ftsz(f) ((ptrdiff_t)(f)->fr.tp.ftsz) -#define frame_pc(f) (mref((f)->fr.tp.pcr, const BCIns)) -#define setframe_gc(f, p, tp) (setgcref((f)->fr.func, (p)), UNUSED(tp)) -#define setframe_ftsz(f, sz) ((f)->fr.tp.ftsz = (int32_t)(sz)) -#define setframe_pc(f, pc) (setmref((f)->fr.tp.pcr, (pc))) -#endif - -#define frame_type(f) (frame_ftsz(f) & FRAME_TYPE) -#define frame_typep(f) (frame_ftsz(f) & FRAME_TYPEP) -#define frame_islua(f) (frame_type(f) == FRAME_LUA) -#define frame_isc(f) (frame_type(f) == FRAME_C) -#define frame_iscont(f) (frame_typep(f) == FRAME_CONT) -#define frame_isvarg(f) (frame_typep(f) == FRAME_VARG) -#define frame_ispcall(f) ((frame_ftsz(f) & 6) == FRAME_PCALL) - -#define frame_func(f) (&frame_gc(f)->fn) -#define frame_delta(f) (frame_ftsz(f) >> 3) -#define frame_sized(f) (frame_ftsz(f) & ~FRAME_TYPEP) - -enum { LJ_CONT_TAILCALL, LJ_CONT_FFI_CALLBACK }; /* Special continuations. */ - -#if LJ_FR2 -#define frame_contpc(f) (frame_pc((f)-2)) -#define frame_contv(f) (((f)-3)->u64) -#else -#define frame_contpc(f) (frame_pc((f)-1)) -#define frame_contv(f) (((f)-1)->u32.lo) -#endif -#if LJ_FR2 -#define frame_contf(f) ((ASMFunction)(uintptr_t)((f)-3)->u64) -#elif LJ_64 -#define frame_contf(f) \ - ((ASMFunction)(void *)((intptr_t)lj_vm_asm_begin + \ - (intptr_t)(int32_t)((f)-1)->u32.lo)) -#else -#define frame_contf(f) ((ASMFunction)gcrefp(((f)-1)->gcr, void)) -#endif -#define frame_iscont_fficb(f) \ - (LJ_HASFFI && frame_contv(f) == LJ_CONT_FFI_CALLBACK) - -#define frame_prevl(f) ((f) - (1+LJ_FR2+bc_a(frame_pc(f)[-1]))) -#define frame_prevd(f) ((TValue *)((char *)(f) - frame_sized(f))) -#define frame_prev(f) (frame_islua(f)?frame_prevl(f):frame_prevd(f)) -/* Note: this macro does not skip over FRAME_VARG. */ - -/* -- C stack frame ------------------------------------------------------- */ - -/* Macros to access and modify the C stack frame chain. */ - -/* These definitions must match with the arch-specific *.dasc files. */ -#if LJ_TARGET_X86 -#if LJ_ABI_WIN -#define CFRAME_OFS_ERRF (19*4) -#define CFRAME_OFS_NRES (18*4) -#define CFRAME_OFS_PREV (17*4) -#define CFRAME_OFS_L (16*4) -#define CFRAME_OFS_SEH (9*4) -#define CFRAME_OFS_PC (6*4) -#define CFRAME_OFS_MULTRES (5*4) -#define CFRAME_SIZE (16*4) -#define CFRAME_SHIFT_MULTRES 0 -#else -#define CFRAME_OFS_ERRF (15*4) -#define CFRAME_OFS_NRES (14*4) -#define CFRAME_OFS_PREV (13*4) -#define CFRAME_OFS_L (12*4) -#define CFRAME_OFS_PC (6*4) -#define CFRAME_OFS_MULTRES (5*4) -#define CFRAME_SIZE (12*4) -#define CFRAME_SHIFT_MULTRES 0 -#endif -#elif LJ_TARGET_X64 -#if LJ_ABI_WIN -#define CFRAME_OFS_PREV (13*8) -#if LJ_GC64 -#define CFRAME_OFS_PC (12*8) -#define CFRAME_OFS_L (11*8) -#define CFRAME_OFS_ERRF (21*4) -#define CFRAME_OFS_NRES (20*4) -#define CFRAME_OFS_MULTRES (8*4) -#else -#define CFRAME_OFS_PC (25*4) -#define CFRAME_OFS_L (24*4) -#define CFRAME_OFS_ERRF (23*4) -#define CFRAME_OFS_NRES (22*4) -#define CFRAME_OFS_MULTRES (21*4) -#endif -#define CFRAME_SIZE (10*8) -#define CFRAME_SIZE_JIT (CFRAME_SIZE + 9*16 + 4*8) -#define CFRAME_SHIFT_MULTRES 0 -#else -#define CFRAME_OFS_PREV (4*8) -#if LJ_GC64 -#define CFRAME_OFS_PC (3*8) -#define CFRAME_OFS_L (2*8) -#define CFRAME_OFS_ERRF (3*4) -#define CFRAME_OFS_NRES (2*4) -#define CFRAME_OFS_MULTRES (0*4) -#else -#define CFRAME_OFS_PC (7*4) -#define CFRAME_OFS_L (6*4) -#define CFRAME_OFS_ERRF (5*4) -#define CFRAME_OFS_NRES (4*4) -#define CFRAME_OFS_MULTRES (1*4) -#endif -#if LJ_NO_UNWIND -#define CFRAME_SIZE (12*8) -#else -#define CFRAME_SIZE (10*8) -#endif -#define CFRAME_SIZE_JIT (CFRAME_SIZE + 16) -#define CFRAME_SHIFT_MULTRES 0 -#endif -#elif LJ_TARGET_ARM -#define CFRAME_OFS_ERRF 24 -#define CFRAME_OFS_NRES 20 -#define CFRAME_OFS_PREV 16 -#define CFRAME_OFS_L 12 -#define CFRAME_OFS_PC 8 -#define CFRAME_OFS_MULTRES 4 -#if LJ_ARCH_HASFPU -#define CFRAME_SIZE 128 -#else -#define CFRAME_SIZE 64 -#endif -#define CFRAME_SHIFT_MULTRES 3 -#elif LJ_TARGET_ARM64 -#define CFRAME_OFS_ERRF 36 -#define CFRAME_OFS_NRES 40 -#define CFRAME_OFS_PREV 0 -#define CFRAME_OFS_L 16 -#define CFRAME_OFS_PC 8 -#define CFRAME_OFS_MULTRES 32 -#define CFRAME_SIZE 208 -#define CFRAME_SHIFT_MULTRES 3 -#elif LJ_TARGET_PPC -#if LJ_TARGET_XBOX360 -#define CFRAME_OFS_ERRF 424 -#define CFRAME_OFS_NRES 420 -#define CFRAME_OFS_PREV 400 -#define CFRAME_OFS_L 416 -#define CFRAME_OFS_PC 412 -#define CFRAME_OFS_MULTRES 408 -#define CFRAME_SIZE 384 -#define CFRAME_SHIFT_MULTRES 3 -#elif LJ_ARCH_PPC32ON64 -#define CFRAME_OFS_ERRF 472 -#define CFRAME_OFS_NRES 468 -#define CFRAME_OFS_PREV 448 -#define CFRAME_OFS_L 464 -#define CFRAME_OFS_PC 460 -#define CFRAME_OFS_MULTRES 456 -#define CFRAME_SIZE 400 -#define CFRAME_SHIFT_MULTRES 3 -#else -#define CFRAME_OFS_ERRF 48 -#define CFRAME_OFS_NRES 44 -#define CFRAME_OFS_PREV 40 -#define CFRAME_OFS_L 36 -#define CFRAME_OFS_PC 32 -#define CFRAME_OFS_MULTRES 28 -#define CFRAME_SIZE (LJ_ARCH_HASFPU ? 272 : 128) -#define CFRAME_SHIFT_MULTRES 3 -#endif -#elif LJ_TARGET_MIPS32 -#if LJ_ARCH_HASFPU -#define CFRAME_OFS_ERRF 124 -#define CFRAME_OFS_NRES 120 -#define CFRAME_OFS_PREV 116 -#define CFRAME_OFS_L 112 -#define CFRAME_SIZE 112 -#else -#define CFRAME_OFS_ERRF 76 -#define CFRAME_OFS_NRES 72 -#define CFRAME_OFS_PREV 68 -#define CFRAME_OFS_L 64 -#define CFRAME_SIZE 64 -#endif -#define CFRAME_OFS_PC 20 -#define CFRAME_OFS_MULTRES 16 -#define CFRAME_SHIFT_MULTRES 3 -#elif LJ_TARGET_MIPS64 -#if LJ_ARCH_HASFPU -#define CFRAME_OFS_ERRF 188 -#define CFRAME_OFS_NRES 184 -#define CFRAME_OFS_PREV 176 -#define CFRAME_OFS_L 168 -#define CFRAME_OFS_PC 160 -#define CFRAME_SIZE 192 -#else -#define CFRAME_OFS_ERRF 124 -#define CFRAME_OFS_NRES 120 -#define CFRAME_OFS_PREV 112 -#define CFRAME_OFS_L 104 -#define CFRAME_OFS_PC 96 -#define CFRAME_SIZE 128 -#endif -#define CFRAME_OFS_MULTRES 0 -#define CFRAME_SHIFT_MULTRES 3 -#else -#error "Missing CFRAME_* definitions for this architecture" -#endif - -#ifndef CFRAME_SIZE_JIT -#define CFRAME_SIZE_JIT CFRAME_SIZE -#endif - -#define CFRAME_RESUME 1 -#define CFRAME_UNWIND_FF 2 /* Only used in unwinder. */ -#define CFRAME_RAWMASK (~(intptr_t)(CFRAME_RESUME|CFRAME_UNWIND_FF)) - -#define cframe_errfunc(cf) (*(int32_t *)(((char *)(cf))+CFRAME_OFS_ERRF)) -#define cframe_nres(cf) (*(int32_t *)(((char *)(cf))+CFRAME_OFS_NRES)) -#define cframe_prev(cf) (*(void **)(((char *)(cf))+CFRAME_OFS_PREV)) -#define cframe_multres(cf) (*(uint32_t *)(((char *)(cf))+CFRAME_OFS_MULTRES)) -#define cframe_multres_n(cf) (cframe_multres((cf)) >> CFRAME_SHIFT_MULTRES) -#define cframe_L(cf) \ - (&gcref(*(GCRef *)(((char *)(cf))+CFRAME_OFS_L))->th) -#define cframe_pc(cf) \ - (mref(*(MRef *)(((char *)(cf))+CFRAME_OFS_PC), const BCIns)) -#define setcframe_L(cf, L) \ - (setmref(*(MRef *)(((char *)(cf))+CFRAME_OFS_L), (L))) -#define setcframe_pc(cf, pc) \ - (setmref(*(MRef *)(((char *)(cf))+CFRAME_OFS_PC), (pc))) -#define cframe_canyield(cf) ((intptr_t)(cf) & CFRAME_RESUME) -#define cframe_unwind_ff(cf) ((intptr_t)(cf) & CFRAME_UNWIND_FF) -#define cframe_raw(cf) ((void *)((intptr_t)(cf) & CFRAME_RAWMASK)) -#define cframe_Lpc(L) cframe_pc(cframe_raw(L->cframe)) - -#endif diff --git a/include/luajit/lj_func.h b/include/luajit/lj_func.h deleted file mode 100644 index 7d538d7..0000000 --- a/include/luajit/lj_func.h +++ /dev/null @@ -1,24 +0,0 @@ -/* -** Function handling (prototypes, functions and upvalues). -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_FUNC_H -#define _LJ_FUNC_H - -#include "lj_obj.h" - -/* Prototypes. */ -LJ_FUNC void LJ_FASTCALL lj_func_freeproto(global_State *g, GCproto *pt); - -/* Upvalues. */ -LJ_FUNCA void LJ_FASTCALL lj_func_closeuv(lua_State *L, TValue *level); -LJ_FUNC void LJ_FASTCALL lj_func_freeuv(global_State *g, GCupval *uv); - -/* Functions (closures). */ -LJ_FUNC GCfunc *lj_func_newC(lua_State *L, MSize nelems, GCtab *env); -LJ_FUNC GCfunc *lj_func_newL_empty(lua_State *L, GCproto *pt, GCtab *env); -LJ_FUNCA GCfunc *lj_func_newL_gc(lua_State *L, GCproto *pt, GCfuncL *parent); -LJ_FUNC void LJ_FASTCALL lj_func_free(global_State *g, GCfunc *c); - -#endif diff --git a/include/luajit/lj_gc.h b/include/luajit/lj_gc.h deleted file mode 100644 index b44095d..0000000 --- a/include/luajit/lj_gc.h +++ /dev/null @@ -1,136 +0,0 @@ -/* -** Garbage collector. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_GC_H -#define _LJ_GC_H - -#include "lj_obj.h" - -/* Garbage collector states. Order matters. */ -enum { - GCSpause, GCSpropagate, GCSatomic, GCSsweepstring, GCSsweep, GCSfinalize -}; - -/* Bitmasks for marked field of GCobj. */ -#define LJ_GC_WHITE0 0x01 -#define LJ_GC_WHITE1 0x02 -#define LJ_GC_BLACK 0x04 -#define LJ_GC_FINALIZED 0x08 -#define LJ_GC_WEAKKEY 0x08 -#define LJ_GC_WEAKVAL 0x10 -#define LJ_GC_CDATA_FIN 0x10 -#define LJ_GC_FIXED 0x20 -#define LJ_GC_SFIXED 0x40 - -#define LJ_GC_WHITES (LJ_GC_WHITE0 | LJ_GC_WHITE1) -#define LJ_GC_COLORS (LJ_GC_WHITES | LJ_GC_BLACK) -#define LJ_GC_WEAK (LJ_GC_WEAKKEY | LJ_GC_WEAKVAL) - -/* Macros to test and set GCobj colors. */ -#define iswhite(x) ((x)->gch.marked & LJ_GC_WHITES) -#define isblack(x) ((x)->gch.marked & LJ_GC_BLACK) -#define isgray(x) (!((x)->gch.marked & (LJ_GC_BLACK|LJ_GC_WHITES))) -#define tviswhite(x) (tvisgcv(x) && iswhite(gcV(x))) -#define otherwhite(g) (g->gc.currentwhite ^ LJ_GC_WHITES) -#define isdead(g, v) ((v)->gch.marked & otherwhite(g) & LJ_GC_WHITES) - -#define curwhite(g) ((g)->gc.currentwhite & LJ_GC_WHITES) -#define newwhite(g, x) (obj2gco(x)->gch.marked = (uint8_t)curwhite(g)) -#define makewhite(g, x) \ - ((x)->gch.marked = ((x)->gch.marked & (uint8_t)~LJ_GC_COLORS) | curwhite(g)) -#define flipwhite(x) ((x)->gch.marked ^= LJ_GC_WHITES) -#define black2gray(x) ((x)->gch.marked &= (uint8_t)~LJ_GC_BLACK) -#define fixstring(s) ((s)->marked |= LJ_GC_FIXED) -#define markfinalized(x) ((x)->gch.marked |= LJ_GC_FINALIZED) - -/* Collector. */ -LJ_FUNC size_t lj_gc_separateudata(global_State *g, int all); -LJ_FUNC void lj_gc_finalize_udata(lua_State *L); -#if LJ_HASFFI -LJ_FUNC void lj_gc_finalize_cdata(lua_State *L); -#else -#define lj_gc_finalize_cdata(L) UNUSED(L) -#endif -LJ_FUNC void lj_gc_freeall(global_State *g); -LJ_FUNCA int LJ_FASTCALL lj_gc_step(lua_State *L); -LJ_FUNCA void LJ_FASTCALL lj_gc_step_fixtop(lua_State *L); -#if LJ_HASJIT -LJ_FUNC int LJ_FASTCALL lj_gc_step_jit(global_State *g, MSize steps); -#endif -LJ_FUNC void lj_gc_fullgc(lua_State *L); - -/* GC check: drive collector forward if the GC threshold has been reached. */ -#define lj_gc_check(L) \ - { if (LJ_UNLIKELY(G(L)->gc.total >= G(L)->gc.threshold)) \ - lj_gc_step(L); } -#define lj_gc_check_fixtop(L) \ - { if (LJ_UNLIKELY(G(L)->gc.total >= G(L)->gc.threshold)) \ - lj_gc_step_fixtop(L); } - -/* Write barriers. */ -LJ_FUNC void lj_gc_barrierf(global_State *g, GCobj *o, GCobj *v); -LJ_FUNCA void LJ_FASTCALL lj_gc_barrieruv(global_State *g, TValue *tv); -LJ_FUNC void lj_gc_closeuv(global_State *g, GCupval *uv); -#if LJ_HASJIT -LJ_FUNC void lj_gc_barriertrace(global_State *g, uint32_t traceno); -#endif - -/* Move the GC propagation frontier back for tables (make it gray again). */ -static LJ_AINLINE void lj_gc_barrierback(global_State *g, GCtab *t) -{ - GCobj *o = obj2gco(t); - lj_assertG(isblack(o) && !isdead(g, o), - "bad object states for backward barrier"); - lj_assertG(g->gc.state != GCSfinalize && g->gc.state != GCSpause, - "bad GC state"); - black2gray(o); - setgcrefr(t->gclist, g->gc.grayagain); - setgcref(g->gc.grayagain, o); -} - -/* Barrier for stores to table objects. TValue and GCobj variant. */ -#define lj_gc_anybarriert(L, t) \ - { if (LJ_UNLIKELY(isblack(obj2gco(t)))) lj_gc_barrierback(G(L), (t)); } -#define lj_gc_barriert(L, t, tv) \ - { if (tviswhite(tv) && isblack(obj2gco(t))) \ - lj_gc_barrierback(G(L), (t)); } -#define lj_gc_objbarriert(L, t, o) \ - { if (iswhite(obj2gco(o)) && isblack(obj2gco(t))) \ - lj_gc_barrierback(G(L), (t)); } - -/* Barrier for stores to any other object. TValue and GCobj variant. */ -#define lj_gc_barrier(L, p, tv) \ - { if (tviswhite(tv) && isblack(obj2gco(p))) \ - lj_gc_barrierf(G(L), obj2gco(p), gcV(tv)); } -#define lj_gc_objbarrier(L, p, o) \ - { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) \ - lj_gc_barrierf(G(L), obj2gco(p), obj2gco(o)); } - -/* Allocator. */ -LJ_FUNC void *lj_mem_realloc(lua_State *L, void *p, GCSize osz, GCSize nsz); -LJ_FUNC void * LJ_FASTCALL lj_mem_newgco(lua_State *L, GCSize size); -LJ_FUNC void *lj_mem_grow(lua_State *L, void *p, - MSize *szp, MSize lim, MSize esz); - -#define lj_mem_new(L, s) lj_mem_realloc(L, NULL, 0, (s)) - -static LJ_AINLINE void lj_mem_free(global_State *g, void *p, size_t osize) -{ - g->gc.total -= (GCSize)osize; - g->allocf(g->allocd, p, osize, 0); -} - -#define lj_mem_newvec(L, n, t) ((t *)lj_mem_new(L, (GCSize)((n)*sizeof(t)))) -#define lj_mem_reallocvec(L, p, on, n, t) \ - ((p) = (t *)lj_mem_realloc(L, p, (on)*sizeof(t), (GCSize)((n)*sizeof(t)))) -#define lj_mem_growvec(L, p, n, m, t) \ - ((p) = (t *)lj_mem_grow(L, (p), &(n), (m), (MSize)sizeof(t))) -#define lj_mem_freevec(g, p, n, t) lj_mem_free(g, (p), (n)*sizeof(t)) - -#define lj_mem_newobj(L, t) ((t *)lj_mem_newgco(L, sizeof(t))) -#define lj_mem_newt(L, s, t) ((t *)lj_mem_new(L, (s))) -#define lj_mem_freet(g, p) lj_mem_free(g, (p), sizeof(*(p))) - -#endif diff --git a/include/luajit/lj_gdbjit.h b/include/luajit/lj_gdbjit.h deleted file mode 100644 index 23b3daa..0000000 --- a/include/luajit/lj_gdbjit.h +++ /dev/null @@ -1,22 +0,0 @@ -/* -** Client for the GDB JIT API. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_GDBJIT_H -#define _LJ_GDBJIT_H - -#include "lj_obj.h" -#include "lj_jit.h" - -#if LJ_HASJIT && defined(LUAJIT_USE_GDBJIT) - -LJ_FUNC void lj_gdbjit_addtrace(jit_State *J, GCtrace *T); -LJ_FUNC void lj_gdbjit_deltrace(jit_State *J, GCtrace *T); - -#else -#define lj_gdbjit_addtrace(J, T) UNUSED(T) -#define lj_gdbjit_deltrace(J, T) UNUSED(T) -#endif - -#endif diff --git a/include/luajit/lj_ir.h b/include/luajit/lj_ir.h deleted file mode 100644 index 06458f2..0000000 --- a/include/luajit/lj_ir.h +++ /dev/null @@ -1,615 +0,0 @@ -/* -** SSA IR (Intermediate Representation) format. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_IR_H -#define _LJ_IR_H - -#include "lj_obj.h" - -/* -- IR instructions ----------------------------------------------------- */ - -/* IR instruction definition. Order matters, see below. ORDER IR */ -#define IRDEF(_) \ - /* Guarded assertions. */ \ - /* Must be properly aligned to flip opposites (^1) and (un)ordered (^4). */ \ - _(LT, N , ref, ref) \ - _(GE, N , ref, ref) \ - _(LE, N , ref, ref) \ - _(GT, N , ref, ref) \ - \ - _(ULT, N , ref, ref) \ - _(UGE, N , ref, ref) \ - _(ULE, N , ref, ref) \ - _(UGT, N , ref, ref) \ - \ - _(EQ, C , ref, ref) \ - _(NE, C , ref, ref) \ - \ - _(ABC, N , ref, ref) \ - _(RETF, S , ref, ref) \ - \ - /* Miscellaneous ops. */ \ - _(NOP, N , ___, ___) \ - _(BASE, N , lit, lit) \ - _(PVAL, N , lit, ___) \ - _(GCSTEP, S , ___, ___) \ - _(HIOP, S , ref, ref) \ - _(LOOP, S , ___, ___) \ - _(USE, S , ref, ___) \ - _(PHI, S , ref, ref) \ - _(RENAME, S , ref, lit) \ - _(PROF, S , ___, ___) \ - \ - /* Constants. */ \ - _(KPRI, N , ___, ___) \ - _(KINT, N , cst, ___) \ - _(KGC, N , cst, ___) \ - _(KPTR, N , cst, ___) \ - _(KKPTR, N , cst, ___) \ - _(KNULL, N , cst, ___) \ - _(KNUM, N , cst, ___) \ - _(KINT64, N , cst, ___) \ - _(KSLOT, N , ref, lit) \ - \ - /* Bit ops. */ \ - _(BNOT, N , ref, ___) \ - _(BSWAP, N , ref, ___) \ - _(BAND, C , ref, ref) \ - _(BOR, C , ref, ref) \ - _(BXOR, C , ref, ref) \ - _(BSHL, N , ref, ref) \ - _(BSHR, N , ref, ref) \ - _(BSAR, N , ref, ref) \ - _(BROL, N , ref, ref) \ - _(BROR, N , ref, ref) \ - \ - /* Arithmetic ops. ORDER ARITH */ \ - _(ADD, C , ref, ref) \ - _(SUB, N , ref, ref) \ - _(MUL, C , ref, ref) \ - _(DIV, N , ref, ref) \ - _(MOD, N , ref, ref) \ - _(POW, N , ref, ref) \ - _(NEG, N , ref, ref) \ - \ - _(ABS, N , ref, ref) \ - _(LDEXP, N , ref, ref) \ - _(MIN, N , ref, ref) \ - _(MAX, N , ref, ref) \ - _(FPMATH, N , ref, lit) \ - \ - /* Overflow-checking arithmetic ops. */ \ - _(ADDOV, CW, ref, ref) \ - _(SUBOV, NW, ref, ref) \ - _(MULOV, CW, ref, ref) \ - \ - /* Memory ops. A = array, H = hash, U = upvalue, F = field, S = stack. */ \ - \ - /* Memory references. */ \ - _(AREF, R , ref, ref) \ - _(HREFK, R , ref, ref) \ - _(HREF, L , ref, ref) \ - _(NEWREF, S , ref, ref) \ - _(UREFO, LW, ref, lit) \ - _(UREFC, LW, ref, lit) \ - _(FREF, R , ref, lit) \ - _(TMPREF, S , ref, lit) \ - _(STRREF, N , ref, ref) \ - _(LREF, L , ___, ___) \ - \ - /* Loads and Stores. These must be in the same order. */ \ - _(ALOAD, L , ref, ___) \ - _(HLOAD, L , ref, ___) \ - _(ULOAD, L , ref, ___) \ - _(FLOAD, L , ref, lit) \ - _(XLOAD, L , ref, lit) \ - _(SLOAD, L , lit, lit) \ - _(VLOAD, L , ref, lit) \ - _(ALEN, L , ref, ref) \ - \ - _(ASTORE, S , ref, ref) \ - _(HSTORE, S , ref, ref) \ - _(USTORE, S , ref, ref) \ - _(FSTORE, S , ref, ref) \ - _(XSTORE, S , ref, ref) \ - \ - /* Allocations. */ \ - _(SNEW, N , ref, ref) /* CSE is ok, not marked as A. */ \ - _(XSNEW, A , ref, ref) \ - _(TNEW, AW, lit, lit) \ - _(TDUP, AW, ref, ___) \ - _(CNEW, AW, ref, ref) \ - _(CNEWI, NW, ref, ref) /* CSE is ok, not marked as A. */ \ - \ - /* Buffer operations. */ \ - _(BUFHDR, L , ref, lit) \ - _(BUFPUT, LW, ref, ref) \ - _(BUFSTR, AW, ref, ref) \ - \ - /* Barriers. */ \ - _(TBAR, S , ref, ___) \ - _(OBAR, S , ref, ref) \ - _(XBAR, S , ___, ___) \ - \ - /* Type conversions. */ \ - _(CONV, N , ref, lit) \ - _(TOBIT, N , ref, ref) \ - _(TOSTR, N , ref, lit) \ - _(STRTO, N , ref, ___) \ - \ - /* Calls. */ \ - _(CALLN, NW, ref, lit) \ - _(CALLA, AW, ref, lit) \ - _(CALLL, LW, ref, lit) \ - _(CALLS, S , ref, lit) \ - _(CALLXS, S , ref, ref) \ - _(CARG, N , ref, ref) \ - \ - /* End of list. */ - -/* IR opcodes (max. 256). */ -typedef enum { -#define IRENUM(name, m, m1, m2) IR_##name, -IRDEF(IRENUM) -#undef IRENUM - IR__MAX -} IROp; - -/* Stored opcode. */ -typedef uint8_t IROp1; - -LJ_STATIC_ASSERT(((int)IR_EQ^1) == (int)IR_NE); -LJ_STATIC_ASSERT(((int)IR_LT^1) == (int)IR_GE); -LJ_STATIC_ASSERT(((int)IR_LE^1) == (int)IR_GT); -LJ_STATIC_ASSERT(((int)IR_LT^3) == (int)IR_GT); -LJ_STATIC_ASSERT(((int)IR_LT^4) == (int)IR_ULT); - -/* Delta between xLOAD and xSTORE. */ -#define IRDELTA_L2S ((int)IR_ASTORE - (int)IR_ALOAD) - -LJ_STATIC_ASSERT((int)IR_HLOAD + IRDELTA_L2S == (int)IR_HSTORE); -LJ_STATIC_ASSERT((int)IR_ULOAD + IRDELTA_L2S == (int)IR_USTORE); -LJ_STATIC_ASSERT((int)IR_FLOAD + IRDELTA_L2S == (int)IR_FSTORE); -LJ_STATIC_ASSERT((int)IR_XLOAD + IRDELTA_L2S == (int)IR_XSTORE); - -/* -- Named IR literals --------------------------------------------------- */ - -/* FPMATH sub-functions. ORDER FPM. */ -#define IRFPMDEF(_) \ - _(FLOOR) _(CEIL) _(TRUNC) /* Must be first and in this order. */ \ - _(SQRT) _(LOG) _(LOG2) \ - _(OTHER) - -typedef enum { -#define FPMENUM(name) IRFPM_##name, -IRFPMDEF(FPMENUM) -#undef FPMENUM - IRFPM__MAX -} IRFPMathOp; - -/* FLOAD fields. */ -#define IRFLDEF(_) \ - _(STR_LEN, offsetof(GCstr, len)) \ - _(FUNC_ENV, offsetof(GCfunc, l.env)) \ - _(FUNC_PC, offsetof(GCfunc, l.pc)) \ - _(FUNC_FFID, offsetof(GCfunc, l.ffid)) \ - _(THREAD_ENV, offsetof(lua_State, env)) \ - _(TAB_META, offsetof(GCtab, metatable)) \ - _(TAB_ARRAY, offsetof(GCtab, array)) \ - _(TAB_NODE, offsetof(GCtab, node)) \ - _(TAB_ASIZE, offsetof(GCtab, asize)) \ - _(TAB_HMASK, offsetof(GCtab, hmask)) \ - _(TAB_NOMM, offsetof(GCtab, nomm)) \ - _(UDATA_META, offsetof(GCudata, metatable)) \ - _(UDATA_UDTYPE, offsetof(GCudata, udtype)) \ - _(UDATA_FILE, sizeof(GCudata)) \ - _(SBUF_W, sizeof(GCudata) + offsetof(SBufExt, w)) \ - _(SBUF_E, sizeof(GCudata) + offsetof(SBufExt, e)) \ - _(SBUF_B, sizeof(GCudata) + offsetof(SBufExt, b)) \ - _(SBUF_L, sizeof(GCudata) + offsetof(SBufExt, L)) \ - _(SBUF_REF, sizeof(GCudata) + offsetof(SBufExt, cowref)) \ - _(SBUF_R, sizeof(GCudata) + offsetof(SBufExt, r)) \ - _(CDATA_CTYPEID, offsetof(GCcdata, ctypeid)) \ - _(CDATA_PTR, sizeof(GCcdata)) \ - _(CDATA_INT, sizeof(GCcdata)) \ - _(CDATA_INT64, sizeof(GCcdata)) \ - _(CDATA_INT64_4, sizeof(GCcdata) + 4) - -typedef enum { -#define FLENUM(name, ofs) IRFL_##name, -IRFLDEF(FLENUM) -#undef FLENUM - IRFL__MAX -} IRFieldID; - -/* TMPREF mode bits, stored in op2. */ -#define IRTMPREF_IN1 0x01 /* First input value. */ -#define IRTMPREF_OUT1 0x02 /* First output value. */ -#define IRTMPREF_OUT2 0x04 /* Second output value. */ - -/* SLOAD mode bits, stored in op2. */ -#define IRSLOAD_PARENT 0x01 /* Coalesce with parent trace. */ -#define IRSLOAD_FRAME 0x02 /* Load 32 bits of ftsz. */ -#define IRSLOAD_TYPECHECK 0x04 /* Needs type check. */ -#define IRSLOAD_CONVERT 0x08 /* Number to integer conversion. */ -#define IRSLOAD_READONLY 0x10 /* Read-only, omit slot store. */ -#define IRSLOAD_INHERIT 0x20 /* Inherited by exits/side traces. */ -#define IRSLOAD_KEYINDEX 0x40 /* Table traversal key index. */ - -/* XLOAD mode bits, stored in op2. */ -#define IRXLOAD_READONLY 0x01 /* Load from read-only data. */ -#define IRXLOAD_VOLATILE 0x02 /* Load from volatile data. */ -#define IRXLOAD_UNALIGNED 0x04 /* Unaligned load. */ - -/* BUFHDR mode, stored in op2. */ -#define IRBUFHDR_RESET 0 /* Reset buffer. */ -#define IRBUFHDR_APPEND 1 /* Append to buffer. */ -#define IRBUFHDR_WRITE 2 /* Write to string buffer. */ - -/* CONV mode, stored in op2. */ -#define IRCONV_SRCMASK 0x001f /* Source IRType. */ -#define IRCONV_DSTMASK 0x03e0 /* Dest. IRType (also in ir->t). */ -#define IRCONV_DSH 5 -#define IRCONV_NUM_INT ((IRT_NUM<>2)&3)) -#define irm_iscomm(m) ((m) & IRM_C) -#define irm_kind(m) ((m) & IRM_S) - -#define IRMODE(name, m, m1, m2) (((IRM##m1)|((IRM##m2)<<2)|(IRM_##m))^IRM_W), - -LJ_DATA const uint8_t lj_ir_mode[IR__MAX+1]; - -/* -- IR instruction types ------------------------------------------------ */ - -#define IRTSIZE_PGC (LJ_GC64 ? 8 : 4) - -/* Map of itypes to non-negative numbers and their sizes. ORDER LJ_T. -** LJ_TUPVAL/LJ_TTRACE never appear in a TValue. Use these itypes for -** IRT_P32 and IRT_P64, which never escape the IR. -** The various integers are only used in the IR and can only escape to -** a TValue after implicit or explicit conversion. Their types must be -** contiguous and next to IRT_NUM (see the typerange macros below). -*/ -#define IRTDEF(_) \ - _(NIL, 4) _(FALSE, 4) _(TRUE, 4) _(LIGHTUD, LJ_64 ? 8 : 4) \ - _(STR, IRTSIZE_PGC) _(P32, 4) _(THREAD, IRTSIZE_PGC) _(PROTO, IRTSIZE_PGC) \ - _(FUNC, IRTSIZE_PGC) _(P64, 8) _(CDATA, IRTSIZE_PGC) _(TAB, IRTSIZE_PGC) \ - _(UDATA, IRTSIZE_PGC) \ - _(FLOAT, 4) _(NUM, 8) _(I8, 1) _(U8, 1) _(I16, 2) _(U16, 2) \ - _(INT, 4) _(U32, 4) _(I64, 8) _(U64, 8) \ - _(SOFTFP, 4) /* There is room for 8 more types. */ - -/* IR result type and flags (8 bit). */ -typedef enum { -#define IRTENUM(name, size) IRT_##name, -IRTDEF(IRTENUM) -#undef IRTENUM - IRT__MAX, - - /* Native pointer type and the corresponding integer type. */ - IRT_PTR = LJ_64 ? IRT_P64 : IRT_P32, - IRT_PGC = LJ_GC64 ? IRT_P64 : IRT_P32, - IRT_IGC = LJ_GC64 ? IRT_I64 : IRT_INT, - IRT_INTP = LJ_64 ? IRT_I64 : IRT_INT, - IRT_UINTP = LJ_64 ? IRT_U64 : IRT_U32, - - /* Additional flags. */ - IRT_MARK = 0x20, /* Marker for misc. purposes. */ - IRT_ISPHI = 0x40, /* Instruction is left or right PHI operand. */ - IRT_GUARD = 0x80, /* Instruction is a guard. */ - - /* Masks. */ - IRT_TYPE = 0x1f, - IRT_T = 0xff -} IRType; - -#define irtype_ispri(irt) ((uint32_t)(irt) <= IRT_TRUE) - -/* Stored IRType. */ -typedef struct IRType1 { uint8_t irt; } IRType1; - -#define IRT(o, t) ((uint32_t)(((o)<<8) | (t))) -#define IRTI(o) (IRT((o), IRT_INT)) -#define IRTN(o) (IRT((o), IRT_NUM)) -#define IRTG(o, t) (IRT((o), IRT_GUARD|(t))) -#define IRTGI(o) (IRT((o), IRT_GUARD|IRT_INT)) - -#define irt_t(t) ((IRType)(t).irt) -#define irt_type(t) ((IRType)((t).irt & IRT_TYPE)) -#define irt_sametype(t1, t2) ((((t1).irt ^ (t2).irt) & IRT_TYPE) == 0) -#define irt_typerange(t, first, last) \ - ((uint32_t)((t).irt & IRT_TYPE) - (uint32_t)(first) <= (uint32_t)(last-first)) - -#define irt_isnil(t) (irt_type(t) == IRT_NIL) -#define irt_ispri(t) ((uint32_t)irt_type(t) <= IRT_TRUE) -#define irt_islightud(t) (irt_type(t) == IRT_LIGHTUD) -#define irt_isstr(t) (irt_type(t) == IRT_STR) -#define irt_istab(t) (irt_type(t) == IRT_TAB) -#define irt_iscdata(t) (irt_type(t) == IRT_CDATA) -#define irt_isfloat(t) (irt_type(t) == IRT_FLOAT) -#define irt_isnum(t) (irt_type(t) == IRT_NUM) -#define irt_isint(t) (irt_type(t) == IRT_INT) -#define irt_isi8(t) (irt_type(t) == IRT_I8) -#define irt_isu8(t) (irt_type(t) == IRT_U8) -#define irt_isi16(t) (irt_type(t) == IRT_I16) -#define irt_isu16(t) (irt_type(t) == IRT_U16) -#define irt_isu32(t) (irt_type(t) == IRT_U32) -#define irt_isi64(t) (irt_type(t) == IRT_I64) -#define irt_isu64(t) (irt_type(t) == IRT_U64) -#define irt_isp32(t) (irt_type(t) == IRT_P32) - -#define irt_isfp(t) (irt_isnum(t) || irt_isfloat(t)) -#define irt_isinteger(t) (irt_typerange((t), IRT_I8, IRT_INT)) -#define irt_isgcv(t) (irt_typerange((t), IRT_STR, IRT_UDATA)) -#define irt_isaddr(t) (irt_typerange((t), IRT_LIGHTUD, IRT_UDATA)) -#define irt_isint64(t) (irt_typerange((t), IRT_I64, IRT_U64)) - -#if LJ_GC64 -/* Include IRT_NIL, so IR(ASMREF_L) (aka REF_NIL) is considered 64 bit. */ -#define IRT_IS64 \ - ((1u<> irt_type(t)) & 1) -#define irt_is64orfp(t) (((IRT_IS64|(1u<>irt_type(t)) & 1) - -#define irt_size(t) (lj_ir_type_size[irt_t((t))]) - -LJ_DATA const uint8_t lj_ir_type_size[]; - -static LJ_AINLINE IRType itype2irt(const TValue *tv) -{ - if (tvisint(tv)) - return IRT_INT; - else if (tvisnum(tv)) - return IRT_NUM; -#if LJ_64 && !LJ_GC64 - else if (tvislightud(tv)) - return IRT_LIGHTUD; -#endif - else - return (IRType)~itype(tv); -} - -static LJ_AINLINE uint32_t irt_toitype_(IRType t) -{ - lj_assertX(!LJ_64 || LJ_GC64 || t != IRT_LIGHTUD, - "no plain type tag for lightuserdata"); - if (LJ_DUALNUM && t > IRT_NUM) { - return LJ_TISNUM; - } else { - lj_assertX(t <= IRT_NUM, "no plain type tag for IR type %d", t); - return ~(uint32_t)t; - } -} - -#define irt_toitype(t) irt_toitype_(irt_type((t))) - -#define irt_isguard(t) ((t).irt & IRT_GUARD) -#define irt_ismarked(t) ((t).irt & IRT_MARK) -#define irt_setmark(t) ((t).irt |= IRT_MARK) -#define irt_clearmark(t) ((t).irt &= ~IRT_MARK) -#define irt_isphi(t) ((t).irt & IRT_ISPHI) -#define irt_setphi(t) ((t).irt |= IRT_ISPHI) -#define irt_clearphi(t) ((t).irt &= ~IRT_ISPHI) - -/* Stored combined IR opcode and type. */ -typedef uint16_t IROpT; - -/* -- IR references ------------------------------------------------------- */ - -/* IR references. */ -typedef uint16_t IRRef1; /* One stored reference. */ -typedef uint32_t IRRef2; /* Two stored references. */ -typedef uint32_t IRRef; /* Used to pass around references. */ - -/* Fixed references. */ -enum { - REF_BIAS = 0x8000, - REF_TRUE = REF_BIAS-3, - REF_FALSE = REF_BIAS-2, - REF_NIL = REF_BIAS-1, /* \--- Constants grow downwards. */ - REF_BASE = REF_BIAS, /* /--- IR grows upwards. */ - REF_FIRST = REF_BIAS+1, - REF_DROP = 0xffff -}; - -/* Note: IRMlit operands must be < REF_BIAS, too! -** This allows for fast and uniform manipulation of all operands -** without looking up the operand mode in lj_ir_mode: -** - CSE calculates the maximum reference of two operands. -** This must work with mixed reference/literal operands, too. -** - DCE marking only checks for operand >= REF_BIAS. -** - LOOP needs to substitute reference operands. -** Constant references and literals must not be modified. -*/ - -#define IRREF2(lo, hi) ((IRRef2)(lo) | ((IRRef2)(hi) << 16)) - -#define irref_isk(ref) ((ref) < REF_BIAS) - -/* Tagged IR references (32 bit). -** -** +-------+-------+---------------+ -** | irt | flags | ref | -** +-------+-------+---------------+ -** -** The tag holds a copy of the IRType and speeds up IR type checks. -*/ -typedef uint32_t TRef; - -#define TREF_REFMASK 0x0000ffff -#define TREF_FRAME 0x00010000 -#define TREF_CONT 0x00020000 -#define TREF_KEYINDEX 0x00100000 - -#define TREF(ref, t) ((TRef)((ref) + ((t)<<24))) - -#define tref_ref(tr) ((IRRef1)(tr)) -#define tref_t(tr) ((IRType)((tr)>>24)) -#define tref_type(tr) ((IRType)(((tr)>>24) & IRT_TYPE)) -#define tref_typerange(tr, first, last) \ - ((((tr)>>24) & IRT_TYPE) - (TRef)(first) <= (TRef)(last-first)) - -#define tref_istype(tr, t) (((tr) & (IRT_TYPE<<24)) == ((t)<<24)) -#define tref_isnil(tr) (tref_istype((tr), IRT_NIL)) -#define tref_isfalse(tr) (tref_istype((tr), IRT_FALSE)) -#define tref_istrue(tr) (tref_istype((tr), IRT_TRUE)) -#define tref_islightud(tr) (tref_istype((tr), IRT_LIGHTUD)) -#define tref_isstr(tr) (tref_istype((tr), IRT_STR)) -#define tref_isfunc(tr) (tref_istype((tr), IRT_FUNC)) -#define tref_iscdata(tr) (tref_istype((tr), IRT_CDATA)) -#define tref_istab(tr) (tref_istype((tr), IRT_TAB)) -#define tref_isudata(tr) (tref_istype((tr), IRT_UDATA)) -#define tref_isnum(tr) (tref_istype((tr), IRT_NUM)) -#define tref_isint(tr) (tref_istype((tr), IRT_INT)) - -#define tref_isbool(tr) (tref_typerange((tr), IRT_FALSE, IRT_TRUE)) -#define tref_ispri(tr) (tref_typerange((tr), IRT_NIL, IRT_TRUE)) -#define tref_istruecond(tr) (!tref_typerange((tr), IRT_NIL, IRT_FALSE)) -#define tref_isinteger(tr) (tref_typerange((tr), IRT_I8, IRT_INT)) -#define tref_isnumber(tr) (tref_typerange((tr), IRT_NUM, IRT_INT)) -#define tref_isnumber_str(tr) (tref_isnumber((tr)) || tref_isstr((tr))) -#define tref_isgcv(tr) (tref_typerange((tr), IRT_STR, IRT_UDATA)) - -#define tref_isk(tr) (irref_isk(tref_ref((tr)))) -#define tref_isk2(tr1, tr2) (irref_isk(tref_ref((tr1) | (tr2)))) - -#define TREF_PRI(t) (TREF(REF_NIL-(t), (t))) -#define TREF_NIL (TREF_PRI(IRT_NIL)) -#define TREF_FALSE (TREF_PRI(IRT_FALSE)) -#define TREF_TRUE (TREF_PRI(IRT_TRUE)) - -/* -- IR format ----------------------------------------------------------- */ - -/* IR instruction format (64 bit). -** -** 16 16 8 8 8 8 -** +-------+-------+---+---+---+---+ -** | op1 | op2 | t | o | r | s | -** +-------+-------+---+---+---+---+ -** | op12/i/gco32 | ot | prev | (alternative fields in union) -** +-------+-------+---+---+---+---+ -** | TValue/gco64 | (2nd IR slot for 64 bit constants) -** +---------------+-------+-------+ -** 32 16 16 -** -** prev is only valid prior to register allocation and then reused for r + s. -*/ - -typedef union IRIns { - struct { - LJ_ENDIAN_LOHI( - IRRef1 op1; /* IR operand 1. */ - , IRRef1 op2; /* IR operand 2. */ - ) - IROpT ot; /* IR opcode and type (overlaps t and o). */ - IRRef1 prev; /* Previous ins in same chain (overlaps r and s). */ - }; - struct { - IRRef2 op12; /* IR operand 1 and 2 (overlaps op1 and op2). */ - LJ_ENDIAN_LOHI( - IRType1 t; /* IR type. */ - , IROp1 o; /* IR opcode. */ - ) - LJ_ENDIAN_LOHI( - uint8_t r; /* Register allocation (overlaps prev). */ - , uint8_t s; /* Spill slot allocation (overlaps prev). */ - ) - }; - int32_t i; /* 32 bit signed integer literal (overlaps op12). */ - GCRef gcr; /* GCobj constant (overlaps op12 or entire slot). */ - MRef ptr; /* Pointer constant (overlaps op12 or entire slot). */ - TValue tv; /* TValue constant (overlaps entire slot). */ -} IRIns; - -#define ir_isk64(ir) \ - ((ir)->o == IR_KNUM || (ir)->o == IR_KINT64 || \ - (LJ_GC64 && \ - ((ir)->o == IR_KGC || (ir)->o == IR_KPTR || (ir)->o == IR_KKPTR))) - -#define ir_kgc(ir) check_exp((ir)->o == IR_KGC, gcref((ir)[LJ_GC64].gcr)) -#define ir_kstr(ir) (gco2str(ir_kgc((ir)))) -#define ir_ktab(ir) (gco2tab(ir_kgc((ir)))) -#define ir_kfunc(ir) (gco2func(ir_kgc((ir)))) -#define ir_kcdata(ir) (gco2cd(ir_kgc((ir)))) -#define ir_knum(ir) check_exp((ir)->o == IR_KNUM, &(ir)[1].tv) -#define ir_kint64(ir) check_exp((ir)->o == IR_KINT64, &(ir)[1].tv) -#define ir_k64(ir) check_exp(ir_isk64(ir), &(ir)[1].tv) -#define ir_kptr(ir) \ - check_exp((ir)->o == IR_KPTR || (ir)->o == IR_KKPTR, \ - mref((ir)[LJ_GC64].ptr, void)) - -/* A store or any other op with a non-weak guard has a side-effect. */ -static LJ_AINLINE int ir_sideeff(IRIns *ir) -{ - return (((ir->t.irt | ~IRT_GUARD) & lj_ir_mode[ir->o]) >= IRM_S); -} - -LJ_STATIC_ASSERT((int)IRT_GUARD == (int)IRM_W); - -/* Replace IR instruction with NOP. */ -static LJ_AINLINE void lj_ir_nop(IRIns *ir) -{ - ir->ot = IRT(IR_NOP, IRT_NIL); - ir->op1 = ir->op2 = 0; - ir->prev = 0; -} - -#endif diff --git a/include/luajit/lj_ircall.h b/include/luajit/lj_ircall.h deleted file mode 100644 index 60b196c..0000000 --- a/include/luajit/lj_ircall.h +++ /dev/null @@ -1,353 +0,0 @@ -/* -** IR CALL* instruction definitions. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_IRCALL_H -#define _LJ_IRCALL_H - -#include "lj_obj.h" -#include "lj_ir.h" -#include "lj_jit.h" - -/* C call info for CALL* instructions. */ -typedef struct CCallInfo { - ASMFunction func; /* Function pointer. */ - uint32_t flags; /* Number of arguments and flags. */ -} CCallInfo; - -#define CCI_NARGS(ci) ((ci)->flags & 0xff) /* # of args. */ -#define CCI_NARGS_MAX 32 /* Max. # of args. */ - -#define CCI_OTSHIFT 16 -#define CCI_OPTYPE(ci) ((ci)->flags >> CCI_OTSHIFT) /* Get op/type. */ -#define CCI_TYPE(ci) (((ci)->flags>>CCI_OTSHIFT) & IRT_TYPE) -#define CCI_OPSHIFT 24 -#define CCI_OP(ci) ((ci)->flags >> CCI_OPSHIFT) /* Get op. */ - -#define CCI_CALL_N (IR_CALLN << CCI_OPSHIFT) -#define CCI_CALL_A (IR_CALLA << CCI_OPSHIFT) -#define CCI_CALL_L (IR_CALLL << CCI_OPSHIFT) -#define CCI_CALL_S (IR_CALLS << CCI_OPSHIFT) -#define CCI_CALL_FN (CCI_CALL_N|CCI_CC_FASTCALL) -#define CCI_CALL_FA (CCI_CALL_A|CCI_CC_FASTCALL) -#define CCI_CALL_FL (CCI_CALL_L|CCI_CC_FASTCALL) -#define CCI_CALL_FS (CCI_CALL_S|CCI_CC_FASTCALL) - -/* C call info flags. */ -#define CCI_T (IRT_GUARD << CCI_OTSHIFT) /* May throw. */ -#define CCI_L 0x0100 /* Implicit L arg. */ -#define CCI_CASTU64 0x0200 /* Cast u64 result to number. */ -#define CCI_NOFPRCLOBBER 0x0400 /* Does not clobber any FPRs. */ -#define CCI_VARARG 0x0800 /* Vararg function. */ - -#define CCI_CC_MASK 0x3000 /* Calling convention mask. */ -#define CCI_CC_SHIFT 12 -/* ORDER CC */ -#define CCI_CC_CDECL 0x0000 /* Default cdecl calling convention. */ -#define CCI_CC_THISCALL 0x1000 /* Thiscall calling convention. */ -#define CCI_CC_FASTCALL 0x2000 /* Fastcall calling convention. */ -#define CCI_CC_STDCALL 0x3000 /* Stdcall calling convention. */ - -/* Extra args for SOFTFP, SPLIT 64 bit. */ -#define CCI_XARGS_SHIFT 14 -#define CCI_XARGS(ci) (((ci)->flags >> CCI_XARGS_SHIFT) & 3) -#define CCI_XA (1u << CCI_XARGS_SHIFT) - -#if LJ_SOFTFP32 || (LJ_32 && LJ_HASFFI) -#define CCI_XNARGS(ci) (CCI_NARGS((ci)) + CCI_XARGS((ci))) -#else -#define CCI_XNARGS(ci) CCI_NARGS((ci)) -#endif - -/* Helpers for conditional function definitions. */ -#define IRCALLCOND_ANY(x) x - -#if LJ_TARGET_X86ORX64 || LJ_TARGET_ARM64 -#define IRCALLCOND_FPMATH(x) NULL -#else -#define IRCALLCOND_FPMATH(x) x -#endif - -#if LJ_SOFTFP -#define IRCALLCOND_SOFTFP(x) x -#if LJ_HASFFI -#define IRCALLCOND_SOFTFP_FFI(x) x -#else -#define IRCALLCOND_SOFTFP_FFI(x) NULL -#endif -#else -#define IRCALLCOND_SOFTFP(x) NULL -#define IRCALLCOND_SOFTFP_FFI(x) NULL -#endif - -#if LJ_SOFTFP && LJ_TARGET_MIPS -#define IRCALLCOND_SOFTFP_MIPS(x) x -#else -#define IRCALLCOND_SOFTFP_MIPS(x) NULL -#endif - -#if LJ_SOFTFP && LJ_TARGET_MIPS64 -#define IRCALLCOND_SOFTFP_MIPS64(x) x -#else -#define IRCALLCOND_SOFTFP_MIPS64(x) NULL -#endif - -#define LJ_NEED_FP64 (LJ_TARGET_ARM || LJ_TARGET_PPC || LJ_TARGET_MIPS) - -#if LJ_HASFFI && (LJ_SOFTFP || LJ_NEED_FP64) -#define IRCALLCOND_FP64_FFI(x) x -#else -#define IRCALLCOND_FP64_FFI(x) NULL -#endif - -#if LJ_HASFFI -#define IRCALLCOND_FFI(x) x -#if LJ_32 -#define IRCALLCOND_FFI32(x) x -#else -#define IRCALLCOND_FFI32(x) NULL -#endif -#else -#define IRCALLCOND_FFI(x) NULL -#define IRCALLCOND_FFI32(x) NULL -#endif - -#if LJ_HASBUFFER -#define IRCALLCOND_BUFFER(x) x -#else -#define IRCALLCOND_BUFFER(x) NULL -#endif - -#if LJ_HASBUFFER && LJ_HASFFI -#define IRCALLCOND_BUFFFI(x) x -#else -#define IRCALLCOND_BUFFFI(x) NULL -#endif - -#if LJ_SOFTFP -#define XA_FP CCI_XA -#define XA2_FP (CCI_XA+CCI_XA) -#else -#define XA_FP 0 -#define XA2_FP 0 -#endif - -#if LJ_SOFTFP32 -#define XA_FP32 CCI_XA -#define XA2_FP32 (CCI_XA+CCI_XA) -#else -#define XA_FP32 0 -#define XA2_FP32 0 -#endif - -#if LJ_32 -#define XA_64 CCI_XA -#define XA2_64 (CCI_XA+CCI_XA) -#else -#define XA_64 0 -#define XA2_64 0 -#endif - -/* Function definitions for CALL* instructions. */ -#define IRCALLDEF(_) \ - _(ANY, lj_str_cmp, 2, FN, INT, CCI_NOFPRCLOBBER) \ - _(ANY, lj_str_find, 4, N, PGC, 0) \ - _(ANY, lj_str_new, 3, S, STR, CCI_L|CCI_T) \ - _(ANY, lj_strscan_num, 2, FN, INT, 0) \ - _(ANY, lj_strfmt_int, 2, FN, STR, CCI_L|CCI_T) \ - _(ANY, lj_strfmt_num, 2, FN, STR, CCI_L|CCI_T) \ - _(ANY, lj_strfmt_char, 2, FN, STR, CCI_L|CCI_T) \ - _(ANY, lj_strfmt_putint, 2, FL, PGC, CCI_T) \ - _(ANY, lj_strfmt_putnum, 2, FL, PGC, CCI_T) \ - _(ANY, lj_strfmt_putquoted, 2, FL, PGC, CCI_T) \ - _(ANY, lj_strfmt_putfxint, 3, L, PGC, XA_64|CCI_T) \ - _(ANY, lj_strfmt_putfnum_int, 3, L, PGC, XA_FP|CCI_T) \ - _(ANY, lj_strfmt_putfnum_uint, 3, L, PGC, XA_FP|CCI_T) \ - _(ANY, lj_strfmt_putfnum, 3, L, PGC, XA_FP|CCI_T) \ - _(ANY, lj_strfmt_putfstr, 3, L, PGC, CCI_T) \ - _(ANY, lj_strfmt_putfchar, 3, L, PGC, CCI_T) \ - _(ANY, lj_buf_putmem, 3, S, PGC, CCI_T) \ - _(ANY, lj_buf_putstr, 2, FL, PGC, CCI_T) \ - _(ANY, lj_buf_putchar, 2, FL, PGC, CCI_T) \ - _(ANY, lj_buf_putstr_reverse, 2, FL, PGC, CCI_T) \ - _(ANY, lj_buf_putstr_lower, 2, FL, PGC, CCI_T) \ - _(ANY, lj_buf_putstr_upper, 2, FL, PGC, CCI_T) \ - _(ANY, lj_buf_putstr_rep, 3, L, PGC, CCI_T) \ - _(ANY, lj_buf_puttab, 5, L, PGC, CCI_T) \ - _(BUFFER, lj_bufx_set, 4, S, NIL, 0) \ - _(BUFFFI, lj_bufx_more, 2, FS, INT, CCI_T) \ - _(BUFFER, lj_serialize_put, 2, FS, PGC, CCI_T) \ - _(BUFFER, lj_serialize_get, 2, FS, PTR, CCI_T) \ - _(BUFFER, lj_serialize_encode, 2, FA, STR, CCI_L|CCI_T) \ - _(BUFFER, lj_serialize_decode, 3, A, INT, CCI_L|CCI_T) \ - _(ANY, lj_buf_tostr, 1, FL, STR, CCI_T) \ - _(ANY, lj_tab_new_ah, 3, A, TAB, CCI_L|CCI_T) \ - _(ANY, lj_tab_new1, 2, FA, TAB, CCI_L|CCI_T) \ - _(ANY, lj_tab_dup, 2, FA, TAB, CCI_L|CCI_T) \ - _(ANY, lj_tab_clear, 1, FS, NIL, 0) \ - _(ANY, lj_tab_newkey, 3, S, PGC, CCI_L|CCI_T) \ - _(ANY, lj_tab_keyindex, 2, FL, INT, 0) \ - _(ANY, lj_vm_next, 2, FL, PTR, 0) \ - _(ANY, lj_tab_len, 1, FL, INT, 0) \ - _(ANY, lj_tab_len_hint, 2, FL, INT, 0) \ - _(ANY, lj_gc_step_jit, 2, FS, NIL, CCI_L) \ - _(ANY, lj_gc_barrieruv, 2, FS, NIL, 0) \ - _(ANY, lj_mem_newgco, 2, FA, PGC, CCI_L|CCI_T) \ - _(ANY, lj_prng_u64d, 1, FS, NUM, CCI_CASTU64) \ - _(ANY, lj_vm_modi, 2, FN, INT, 0) \ - _(ANY, log10, 1, N, NUM, XA_FP) \ - _(ANY, exp, 1, N, NUM, XA_FP) \ - _(ANY, sin, 1, N, NUM, XA_FP) \ - _(ANY, cos, 1, N, NUM, XA_FP) \ - _(ANY, tan, 1, N, NUM, XA_FP) \ - _(ANY, asin, 1, N, NUM, XA_FP) \ - _(ANY, acos, 1, N, NUM, XA_FP) \ - _(ANY, atan, 1, N, NUM, XA_FP) \ - _(ANY, sinh, 1, N, NUM, XA_FP) \ - _(ANY, cosh, 1, N, NUM, XA_FP) \ - _(ANY, tanh, 1, N, NUM, XA_FP) \ - _(ANY, fputc, 2, S, INT, 0) \ - _(ANY, fwrite, 4, S, INT, 0) \ - _(ANY, fflush, 1, S, INT, 0) \ - /* ORDER FPM */ \ - _(FPMATH, lj_vm_floor, 1, N, NUM, XA_FP) \ - _(FPMATH, lj_vm_ceil, 1, N, NUM, XA_FP) \ - _(FPMATH, lj_vm_trunc, 1, N, NUM, XA_FP) \ - _(FPMATH, sqrt, 1, N, NUM, XA_FP) \ - _(ANY, log, 1, N, NUM, XA_FP) \ - _(ANY, lj_vm_log2, 1, N, NUM, XA_FP) \ - _(ANY, pow, 2, N, NUM, XA2_FP) \ - _(ANY, atan2, 2, N, NUM, XA2_FP) \ - _(ANY, ldexp, 2, N, NUM, XA_FP) \ - _(SOFTFP, lj_vm_tobit, 1, N, INT, XA_FP32) \ - _(SOFTFP, softfp_add, 2, N, NUM, XA2_FP32) \ - _(SOFTFP, softfp_sub, 2, N, NUM, XA2_FP32) \ - _(SOFTFP, softfp_mul, 2, N, NUM, XA2_FP32) \ - _(SOFTFP, softfp_div, 2, N, NUM, XA2_FP32) \ - _(SOFTFP, softfp_cmp, 2, N, NIL, XA2_FP32) \ - _(SOFTFP, softfp_i2d, 1, N, NUM, 0) \ - _(SOFTFP, softfp_d2i, 1, N, INT, XA_FP32) \ - _(SOFTFP_MIPS, lj_vm_sfmin, 2, N, NUM, XA2_FP32) \ - _(SOFTFP_MIPS, lj_vm_sfmax, 2, N, NUM, XA2_FP32) \ - _(SOFTFP_MIPS64, lj_vm_tointg, 1, N, INT, 0) \ - _(SOFTFP_FFI, softfp_ui2d, 1, N, NUM, 0) \ - _(SOFTFP_FFI, softfp_f2d, 1, N, NUM, 0) \ - _(SOFTFP_FFI, softfp_d2f, 1, N, FLOAT, XA_FP32) \ - _(SOFTFP_FFI, softfp_i2f, 1, N, FLOAT, 0) \ - _(SOFTFP_FFI, softfp_ui2f, 1, N, FLOAT, 0) \ - _(SOFTFP_FFI, softfp_f2i, 1, N, INT, 0) \ - _(FP64_FFI, fp64_l2d, 1, N, NUM, XA_64) \ - _(FP64_FFI, fp64_ul2d, 1, N, NUM, XA_64) \ - _(FP64_FFI, fp64_l2f, 1, N, FLOAT, XA_64) \ - _(FP64_FFI, fp64_ul2f, 1, N, FLOAT, XA_64) \ - _(FP64_FFI, lj_vm_num2u64, 1, N, U64, XA_FP) \ - _(FFI, lj_carith_divi64, 2, N, I64, XA2_64|CCI_NOFPRCLOBBER) \ - _(FFI, lj_carith_divu64, 2, N, U64, XA2_64|CCI_NOFPRCLOBBER) \ - _(FFI, lj_carith_modi64, 2, N, I64, XA2_64|CCI_NOFPRCLOBBER) \ - _(FFI, lj_carith_modu64, 2, N, U64, XA2_64|CCI_NOFPRCLOBBER) \ - _(FFI, lj_carith_powi64, 2, N, I64, XA2_64|CCI_NOFPRCLOBBER) \ - _(FFI, lj_carith_powu64, 2, N, U64, XA2_64|CCI_NOFPRCLOBBER) \ - _(FFI, lj_cdata_newv, 4, S, CDATA, CCI_L) \ - _(FFI, lj_cdata_setfin, 4, S, NIL, CCI_L) \ - _(FFI, strlen, 1, L, INTP, 0) \ - _(FFI, memcpy, 3, S, PTR, 0) \ - _(FFI, memset, 3, S, PTR, 0) \ - _(FFI, lj_vm_errno, 0, S, INT, CCI_NOFPRCLOBBER) \ - _(FFI32, lj_carith_mul64, 2, N, I64, XA2_64|CCI_NOFPRCLOBBER) \ - _(FFI32, lj_carith_shl64, 2, N, U64, XA_64|CCI_NOFPRCLOBBER) \ - _(FFI32, lj_carith_shr64, 2, N, U64, XA_64|CCI_NOFPRCLOBBER) \ - _(FFI32, lj_carith_sar64, 2, N, U64, XA_64|CCI_NOFPRCLOBBER) \ - _(FFI32, lj_carith_rol64, 2, N, U64, XA_64|CCI_NOFPRCLOBBER) \ - _(FFI32, lj_carith_ror64, 2, N, U64, XA_64|CCI_NOFPRCLOBBER) \ - \ - /* End of list. */ - -typedef enum { -#define IRCALLENUM(cond, name, nargs, kind, type, flags) IRCALL_##name, -IRCALLDEF(IRCALLENUM) -#undef IRCALLENUM - IRCALL__MAX -} IRCallID; - -LJ_FUNC TRef lj_ir_call(jit_State *J, IRCallID id, ...); - -LJ_DATA const CCallInfo lj_ir_callinfo[IRCALL__MAX+1]; - -/* Soft-float declarations. */ -#if LJ_SOFTFP -#if LJ_TARGET_ARM -#define softfp_add __aeabi_dadd -#define softfp_sub __aeabi_dsub -#define softfp_mul __aeabi_dmul -#define softfp_div __aeabi_ddiv -#define softfp_cmp __aeabi_cdcmple -#define softfp_i2d __aeabi_i2d -#define softfp_d2i __aeabi_d2iz -#define softfp_ui2d __aeabi_ui2d -#define softfp_f2d __aeabi_f2d -#define softfp_d2f __aeabi_d2f -#define softfp_i2f __aeabi_i2f -#define softfp_ui2f __aeabi_ui2f -#define softfp_f2i __aeabi_f2iz -#define fp64_l2d __aeabi_l2d -#define fp64_ul2d __aeabi_ul2d -#define fp64_l2f __aeabi_l2f -#define fp64_ul2f __aeabi_ul2f -#elif LJ_TARGET_MIPS || LJ_TARGET_PPC -#define softfp_add __adddf3 -#define softfp_sub __subdf3 -#define softfp_mul __muldf3 -#define softfp_div __divdf3 -#define softfp_cmp __ledf2 -#define softfp_i2d __floatsidf -#define softfp_d2i __fixdfsi -#define softfp_ui2d __floatunsidf -#define softfp_f2d __extendsfdf2 -#define softfp_d2f __truncdfsf2 -#define softfp_i2f __floatsisf -#define softfp_ui2f __floatunsisf -#define softfp_f2i __fixsfsi -#else -#error "Missing soft-float definitions for target architecture" -#endif -extern double softfp_add(double a, double b); -extern double softfp_sub(double a, double b); -extern double softfp_mul(double a, double b); -extern double softfp_div(double a, double b); -extern void softfp_cmp(double a, double b); -extern double softfp_i2d(int32_t a); -extern int32_t softfp_d2i(double a); -#if LJ_HASFFI -extern double softfp_ui2d(uint32_t a); -extern double softfp_f2d(float a); -extern float softfp_d2f(double a); -extern float softfp_i2f(int32_t a); -extern float softfp_ui2f(uint32_t a); -extern int32_t softfp_f2i(float a); -#endif -#if LJ_TARGET_MIPS -extern double lj_vm_sfmin(double a, double b); -extern double lj_vm_sfmax(double a, double b); -#endif -#endif - -#if LJ_HASFFI && LJ_NEED_FP64 && !(LJ_TARGET_ARM && LJ_SOFTFP) -#if defined(__GNUC__) || defined(__clang__) -#define fp64_l2d __floatdidf -#define fp64_ul2d __floatundidf -#define fp64_l2f __floatdisf -#define fp64_ul2f __floatundisf -#else -#error "Missing fp64 helper definitions for this compiler" -#endif -#endif - -#if LJ_HASFFI && (LJ_SOFTFP || LJ_NEED_FP64) -extern double fp64_l2d(int64_t a); -extern double fp64_ul2d(uint64_t a); -extern float fp64_l2f(int64_t a); -extern float fp64_ul2f(uint64_t a); -#endif - -#endif diff --git a/include/luajit/lj_iropt.h b/include/luajit/lj_iropt.h deleted file mode 100644 index b9fb13e..0000000 --- a/include/luajit/lj_iropt.h +++ /dev/null @@ -1,168 +0,0 @@ -/* -** Common header for IR emitter and optimizations. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_IROPT_H -#define _LJ_IROPT_H - -#include - -#include "lj_obj.h" -#include "lj_jit.h" - -#if LJ_HASJIT -/* IR emitter. */ -LJ_FUNC void LJ_FASTCALL lj_ir_growtop(jit_State *J); -LJ_FUNC TRef LJ_FASTCALL lj_ir_emit(jit_State *J); - -/* Save current IR in J->fold.ins, but do not emit it (yet). */ -static LJ_AINLINE void lj_ir_set_(jit_State *J, uint16_t ot, IRRef1 a, IRRef1 b) -{ - J->fold.ins.ot = ot; J->fold.ins.op1 = a; J->fold.ins.op2 = b; -} - -#define lj_ir_set(J, ot, a, b) \ - lj_ir_set_(J, (uint16_t)(ot), (IRRef1)(a), (IRRef1)(b)) - -/* Get ref of next IR instruction and optionally grow IR. -** Note: this may invalidate all IRIns*! -*/ -static LJ_AINLINE IRRef lj_ir_nextins(jit_State *J) -{ - IRRef ref = J->cur.nins; - if (LJ_UNLIKELY(ref >= J->irtoplim)) lj_ir_growtop(J); - J->cur.nins = ref + 1; - return ref; -} - -LJ_FUNC TRef lj_ir_ggfload(jit_State *J, IRType t, uintptr_t ofs); - -/* Interning of constants. */ -LJ_FUNC TRef LJ_FASTCALL lj_ir_kint(jit_State *J, int32_t k); -LJ_FUNC TRef lj_ir_k64(jit_State *J, IROp op, uint64_t u64); -LJ_FUNC TRef lj_ir_knum_u64(jit_State *J, uint64_t u64); -LJ_FUNC TRef lj_ir_knumint(jit_State *J, lua_Number n); -LJ_FUNC TRef lj_ir_kint64(jit_State *J, uint64_t u64); -LJ_FUNC TRef lj_ir_kgc(jit_State *J, GCobj *o, IRType t); -LJ_FUNC TRef lj_ir_kptr_(jit_State *J, IROp op, void *ptr); -LJ_FUNC TRef lj_ir_knull(jit_State *J, IRType t); -LJ_FUNC TRef lj_ir_kslot(jit_State *J, TRef key, IRRef slot); -LJ_FUNC TRef lj_ir_ktrace(jit_State *J); - -#if LJ_64 -#define lj_ir_kintp(J, k) lj_ir_kint64(J, (uint64_t)(k)) -#else -#define lj_ir_kintp(J, k) lj_ir_kint(J, (int32_t)(k)) -#endif - -#if LJ_GC64 -#define lj_ir_kintpgc lj_ir_kintp -#else -#define lj_ir_kintpgc lj_ir_kint -#endif - -static LJ_AINLINE TRef lj_ir_knum(jit_State *J, lua_Number n) -{ - TValue tv; - tv.n = n; - return lj_ir_knum_u64(J, tv.u64); -} - -#define lj_ir_kstr(J, str) lj_ir_kgc(J, obj2gco((str)), IRT_STR) -#define lj_ir_ktab(J, tab) lj_ir_kgc(J, obj2gco((tab)), IRT_TAB) -#define lj_ir_kfunc(J, func) lj_ir_kgc(J, obj2gco((func)), IRT_FUNC) -#define lj_ir_kptr(J, ptr) lj_ir_kptr_(J, IR_KPTR, (ptr)) -#define lj_ir_kkptr(J, ptr) lj_ir_kptr_(J, IR_KKPTR, (ptr)) - -/* Special FP constants. */ -#define lj_ir_knum_zero(J) lj_ir_knum_u64(J, U64x(00000000,00000000)) -#define lj_ir_knum_one(J) lj_ir_knum_u64(J, U64x(3ff00000,00000000)) -#define lj_ir_knum_tobit(J) lj_ir_knum_u64(J, U64x(43380000,00000000)) - -/* Special 128 bit SIMD constants. */ -#define lj_ir_ksimd(J, idx) \ - lj_ir_ggfload(J, IRT_NUM, (uintptr_t)LJ_KSIMD(J, idx) - (uintptr_t)J2GG(J)) - -/* Access to constants. */ -LJ_FUNC void lj_ir_kvalue(lua_State *L, TValue *tv, const IRIns *ir); - -/* Convert IR operand types. */ -LJ_FUNC TRef LJ_FASTCALL lj_ir_tonumber(jit_State *J, TRef tr); -LJ_FUNC TRef LJ_FASTCALL lj_ir_tonum(jit_State *J, TRef tr); -LJ_FUNC TRef LJ_FASTCALL lj_ir_tostr(jit_State *J, TRef tr); - -/* Miscellaneous IR ops. */ -LJ_FUNC int lj_ir_numcmp(lua_Number a, lua_Number b, IROp op); -LJ_FUNC int lj_ir_strcmp(GCstr *a, GCstr *b, IROp op); -LJ_FUNC void lj_ir_rollback(jit_State *J, IRRef ref); - -/* Emit IR instructions with on-the-fly optimizations. */ -LJ_FUNC TRef LJ_FASTCALL lj_opt_fold(jit_State *J); -LJ_FUNC TRef LJ_FASTCALL lj_opt_cse(jit_State *J); -LJ_FUNC TRef LJ_FASTCALL lj_opt_cselim(jit_State *J, IRRef lim); - -/* Special return values for the fold functions. */ -enum { - NEXTFOLD, /* Couldn't fold, pass on. */ - RETRYFOLD, /* Retry fold with modified fins. */ - KINTFOLD, /* Return ref for int constant in fins->i. */ - FAILFOLD, /* Guard would always fail. */ - DROPFOLD, /* Guard eliminated. */ - MAX_FOLD -}; - -#define INTFOLD(k) ((J->fold.ins.i = (k)), (TRef)KINTFOLD) -#define INT64FOLD(k) (lj_ir_kint64(J, (k))) -#define CONDFOLD(cond) ((TRef)FAILFOLD + (TRef)(cond)) -#define LEFTFOLD (J->fold.ins.op1) -#define RIGHTFOLD (J->fold.ins.op2) -#define CSEFOLD (lj_opt_cse(J)) -#define EMITFOLD (lj_ir_emit(J)) - -/* Load/store forwarding. */ -LJ_FUNC TRef LJ_FASTCALL lj_opt_fwd_aload(jit_State *J); -LJ_FUNC TRef LJ_FASTCALL lj_opt_fwd_hload(jit_State *J); -LJ_FUNC TRef LJ_FASTCALL lj_opt_fwd_uload(jit_State *J); -LJ_FUNC TRef LJ_FASTCALL lj_opt_fwd_fload(jit_State *J); -LJ_FUNC TRef LJ_FASTCALL lj_opt_fwd_xload(jit_State *J); -LJ_FUNC TRef LJ_FASTCALL lj_opt_fwd_alen(jit_State *J); -LJ_FUNC TRef LJ_FASTCALL lj_opt_fwd_hrefk(jit_State *J); -LJ_FUNC int LJ_FASTCALL lj_opt_fwd_href_nokey(jit_State *J); -LJ_FUNC int LJ_FASTCALL lj_opt_fwd_tptr(jit_State *J, IRRef lim); -LJ_FUNC int LJ_FASTCALL lj_opt_fwd_sbuf(jit_State *J, IRRef lim); -LJ_FUNC int lj_opt_fwd_wasnonnil(jit_State *J, IROpT loadop, IRRef xref); - -/* Dead-store elimination. */ -LJ_FUNC TRef LJ_FASTCALL lj_opt_dse_ahstore(jit_State *J); -LJ_FUNC TRef LJ_FASTCALL lj_opt_dse_ustore(jit_State *J); -LJ_FUNC TRef LJ_FASTCALL lj_opt_dse_fstore(jit_State *J); -LJ_FUNC TRef LJ_FASTCALL lj_opt_dse_xstore(jit_State *J); - -/* Narrowing. */ -LJ_FUNC TRef LJ_FASTCALL lj_opt_narrow_convert(jit_State *J); -LJ_FUNC TRef LJ_FASTCALL lj_opt_narrow_index(jit_State *J, TRef key); -LJ_FUNC TRef LJ_FASTCALL lj_opt_narrow_toint(jit_State *J, TRef tr); -LJ_FUNC TRef LJ_FASTCALL lj_opt_narrow_tobit(jit_State *J, TRef tr); -#if LJ_HASFFI -LJ_FUNC TRef LJ_FASTCALL lj_opt_narrow_cindex(jit_State *J, TRef key); -#endif -LJ_FUNC TRef lj_opt_narrow_arith(jit_State *J, TRef rb, TRef rc, - TValue *vb, TValue *vc, IROp op); -LJ_FUNC TRef lj_opt_narrow_unm(jit_State *J, TRef rc, TValue *vc); -LJ_FUNC TRef lj_opt_narrow_mod(jit_State *J, TRef rb, TRef rc, TValue *vb, TValue *vc); -LJ_FUNC IRType lj_opt_narrow_forl(jit_State *J, cTValue *forbase); - -/* Optimization passes. */ -LJ_FUNC void lj_opt_dce(jit_State *J); -LJ_FUNC int lj_opt_loop(jit_State *J); -#if LJ_SOFTFP32 || (LJ_32 && LJ_HASFFI) -LJ_FUNC void lj_opt_split(jit_State *J); -#else -#define lj_opt_split(J) UNUSED(J) -#endif -LJ_FUNC void lj_opt_sink(jit_State *J); - -#endif - -#endif diff --git a/include/luajit/lj_jit.h b/include/luajit/lj_jit.h deleted file mode 100644 index c052345..0000000 --- a/include/luajit/lj_jit.h +++ /dev/null @@ -1,529 +0,0 @@ -/* -** Common definitions for the JIT compiler. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_JIT_H -#define _LJ_JIT_H - -#include "lj_obj.h" -#if LJ_HASJIT -#include "lj_ir.h" - -/* -- JIT engine flags ---------------------------------------------------- */ - -/* General JIT engine flags. 4 bits. */ -#define JIT_F_ON 0x00000001 - -/* CPU-specific JIT engine flags. 12 bits. Flags and strings must match. */ -#define JIT_F_CPU 0x00000010 - -#if LJ_TARGET_X86ORX64 - -#define JIT_F_SSE3 (JIT_F_CPU << 0) -#define JIT_F_SSE4_1 (JIT_F_CPU << 1) -#define JIT_F_BMI2 (JIT_F_CPU << 2) - - -#define JIT_F_CPUSTRING "\4SSE3\6SSE4.1\4BMI2" - -#elif LJ_TARGET_ARM - -#define JIT_F_ARMV6_ (JIT_F_CPU << 0) -#define JIT_F_ARMV6T2_ (JIT_F_CPU << 1) -#define JIT_F_ARMV7 (JIT_F_CPU << 2) -#define JIT_F_ARMV8 (JIT_F_CPU << 3) -#define JIT_F_VFPV2 (JIT_F_CPU << 4) -#define JIT_F_VFPV3 (JIT_F_CPU << 5) - -#define JIT_F_ARMV6 (JIT_F_ARMV6_|JIT_F_ARMV6T2_|JIT_F_ARMV7|JIT_F_ARMV8) -#define JIT_F_ARMV6T2 (JIT_F_ARMV6T2_|JIT_F_ARMV7|JIT_F_ARMV8) -#define JIT_F_VFP (JIT_F_VFPV2|JIT_F_VFPV3) - -#define JIT_F_CPUSTRING "\5ARMv6\7ARMv6T2\5ARMv7\5ARMv8\5VFPv2\5VFPv3" - -#elif LJ_TARGET_PPC - -#define JIT_F_SQRT (JIT_F_CPU << 0) -#define JIT_F_ROUND (JIT_F_CPU << 1) - -#define JIT_F_CPUSTRING "\4SQRT\5ROUND" - -#elif LJ_TARGET_MIPS - -#define JIT_F_MIPSXXR2 (JIT_F_CPU << 0) - -#if LJ_TARGET_MIPS32 -#if LJ_TARGET_MIPSR6 -#define JIT_F_CPUSTRING "\010MIPS32R6" -#else -#define JIT_F_CPUSTRING "\010MIPS32R2" -#endif -#else -#if LJ_TARGET_MIPSR6 -#define JIT_F_CPUSTRING "\010MIPS64R6" -#else -#define JIT_F_CPUSTRING "\010MIPS64R2" -#endif -#endif - -#else - -#define JIT_F_CPUSTRING "" - -#endif - -/* Optimization flags. 12 bits. */ -#define JIT_F_OPT 0x00010000 -#define JIT_F_OPT_MASK 0x0fff0000 - -#define JIT_F_OPT_FOLD (JIT_F_OPT << 0) -#define JIT_F_OPT_CSE (JIT_F_OPT << 1) -#define JIT_F_OPT_DCE (JIT_F_OPT << 2) -#define JIT_F_OPT_FWD (JIT_F_OPT << 3) -#define JIT_F_OPT_DSE (JIT_F_OPT << 4) -#define JIT_F_OPT_NARROW (JIT_F_OPT << 5) -#define JIT_F_OPT_LOOP (JIT_F_OPT << 6) -#define JIT_F_OPT_ABC (JIT_F_OPT << 7) -#define JIT_F_OPT_SINK (JIT_F_OPT << 8) -#define JIT_F_OPT_FUSE (JIT_F_OPT << 9) -#define JIT_F_OPT_FMA (JIT_F_OPT << 10) - -/* Optimizations names for -O. Must match the order above. */ -#define JIT_F_OPTSTRING \ - "\4fold\3cse\3dce\3fwd\3dse\6narrow\4loop\3abc\4sink\4fuse\3fma" - -/* Optimization levels set a fixed combination of flags. */ -#define JIT_F_OPT_0 0 -#define JIT_F_OPT_1 (JIT_F_OPT_FOLD|JIT_F_OPT_CSE|JIT_F_OPT_DCE) -#define JIT_F_OPT_2 (JIT_F_OPT_1|JIT_F_OPT_NARROW|JIT_F_OPT_LOOP) -#define JIT_F_OPT_3 (JIT_F_OPT_2|\ - JIT_F_OPT_FWD|JIT_F_OPT_DSE|JIT_F_OPT_ABC|JIT_F_OPT_SINK|JIT_F_OPT_FUSE) -#define JIT_F_OPT_DEFAULT JIT_F_OPT_3 -/* Note: FMA is not set by default. */ - -/* -- JIT engine parameters ----------------------------------------------- */ - -/* Optimization parameters and their defaults. Length is a char in octal! */ -#define JIT_PARAMDEF(_) \ - _(\010, maxtrace, 1000) /* Max. # of traces in cache. */ \ - _(\011, maxrecord, 4000) /* Max. # of recorded IR instructions. */ \ - _(\012, maxirconst, 500) /* Max. # of IR constants of a trace. */ \ - _(\007, maxside, 100) /* Max. # of side traces of a root trace. */ \ - _(\007, maxsnap, 500) /* Max. # of snapshots for a trace. */ \ - _(\011, minstitch, 0) /* Min. # of IR ins for a stitched trace. */ \ - \ - _(\007, hotloop, 56) /* # of iter. to detect a hot loop/call. */ \ - _(\007, hotexit, 10) /* # of taken exits to start a side trace. */ \ - _(\007, tryside, 4) /* # of attempts to compile a side trace. */ \ - \ - _(\012, instunroll, 4) /* Max. unroll for instable loops. */ \ - _(\012, loopunroll, 15) /* Max. unroll for loop ops in side traces. */ \ - _(\012, callunroll, 3) /* Max. unroll for recursive calls. */ \ - _(\011, recunroll, 2) /* Min. unroll for true recursion. */ \ - \ - /* Size of each machine code area (in KBytes). */ \ - _(\011, sizemcode, 64) \ - /* Max. total size of all machine code areas (in KBytes). */ \ - _(\010, maxmcode, 2048) \ - /* End of list. */ - -enum { -#define JIT_PARAMENUM(len, name, value) JIT_P_##name, -JIT_PARAMDEF(JIT_PARAMENUM) -#undef JIT_PARAMENUM - JIT_P__MAX -}; - -#define JIT_PARAMSTR(len, name, value) #len #name -#define JIT_P_STRING JIT_PARAMDEF(JIT_PARAMSTR) - -/* -- JIT engine data structures ------------------------------------------ */ - -/* Trace compiler state. */ -typedef enum { - LJ_TRACE_IDLE, /* Trace compiler idle. */ - LJ_TRACE_ACTIVE = 0x10, - LJ_TRACE_RECORD, /* Bytecode recording active. */ - LJ_TRACE_RECORD_1ST, /* Record 1st instruction, too. */ - LJ_TRACE_START, /* New trace started. */ - LJ_TRACE_END, /* End of trace. */ - LJ_TRACE_ASM, /* Assemble trace. */ - LJ_TRACE_ERR /* Trace aborted with error. */ -} TraceState; - -/* Post-processing action. */ -typedef enum { - LJ_POST_NONE, /* No action. */ - LJ_POST_FIXCOMP, /* Fixup comparison and emit pending guard. */ - LJ_POST_FIXGUARD, /* Fixup and emit pending guard. */ - LJ_POST_FIXGUARDSNAP, /* Fixup and emit pending guard and snapshot. */ - LJ_POST_FIXBOOL, /* Fixup boolean result. */ - LJ_POST_FIXCONST, /* Fixup constant results. */ - LJ_POST_FFRETRY /* Suppress recording of retried fast functions. */ -} PostProc; - -/* Machine code type. */ -#if LJ_TARGET_X86ORX64 -typedef uint8_t MCode; -#else -typedef uint32_t MCode; -#endif - -/* Linked list of MCode areas. */ -typedef struct MCLink { - MCode *next; /* Next area. */ - size_t size; /* Size of current area. */ -} MCLink; - -/* Stack snapshot header. */ -typedef struct SnapShot { - uint32_t mapofs; /* Offset into snapshot map. */ - IRRef1 ref; /* First IR ref for this snapshot. */ - uint16_t mcofs; /* Offset into machine code in MCode units. */ - uint8_t nslots; /* Number of valid slots. */ - uint8_t topslot; /* Maximum frame extent. */ - uint8_t nent; /* Number of compressed entries. */ - uint8_t count; /* Count of taken exits for this snapshot. */ -} SnapShot; - -#define SNAPCOUNT_DONE 255 /* Already compiled and linked a side trace. */ - -/* Compressed snapshot entry. */ -typedef uint32_t SnapEntry; - -#define SNAP_FRAME 0x010000 /* Frame slot. */ -#define SNAP_CONT 0x020000 /* Continuation slot. */ -#define SNAP_NORESTORE 0x040000 /* No need to restore slot. */ -#define SNAP_SOFTFPNUM 0x080000 /* Soft-float number. */ -#define SNAP_KEYINDEX 0x100000 /* Traversal key index. */ -LJ_STATIC_ASSERT(SNAP_FRAME == TREF_FRAME); -LJ_STATIC_ASSERT(SNAP_CONT == TREF_CONT); -LJ_STATIC_ASSERT(SNAP_KEYINDEX == TREF_KEYINDEX); - -#define SNAP(slot, flags, ref) (((SnapEntry)(slot) << 24) + (flags) + (ref)) -#define SNAP_TR(slot, tr) \ - (((SnapEntry)(slot) << 24) + \ - ((tr) & (TREF_KEYINDEX|TREF_CONT|TREF_FRAME|TREF_REFMASK))) -#if !LJ_FR2 -#define SNAP_MKPC(pc) ((SnapEntry)u32ptr(pc)) -#endif -#define SNAP_MKFTSZ(ftsz) ((SnapEntry)(ftsz)) -#define snap_ref(sn) ((sn) & 0xffff) -#define snap_slot(sn) ((BCReg)((sn) >> 24)) -#define snap_isframe(sn) ((sn) & SNAP_FRAME) -#define snap_setref(sn, ref) (((sn) & (0xffff0000&~SNAP_NORESTORE)) | (ref)) - -static LJ_AINLINE const BCIns *snap_pc(SnapEntry *sn) -{ -#if LJ_FR2 - uint64_t pcbase; - memcpy(&pcbase, sn, sizeof(uint64_t)); - return (const BCIns *)(pcbase >> 8); -#else - return (const BCIns *)(uintptr_t)*sn; -#endif -} - -/* Snapshot and exit numbers. */ -typedef uint32_t SnapNo; -typedef uint32_t ExitNo; - -/* Trace number. */ -typedef uint32_t TraceNo; /* Used to pass around trace numbers. */ -typedef uint16_t TraceNo1; /* Stored trace number. */ - -/* Type of link. ORDER LJ_TRLINK */ -typedef enum { - LJ_TRLINK_NONE, /* Incomplete trace. No link, yet. */ - LJ_TRLINK_ROOT, /* Link to other root trace. */ - LJ_TRLINK_LOOP, /* Loop to same trace. */ - LJ_TRLINK_TAILREC, /* Tail-recursion. */ - LJ_TRLINK_UPREC, /* Up-recursion. */ - LJ_TRLINK_DOWNREC, /* Down-recursion. */ - LJ_TRLINK_INTERP, /* Fallback to interpreter. */ - LJ_TRLINK_RETURN, /* Return to interpreter. */ - LJ_TRLINK_STITCH /* Trace stitching. */ -} TraceLink; - -/* Trace object. */ -typedef struct GCtrace { - GCHeader; - uint16_t nsnap; /* Number of snapshots. */ - IRRef nins; /* Next IR instruction. Biased with REF_BIAS. */ -#if LJ_GC64 - uint32_t unused_gc64; -#endif - GCRef gclist; - IRIns *ir; /* IR instructions/constants. Biased with REF_BIAS. */ - IRRef nk; /* Lowest IR constant. Biased with REF_BIAS. */ - uint32_t nsnapmap; /* Number of snapshot map elements. */ - SnapShot *snap; /* Snapshot array. */ - SnapEntry *snapmap; /* Snapshot map. */ - GCRef startpt; /* Starting prototype. */ - MRef startpc; /* Bytecode PC of starting instruction. */ - BCIns startins; /* Original bytecode of starting instruction. */ - MSize szmcode; /* Size of machine code. */ - MCode *mcode; /* Start of machine code. */ -#if LJ_ABI_PAUTH - ASMFunction mcauth; /* Start of machine code, with ptr auth applied. */ -#endif - MSize mcloop; /* Offset of loop start in machine code. */ - uint16_t nchild; /* Number of child traces (root trace only). */ - uint16_t spadjust; /* Stack pointer adjustment (offset in bytes). */ - TraceNo1 traceno; /* Trace number. */ - TraceNo1 link; /* Linked trace (or self for loops). */ - TraceNo1 root; /* Root trace of side trace (or 0 for root traces). */ - TraceNo1 nextroot; /* Next root trace for same prototype. */ - TraceNo1 nextside; /* Next side trace of same root trace. */ - uint8_t sinktags; /* Trace has SINK tags. */ - uint8_t topslot; /* Top stack slot already checked to be allocated. */ - uint8_t linktype; /* Type of link. */ - uint8_t unused1; -#ifdef LUAJIT_USE_GDBJIT - void *gdbjit_entry; /* GDB JIT entry. */ -#endif -} GCtrace; - -#define gco2trace(o) check_exp((o)->gch.gct == ~LJ_TTRACE, (GCtrace *)(o)) -#define traceref(J, n) \ - check_exp((n)>0 && (MSize)(n)sizetrace, (GCtrace *)gcref(J->trace[(n)])) - -LJ_STATIC_ASSERT(offsetof(GChead, gclist) == offsetof(GCtrace, gclist)); - -static LJ_AINLINE MSize snap_nextofs(GCtrace *T, SnapShot *snap) -{ - if (snap+1 == &T->snap[T->nsnap]) - return T->nsnapmap; - else - return (snap+1)->mapofs; -} - -/* Round-robin penalty cache for bytecodes leading to aborted traces. */ -typedef struct HotPenalty { - MRef pc; /* Starting bytecode PC. */ - uint16_t val; /* Penalty value, i.e. hotcount start. */ - uint16_t reason; /* Abort reason (really TraceErr). */ -} HotPenalty; - -#define PENALTY_SLOTS 64 /* Penalty cache slot. Must be a power of 2. */ -#define PENALTY_MIN (36*2) /* Minimum penalty value. */ -#define PENALTY_MAX 60000 /* Maximum penalty value. */ -#define PENALTY_RNDBITS 4 /* # of random bits to add to penalty value. */ - -/* Round-robin backpropagation cache for narrowing conversions. */ -typedef struct BPropEntry { - IRRef1 key; /* Key: original reference. */ - IRRef1 val; /* Value: reference after conversion. */ - IRRef mode; /* Mode for this entry (currently IRCONV_*). */ -} BPropEntry; - -/* Number of slots for the backpropagation cache. Must be a power of 2. */ -#define BPROP_SLOTS 16 - -/* Scalar evolution analysis cache. */ -typedef struct ScEvEntry { - MRef pc; /* Bytecode PC of FORI. */ - IRRef1 idx; /* Index reference. */ - IRRef1 start; /* Constant start reference. */ - IRRef1 stop; /* Constant stop reference. */ - IRRef1 step; /* Constant step reference. */ - IRType1 t; /* Scalar type. */ - uint8_t dir; /* Direction. 1: +, 0: -. */ -} ScEvEntry; - -/* Reverse bytecode map (IRRef -> PC). Only for selected instructions. */ -typedef struct RBCHashEntry { - MRef pc; /* Bytecode PC. */ - GCRef pt; /* Prototype. */ - IRRef ref; /* IR reference. */ -} RBCHashEntry; - -/* Number of slots in the reverse bytecode hash table. Must be a power of 2. */ -#define RBCHASH_SLOTS 8 - -/* 128 bit SIMD constants. */ -enum { - LJ_KSIMD_ABS, - LJ_KSIMD_NEG, - LJ_KSIMD__MAX -}; - -enum { -#if LJ_TARGET_X64 || LJ_TARGET_MIPS64 - LJ_K64_M2P64, /* -2^64 */ -#endif -#if LJ_TARGET_X86ORX64 - LJ_K64_TOBIT, /* 2^52 + 2^51 */ - LJ_K64_2P64, /* 2^64 */ -#endif -#if LJ_TARGET_MIPS64 - LJ_K64_2P63, /* 2^63 */ -#endif -#if LJ_TARGET_MIPS - LJ_K64_2P31, /* 2^31 */ -#endif -#if LJ_TARGET_ARM64 || LJ_TARGET_MIPS64 - LJ_K64_VM_EXIT_HANDLER, - LJ_K64_VM_EXIT_INTERP, -#endif - LJ_K64__MAX, -}; -#define LJ_K64__USED (LJ_TARGET_X86ORX64 || LJ_TARGET_ARM64 || LJ_TARGET_MIPS) - -enum { -#if LJ_TARGET_X86ORX64 || LJ_TARGET_MIPS64 - LJ_K32_M2P64, /* -2^64 */ -#endif -#if LJ_TARGET_MIPS64 - LJ_K32_2P63, /* 2^63 */ -#endif -#if LJ_TARGET_PPC - LJ_K32_2P52_2P31, /* 2^52 + 2^31 */ - LJ_K32_2P52, /* 2^52 */ -#endif -#if LJ_TARGET_PPC - LJ_K32_2P31, /* 2^31 */ -#endif -#if LJ_TARGET_PPC || LJ_TARGET_MIPS32 - LJ_K32_VM_EXIT_HANDLER, - LJ_K32_VM_EXIT_INTERP, -#endif - LJ_K32__MAX -}; -#define LJ_K32__USED (LJ_TARGET_X86ORX64 || LJ_TARGET_PPC || LJ_TARGET_MIPS) - -/* Get 16 byte aligned pointer to SIMD constant. */ -#define LJ_KSIMD(J, n) \ - ((TValue *)(((intptr_t)&J->ksimd[2*(n)] + 15) & ~(intptr_t)15)) - -/* Set/reset flag to activate the SPLIT pass for the current trace. */ -#if LJ_SOFTFP32 || (LJ_32 && LJ_HASFFI) -#define lj_needsplit(J) (J->needsplit = 1) -#define lj_resetsplit(J) (J->needsplit = 0) -#else -#define lj_needsplit(J) UNUSED(J) -#define lj_resetsplit(J) UNUSED(J) -#endif - -/* Fold state is used to fold instructions on-the-fly. */ -typedef struct FoldState { - IRIns ins; /* Currently emitted instruction. */ - IRIns left[2]; /* Instruction referenced by left operand. */ - IRIns right[2]; /* Instruction referenced by right operand. */ -} FoldState; - -/* JIT compiler state. */ -typedef struct jit_State { - GCtrace cur; /* Current trace. */ - GCtrace *curfinal; /* Final address of current trace (set during asm). */ - - lua_State *L; /* Current Lua state. */ - const BCIns *pc; /* Current PC. */ - GCfunc *fn; /* Current function. */ - GCproto *pt; /* Current prototype. */ - TRef *base; /* Current frame base, points into J->slots. */ - - uint32_t flags; /* JIT engine flags. */ - BCReg maxslot; /* Relative to baseslot. */ - BCReg baseslot; /* Current frame base, offset into J->slots. */ - - uint8_t mergesnap; /* Allowed to merge with next snapshot. */ - uint8_t needsnap; /* Need snapshot before recording next bytecode. */ - IRType1 guardemit; /* Accumulated IRT_GUARD for emitted instructions. */ - uint8_t bcskip; /* Number of bytecode instructions to skip. */ - - FoldState fold; /* Fold state. */ - - const BCIns *bc_min; /* Start of allowed bytecode range for root trace. */ - MSize bc_extent; /* Extent of the range. */ - - TraceState state; /* Trace compiler state. */ - - int32_t instunroll; /* Unroll counter for instable loops. */ - int32_t loopunroll; /* Unroll counter for loop ops in side traces. */ - int32_t tailcalled; /* Number of successive tailcalls. */ - int32_t framedepth; /* Current frame depth. */ - int32_t retdepth; /* Return frame depth (count of RETF). */ - -#if LJ_K32__USED - uint32_t k32[LJ_K32__MAX]; /* Common 4 byte constants used by backends. */ -#endif - TValue ksimd[LJ_KSIMD__MAX*2+1]; /* 16 byte aligned SIMD constants. */ -#if LJ_K64__USED - TValue k64[LJ_K64__MAX]; /* Common 8 byte constants. */ -#endif - - IRIns *irbuf; /* Temp. IR instruction buffer. Biased with REF_BIAS. */ - IRRef irtoplim; /* Upper limit of instruction buffer (biased). */ - IRRef irbotlim; /* Lower limit of instruction buffer (biased). */ - IRRef loopref; /* Last loop reference or ref of final LOOP (or 0). */ - - MSize sizesnap; /* Size of temp. snapshot buffer. */ - SnapShot *snapbuf; /* Temp. snapshot buffer. */ - SnapEntry *snapmapbuf; /* Temp. snapshot map buffer. */ - MSize sizesnapmap; /* Size of temp. snapshot map buffer. */ - - PostProc postproc; /* Required post-processing after execution. */ -#if LJ_SOFTFP32 || (LJ_32 && LJ_HASFFI) - uint8_t needsplit; /* Need SPLIT pass. */ -#endif - uint8_t retryrec; /* Retry recording. */ - - GCRef *trace; /* Array of traces. */ - TraceNo freetrace; /* Start of scan for next free trace. */ - MSize sizetrace; /* Size of trace array. */ - IRRef1 ktrace; /* Reference to KGC with GCtrace. */ - - IRRef1 chain[IR__MAX]; /* IR instruction skip-list chain anchors. */ - TRef slot[LJ_MAX_JSLOTS+LJ_STACK_EXTRA]; /* Stack slot map. */ - - int32_t param[JIT_P__MAX]; /* JIT engine parameters. */ - - MCode *exitstubgroup[LJ_MAX_EXITSTUBGR]; /* Exit stub group addresses. */ - - HotPenalty penalty[PENALTY_SLOTS]; /* Penalty slots. */ - uint32_t penaltyslot; /* Round-robin index into penalty slots. */ - -#ifdef LUAJIT_ENABLE_TABLE_BUMP - RBCHashEntry rbchash[RBCHASH_SLOTS]; /* Reverse bytecode map. */ -#endif - - BPropEntry bpropcache[BPROP_SLOTS]; /* Backpropagation cache slots. */ - uint32_t bpropslot; /* Round-robin index into bpropcache slots. */ - - ScEvEntry scev; /* Scalar evolution analysis cache slots. */ - - const BCIns *startpc; /* Bytecode PC of starting instruction. */ - TraceNo parent; /* Parent of current side trace (0 for root traces). */ - ExitNo exitno; /* Exit number in parent of current side trace. */ - int exitcode; /* Exit code from unwound trace. */ - - BCIns *patchpc; /* PC for pending re-patch. */ - BCIns patchins; /* Instruction for pending re-patch. */ - - int mcprot; /* Protection of current mcode area. */ - MCode *mcarea; /* Base of current mcode area. */ - MCode *mctop; /* Top of current mcode area. */ - MCode *mcbot; /* Bottom of current mcode area. */ - size_t szmcarea; /* Size of current mcode area. */ - size_t szallmcarea; /* Total size of all allocated mcode areas. */ - uintptr_t mcmin, mcmax; /* Mcode allocation range. */ - - TValue errinfo; /* Additional info element for trace errors. */ - -#if LJ_HASPROFILE - GCproto *prev_pt; /* Previous prototype. */ - BCLine prev_line; /* Previous line. */ - int prof_mode; /* Profiling mode: 0, 'f', 'l'. */ -#endif -} jit_State; - -#ifdef LUA_USE_ASSERT -#define lj_assertJ(c, ...) lj_assertG_(J2G(J), (c), __VA_ARGS__) -#else -#define lj_assertJ(c, ...) ((void)J) -#endif -#endif - -#endif diff --git a/include/luajit/lj_lex.h b/include/luajit/lj_lex.h deleted file mode 100644 index a7aacb4..0000000 --- a/include/luajit/lj_lex.h +++ /dev/null @@ -1,94 +0,0 @@ -/* -** Lexical analyzer. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_LEX_H -#define _LJ_LEX_H - -#include - -#include "lj_obj.h" -#include "lj_err.h" - -/* Lua lexer tokens. */ -#define TKDEF(_, __) \ - _(and) _(break) _(do) _(else) _(elseif) _(end) _(false) \ - _(for) _(function) _(goto) _(if) _(in) _(local) _(nil) _(not) _(or) \ - _(repeat) _(return) _(then) _(true) _(until) _(while) \ - __(concat, ..) __(dots, ...) __(eq, ==) __(ge, >=) __(le, <=) __(ne, ~=) \ - __(label, ::) __(number, ) __(name, ) __(string, ) \ - __(eof, ) - -enum { - TK_OFS = 256, -#define TKENUM1(name) TK_##name, -#define TKENUM2(name, sym) TK_##name, -TKDEF(TKENUM1, TKENUM2) -#undef TKENUM1 -#undef TKENUM2 - TK_RESERVED = TK_while - TK_OFS -}; - -typedef int LexChar; /* Lexical character. Unsigned ext. from char. */ -typedef int LexToken; /* Lexical token. */ - -/* Combined bytecode ins/line. Only used during bytecode generation. */ -typedef struct BCInsLine { - BCIns ins; /* Bytecode instruction. */ - BCLine line; /* Line number for this bytecode. */ -} BCInsLine; - -/* Info for local variables. Only used during bytecode generation. */ -typedef struct VarInfo { - GCRef name; /* Local variable name or goto/label name. */ - BCPos startpc; /* First point where the local variable is active. */ - BCPos endpc; /* First point where the local variable is dead. */ - uint8_t slot; /* Variable slot. */ - uint8_t info; /* Variable/goto/label info. */ -} VarInfo; - -/* Lua lexer state. */ -typedef struct LexState { - struct FuncState *fs; /* Current FuncState. Defined in lj_parse.c. */ - struct lua_State *L; /* Lua state. */ - TValue tokval; /* Current token value. */ - TValue lookaheadval; /* Lookahead token value. */ - const char *p; /* Current position in input buffer. */ - const char *pe; /* End of input buffer. */ - LexChar c; /* Current character. */ - LexToken tok; /* Current token. */ - LexToken lookahead; /* Lookahead token. */ - SBuf sb; /* String buffer for tokens. */ - lua_Reader rfunc; /* Reader callback. */ - void *rdata; /* Reader callback data. */ - BCLine linenumber; /* Input line counter. */ - BCLine lastline; /* Line of last token. */ - GCstr *chunkname; /* Current chunk name (interned string). */ - const char *chunkarg; /* Chunk name argument. */ - const char *mode; /* Allow loading bytecode (b) and/or source text (t). */ - VarInfo *vstack; /* Stack for names and extents of local variables. */ - MSize sizevstack; /* Size of variable stack. */ - MSize vtop; /* Top of variable stack. */ - BCInsLine *bcstack; /* Stack for bytecode instructions/line numbers. */ - MSize sizebcstack; /* Size of bytecode stack. */ - uint32_t level; /* Syntactical nesting level. */ - int endmark; /* Trust bytecode end marker, even if not at EOF. */ - int fr2; /* Generate bytecode for LJ_FR2 mode. */ -} LexState; - -LJ_FUNC int lj_lex_setup(lua_State *L, LexState *ls); -LJ_FUNC void lj_lex_cleanup(lua_State *L, LexState *ls); -LJ_FUNC void lj_lex_next(LexState *ls); -LJ_FUNC LexToken lj_lex_lookahead(LexState *ls); -LJ_FUNC const char *lj_lex_token2str(LexState *ls, LexToken tok); -LJ_FUNC_NORET void lj_lex_error(LexState *ls, LexToken tok, ErrMsg em, ...); -LJ_FUNC void lj_lex_init(lua_State *L); - -#ifdef LUA_USE_ASSERT -#define lj_assertLS(c, ...) (lj_assertG_(G(ls->L), (c), __VA_ARGS__)) -#else -#define lj_assertLS(c, ...) ((void)ls) -#endif - -#endif diff --git a/include/luajit/lj_lib.h b/include/luajit/lj_lib.h deleted file mode 100644 index ec54885..0000000 --- a/include/luajit/lj_lib.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -** Library function support. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_LIB_H -#define _LJ_LIB_H - -#include "lj_obj.h" - -/* -** A fallback handler is called by the assembler VM if the fast path fails: -** -** - too few arguments: unrecoverable. -** - wrong argument type: recoverable, if coercion succeeds. -** - bad argument value: unrecoverable. -** - stack overflow: recoverable, if stack reallocation succeeds. -** - extra handling: recoverable. -** -** The unrecoverable cases throw an error with lj_err_arg(), lj_err_argtype(), -** lj_err_caller() or lj_err_callermsg(). -** The recoverable cases return 0 or the number of results + 1. -** The assembler VM retries the fast path only if 0 is returned. -** This time the fallback must not be called again or it gets stuck in a loop. -*/ - -/* Return values from fallback handler. */ -#define FFH_RETRY 0 -#define FFH_UNREACHABLE FFH_RETRY -#define FFH_RES(n) ((n)+1) -#define FFH_TAILCALL (-1) - -LJ_FUNC TValue *lj_lib_checkany(lua_State *L, int narg); -LJ_FUNC GCstr *lj_lib_checkstr(lua_State *L, int narg); -LJ_FUNC GCstr *lj_lib_optstr(lua_State *L, int narg); -#if LJ_DUALNUM -LJ_FUNC void lj_lib_checknumber(lua_State *L, int narg); -#else -#define lj_lib_checknumber(L, narg) lj_lib_checknum((L), (narg)) -#endif -LJ_FUNC lua_Number lj_lib_checknum(lua_State *L, int narg); -LJ_FUNC int32_t lj_lib_checkint(lua_State *L, int narg); -LJ_FUNC int32_t lj_lib_optint(lua_State *L, int narg, int32_t def); -LJ_FUNC GCfunc *lj_lib_checkfunc(lua_State *L, int narg); -LJ_FUNC GCproto *lj_lib_checkLproto(lua_State *L, int narg, int nolua); -LJ_FUNC GCtab *lj_lib_checktab(lua_State *L, int narg); -LJ_FUNC GCtab *lj_lib_checktabornil(lua_State *L, int narg); -LJ_FUNC int lj_lib_checkopt(lua_State *L, int narg, int def, const char *lst); - -#if LJ_HASBUFFER -LJ_FUNC GCstr *lj_lib_checkstrx(lua_State *L, int narg); -LJ_FUNC int32_t lj_lib_checkintrange(lua_State *L, int narg, - int32_t a, int32_t b); -#endif - -/* Avoid including lj_frame.h. */ -#if LJ_GC64 -#define lj_lib_upvalue(L, n) \ - (&gcval(L->base-2)->fn.c.upvalue[(n)-1]) -#elif LJ_FR2 -#define lj_lib_upvalue(L, n) \ - (&gcref((L->base-2)->gcr)->fn.c.upvalue[(n)-1]) -#else -#define lj_lib_upvalue(L, n) \ - (&gcref((L->base-1)->fr.func)->fn.c.upvalue[(n)-1]) -#endif - -#if LJ_TARGET_WINDOWS -#define lj_lib_checkfpu(L) \ - do { setnumV(L->top++, (lua_Number)1437217655); \ - if (lua_tointeger(L, -1) != 1437217655) lj_err_caller(L, LJ_ERR_BADFPU); \ - L->top--; } while (0) -#else -#define lj_lib_checkfpu(L) UNUSED(L) -#endif - -LJ_FUNC GCfunc *lj_lib_pushcc(lua_State *L, lua_CFunction f, int id, int n); -#define lj_lib_pushcf(L, fn, id) (lj_lib_pushcc(L, (fn), (id), 0)) - -/* Library function declarations. Scanned by buildvm. */ -#define LJLIB_CF(name) static int lj_cf_##name(lua_State *L) -#define LJLIB_ASM(name) static int lj_ffh_##name(lua_State *L) -#define LJLIB_ASM_(name) -#define LJLIB_LUA(name) -#define LJLIB_SET(name) -#define LJLIB_PUSH(arg) -#define LJLIB_REC(handler) -#define LJLIB_NOREGUV -#define LJLIB_NOREG - -#define LJ_LIB_REG(L, regname, name) \ - lj_lib_register(L, regname, lj_lib_init_##name, lj_lib_cf_##name) - -LJ_FUNC void lj_lib_register(lua_State *L, const char *libname, - const uint8_t *init, const lua_CFunction *cf); -LJ_FUNC void lj_lib_prereg(lua_State *L, const char *name, lua_CFunction f, - GCtab *env); -LJ_FUNC int lj_lib_postreg(lua_State *L, lua_CFunction cf, int id, - const char *name); - -/* Library init data tags. */ -#define LIBINIT_LENMASK 0x3f -#define LIBINIT_TAGMASK 0xc0 -#define LIBINIT_CF 0x00 -#define LIBINIT_ASM 0x40 -#define LIBINIT_ASM_ 0x80 -#define LIBINIT_STRING 0xc0 -#define LIBINIT_MAXSTR 0x38 -#define LIBINIT_LUA 0xf9 -#define LIBINIT_SET 0xfa -#define LIBINIT_NUMBER 0xfb -#define LIBINIT_COPY 0xfc -#define LIBINIT_LASTCL 0xfd -#define LIBINIT_FFID 0xfe -#define LIBINIT_END 0xff - -#endif diff --git a/include/luajit/lj_mcode.h b/include/luajit/lj_mcode.h deleted file mode 100644 index bd8d257..0000000 --- a/include/luajit/lj_mcode.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -** Machine code management. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_MCODE_H -#define _LJ_MCODE_H - -#include "lj_obj.h" - -#if LJ_HASJIT || LJ_HASFFI -LJ_FUNC void lj_mcode_sync(void *start, void *end); -#endif - -#if LJ_HASJIT - -#include "lj_jit.h" - -LJ_FUNC void lj_mcode_free(jit_State *J); -LJ_FUNC MCode *lj_mcode_reserve(jit_State *J, MCode **lim); -LJ_FUNC void lj_mcode_commit(jit_State *J, MCode *m); -LJ_FUNC void lj_mcode_abort(jit_State *J); -LJ_FUNC MCode *lj_mcode_patch(jit_State *J, MCode *ptr, int finish); -LJ_FUNC_NORET void lj_mcode_limiterr(jit_State *J, size_t need); - -#define lj_mcode_commitbot(J, m) (J->mcbot = (m)) - -#endif - -#endif diff --git a/include/luajit/lj_meta.h b/include/luajit/lj_meta.h deleted file mode 100644 index 0f53767..0000000 --- a/include/luajit/lj_meta.h +++ /dev/null @@ -1,38 +0,0 @@ -/* -** Metamethod handling. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_META_H -#define _LJ_META_H - -#include "lj_obj.h" - -/* Metamethod handling */ -LJ_FUNC void lj_meta_init(lua_State *L); -LJ_FUNC cTValue *lj_meta_cache(GCtab *mt, MMS mm, GCstr *name); -LJ_FUNC cTValue *lj_meta_lookup(lua_State *L, cTValue *o, MMS mm); -#if LJ_HASFFI -LJ_FUNC int lj_meta_tailcall(lua_State *L, cTValue *tv); -#endif - -#define lj_meta_fastg(g, mt, mm) \ - ((mt) == NULL ? NULL : ((mt)->nomm & (1u<<(mm))) ? NULL : \ - lj_meta_cache(mt, mm, mmname_str(g, mm))) -#define lj_meta_fast(L, mt, mm) lj_meta_fastg(G(L), mt, mm) - -/* C helpers for some instructions, called from assembler VM. */ -LJ_FUNCA cTValue *lj_meta_tget(lua_State *L, cTValue *o, cTValue *k); -LJ_FUNCA TValue *lj_meta_tset(lua_State *L, cTValue *o, cTValue *k); -LJ_FUNCA TValue *lj_meta_arith(lua_State *L, TValue *ra, cTValue *rb, - cTValue *rc, BCReg op); -LJ_FUNCA TValue *lj_meta_cat(lua_State *L, TValue *top, int left); -LJ_FUNCA TValue * LJ_FASTCALL lj_meta_len(lua_State *L, cTValue *o); -LJ_FUNCA TValue *lj_meta_equal(lua_State *L, GCobj *o1, GCobj *o2, int ne); -LJ_FUNCA TValue * LJ_FASTCALL lj_meta_equal_cd(lua_State *L, BCIns ins); -LJ_FUNCA TValue *lj_meta_comp(lua_State *L, cTValue *o1, cTValue *o2, int op); -LJ_FUNCA void lj_meta_istype(lua_State *L, BCReg ra, BCReg tp); -LJ_FUNCA void lj_meta_call(lua_State *L, TValue *func, TValue *top); -LJ_FUNCA void LJ_FASTCALL lj_meta_for(lua_State *L, TValue *o); - -#endif diff --git a/include/luajit/lj_obj.h b/include/luajit/lj_obj.h deleted file mode 100644 index 58e5049..0000000 --- a/include/luajit/lj_obj.h +++ /dev/null @@ -1,1089 +0,0 @@ -/* -** LuaJIT VM tags, values and objects. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -** -** Portions taken verbatim or adapted from the Lua interpreter. -** Copyright (C) 1994-2008 Lua.org, PUC-Rio. See Copyright Notice in lua.h -*/ - -#ifndef _LJ_OBJ_H -#define _LJ_OBJ_H - -#include "lua.h" -#include "lj_def.h" -#include "lj_arch.h" - -/* -- Memory references --------------------------------------------------- */ - -/* Memory and GC object sizes. */ -typedef uint32_t MSize; -#if LJ_GC64 -typedef uint64_t GCSize; -#else -typedef uint32_t GCSize; -#endif - -/* Memory reference */ -typedef struct MRef { -#if LJ_GC64 - uint64_t ptr64; /* True 64 bit pointer. */ -#else - uint32_t ptr32; /* Pseudo 32 bit pointer. */ -#endif -} MRef; - -#if LJ_GC64 -#define mref(r, t) ((t *)(void *)(r).ptr64) -#define mrefu(r) ((r).ptr64) - -#define setmref(r, p) ((r).ptr64 = (uint64_t)(void *)(p)) -#define setmrefu(r, u) ((r).ptr64 = (uint64_t)(u)) -#define setmrefr(r, v) ((r).ptr64 = (v).ptr64) -#else -#define mref(r, t) ((t *)(void *)(uintptr_t)(r).ptr32) -#define mrefu(r) ((r).ptr32) - -#define setmref(r, p) ((r).ptr32 = (uint32_t)(uintptr_t)(void *)(p)) -#define setmrefu(r, u) ((r).ptr32 = (uint32_t)(u)) -#define setmrefr(r, v) ((r).ptr32 = (v).ptr32) -#endif - -/* -- GC object references ------------------------------------------------ */ - -/* GCobj reference */ -typedef struct GCRef { -#if LJ_GC64 - uint64_t gcptr64; /* True 64 bit pointer. */ -#else - uint32_t gcptr32; /* Pseudo 32 bit pointer. */ -#endif -} GCRef; - -/* Common GC header for all collectable objects. */ -#define GCHeader GCRef nextgc; uint8_t marked; uint8_t gct -/* This occupies 6 bytes, so use the next 2 bytes for non-32 bit fields. */ - -#if LJ_GC64 -#define gcref(r) ((GCobj *)(r).gcptr64) -#define gcrefp(r, t) ((t *)(void *)(r).gcptr64) -#define gcrefu(r) ((r).gcptr64) -#define gcrefeq(r1, r2) ((r1).gcptr64 == (r2).gcptr64) - -#define setgcref(r, gc) ((r).gcptr64 = (uint64_t)&(gc)->gch) -#define setgcreft(r, gc, it) \ - (r).gcptr64 = (uint64_t)&(gc)->gch | (((uint64_t)(it)) << 47) -#define setgcrefp(r, p) ((r).gcptr64 = (uint64_t)(p)) -#define setgcrefnull(r) ((r).gcptr64 = 0) -#define setgcrefr(r, v) ((r).gcptr64 = (v).gcptr64) -#else -#define gcref(r) ((GCobj *)(uintptr_t)(r).gcptr32) -#define gcrefp(r, t) ((t *)(void *)(uintptr_t)(r).gcptr32) -#define gcrefu(r) ((r).gcptr32) -#define gcrefeq(r1, r2) ((r1).gcptr32 == (r2).gcptr32) - -#define setgcref(r, gc) ((r).gcptr32 = (uint32_t)(uintptr_t)&(gc)->gch) -#define setgcrefp(r, p) ((r).gcptr32 = (uint32_t)(uintptr_t)(p)) -#define setgcrefnull(r) ((r).gcptr32 = 0) -#define setgcrefr(r, v) ((r).gcptr32 = (v).gcptr32) -#endif - -#define gcnext(gc) (gcref((gc)->gch.nextgc)) - -/* IMPORTANT NOTE: -** -** All uses of the setgcref* macros MUST be accompanied with a write barrier. -** -** This is to ensure the integrity of the incremental GC. The invariant -** to preserve is that a black object never points to a white object. -** I.e. never store a white object into a field of a black object. -** -** It's ok to LEAVE OUT the write barrier ONLY in the following cases: -** - The source is not a GC object (NULL). -** - The target is a GC root. I.e. everything in global_State. -** - The target is a lua_State field (threads are never black). -** - The target is a stack slot, see setgcV et al. -** - The target is an open upvalue, i.e. pointing to a stack slot. -** - The target is a newly created object (i.e. marked white). But make -** sure nothing invokes the GC inbetween. -** - The target and the source are the same object (self-reference). -** - The target already contains the object (e.g. moving elements around). -** -** The most common case is a store to a stack slot. All other cases where -** a barrier has been omitted are annotated with a NOBARRIER comment. -** -** The same logic applies for stores to table slots (array part or hash -** part). ALL uses of lj_tab_set* require a barrier for the stored value -** *and* the stored key, based on the above rules. In practice this means -** a barrier is needed if *either* of the key or value are a GC object. -** -** It's ok to LEAVE OUT the write barrier in the following special cases: -** - The stored value is nil. The key doesn't matter because it's either -** not resurrected or lj_tab_newkey() will take care of the key barrier. -** - The key doesn't matter if the *previously* stored value is guaranteed -** to be non-nil (because the key is kept alive in the table). -** - The key doesn't matter if it's guaranteed not to be part of the table, -** since lj_tab_newkey() takes care of the key barrier. This applies -** trivially to new tables, but watch out for resurrected keys. Storing -** a nil value leaves the key in the table! -** -** In case of doubt use lj_gc_anybarriert() as it's rather cheap. It's used -** by the interpreter for all table stores. -** -** Note: In contrast to Lua's GC, LuaJIT's GC does *not* specially mark -** dead keys in tables. The reference is left in, but it's guaranteed to -** be never dereferenced as long as the value is nil. It's ok if the key is -** freed or if any object subsequently gets the same address. -** -** Not destroying dead keys helps to keep key hash slots stable. This avoids -** specialization back-off for HREFK when a value flips between nil and -** non-nil and the GC gets in the way. It also allows safely hoisting -** HREF/HREFK across GC steps. Dead keys are only removed if a table is -** resized (i.e. by NEWREF) and xREF must not be CSEd across a resize. -** -** The trade-off is that a write barrier for tables must take the key into -** account, too. Implicitly resurrecting the key by storing a non-nil value -** may invalidate the incremental GC invariant. -*/ - -/* -- Common type definitions --------------------------------------------- */ - -/* Types for handling bytecodes. Need this here, details in lj_bc.h. */ -typedef uint32_t BCIns; /* Bytecode instruction. */ -typedef uint32_t BCPos; /* Bytecode position. */ -typedef uint32_t BCReg; /* Bytecode register. */ -typedef int32_t BCLine; /* Bytecode line number. */ - -/* Internal assembler functions. Never call these directly from C. */ -typedef void (*ASMFunction)(void); - -/* Resizable string buffer. Need this here, details in lj_buf.h. */ -#define SBufHeader char *w, *e, *b; MRef L -typedef struct SBuf { - SBufHeader; -} SBuf; - -/* -- Tags and values ----------------------------------------------------- */ - -/* Frame link. */ -typedef union { - int32_t ftsz; /* Frame type and size of previous frame. */ - MRef pcr; /* Or PC for Lua frames. */ -} FrameLink; - -/* Tagged value. */ -typedef LJ_ALIGN(8) union TValue { - uint64_t u64; /* 64 bit pattern overlaps number. */ - lua_Number n; /* Number object overlaps split tag/value object. */ -#if LJ_GC64 - GCRef gcr; /* GCobj reference with tag. */ - int64_t it64; - struct { - LJ_ENDIAN_LOHI( - int32_t i; /* Integer value. */ - , uint32_t it; /* Internal object tag. Must overlap MSW of number. */ - ) - }; -#else - struct { - LJ_ENDIAN_LOHI( - union { - GCRef gcr; /* GCobj reference (if any). */ - int32_t i; /* Integer value. */ - }; - , uint32_t it; /* Internal object tag. Must overlap MSW of number. */ - ) - }; -#endif -#if LJ_FR2 - int64_t ftsz; /* Frame type and size of previous frame, or PC. */ -#else - struct { - LJ_ENDIAN_LOHI( - GCRef func; /* Function for next frame (or dummy L). */ - , FrameLink tp; /* Link to previous frame. */ - ) - } fr; -#endif - struct { - LJ_ENDIAN_LOHI( - uint32_t lo; /* Lower 32 bits of number. */ - , uint32_t hi; /* Upper 32 bits of number. */ - ) - } u32; -} TValue; - -typedef const TValue cTValue; - -#define tvref(r) (mref(r, TValue)) - -/* More external and GCobj tags for internal objects. */ -#define LAST_TT LUA_TTHREAD -#define LUA_TPROTO (LAST_TT+1) -#define LUA_TCDATA (LAST_TT+2) - -/* Internal object tags. -** -** Format for 32 bit GC references (!LJ_GC64): -** -** Internal tags overlap the MSW of a number object (must be a double). -** Interpreted as a double these are special NaNs. The FPU only generates -** one type of NaN (0xfff8_0000_0000_0000). So MSWs > 0xfff80000 are available -** for use as internal tags. Small negative numbers are used to shorten the -** encoding of type comparisons (reg/mem against sign-ext. 8 bit immediate). -** -** ---MSW---.---LSW--- -** primitive types | itype | | -** lightuserdata | itype | void * | (32 bit platforms) -** lightuserdata |ffff|seg| ofs | (64 bit platforms) -** GC objects | itype | GCRef | -** int (LJ_DUALNUM)| itype | int | -** number -------double------ -** -** Format for 64 bit GC references (LJ_GC64): -** -** The upper 13 bits must be 1 (0xfff8...) for a special NaN. The next -** 4 bits hold the internal tag. The lowest 47 bits either hold a pointer, -** a zero-extended 32 bit integer or all bits set to 1 for primitive types. -** -** ------MSW------.------LSW------ -** primitive types |1..1|itype|1..................1| -** GC objects |1..1|itype|-------GCRef--------| -** lightuserdata |1..1|itype|seg|------ofs-------| -** int (LJ_DUALNUM) |1..1|itype|0..0|-----int-------| -** number ------------double------------- -** -** ORDER LJ_T -** Primitive types nil/false/true must be first, lightuserdata next. -** GC objects are at the end, table/userdata must be lowest. -** Also check lj_ir.h for similar ordering constraints. -*/ -#define LJ_TNIL (~0u) -#define LJ_TFALSE (~1u) -#define LJ_TTRUE (~2u) -#define LJ_TLIGHTUD (~3u) -#define LJ_TSTR (~4u) -#define LJ_TUPVAL (~5u) -#define LJ_TTHREAD (~6u) -#define LJ_TPROTO (~7u) -#define LJ_TFUNC (~8u) -#define LJ_TTRACE (~9u) -#define LJ_TCDATA (~10u) -#define LJ_TTAB (~11u) -#define LJ_TUDATA (~12u) -/* This is just the canonical number type used in some places. */ -#define LJ_TNUMX (~13u) - -/* Integers have itype == LJ_TISNUM doubles have itype < LJ_TISNUM */ -#if LJ_64 && !LJ_GC64 -#define LJ_TISNUM 0xfffeffffu -#else -#define LJ_TISNUM LJ_TNUMX -#endif -#define LJ_TISTRUECOND LJ_TFALSE -#define LJ_TISPRI LJ_TTRUE -#define LJ_TISGCV (LJ_TSTR+1) -#define LJ_TISTABUD LJ_TTAB - -/* Type marker for slot holding a traversal index. Must be lightuserdata. */ -#define LJ_KEYINDEX 0xfffe7fffu - -#if LJ_GC64 -#define LJ_GCVMASK (((uint64_t)1 << 47) - 1) -#endif - -#if LJ_64 -/* To stay within 47 bits, lightuserdata is segmented. */ -#define LJ_LIGHTUD_BITS_SEG 8 -#define LJ_LIGHTUD_BITS_LO (47 - LJ_LIGHTUD_BITS_SEG) -#endif - -/* -- String object ------------------------------------------------------- */ - -typedef uint32_t StrHash; /* String hash value. */ -typedef uint32_t StrID; /* String ID. */ - -/* String object header. String payload follows. */ -typedef struct GCstr { - GCHeader; - uint8_t reserved; /* Used by lexer for fast lookup of reserved words. */ - uint8_t hashalg; /* Hash algorithm. */ - StrID sid; /* Interned string ID. */ - StrHash hash; /* Hash of string. */ - MSize len; /* Size of string. */ -} GCstr; - -#define strref(r) (&gcref((r))->str) -#define strdata(s) ((const char *)((s)+1)) -#define strdatawr(s) ((char *)((s)+1)) -#define strVdata(o) strdata(strV(o)) - -/* -- Userdata object ----------------------------------------------------- */ - -/* Userdata object. Payload follows. */ -typedef struct GCudata { - GCHeader; - uint8_t udtype; /* Userdata type. */ - uint8_t unused2; - GCRef env; /* Should be at same offset in GCfunc. */ - MSize len; /* Size of payload. */ - GCRef metatable; /* Must be at same offset in GCtab. */ - uint32_t align1; /* To force 8 byte alignment of the payload. */ -} GCudata; - -/* Userdata types. */ -enum { - UDTYPE_USERDATA, /* Regular userdata. */ - UDTYPE_IO_FILE, /* I/O library FILE. */ - UDTYPE_FFI_CLIB, /* FFI C library namespace. */ - UDTYPE_BUFFER, /* String buffer. */ - UDTYPE__MAX -}; - -#define uddata(u) ((void *)((u)+1)) -#define sizeudata(u) (sizeof(struct GCudata)+(u)->len) - -/* -- C data object ------------------------------------------------------- */ - -/* C data object. Payload follows. */ -typedef struct GCcdata { - GCHeader; - uint16_t ctypeid; /* C type ID. */ -} GCcdata; - -/* Prepended to variable-sized or realigned C data objects. */ -typedef struct GCcdataVar { - uint16_t offset; /* Offset to allocated memory (relative to GCcdata). */ - uint16_t extra; /* Extra space allocated (incl. GCcdata + GCcdatav). */ - MSize len; /* Size of payload. */ -} GCcdataVar; - -#define cdataptr(cd) ((void *)((cd)+1)) -#define cdataisv(cd) ((cd)->marked & 0x80) -#define cdatav(cd) ((GCcdataVar *)((char *)(cd) - sizeof(GCcdataVar))) -#define cdatavlen(cd) check_exp(cdataisv(cd), cdatav(cd)->len) -#define sizecdatav(cd) (cdatavlen(cd) + cdatav(cd)->extra) -#define memcdatav(cd) ((void *)((char *)(cd) - cdatav(cd)->offset)) - -/* -- Prototype object ---------------------------------------------------- */ - -#define SCALE_NUM_GCO ((int32_t)sizeof(lua_Number)/sizeof(GCRef)) -#define round_nkgc(n) (((n) + SCALE_NUM_GCO-1) & ~(SCALE_NUM_GCO-1)) - -typedef struct GCproto { - GCHeader; - uint8_t numparams; /* Number of parameters. */ - uint8_t framesize; /* Fixed frame size. */ - MSize sizebc; /* Number of bytecode instructions. */ -#if LJ_GC64 - uint32_t unused_gc64; -#endif - GCRef gclist; - MRef k; /* Split constant array (points to the middle). */ - MRef uv; /* Upvalue list. local slot|0x8000 or parent uv idx. */ - MSize sizekgc; /* Number of collectable constants. */ - MSize sizekn; /* Number of lua_Number constants. */ - MSize sizept; /* Total size including colocated arrays. */ - uint8_t sizeuv; /* Number of upvalues. */ - uint8_t flags; /* Miscellaneous flags (see below). */ - uint16_t trace; /* Anchor for chain of root traces. */ - /* ------ The following fields are for debugging/tracebacks only ------ */ - GCRef chunkname; /* Name of the chunk this function was defined in. */ - BCLine firstline; /* First line of the function definition. */ - BCLine numline; /* Number of lines for the function definition. */ - MRef lineinfo; /* Compressed map from bytecode ins. to source line. */ - MRef uvinfo; /* Upvalue names. */ - MRef varinfo; /* Names and compressed extents of local variables. */ -} GCproto; - -/* Flags for prototype. */ -#define PROTO_CHILD 0x01 /* Has child prototypes. */ -#define PROTO_VARARG 0x02 /* Vararg function. */ -#define PROTO_FFI 0x04 /* Uses BC_KCDATA for FFI datatypes. */ -#define PROTO_NOJIT 0x08 /* JIT disabled for this function. */ -#define PROTO_ILOOP 0x10 /* Patched bytecode with ILOOP etc. */ -/* Only used during parsing. */ -#define PROTO_HAS_RETURN 0x20 /* Already emitted a return. */ -#define PROTO_FIXUP_RETURN 0x40 /* Need to fixup emitted returns. */ -/* Top bits used for counting created closures. */ -#define PROTO_CLCOUNT 0x20 /* Base of saturating 3 bit counter. */ -#define PROTO_CLC_BITS 3 -#define PROTO_CLC_POLY (3*PROTO_CLCOUNT) /* Polymorphic threshold. */ - -#define PROTO_UV_LOCAL 0x8000 /* Upvalue for local slot. */ -#define PROTO_UV_IMMUTABLE 0x4000 /* Immutable upvalue. */ - -#define proto_kgc(pt, idx) \ - check_exp((uintptr_t)(intptr_t)(idx) >= ~(uintptr_t)(pt)->sizekgc+1u, \ - gcref(mref((pt)->k, GCRef)[(idx)])) -#define proto_knumtv(pt, idx) \ - check_exp((uintptr_t)(idx) < (pt)->sizekn, &mref((pt)->k, TValue)[(idx)]) -#define proto_bc(pt) ((BCIns *)((char *)(pt) + sizeof(GCproto))) -#define proto_bcpos(pt, pc) ((BCPos)((pc) - proto_bc(pt))) -#define proto_uv(pt) (mref((pt)->uv, uint16_t)) - -#define proto_chunkname(pt) (strref((pt)->chunkname)) -#define proto_chunknamestr(pt) (strdata(proto_chunkname((pt)))) -#define proto_lineinfo(pt) (mref((pt)->lineinfo, const void)) -#define proto_uvinfo(pt) (mref((pt)->uvinfo, const uint8_t)) -#define proto_varinfo(pt) (mref((pt)->varinfo, const uint8_t)) - -/* -- Upvalue object ------------------------------------------------------ */ - -typedef struct GCupval { - GCHeader; - uint8_t closed; /* Set if closed (i.e. uv->v == &uv->u.value). */ - uint8_t immutable; /* Immutable value. */ - union { - TValue tv; /* If closed: the value itself. */ - struct { /* If open: double linked list, anchored at thread. */ - GCRef prev; - GCRef next; - }; - }; - MRef v; /* Points to stack slot (open) or above (closed). */ - uint32_t dhash; /* Disambiguation hash: dh1 != dh2 => cannot alias. */ -} GCupval; - -#define uvprev(uv_) (&gcref((uv_)->prev)->uv) -#define uvnext(uv_) (&gcref((uv_)->next)->uv) -#define uvval(uv_) (mref((uv_)->v, TValue)) - -/* -- Function object (closures) ------------------------------------------ */ - -/* Common header for functions. env should be at same offset in GCudata. */ -#define GCfuncHeader \ - GCHeader; uint8_t ffid; uint8_t nupvalues; \ - GCRef env; GCRef gclist; MRef pc - -typedef struct GCfuncC { - GCfuncHeader; - lua_CFunction f; /* C function to be called. */ - TValue upvalue[1]; /* Array of upvalues (TValue). */ -} GCfuncC; - -typedef struct GCfuncL { - GCfuncHeader; - GCRef uvptr[1]; /* Array of _pointers_ to upvalue objects (GCupval). */ -} GCfuncL; - -typedef union GCfunc { - GCfuncC c; - GCfuncL l; -} GCfunc; - -#define FF_LUA 0 -#define FF_C 1 -#define isluafunc(fn) ((fn)->c.ffid == FF_LUA) -#define iscfunc(fn) ((fn)->c.ffid == FF_C) -#define isffunc(fn) ((fn)->c.ffid > FF_C) -#define funcproto(fn) \ - check_exp(isluafunc(fn), (GCproto *)(mref((fn)->l.pc, char)-sizeof(GCproto))) -#define sizeCfunc(n) (sizeof(GCfuncC)-sizeof(TValue)+sizeof(TValue)*(n)) -#define sizeLfunc(n) (sizeof(GCfuncL)-sizeof(GCRef)+sizeof(GCRef)*(n)) - -/* -- Table object -------------------------------------------------------- */ - -/* Hash node. */ -typedef struct Node { - TValue val; /* Value object. Must be first field. */ - TValue key; /* Key object. */ - MRef next; /* Hash chain. */ -#if !LJ_GC64 - MRef freetop; /* Top of free elements (stored in t->node[0]). */ -#endif -} Node; - -LJ_STATIC_ASSERT(offsetof(Node, val) == 0); - -typedef struct GCtab { - GCHeader; - uint8_t nomm; /* Negative cache for fast metamethods. */ - int8_t colo; /* Array colocation. */ - MRef array; /* Array part. */ - GCRef gclist; - GCRef metatable; /* Must be at same offset in GCudata. */ - MRef node; /* Hash part. */ - uint32_t asize; /* Size of array part (keys [0, asize-1]). */ - uint32_t hmask; /* Hash part mask (size of hash part - 1). */ -#if LJ_GC64 - MRef freetop; /* Top of free elements. */ -#endif -} GCtab; - -#define sizetabcolo(n) ((n)*sizeof(TValue) + sizeof(GCtab)) -#define tabref(r) ((GCtab *)gcref((r))) -#define noderef(r) (mref((r), Node)) -#define nextnode(n) (mref((n)->next, Node)) -#if LJ_GC64 -#define getfreetop(t, n) (noderef((t)->freetop)) -#define setfreetop(t, n, v) (setmref((t)->freetop, (v))) -#else -#define getfreetop(t, n) (noderef((n)->freetop)) -#define setfreetop(t, n, v) (setmref((n)->freetop, (v))) -#endif - -/* -- State objects ------------------------------------------------------- */ - -/* VM states. */ -enum { - LJ_VMST_INTERP, /* Interpreter. */ - LJ_VMST_C, /* C function. */ - LJ_VMST_GC, /* Garbage collector. */ - LJ_VMST_EXIT, /* Trace exit handler. */ - LJ_VMST_RECORD, /* Trace recorder. */ - LJ_VMST_OPT, /* Optimizer. */ - LJ_VMST_ASM, /* Assembler. */ - LJ_VMST__MAX -}; - -#define setvmstate(g, st) ((g)->vmstate = ~LJ_VMST_##st) - -/* Metamethods. ORDER MM */ -#ifdef LJ_HASFFI -#define MMDEF_FFI(_) _(new) -#else -#define MMDEF_FFI(_) -#endif - -#if LJ_52 || LJ_HASFFI -#define MMDEF_PAIRS(_) _(pairs) _(ipairs) -#else -#define MMDEF_PAIRS(_) -#define MM_pairs 255 -#define MM_ipairs 255 -#endif - -#define MMDEF(_) \ - _(index) _(newindex) _(gc) _(mode) _(eq) _(len) \ - /* Only the above (fast) metamethods are negative cached (max. 8). */ \ - _(lt) _(le) _(concat) _(call) \ - /* The following must be in ORDER ARITH. */ \ - _(add) _(sub) _(mul) _(div) _(mod) _(pow) _(unm) \ - /* The following are used in the standard libraries. */ \ - _(metatable) _(tostring) MMDEF_FFI(_) MMDEF_PAIRS(_) - -typedef enum { -#define MMENUM(name) MM_##name, -MMDEF(MMENUM) -#undef MMENUM - MM__MAX, - MM____ = MM__MAX, - MM_FAST = MM_len -} MMS; - -/* GC root IDs. */ -typedef enum { - GCROOT_MMNAME, /* Metamethod names. */ - GCROOT_MMNAME_LAST = GCROOT_MMNAME + MM__MAX-1, - GCROOT_BASEMT, /* Metatables for base types. */ - GCROOT_BASEMT_NUM = GCROOT_BASEMT + ~LJ_TNUMX, - GCROOT_IO_INPUT, /* Userdata for default I/O input file. */ - GCROOT_IO_OUTPUT, /* Userdata for default I/O output file. */ -#if LJ_HASFFI - GCROOT_FFI_FIN, /* FFI finalizer table. */ -#endif - GCROOT_MAX -} GCRootID; - -#define basemt_it(g, it) ((g)->gcroot[GCROOT_BASEMT+~(it)]) -#define basemt_obj(g, o) ((g)->gcroot[GCROOT_BASEMT+itypemap(o)]) -#define mmname_str(g, mm) (strref((g)->gcroot[GCROOT_MMNAME+(mm)])) - -/* Garbage collector state. */ -typedef struct GCState { - GCSize total; /* Memory currently allocated. */ - GCSize threshold; /* Memory threshold. */ - uint8_t currentwhite; /* Current white color. */ - uint8_t state; /* GC state. */ - uint8_t unused0; -#if LJ_64 - uint8_t lightudnum; /* Number of lightuserdata segments - 1. */ -#else - uint8_t unused1; -#endif - MSize sweepstr; /* Sweep position in string table. */ - GCRef root; /* List of all collectable objects. */ - MRef sweep; /* Sweep position in root list. */ - GCRef gray; /* List of gray objects. */ - GCRef grayagain; /* List of objects for atomic traversal. */ - GCRef weak; /* List of weak tables (to be cleared). */ - GCRef mmudata; /* List of userdata (to be finalized). */ - GCSize debt; /* Debt (how much GC is behind schedule). */ - GCSize estimate; /* Estimate of memory actually in use. */ - MSize stepmul; /* Incremental GC step granularity. */ - MSize pause; /* Pause between successive GC cycles. */ -#if LJ_64 - MRef lightudseg; /* Upper bits of lightuserdata segments. */ -#endif -} GCState; - -/* String interning state. */ -typedef struct StrInternState { - GCRef *tab; /* String hash table anchors. */ - MSize mask; /* String hash mask (size of hash table - 1). */ - MSize num; /* Number of strings in hash table. */ - StrID id; /* Next string ID. */ - uint8_t idreseed; /* String ID reseed counter. */ - uint8_t second; /* String interning table uses secondary hashing. */ - uint8_t unused1; - uint8_t unused2; - LJ_ALIGN(8) uint64_t seed; /* Random string seed. */ -} StrInternState; - -/* Global state, shared by all threads of a Lua universe. */ -typedef struct global_State { - lua_Alloc allocf; /* Memory allocator. */ - void *allocd; /* Memory allocator data. */ - GCState gc; /* Garbage collector. */ - GCstr strempty; /* Empty string. */ - uint8_t stremptyz; /* Zero terminator of empty string. */ - uint8_t hookmask; /* Hook mask. */ - uint8_t dispatchmode; /* Dispatch mode. */ - uint8_t vmevmask; /* VM event mask. */ - StrInternState str; /* String interning. */ - volatile int32_t vmstate; /* VM state or current JIT code trace number. */ - GCRef mainthref; /* Link to main thread. */ - SBuf tmpbuf; /* Temporary string buffer. */ - TValue tmptv, tmptv2; /* Temporary TValues. */ - Node nilnode; /* Fallback 1-element hash part (nil key and value). */ - TValue registrytv; /* Anchor for registry. */ - GCRef vmthref; /* Link to VM thread. */ - GCupval uvhead; /* Head of double-linked list of all open upvalues. */ - int32_t hookcount; /* Instruction hook countdown. */ - int32_t hookcstart; /* Start count for instruction hook counter. */ - lua_Hook hookf; /* Hook function. */ - lua_CFunction wrapf; /* Wrapper for C function calls. */ - lua_CFunction panic; /* Called as a last resort for errors. */ - BCIns bc_cfunc_int; /* Bytecode for internal C function calls. */ - BCIns bc_cfunc_ext; /* Bytecode for external C function calls. */ - GCRef cur_L; /* Currently executing lua_State. */ - MRef jit_base; /* Current JIT code L->base or NULL. */ - MRef ctype_state; /* Pointer to C type state. */ - PRNGState prng; /* Global PRNG state. */ - GCRef gcroot[GCROOT_MAX]; /* GC roots. */ -} global_State; - -#define mainthread(g) (&gcref(g->mainthref)->th) -#define vmthread(g) (&gcref(g->vmthref)->th) -#define niltv(L) \ - check_exp(tvisnil(&G(L)->nilnode.val), &G(L)->nilnode.val) -#define niltvg(g) \ - check_exp(tvisnil(&(g)->nilnode.val), &(g)->nilnode.val) - -/* Hook management. Hook event masks are defined in lua.h. */ -#define HOOK_EVENTMASK 0x0f -#define HOOK_ACTIVE 0x10 -#define HOOK_ACTIVE_SHIFT 4 -#define HOOK_VMEVENT 0x20 -#define HOOK_GC 0x40 -#define HOOK_PROFILE 0x80 -#define hook_active(g) ((g)->hookmask & HOOK_ACTIVE) -#define hook_enter(g) ((g)->hookmask |= HOOK_ACTIVE) -#define hook_entergc(g) \ - ((g)->hookmask = ((g)->hookmask | (HOOK_ACTIVE|HOOK_GC)) & ~HOOK_PROFILE) -#define hook_vmevent(g) ((g)->hookmask |= (HOOK_ACTIVE|HOOK_VMEVENT)) -#define hook_leave(g) ((g)->hookmask &= ~HOOK_ACTIVE) -#define hook_save(g) ((g)->hookmask & ~HOOK_EVENTMASK) -#define hook_restore(g, h) \ - ((g)->hookmask = ((g)->hookmask & HOOK_EVENTMASK) | (h)) - -/* Per-thread state object. */ -struct lua_State { - GCHeader; - uint8_t dummy_ffid; /* Fake FF_C for curr_funcisL() on dummy frames. */ - uint8_t status; /* Thread status. */ - MRef glref; /* Link to global state. */ - GCRef gclist; /* GC chain. */ - TValue *base; /* Base of currently executing function. */ - TValue *top; /* First free slot in the stack. */ - MRef maxstack; /* Last free slot in the stack. */ - MRef stack; /* Stack base. */ - GCRef openupval; /* List of open upvalues in the stack. */ - GCRef env; /* Thread environment (table of globals). */ - void *cframe; /* End of C stack frame chain. */ - MSize stacksize; /* True stack size (incl. LJ_STACK_EXTRA). */ -}; - -#define G(L) (mref(L->glref, global_State)) -#define registry(L) (&G(L)->registrytv) - -/* Macros to access the currently executing (Lua) function. */ -#if LJ_GC64 -#define curr_func(L) (&gcval(L->base-2)->fn) -#elif LJ_FR2 -#define curr_func(L) (&gcref((L->base-2)->gcr)->fn) -#else -#define curr_func(L) (&gcref((L->base-1)->fr.func)->fn) -#endif -#define curr_funcisL(L) (isluafunc(curr_func(L))) -#define curr_proto(L) (funcproto(curr_func(L))) -#define curr_topL(L) (L->base + curr_proto(L)->framesize) -#define curr_top(L) (curr_funcisL(L) ? curr_topL(L) : L->top) - -#if defined(LUA_USE_ASSERT) || defined(LUA_USE_APICHECK) -LJ_FUNC_NORET void lj_assert_fail(global_State *g, const char *file, int line, - const char *func, const char *fmt, ...); -#endif - -/* -- GC object definition and conversions -------------------------------- */ - -/* GC header for generic access to common fields of GC objects. */ -typedef struct GChead { - GCHeader; - uint8_t unused1; - uint8_t unused2; - GCRef env; - GCRef gclist; - GCRef metatable; -} GChead; - -/* The env field SHOULD be at the same offset for all GC objects. */ -LJ_STATIC_ASSERT(offsetof(GChead, env) == offsetof(GCfuncL, env)); -LJ_STATIC_ASSERT(offsetof(GChead, env) == offsetof(GCudata, env)); - -/* The metatable field MUST be at the same offset for all GC objects. */ -LJ_STATIC_ASSERT(offsetof(GChead, metatable) == offsetof(GCtab, metatable)); -LJ_STATIC_ASSERT(offsetof(GChead, metatable) == offsetof(GCudata, metatable)); - -/* The gclist field MUST be at the same offset for all GC objects. */ -LJ_STATIC_ASSERT(offsetof(GChead, gclist) == offsetof(lua_State, gclist)); -LJ_STATIC_ASSERT(offsetof(GChead, gclist) == offsetof(GCproto, gclist)); -LJ_STATIC_ASSERT(offsetof(GChead, gclist) == offsetof(GCfuncL, gclist)); -LJ_STATIC_ASSERT(offsetof(GChead, gclist) == offsetof(GCtab, gclist)); - -typedef union GCobj { - GChead gch; - GCstr str; - GCupval uv; - lua_State th; - GCproto pt; - GCfunc fn; - GCcdata cd; - GCtab tab; - GCudata ud; -} GCobj; - -/* Macros to convert a GCobj pointer into a specific value. */ -#define gco2str(o) check_exp((o)->gch.gct == ~LJ_TSTR, &(o)->str) -#define gco2uv(o) check_exp((o)->gch.gct == ~LJ_TUPVAL, &(o)->uv) -#define gco2th(o) check_exp((o)->gch.gct == ~LJ_TTHREAD, &(o)->th) -#define gco2pt(o) check_exp((o)->gch.gct == ~LJ_TPROTO, &(o)->pt) -#define gco2func(o) check_exp((o)->gch.gct == ~LJ_TFUNC, &(o)->fn) -#define gco2cd(o) check_exp((o)->gch.gct == ~LJ_TCDATA, &(o)->cd) -#define gco2tab(o) check_exp((o)->gch.gct == ~LJ_TTAB, &(o)->tab) -#define gco2ud(o) check_exp((o)->gch.gct == ~LJ_TUDATA, &(o)->ud) - -/* Macro to convert any collectable object into a GCobj pointer. */ -#define obj2gco(v) ((GCobj *)(v)) - -/* -- TValue getters/setters ---------------------------------------------- */ - -/* Macros to test types. */ -#if LJ_GC64 -#define itype(o) ((uint32_t)((o)->it64 >> 47)) -#define tvisnil(o) ((o)->it64 == -1) -#else -#define itype(o) ((o)->it) -#define tvisnil(o) (itype(o) == LJ_TNIL) -#endif -#define tvisfalse(o) (itype(o) == LJ_TFALSE) -#define tvistrue(o) (itype(o) == LJ_TTRUE) -#define tvisbool(o) (tvisfalse(o) || tvistrue(o)) -#if LJ_64 && !LJ_GC64 -#define tvislightud(o) (((int32_t)itype(o) >> 15) == -2) -#else -#define tvislightud(o) (itype(o) == LJ_TLIGHTUD) -#endif -#define tvisstr(o) (itype(o) == LJ_TSTR) -#define tvisfunc(o) (itype(o) == LJ_TFUNC) -#define tvisthread(o) (itype(o) == LJ_TTHREAD) -#define tvisproto(o) (itype(o) == LJ_TPROTO) -#define tviscdata(o) (itype(o) == LJ_TCDATA) -#define tvistab(o) (itype(o) == LJ_TTAB) -#define tvisudata(o) (itype(o) == LJ_TUDATA) -#define tvisnumber(o) (itype(o) <= LJ_TISNUM) -#define tvisint(o) (LJ_DUALNUM && itype(o) == LJ_TISNUM) -#define tvisnum(o) (itype(o) < LJ_TISNUM) - -#define tvistruecond(o) (itype(o) < LJ_TISTRUECOND) -#define tvispri(o) (itype(o) >= LJ_TISPRI) -#define tvistabud(o) (itype(o) <= LJ_TISTABUD) /* && !tvisnum() */ -#define tvisgcv(o) ((itype(o) - LJ_TISGCV) > (LJ_TNUMX - LJ_TISGCV)) - -/* Special macros to test numbers for NaN, +0, -0, +1 and raw equality. */ -#define tvisnan(o) ((o)->n != (o)->n) -#if LJ_64 -#define tviszero(o) (((o)->u64 << 1) == 0) -#else -#define tviszero(o) (((o)->u32.lo | ((o)->u32.hi << 1)) == 0) -#endif -#define tvispzero(o) ((o)->u64 == 0) -#define tvismzero(o) ((o)->u64 == U64x(80000000,00000000)) -#define tvispone(o) ((o)->u64 == U64x(3ff00000,00000000)) -#define rawnumequal(o1, o2) ((o1)->u64 == (o2)->u64) - -/* Macros to convert type ids. */ -#if LJ_64 && !LJ_GC64 -#define itypemap(o) \ - (tvisnumber(o) ? ~LJ_TNUMX : tvislightud(o) ? ~LJ_TLIGHTUD : ~itype(o)) -#else -#define itypemap(o) (tvisnumber(o) ? ~LJ_TNUMX : ~itype(o)) -#endif - -/* Macros to get tagged values. */ -#if LJ_GC64 -#define gcval(o) ((GCobj *)(gcrefu((o)->gcr) & LJ_GCVMASK)) -#else -#define gcval(o) (gcref((o)->gcr)) -#endif -#define boolV(o) check_exp(tvisbool(o), (LJ_TFALSE - itype(o))) -#if LJ_64 -#define lightudseg(u) \ - (((u) >> LJ_LIGHTUD_BITS_LO) & ((1 << LJ_LIGHTUD_BITS_SEG)-1)) -#define lightudlo(u) \ - ((u) & (((uint64_t)1 << LJ_LIGHTUD_BITS_LO) - 1)) -#define lightudup(p) \ - ((uint32_t)(((p) >> LJ_LIGHTUD_BITS_LO) << (LJ_LIGHTUD_BITS_LO-32))) -static LJ_AINLINE void *lightudV(global_State *g, cTValue *o) -{ - uint64_t u = o->u64; - uint64_t seg = lightudseg(u); - uint32_t *segmap = mref(g->gc.lightudseg, uint32_t); - lj_assertG(tvislightud(o), "lightuserdata expected"); - if (seg == (1 << LJ_LIGHTUD_BITS_SEG)-1) return NULL; - lj_assertG(seg <= g->gc.lightudnum, "bad lightuserdata segment %d", seg); - return (void *)(((uint64_t)segmap[seg] << 32) | lightudlo(u)); -} -#else -#define lightudV(g, o) check_exp(tvislightud(o), gcrefp((o)->gcr, void)) -#endif -#define gcV(o) check_exp(tvisgcv(o), gcval(o)) -#define strV(o) check_exp(tvisstr(o), &gcval(o)->str) -#define funcV(o) check_exp(tvisfunc(o), &gcval(o)->fn) -#define threadV(o) check_exp(tvisthread(o), &gcval(o)->th) -#define protoV(o) check_exp(tvisproto(o), &gcval(o)->pt) -#define cdataV(o) check_exp(tviscdata(o), &gcval(o)->cd) -#define tabV(o) check_exp(tvistab(o), &gcval(o)->tab) -#define udataV(o) check_exp(tvisudata(o), &gcval(o)->ud) -#define numV(o) check_exp(tvisnum(o), (o)->n) -#define intV(o) check_exp(tvisint(o), (int32_t)(o)->i) - -/* Macros to set tagged values. */ -#if LJ_GC64 -#define setitype(o, i) ((o)->it = ((i) << 15)) -#define setnilV(o) ((o)->it64 = -1) -#define setpriV(o, x) ((o)->it64 = (int64_t)~((uint64_t)~(x)<<47)) -#define setboolV(o, x) ((o)->it64 = (int64_t)~((uint64_t)((x)+1)<<47)) -#else -#define setitype(o, i) ((o)->it = (i)) -#define setnilV(o) ((o)->it = LJ_TNIL) -#define setboolV(o, x) ((o)->it = LJ_TFALSE-(uint32_t)(x)) -#define setpriV(o, i) (setitype((o), (i))) -#endif - -static LJ_AINLINE void setrawlightudV(TValue *o, void *p) -{ -#if LJ_GC64 - o->u64 = (uint64_t)p | (((uint64_t)LJ_TLIGHTUD) << 47); -#elif LJ_64 - o->u64 = (uint64_t)p | (((uint64_t)0xffff) << 48); -#else - setgcrefp(o->gcr, p); setitype(o, LJ_TLIGHTUD); -#endif -} - -#if LJ_FR2 || LJ_32 -#define contptr(f) ((void *)(f)) -#define setcont(o, f) ((o)->u64 = (uint64_t)(uintptr_t)contptr(f)) -#else -#define contptr(f) \ - ((void *)(uintptr_t)(uint32_t)((intptr_t)(f) - (intptr_t)lj_vm_asm_begin)) -#define setcont(o, f) \ - ((o)->u64 = (uint64_t)(void *)(f) - (uint64_t)lj_vm_asm_begin) -#endif - -static LJ_AINLINE void checklivetv(lua_State *L, TValue *o, const char *msg) -{ - UNUSED(L); UNUSED(o); UNUSED(msg); -#if LUA_USE_ASSERT - if (tvisgcv(o)) { - lj_assertL(~itype(o) == gcval(o)->gch.gct, - "mismatch of TValue type %d vs GC type %d", - ~itype(o), gcval(o)->gch.gct); - /* Copy of isdead check from lj_gc.h to avoid circular include. */ - lj_assertL(!(gcval(o)->gch.marked & (G(L)->gc.currentwhite ^ 3) & 3), msg); - } -#endif -} - -static LJ_AINLINE void setgcVraw(TValue *o, GCobj *v, uint32_t itype) -{ -#if LJ_GC64 - setgcreft(o->gcr, v, itype); -#else - setgcref(o->gcr, v); setitype(o, itype); -#endif -} - -static LJ_AINLINE void setgcV(lua_State *L, TValue *o, GCobj *v, uint32_t it) -{ - setgcVraw(o, v, it); - checklivetv(L, o, "store to dead GC object"); -} - -#define define_setV(name, type, tag) \ -static LJ_AINLINE void name(lua_State *L, TValue *o, const type *v) \ -{ \ - setgcV(L, o, obj2gco(v), tag); \ -} -define_setV(setstrV, GCstr, LJ_TSTR) -define_setV(setthreadV, lua_State, LJ_TTHREAD) -define_setV(setprotoV, GCproto, LJ_TPROTO) -define_setV(setfuncV, GCfunc, LJ_TFUNC) -define_setV(setcdataV, GCcdata, LJ_TCDATA) -define_setV(settabV, GCtab, LJ_TTAB) -define_setV(setudataV, GCudata, LJ_TUDATA) - -#define setnumV(o, x) ((o)->n = (x)) -#define setnanV(o) ((o)->u64 = U64x(fff80000,00000000)) -#define setpinfV(o) ((o)->u64 = U64x(7ff00000,00000000)) -#define setminfV(o) ((o)->u64 = U64x(fff00000,00000000)) - -static LJ_AINLINE void setintV(TValue *o, int32_t i) -{ -#if LJ_DUALNUM - o->i = (uint32_t)i; setitype(o, LJ_TISNUM); -#else - o->n = (lua_Number)i; -#endif -} - -static LJ_AINLINE void setint64V(TValue *o, int64_t i) -{ - if (LJ_DUALNUM && LJ_LIKELY(i == (int64_t)(int32_t)i)) - setintV(o, (int32_t)i); - else - setnumV(o, (lua_Number)i); -} - -#if LJ_64 -#define setintptrV(o, i) setint64V((o), (i)) -#else -#define setintptrV(o, i) setintV((o), (i)) -#endif - -/* Copy tagged values. */ -static LJ_AINLINE void copyTV(lua_State *L, TValue *o1, const TValue *o2) -{ - *o1 = *o2; - checklivetv(L, o1, "copy of dead GC object"); -} - -/* -- Number to integer conversion ---------------------------------------- */ - -/* -** The C standard leaves many aspects of FP to integer conversions as -** undefined behavior. Portability is a mess, hardware support varies, -** and modern C compilers are like a box of chocolates -- you never know -** what you're gonna get. -** -** However, we need 100% matching behavior between the interpreter (asm + C), -** optimizations (C) and the code generated by the JIT compiler (asm). -** Mixing Lua numbers with FFI numbers creates some extra requirements. -** -** These conversions have been moved to assembler code, even if they seem -** trivial, to foil unanticipated C compiler 'optimizations' with the -** surrounding code. Only the unchecked double to int32_t conversion -** is still in C, because it ought to be pretty safe -- we'll see. -** -** These macros also serve to document all places where FP to integer -** conversions happen. -*/ - -/* Unchecked double to int32_t conversion. */ -#define lj_num2int(n) ((int32_t)(n)) - -/* Unchecked double to arch/os-dependent signed integer type conversion. -** This assumes the 32/64-bit signed conversions are NOT range-extended. -*/ -#define lj_num2int_type(n, tp) ((tp)(n)) - -/* Convert a double to int32_t and check for exact conversion. -** Returns the zero-extended int32_t on success. -0 is OK, too. -** Returns 0x8000000080000000LL on failure (simplifies range checks). -*/ -LJ_ASMF LJ_CONSTF int64_t lj_vm_num2int_check(double x); - -/* Check for exact conversion only, without storing the result. */ -#define lj_num2int_ok(x) (lj_vm_num2int_check((x)) >= 0) - -/* Check for exact conversion and conditionally store result. -** Note: conditions that fail for 0x80000000 may check only the lower -** 32 bits. This generates good code for both 32 and 64 bit archs. -*/ -#define lj_num2int_cond(x, i64, i, cond) \ - (i64 = lj_vm_num2int_check((x)), cond ? (i = (int32_t)i64, 1) : 0) - -/* This is the generic check for a full-range int32_t result. */ -#define lj_num2int_check(x, i64, i) \ - lj_num2int_cond((x), i64, i, i64 >= 0) - -/* Predictable conversion from double to int64_t or uint64_t. -** Truncates towards zero. Out-of-range values, NaN and +-Inf return -** an arch-dependent result, but do not cause C undefined behavior. -** The uint64_t conversion accepts the union of the unsigned + signed range. -*/ -LJ_ASMF LJ_CONSTF int64_t lj_vm_num2i64(double x); -LJ_ASMF LJ_CONSTF int64_t lj_vm_num2u64(double x); - -#define lj_num2i64(x) (lj_vm_num2i64((x))) -#define lj_num2u64(x) (lj_vm_num2u64((x))) - -/* Lua BitOp conversion semantics use the 2^52 + 2^51 trick. */ -LJ_ASMF LJ_CONSTF int32_t lj_vm_tobit(double x); - -#define lj_num2bit(x) lj_vm_tobit((x)) - -static LJ_AINLINE int32_t numberVint(cTValue *o) -{ - if (LJ_LIKELY(tvisint(o))) - return intV(o); - else - return lj_num2int(numV(o)); -} - -static LJ_AINLINE lua_Number numberVnum(cTValue *o) -{ - if (LJ_UNLIKELY(tvisint(o))) - return (lua_Number)intV(o); - else - return numV(o); -} - -/* -- Miscellaneous object handling --------------------------------------- */ - -/* Names and maps for internal and external object tags. */ -LJ_DATA const char *const lj_obj_typename[1+LUA_TCDATA+1]; -LJ_DATA const char *const lj_obj_itypename[~LJ_TNUMX+1]; - -#define lj_typename(o) (lj_obj_itypename[itypemap(o)]) - -/* Compare two objects without calling metamethods. */ -LJ_FUNC int LJ_FASTCALL lj_obj_equal(cTValue *o1, cTValue *o2); -LJ_FUNC const void * LJ_FASTCALL lj_obj_ptr(global_State *g, cTValue *o); - -#if LJ_ABI_PAUTH -#if LJ_TARGET_ARM64 -#include -#define lj_ptr_sign(ptr, ctx) \ - ptrauth_sign_unauthenticated((ptr), ptrauth_key_function_pointer, (ctx)) -#define lj_ptr_strip(ptr) ptrauth_strip((ptr), ptrauth_key_function_pointer) -#else -#error "No support for pointer authentication for this architecture" -#endif -#else -#define lj_ptr_sign(ptr, ctx) (ptr) -#define lj_ptr_strip(ptr) (ptr) -#endif - -#endif diff --git a/include/luajit/lj_parse.h b/include/luajit/lj_parse.h deleted file mode 100644 index 3870a32..0000000 --- a/include/luajit/lj_parse.h +++ /dev/null @@ -1,18 +0,0 @@ -/* -** Lua parser (source code -> bytecode). -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_PARSE_H -#define _LJ_PARSE_H - -#include "lj_obj.h" -#include "lj_lex.h" - -LJ_FUNC GCproto *lj_parse(LexState *ls); -LJ_FUNC GCstr *lj_parse_keepstr(LexState *ls, const char *str, size_t l); -#if LJ_HASFFI -LJ_FUNC void lj_parse_keepcdata(LexState *ls, TValue *tv, GCcdata *cd); -#endif - -#endif diff --git a/include/luajit/lj_prng.h b/include/luajit/lj_prng.h deleted file mode 100644 index 7dc5eeb..0000000 --- a/include/luajit/lj_prng.h +++ /dev/null @@ -1,24 +0,0 @@ -/* -** Pseudo-random number generation. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_PRNG_H -#define _LJ_PRNG_H - -#include "lj_def.h" - -LJ_FUNC int LJ_FASTCALL lj_prng_seed_secure(PRNGState *rs); -LJ_FUNC uint64_t LJ_FASTCALL lj_prng_u64(PRNGState *rs); -LJ_FUNC uint64_t LJ_FASTCALL lj_prng_u64d(PRNGState *rs); - -/* This is just the precomputed result of lib_math.c:random_seed(rs, 0.0). */ -static LJ_AINLINE void lj_prng_seed_fixed(PRNGState *rs) -{ - rs->u[0] = U64x(a0d27757,0a345b8c); - rs->u[1] = U64x(764a296c,5d4aa64f); - rs->u[2] = U64x(51220704,070adeaa); - rs->u[3] = U64x(2a2717b5,a7b7b927); -} - -#endif diff --git a/include/luajit/lj_profile.h b/include/luajit/lj_profile.h deleted file mode 100644 index 24fbd9d..0000000 --- a/include/luajit/lj_profile.h +++ /dev/null @@ -1,21 +0,0 @@ -/* -** Low-overhead profiling. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_PROFILE_H -#define _LJ_PROFILE_H - -#include "lj_obj.h" - -#if LJ_HASPROFILE - -LJ_FUNC void LJ_FASTCALL lj_profile_interpreter(lua_State *L); -#if !LJ_PROFILE_SIGPROF -LJ_FUNC void LJ_FASTCALL lj_profile_hook_enter(global_State *g); -LJ_FUNC void LJ_FASTCALL lj_profile_hook_leave(global_State *g); -#endif - -#endif - -#endif diff --git a/include/luajit/lj_record.h b/include/luajit/lj_record.h deleted file mode 100644 index 2c7a575..0000000 --- a/include/luajit/lj_record.h +++ /dev/null @@ -1,47 +0,0 @@ -/* -** Trace recorder (bytecode -> SSA IR). -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_RECORD_H -#define _LJ_RECORD_H - -#include "lj_obj.h" -#include "lj_jit.h" - -#if LJ_HASJIT -/* Context for recording an indexed load/store. */ -typedef struct RecordIndex { - TValue tabv; /* Runtime value of table (or indexed object). */ - TValue keyv; /* Runtime value of key. */ - TValue valv; /* Runtime value of stored value. */ - TValue mobjv; /* Runtime value of metamethod object. */ - GCtab *mtv; /* Runtime value of metatable object. */ - cTValue *oldv; /* Runtime value of previously stored value. */ - TRef tab; /* Table (or indexed object) reference. */ - TRef key; /* Key reference. */ - TRef val; /* Value reference for a store or 0 for a load. */ - TRef mt; /* Metatable reference. */ - TRef mobj; /* Metamethod object reference. */ - int idxchain; /* Index indirections left or 0 for raw lookup. */ -} RecordIndex; - -LJ_FUNC int lj_record_objcmp(jit_State *J, TRef a, TRef b, - cTValue *av, cTValue *bv); -LJ_FUNC void lj_record_stop(jit_State *J, TraceLink linktype, TraceNo lnk); -LJ_FUNC TRef lj_record_constify(jit_State *J, cTValue *o); -LJ_FUNC TRef lj_record_vload(jit_State *J, TRef ref, MSize idx, IRType t); - -LJ_FUNC void lj_record_call(jit_State *J, BCReg func, ptrdiff_t nargs); -LJ_FUNC void lj_record_tailcall(jit_State *J, BCReg func, ptrdiff_t nargs); -LJ_FUNC void lj_record_ret(jit_State *J, BCReg rbase, ptrdiff_t gotresults); - -LJ_FUNC int lj_record_mm_lookup(jit_State *J, RecordIndex *ix, MMS mm); -LJ_FUNC TRef lj_record_idx(jit_State *J, RecordIndex *ix); -LJ_FUNC int lj_record_next(jit_State *J, RecordIndex *ix); - -LJ_FUNC void lj_record_ins(jit_State *J); -LJ_FUNC void lj_record_setup(jit_State *J); -#endif - -#endif diff --git a/include/luajit/lj_serialize.h b/include/luajit/lj_serialize.h deleted file mode 100644 index 9e082b3..0000000 --- a/include/luajit/lj_serialize.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -** Object de/serialization. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_SERIALIZE_H -#define _LJ_SERIALIZE_H - -#include "lj_obj.h" -#include "lj_buf.h" - -#if LJ_HASBUFFER - -#define LJ_SERIALIZE_DEPTH 100 /* Default depth. */ - -LJ_FUNC void LJ_FASTCALL lj_serialize_dict_prep_str(lua_State *L, GCtab *dict); -LJ_FUNC void LJ_FASTCALL lj_serialize_dict_prep_mt(lua_State *L, GCtab *dict); -LJ_FUNC SBufExt * LJ_FASTCALL lj_serialize_put(SBufExt *sbx, cTValue *o); -LJ_FUNC char * LJ_FASTCALL lj_serialize_get(SBufExt *sbx, TValue *o); -LJ_FUNC GCstr * LJ_FASTCALL lj_serialize_encode(lua_State *L, cTValue *o); -LJ_FUNC void lj_serialize_decode(lua_State *L, TValue *o, GCstr *str); -#if LJ_HASJIT -LJ_FUNC MSize LJ_FASTCALL lj_serialize_peektype(SBufExt *sbx); -#endif - -#endif - -#endif diff --git a/include/luajit/lj_snap.h b/include/luajit/lj_snap.h deleted file mode 100644 index 0958c16..0000000 --- a/include/luajit/lj_snap.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -** Snapshot handling. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_SNAP_H -#define _LJ_SNAP_H - -#include "lj_obj.h" -#include "lj_jit.h" - -#if LJ_HASJIT -LJ_FUNC void lj_snap_add(jit_State *J); -LJ_FUNC void lj_snap_purge(jit_State *J); -LJ_FUNC void lj_snap_shrink(jit_State *J); -LJ_FUNC IRIns *lj_snap_regspmap(jit_State *J, GCtrace *T, SnapNo snapno, - IRIns *ir); -LJ_FUNC void lj_snap_replay(jit_State *J, GCtrace *T); -LJ_FUNC const BCIns *lj_snap_restore(jit_State *J, void *exptr); -LJ_FUNC void lj_snap_grow_buf_(jit_State *J, MSize need); -LJ_FUNC void lj_snap_grow_map_(jit_State *J, MSize need); - -static LJ_AINLINE void lj_snap_grow_buf(jit_State *J, MSize need) -{ - if (LJ_UNLIKELY(need > J->sizesnap)) lj_snap_grow_buf_(J, need); -} - -static LJ_AINLINE void lj_snap_grow_map(jit_State *J, MSize need) -{ - if (LJ_UNLIKELY(need > J->sizesnapmap)) lj_snap_grow_map_(J, need); -} - -#endif - -#endif diff --git a/include/luajit/lj_state.h b/include/luajit/lj_state.h deleted file mode 100644 index 15f9fd4..0000000 --- a/include/luajit/lj_state.h +++ /dev/null @@ -1,38 +0,0 @@ -/* -** State and stack handling. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_STATE_H -#define _LJ_STATE_H - -#include "lj_obj.h" - -#define incr_top(L) \ - (++L->top >= tvref(L->maxstack) && (lj_state_growstack1(L), 0)) - -#define savestack(L, p) ((char *)(p) - mref(L->stack, char)) -#define restorestack(L, n) ((TValue *)(mref(L->stack, char) + (n))) - -LJ_FUNC void lj_state_relimitstack(lua_State *L); -LJ_FUNC void lj_state_shrinkstack(lua_State *L, MSize used); -LJ_FUNCA void LJ_FASTCALL lj_state_growstack(lua_State *L, MSize need); -LJ_FUNC void LJ_FASTCALL lj_state_growstack1(lua_State *L); -LJ_FUNC int LJ_FASTCALL lj_state_cpgrowstack(lua_State *L, MSize need); - -static LJ_AINLINE void lj_state_checkstack(lua_State *L, MSize need) -{ - if ((mref(L->maxstack, char) - (char *)L->top) <= - (ptrdiff_t)need*(ptrdiff_t)sizeof(TValue)) - lj_state_growstack(L, need); -} - -LJ_FUNC lua_State *lj_state_new(lua_State *L); -LJ_FUNC void LJ_FASTCALL lj_state_free(global_State *g, lua_State *L); -#if LJ_64 && !LJ_GC64 && !(defined(LUAJIT_USE_VALGRIND) && defined(LUAJIT_USE_SYSMALLOC)) -LJ_FUNC lua_State *lj_state_newstate(lua_Alloc f, void *ud); -#endif - -#define LJ_ALLOCF_INTERNAL ((lua_Alloc)(void *)(uintptr_t)(1237<<4)) - -#endif diff --git a/include/luajit/lj_str.h b/include/luajit/lj_str.h deleted file mode 100644 index 44341b9..0000000 --- a/include/luajit/lj_str.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -** String handling. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_STR_H -#define _LJ_STR_H - -#include - -#include "lj_obj.h" - -/* String helpers. */ -LJ_FUNC int32_t LJ_FASTCALL lj_str_cmp(GCstr *a, GCstr *b); -LJ_FUNC const char *lj_str_find(const char *s, const char *f, - MSize slen, MSize flen); -LJ_FUNC int lj_str_haspattern(GCstr *s); - -/* String interning. */ -LJ_FUNC void lj_str_resize(lua_State *L, MSize newmask); -LJ_FUNCA GCstr *lj_str_new(lua_State *L, const char *str, size_t len); -LJ_FUNC void LJ_FASTCALL lj_str_free(global_State *g, GCstr *s); -LJ_FUNC void LJ_FASTCALL lj_str_init(lua_State *L); -#define lj_str_freetab(g) \ - (lj_mem_freevec(g, g->str.tab, g->str.mask+1, GCRef)) - -#define lj_str_newz(L, s) (lj_str_new(L, s, strlen(s))) -#define lj_str_newlit(L, s) (lj_str_new(L, "" s, sizeof(s)-1)) -#define lj_str_size(len) (sizeof(GCstr) + (((len)+4) & ~(MSize)3)) - -#endif diff --git a/include/luajit/lj_strfmt.h b/include/luajit/lj_strfmt.h deleted file mode 100644 index 43cf537..0000000 --- a/include/luajit/lj_strfmt.h +++ /dev/null @@ -1,131 +0,0 @@ -/* -** String formatting. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_STRFMT_H -#define _LJ_STRFMT_H - -#include "lj_obj.h" - -typedef uint32_t SFormat; /* Format indicator. */ - -/* Format parser state. */ -typedef struct FormatState { - const uint8_t *p; /* Current format string pointer. */ - const uint8_t *e; /* End of format string. */ - const char *str; /* Returned literal string. */ - MSize len; /* Size of literal string. */ -} FormatState; - -/* Format types (max. 16). */ -typedef enum FormatType { - STRFMT_EOF, STRFMT_ERR, STRFMT_LIT, - STRFMT_INT, STRFMT_UINT, STRFMT_NUM, STRFMT_STR, STRFMT_CHAR, STRFMT_PTR -} FormatType; - -/* Format subtypes (bits are reused). */ -#define STRFMT_T_HEX 0x0010 /* STRFMT_UINT */ -#define STRFMT_T_OCT 0x0020 /* STRFMT_UINT */ -#define STRFMT_T_FP_A 0x0000 /* STRFMT_NUM */ -#define STRFMT_T_FP_E 0x0010 /* STRFMT_NUM */ -#define STRFMT_T_FP_F 0x0020 /* STRFMT_NUM */ -#define STRFMT_T_FP_G 0x0030 /* STRFMT_NUM */ -#define STRFMT_T_QUOTED 0x0010 /* STRFMT_STR */ - -/* Format flags. */ -#define STRFMT_F_LEFT 0x0100 -#define STRFMT_F_PLUS 0x0200 -#define STRFMT_F_ZERO 0x0400 -#define STRFMT_F_SPACE 0x0800 -#define STRFMT_F_ALT 0x1000 -#define STRFMT_F_UPPER 0x2000 - -/* Format indicator fields. */ -#define STRFMT_SH_WIDTH 16 -#define STRFMT_SH_PREC 24 - -#define STRFMT_TYPE(sf) ((FormatType)((sf) & 15)) -#define STRFMT_WIDTH(sf) (((sf) >> STRFMT_SH_WIDTH) & 255u) -#define STRFMT_PREC(sf) ((((sf) >> STRFMT_SH_PREC) & 255u) - 1u) -#define STRFMT_FP(sf) (((sf) >> 4) & 3) - -/* Formats for conversion characters. */ -#define STRFMT_A (STRFMT_NUM|STRFMT_T_FP_A) -#define STRFMT_C (STRFMT_CHAR) -#define STRFMT_D (STRFMT_INT) -#define STRFMT_E (STRFMT_NUM|STRFMT_T_FP_E) -#define STRFMT_F (STRFMT_NUM|STRFMT_T_FP_F) -#define STRFMT_G (STRFMT_NUM|STRFMT_T_FP_G) -#define STRFMT_I STRFMT_D -#define STRFMT_O (STRFMT_UINT|STRFMT_T_OCT) -#define STRFMT_P (STRFMT_PTR) -#define STRFMT_Q (STRFMT_STR|STRFMT_T_QUOTED) -#define STRFMT_S (STRFMT_STR) -#define STRFMT_U (STRFMT_UINT) -#define STRFMT_X (STRFMT_UINT|STRFMT_T_HEX) -#define STRFMT_G14 (STRFMT_G | ((14+1) << STRFMT_SH_PREC)) - -/* Maximum buffer sizes for conversions. */ -#define STRFMT_MAXBUF_XINT (1+22) /* '0' prefix + uint64_t in octal. */ -#define STRFMT_MAXBUF_INT (1+10) /* Sign + int32_t in decimal. */ -#define STRFMT_MAXBUF_NUM 32 /* Must correspond with STRFMT_G14. */ -#define STRFMT_MAXBUF_PTR (2+2*sizeof(ptrdiff_t)) /* "0x" + hex ptr. */ - -/* Format parser. */ -LJ_FUNC SFormat LJ_FASTCALL lj_strfmt_parse(FormatState *fs); - -static LJ_AINLINE void lj_strfmt_init(FormatState *fs, const char *p, MSize len) -{ - fs->p = (const uint8_t *)p; - fs->e = (const uint8_t *)p + len; - /* Must be NUL-terminated. May have NULs inside, too. */ - lj_assertX(*fs->e == 0, "format not NUL-terminated"); -} - -/* Raw conversions. */ -LJ_FUNC char * LJ_FASTCALL lj_strfmt_wint(char *p, int32_t k); -LJ_FUNC char * LJ_FASTCALL lj_strfmt_wptr(char *p, const void *v); -LJ_FUNC char * LJ_FASTCALL lj_strfmt_wuleb128(char *p, uint32_t v); -LJ_FUNC const char *lj_strfmt_wstrnum(lua_State *L, cTValue *o, MSize *lenp); - -/* Unformatted conversions to buffer. */ -LJ_FUNC SBuf * LJ_FASTCALL lj_strfmt_putint(SBuf *sb, int32_t k); -#if LJ_HASJIT -LJ_FUNC SBuf * LJ_FASTCALL lj_strfmt_putnum(SBuf *sb, cTValue *o); -#endif -LJ_FUNC SBuf * LJ_FASTCALL lj_strfmt_putptr(SBuf *sb, const void *v); -#if LJ_HASJIT -LJ_FUNC SBuf * LJ_FASTCALL lj_strfmt_putquoted(SBuf *sb, GCstr *str); -#endif - -/* Formatted conversions to buffer. */ -LJ_FUNC SBuf *lj_strfmt_putfxint(SBuf *sb, SFormat sf, uint64_t k); -LJ_FUNC SBuf *lj_strfmt_putfnum_int(SBuf *sb, SFormat sf, lua_Number n); -LJ_FUNC SBuf *lj_strfmt_putfnum_uint(SBuf *sb, SFormat sf, lua_Number n); -LJ_FUNC SBuf *lj_strfmt_putfnum(SBuf *sb, SFormat, lua_Number n); -LJ_FUNC SBuf *lj_strfmt_putfchar(SBuf *sb, SFormat, int32_t c); -#if LJ_HASJIT -LJ_FUNC SBuf *lj_strfmt_putfstr(SBuf *sb, SFormat, GCstr *str); -#endif -LJ_FUNC int lj_strfmt_putarg(lua_State *L, SBuf *sb, int arg, int retry); - -/* Conversions to strings. */ -LJ_FUNC GCstr * LJ_FASTCALL lj_strfmt_int(lua_State *L, int32_t k); -LJ_FUNCA GCstr * LJ_FASTCALL lj_strfmt_num(lua_State *L, cTValue *o); -LJ_FUNCA GCstr * LJ_FASTCALL lj_strfmt_number(lua_State *L, cTValue *o); -#if LJ_HASJIT -LJ_FUNC GCstr * LJ_FASTCALL lj_strfmt_char(lua_State *L, int c); -#endif -LJ_FUNC GCstr * LJ_FASTCALL lj_strfmt_obj(lua_State *L, cTValue *o); - -/* Internal string formatting. */ -LJ_FUNC const char *lj_strfmt_pushvf(lua_State *L, const char *fmt, - va_list argp); -LJ_FUNC const char *lj_strfmt_pushf(lua_State *L, const char *fmt, ...) -#if defined(__GNUC__) || defined(__clang__) - __attribute__ ((format (printf, 2, 3))) -#endif - ; - -#endif diff --git a/include/luajit/lj_strscan.h b/include/luajit/lj_strscan.h deleted file mode 100644 index 397fb76..0000000 --- a/include/luajit/lj_strscan.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -** String scanning. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_STRSCAN_H -#define _LJ_STRSCAN_H - -#include "lj_obj.h" - -/* Options for accepted/returned formats. */ -#define STRSCAN_OPT_TOINT 0x01 /* Convert to int32_t, if possible. */ -#define STRSCAN_OPT_TONUM 0x02 /* Always convert to double. */ -#define STRSCAN_OPT_IMAG 0x04 -#define STRSCAN_OPT_LL 0x08 -#define STRSCAN_OPT_C 0x10 - -/* Returned format. */ -typedef enum { - STRSCAN_ERROR, - STRSCAN_NUM, STRSCAN_IMAG, - STRSCAN_INT, STRSCAN_U32, STRSCAN_I64, STRSCAN_U64, -} StrScanFmt; - -LJ_FUNC StrScanFmt lj_strscan_scan(const uint8_t *p, MSize len, TValue *o, - uint32_t opt); -LJ_FUNC int LJ_FASTCALL lj_strscan_num(GCstr *str, TValue *o); -#if LJ_DUALNUM -LJ_FUNC int LJ_FASTCALL lj_strscan_number(GCstr *str, TValue *o); -#else -#define lj_strscan_number(s, o) lj_strscan_num((s), (o)) -#endif - -/* Check for number or convert string to number/int in-place (!). */ -static LJ_AINLINE int lj_strscan_numberobj(TValue *o) -{ - return tvisnumber(o) || (tvisstr(o) && lj_strscan_number(strV(o), o)); -} - -#endif diff --git a/include/luajit/lj_tab.h b/include/luajit/lj_tab.h deleted file mode 100644 index 4296d10..0000000 --- a/include/luajit/lj_tab.h +++ /dev/null @@ -1,93 +0,0 @@ -/* -** Table handling. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_TAB_H -#define _LJ_TAB_H - -#include "lj_obj.h" - -/* Hash constants. Tuned using a brute force search. */ -#define HASH_BIAS (-0x04c11db7) -#define HASH_ROT1 14 -#define HASH_ROT2 5 -#define HASH_ROT3 13 - -/* Scramble the bits of numbers and pointers. */ -static LJ_AINLINE uint32_t hashrot(uint32_t lo, uint32_t hi) -{ -#if LJ_TARGET_X86ORX64 - /* Prefer variant that compiles well for a 2-operand CPU. */ - lo ^= hi; hi = lj_rol(hi, HASH_ROT1); - lo -= hi; hi = lj_rol(hi, HASH_ROT2); - hi ^= lo; hi -= lj_rol(lo, HASH_ROT3); -#else - lo ^= hi; - lo = lo - lj_rol(hi, HASH_ROT1); - hi = lo ^ lj_rol(hi, HASH_ROT1 + HASH_ROT2); - hi = hi - lj_rol(lo, HASH_ROT3); -#endif - return hi; -} - -/* Hash values are masked with the table hash mask and used as an index. */ -static LJ_AINLINE Node *hashmask(const GCtab *t, uint32_t hash) -{ - Node *n = noderef(t->node); - return &n[hash & t->hmask]; -} - -/* String IDs are generated when a string is interned. */ -#define hashstr(t, s) hashmask(t, (s)->sid) - -#define hashlohi(t, lo, hi) hashmask((t), hashrot((lo), (hi))) -#define hashnum(t, o) hashlohi((t), (o)->u32.lo, ((o)->u32.hi << 1)) -#if LJ_GC64 -#define hashgcref(t, r) \ - hashlohi((t), (uint32_t)gcrefu(r), (uint32_t)(gcrefu(r) >> 32)) -#else -#define hashgcref(t, r) hashlohi((t), gcrefu(r), gcrefu(r) + HASH_BIAS) -#endif - -#define hsize2hbits(s) ((s) ? ((s)==1 ? 1 : 1+lj_fls((uint32_t)((s)-1))) : 0) - -LJ_FUNCA GCtab *lj_tab_new(lua_State *L, uint32_t asize, uint32_t hbits); -LJ_FUNC GCtab *lj_tab_new_ah(lua_State *L, int32_t a, int32_t h); -#if LJ_HASJIT -LJ_FUNC GCtab * LJ_FASTCALL lj_tab_new1(lua_State *L, uint32_t ahsize); -#endif -LJ_FUNCA GCtab * LJ_FASTCALL lj_tab_dup(lua_State *L, const GCtab *kt); -LJ_FUNC void LJ_FASTCALL lj_tab_clear(GCtab *t); -LJ_FUNC void LJ_FASTCALL lj_tab_free(global_State *g, GCtab *t); -LJ_FUNC void lj_tab_resize(lua_State *L, GCtab *t, uint32_t asize, uint32_t hbits); -LJ_FUNCA void lj_tab_reasize(lua_State *L, GCtab *t, uint32_t nasize); - -/* Caveat: all getters except lj_tab_get() can return NULL! */ - -LJ_FUNCA cTValue * LJ_FASTCALL lj_tab_getinth(GCtab *t, int32_t key); -LJ_FUNC cTValue *lj_tab_getstr(GCtab *t, const GCstr *key); -LJ_FUNCA cTValue *lj_tab_get(lua_State *L, GCtab *t, cTValue *key); - -/* Caveat: all setters require a write barrier for the stored value. */ - -LJ_FUNCA TValue *lj_tab_newkey(lua_State *L, GCtab *t, cTValue *key); -LJ_FUNCA TValue *lj_tab_setinth(lua_State *L, GCtab *t, int32_t key); -LJ_FUNC TValue *lj_tab_setstr(lua_State *L, GCtab *t, const GCstr *key); -LJ_FUNC TValue *lj_tab_set(lua_State *L, GCtab *t, cTValue *key); - -#define inarray(t, key) ((MSize)(key) < (MSize)(t)->asize) -#define arrayslot(t, i) (&tvref((t)->array)[(i)]) -#define lj_tab_getint(t, key) \ - (inarray((t), (key)) ? arrayslot((t), (key)) : lj_tab_getinth((t), (key))) -#define lj_tab_setint(L, t, key) \ - (inarray((t), (key)) ? arrayslot((t), (key)) : lj_tab_setinth(L, (t), (key))) - -LJ_FUNC uint32_t LJ_FASTCALL lj_tab_keyindex(GCtab *t, cTValue *key); -LJ_FUNCA int lj_tab_next(GCtab *t, cTValue *key, TValue *o); -LJ_FUNCA MSize LJ_FASTCALL lj_tab_len(GCtab *t); -#if LJ_HASJIT -LJ_FUNC MSize LJ_FASTCALL lj_tab_len_hint(GCtab *t, size_t hint); -#endif - -#endif diff --git a/include/luajit/lj_target.h b/include/luajit/lj_target.h deleted file mode 100644 index 4759243..0000000 --- a/include/luajit/lj_target.h +++ /dev/null @@ -1,164 +0,0 @@ -/* -** Definitions for target CPU. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_TARGET_H -#define _LJ_TARGET_H - -#include "lj_def.h" -#include "lj_arch.h" - -/* -- Registers and spill slots ------------------------------------------- */ - -/* Register type (uint8_t in ir->r). */ -typedef uint32_t Reg; - -/* The hi-bit is NOT set for an allocated register. This means the value -** can be directly used without masking. The hi-bit is set for a register -** allocation hint or for RID_INIT, RID_SINK or RID_SUNK. -*/ -#define RID_NONE 0x80 -#define RID_MASK 0x7f -#define RID_INIT (RID_NONE|RID_MASK) -#define RID_SINK (RID_INIT-1) -#define RID_SUNK (RID_INIT-2) - -#define ra_noreg(r) ((r) & RID_NONE) -#define ra_hasreg(r) (!((r) & RID_NONE)) - -/* The ra_hashint() macro assumes a previous test for ra_noreg(). */ -#define ra_hashint(r) ((r) < RID_SUNK) -#define ra_gethint(r) ((Reg)((r) & RID_MASK)) -#define ra_sethint(rr, r) rr = (uint8_t)((r)|RID_NONE) -#define ra_samehint(r1, r2) (ra_gethint((r1)^(r2)) == 0) - -/* Spill slot 0 means no spill slot has been allocated. */ -#define SPS_NONE 0 - -#define ra_hasspill(s) ((s) != SPS_NONE) - -/* Combined register and spill slot (uint16_t in ir->prev). */ -typedef uint32_t RegSP; - -#define REGSP(r, s) ((r) + ((s) << 8)) -#define REGSP_HINT(r) ((r)|RID_NONE) -#define REGSP_INIT REGSP(RID_INIT, 0) - -#define regsp_reg(rs) ((rs) & 255) -#define regsp_spill(rs) ((rs) >> 8) -#define regsp_used(rs) \ - (((rs) & ~REGSP(RID_MASK, 0)) != REGSP(RID_NONE, 0)) - -/* -- Register sets ------------------------------------------------------- */ - -/* Bitset for registers. 32 registers suffice for most architectures. -** Note that one set holds bits for both GPRs and FPRs. -*/ -#if LJ_TARGET_PPC || LJ_TARGET_MIPS || LJ_TARGET_ARM64 -typedef uint64_t RegSet; -#define RSET_BITS 6 -#define rset_picktop_(rs) ((Reg)lj_fls64(rs)) -#define rset_pickbot_(rs) ((Reg)lj_ffs64(rs)) -#else -typedef uint32_t RegSet; -#define RSET_BITS 5 -#define rset_picktop_(rs) ((Reg)lj_fls(rs)) -#define rset_pickbot_(rs) ((Reg)lj_ffs(rs)) -#endif - -#define RID2RSET(r) (((RegSet)1) << (r)) -#define RSET_EMPTY ((RegSet)0) -#define RSET_RANGE(lo, hi) ((RID2RSET((hi)-(lo))-1) << (lo)) - -#define rset_test(rs, r) ((int)((rs) >> (r)) & 1) -#define rset_set(rs, r) (rs |= RID2RSET(r)) -#define rset_clear(rs, r) (rs &= ~RID2RSET(r)) -#define rset_exclude(rs, r) (rs & ~RID2RSET(r)) - -/* -- Register allocation cost -------------------------------------------- */ - -/* The register allocation heuristic keeps track of the cost for allocating -** a specific register: -** -** A free register (obviously) has a cost of 0 and a 1-bit in the free mask. -** -** An already allocated register has the (non-zero) IR reference in the lowest -** bits and the result of a blended cost-model in the higher bits. -** -** The allocator first checks the free mask for a hit. Otherwise an (unrolled) -** linear search for the minimum cost is used. The search doesn't need to -** keep track of the position of the minimum, which makes it very fast. -** The lowest bits of the minimum cost show the desired IR reference whose -** register is the one to evict. -** -** Without the cost-model this degenerates to the standard heuristics for -** (reverse) linear-scan register allocation. Since code generation is done -** in reverse, a live interval extends from the last use to the first def. -** For an SSA IR the IR reference is the first (and only) def and thus -** trivially marks the end of the interval. The LSRA heuristics says to pick -** the register whose live interval has the furthest extent, i.e. the lowest -** IR reference in our case. -** -** A cost-model should take into account other factors, like spill-cost and -** restore- or rematerialization-cost, which depend on the kind of instruction. -** E.g. constants have zero spill costs, variant instructions have higher -** costs than invariants and PHIs should preferably never be spilled. -** -** Here's a first cut at simple, but effective blended cost-model for R-LSRA: -** - Due to careful design of the IR, constants already have lower IR -** references than invariants and invariants have lower IR references -** than variants. -** - The cost in the upper 16 bits is the sum of the IR reference and a -** weighted score. The score currently only takes into account whether -** the IRT_ISPHI bit is set in the instruction type. -** - The PHI weight is the minimum distance (in IR instructions) a PHI -** reference has to be further apart from a non-PHI reference to be spilled. -** - It should be a power of two (for speed) and must be between 2 and 32768. -** Good values for the PHI weight seem to be between 40 and 150. -** - Further study is required. -*/ -#define REGCOST_PHI_WEIGHT 64 - -/* Cost for allocating a specific register. */ -typedef uint32_t RegCost; - -/* Note: assumes 16 bit IRRef1. */ -#define REGCOST(cost, ref) ((RegCost)(ref) + ((RegCost)(cost) << 16)) -#define regcost_ref(rc) ((IRRef1)(rc)) - -#define REGCOST_T(t) \ - ((RegCost)((t)&IRT_ISPHI) * (((RegCost)(REGCOST_PHI_WEIGHT)<<16)/IRT_ISPHI)) -#define REGCOST_REF_T(ref, t) (REGCOST((ref), (ref)) + REGCOST_T((t))) - -/* -- Target-specific definitions ----------------------------------------- */ - -#if LJ_TARGET_X86ORX64 -#include "lj_target_x86.h" -#elif LJ_TARGET_ARM -#include "lj_target_arm.h" -#elif LJ_TARGET_ARM64 -#include "lj_target_arm64.h" -#elif LJ_TARGET_PPC -#include "lj_target_ppc.h" -#elif LJ_TARGET_MIPS -#include "lj_target_mips.h" -#else -#error "Missing include for target CPU" -#endif - -#ifdef EXITSTUBS_PER_GROUP -/* Return the address of an exit stub. */ -static LJ_AINLINE char *exitstub_addr_(char **group, uint32_t exitno) -{ - lj_assertX(group[exitno / EXITSTUBS_PER_GROUP] != NULL, - "exit stub group for exit %d uninitialized", exitno); - return (char *)group[exitno / EXITSTUBS_PER_GROUP] + - EXITSTUB_SPACING*(exitno % EXITSTUBS_PER_GROUP); -} -/* Avoid dependence on lj_jit.h if only including lj_target.h. */ -#define exitstub_addr(J, exitno) \ - ((MCode *)exitstub_addr_((char **)((J)->exitstubgroup), (exitno))) -#endif - -#endif diff --git a/include/luajit/lj_target_arm.h b/include/luajit/lj_target_arm.h deleted file mode 100644 index 947545f..0000000 --- a/include/luajit/lj_target_arm.h +++ /dev/null @@ -1,273 +0,0 @@ -/* -** Definitions for ARM CPUs. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_TARGET_ARM_H -#define _LJ_TARGET_ARM_H - -/* -- Registers IDs ------------------------------------------------------- */ - -#define GPRDEF(_) \ - _(R0) _(R1) _(R2) _(R3) _(R4) _(R5) _(R6) _(R7) \ - _(R8) _(R9) _(R10) _(R11) _(R12) _(SP) _(LR) _(PC) -#if LJ_SOFTFP -#define FPRDEF(_) -#else -#define FPRDEF(_) \ - _(D0) _(D1) _(D2) _(D3) _(D4) _(D5) _(D6) _(D7) \ - _(D8) _(D9) _(D10) _(D11) _(D12) _(D13) _(D14) _(D15) -#endif -#define VRIDDEF(_) - -#define RIDENUM(name) RID_##name, - -enum { - GPRDEF(RIDENUM) /* General-purpose registers (GPRs). */ - FPRDEF(RIDENUM) /* Floating-point registers (FPRs). */ - RID_MAX, - RID_TMP = RID_LR, - - /* Calling conventions. */ - RID_RET = RID_R0, - RID_RETLO = RID_R0, - RID_RETHI = RID_R1, -#if LJ_SOFTFP - RID_FPRET = RID_R0, -#else - RID_FPRET = RID_D0, -#endif - - /* These definitions must match with the *.dasc file(s): */ - RID_BASE = RID_R9, /* Interpreter BASE. */ - RID_LPC = RID_R6, /* Interpreter PC. */ - RID_DISPATCH = RID_R7, /* Interpreter DISPATCH table. */ - RID_LREG = RID_R8, /* Interpreter L. */ - - /* Register ranges [min, max) and number of registers. */ - RID_MIN_GPR = RID_R0, - RID_MAX_GPR = RID_PC+1, - RID_MIN_FPR = RID_MAX_GPR, -#if LJ_SOFTFP - RID_MAX_FPR = RID_MIN_FPR, -#else - RID_MAX_FPR = RID_D15+1, -#endif - RID_NUM_GPR = RID_MAX_GPR - RID_MIN_GPR, - RID_NUM_FPR = RID_MAX_FPR - RID_MIN_FPR -}; - -#define RID_NUM_KREF RID_NUM_GPR -#define RID_MIN_KREF RID_R0 - -/* -- Register sets ------------------------------------------------------- */ - -/* Make use of all registers, except sp, lr and pc. */ -#define RSET_GPR (RSET_RANGE(RID_MIN_GPR, RID_R12+1)) -#define RSET_GPREVEN \ - (RID2RSET(RID_R0)|RID2RSET(RID_R2)|RID2RSET(RID_R4)|RID2RSET(RID_R6)| \ - RID2RSET(RID_R8)|RID2RSET(RID_R10)) -#define RSET_GPRODD \ - (RID2RSET(RID_R1)|RID2RSET(RID_R3)|RID2RSET(RID_R5)|RID2RSET(RID_R7)| \ - RID2RSET(RID_R9)|RID2RSET(RID_R11)) -#if LJ_SOFTFP -#define RSET_FPR 0 -#else -#define RSET_FPR (RSET_RANGE(RID_MIN_FPR, RID_MAX_FPR)) -#endif -#define RSET_ALL (RSET_GPR|RSET_FPR) -#define RSET_INIT RSET_ALL - -/* ABI-specific register sets. lr is an implicit scratch register. */ -#define RSET_SCRATCH_GPR_ (RSET_RANGE(RID_R0, RID_R3+1)|RID2RSET(RID_R12)) -#ifdef __APPLE__ -#define RSET_SCRATCH_GPR (RSET_SCRATCH_GPR_|RID2RSET(RID_R9)) -#else -#define RSET_SCRATCH_GPR RSET_SCRATCH_GPR_ -#endif -#if LJ_SOFTFP -#define RSET_SCRATCH_FPR 0 -#else -#define RSET_SCRATCH_FPR (RSET_RANGE(RID_D0, RID_D7+1)) -#endif -#define RSET_SCRATCH (RSET_SCRATCH_GPR|RSET_SCRATCH_FPR) -#define REGARG_FIRSTGPR RID_R0 -#define REGARG_LASTGPR RID_R3 -#define REGARG_NUMGPR 4 -#if LJ_ABI_SOFTFP -#define REGARG_FIRSTFPR 0 -#define REGARG_LASTFPR 0 -#define REGARG_NUMFPR 0 -#else -#define REGARG_FIRSTFPR RID_D0 -#define REGARG_LASTFPR RID_D7 -#define REGARG_NUMFPR 8 -#endif - -/* -- Spill slots --------------------------------------------------------- */ - -/* Spill slots are 32 bit wide. An even/odd pair is used for FPRs. -** -** SPS_FIXED: Available fixed spill slots in interpreter frame. -** This definition must match with the *.dasc file(s). -** -** SPS_FIRST: First spill slot for general use. Reserve min. two 32 bit slots. -*/ -#define SPS_FIXED 2 -#define SPS_FIRST 2 - -#define SPOFS_TMP 0 - -#define sps_scale(slot) (4 * (int32_t)(slot)) -#define sps_align(slot) (((slot) - SPS_FIXED + 1) & ~1) - -/* -- Exit state ---------------------------------------------------------- */ - -/* This definition must match with the *.dasc file(s). */ -typedef struct { -#if !LJ_SOFTFP - lua_Number fpr[RID_NUM_FPR]; /* Floating-point registers. */ -#endif - int32_t gpr[RID_NUM_GPR]; /* General-purpose registers. */ - int32_t spill[256]; /* Spill slots. */ -} ExitState; - -/* PC after instruction that caused an exit. Used to find the trace number. */ -#define EXITSTATE_PCREG RID_PC -/* Highest exit + 1 indicates stack check. */ -#define EXITSTATE_CHECKEXIT 1 - -#define EXITSTUB_SPACING 4 -#define EXITSTUBS_PER_GROUP 32 - -/* -- Instructions -------------------------------------------------------- */ - -/* Instruction fields. */ -#define ARMF_CC(ai, cc) (((ai) ^ ARMI_CCAL) | ((cc) << 28)) -#define ARMF_N(r) ((r) << 16) -#define ARMF_D(r) ((r) << 12) -#define ARMF_S(r) ((r) << 8) -#define ARMF_M(r) (r) -#define ARMF_SH(sh, n) (((sh) << 5) | ((n) << 7)) -#define ARMF_RSH(sh, r) (0x10 | ((sh) << 5) | ARMF_S(r)) - -typedef enum ARMIns { - ARMI_CCAL = 0xe0000000, - ARMI_S = 0x000100000, - ARMI_K12 = 0x02000000, - ARMI_KNEG = 0x00200000, - ARMI_LS_W = 0x00200000, - ARMI_LS_U = 0x00800000, - ARMI_LS_P = 0x01000000, - ARMI_LS_R = 0x02000000, - ARMI_LSX_I = 0x00400000, - - ARMI_AND = 0xe0000000, - ARMI_EOR = 0xe0200000, - ARMI_SUB = 0xe0400000, - ARMI_RSB = 0xe0600000, - ARMI_ADD = 0xe0800000, - ARMI_ADC = 0xe0a00000, - ARMI_SBC = 0xe0c00000, - ARMI_RSC = 0xe0e00000, - ARMI_TST = 0xe1100000, - ARMI_TEQ = 0xe1300000, - ARMI_CMP = 0xe1500000, - ARMI_CMN = 0xe1700000, - ARMI_ORR = 0xe1800000, - ARMI_MOV = 0xe1a00000, - ARMI_BIC = 0xe1c00000, - ARMI_MVN = 0xe1e00000, - - ARMI_NOP = 0xe1a00000, - - ARMI_MUL = 0xe0000090, - ARMI_SMULL = 0xe0c00090, - - ARMI_LDR = 0xe4100000, - ARMI_LDRB = 0xe4500000, - ARMI_LDRH = 0xe01000b0, - ARMI_LDRSB = 0xe01000d0, - ARMI_LDRSH = 0xe01000f0, - ARMI_LDRD = 0xe00000d0, - ARMI_LDRL = 0xe51f0000, - ARMI_STR = 0xe4000000, - ARMI_STRB = 0xe4400000, - ARMI_STRH = 0xe00000b0, - ARMI_STRD = 0xe00000f0, - ARMI_PUSH = 0xe92d0000, - - ARMI_B = 0xea000000, - ARMI_BL = 0xeb000000, - ARMI_BLX = 0xfa000000, - ARMI_BLXr = 0xe12fff30, - ARMI_BX = 0xe12fff10, - - /* ARMv6 */ - ARMI_REV = 0xe6bf0f30, - ARMI_SXTB = 0xe6af0070, - ARMI_SXTH = 0xe6bf0070, - ARMI_UXTB = 0xe6ef0070, - ARMI_UXTH = 0xe6ff0070, - - /* ARMv6T2 */ - ARMI_MOVW = 0xe3000000, - ARMI_MOVT = 0xe3400000, - ARMI_BFI = 0xe7c00010, - - /* VFP */ - ARMI_VMOV_D = 0xeeb00b40, - ARMI_VMOV_S = 0xeeb00a40, - ARMI_VMOVI_D = 0xeeb00b00, - - ARMI_VMOV_R_S = 0xee100a10, - ARMI_VMOV_S_R = 0xee000a10, - ARMI_VMOV_RR_D = 0xec500b10, - ARMI_VMOV_D_RR = 0xec400b10, - - ARMI_VADD_D = 0xee300b00, - ARMI_VSUB_D = 0xee300b40, - ARMI_VMUL_D = 0xee200b00, - ARMI_VMLA_D = 0xee000b00, - ARMI_VMLS_D = 0xee000b40, - ARMI_VNMLS_D = 0xee100b00, - ARMI_VDIV_D = 0xee800b00, - - ARMI_VABS_D = 0xeeb00bc0, - ARMI_VNEG_D = 0xeeb10b40, - ARMI_VSQRT_D = 0xeeb10bc0, - - ARMI_VCMP_D = 0xeeb40b40, - ARMI_VCMPZ_D = 0xeeb50b40, - - ARMI_VMRS = 0xeef1fa10, - - ARMI_VCVT_S32_F32 = 0xeebd0ac0, - ARMI_VCVT_S32_F64 = 0xeebd0bc0, - ARMI_VCVT_U32_F32 = 0xeebc0ac0, - ARMI_VCVT_U32_F64 = 0xeebc0bc0, - ARMI_VCVT_F32_S32 = 0xeeb80ac0, - ARMI_VCVT_F64_S32 = 0xeeb80bc0, - ARMI_VCVT_F32_U32 = 0xeeb80a40, - ARMI_VCVT_F64_U32 = 0xeeb80b40, - ARMI_VCVT_F32_F64 = 0xeeb70bc0, - ARMI_VCVT_F64_F32 = 0xeeb70ac0, - - ARMI_VLDR_S = 0xed100a00, - ARMI_VLDR_D = 0xed100b00, - ARMI_VSTR_S = 0xed000a00, - ARMI_VSTR_D = 0xed000b00, -} ARMIns; - -typedef enum ARMShift { - ARMSH_LSL, ARMSH_LSR, ARMSH_ASR, ARMSH_ROR -} ARMShift; - -/* ARM condition codes. */ -typedef enum ARMCC { - CC_EQ, CC_NE, CC_CS, CC_CC, CC_MI, CC_PL, CC_VS, CC_VC, - CC_HI, CC_LS, CC_GE, CC_LT, CC_GT, CC_LE, CC_AL, - CC_HS = CC_CS, CC_LO = CC_CC -} ARMCC; - -#endif diff --git a/include/luajit/lj_target_arm64.h b/include/luajit/lj_target_arm64.h deleted file mode 100644 index 3113d14..0000000 --- a/include/luajit/lj_target_arm64.h +++ /dev/null @@ -1,351 +0,0 @@ -/* -** Definitions for ARM64 CPUs. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_TARGET_ARM64_H -#define _LJ_TARGET_ARM64_H - -/* -- Registers IDs ------------------------------------------------------- */ - -#define GPRDEF(_) \ - _(X0) _(X1) _(X2) _(X3) _(X4) _(X5) _(X6) _(X7) \ - _(X8) _(X9) _(X10) _(X11) _(X12) _(X13) _(X14) _(X15) \ - _(X16) _(X17) _(X18) _(X19) _(X20) _(X21) _(X22) _(X23) \ - _(X24) _(X25) _(X26) _(X27) _(X28) _(FP) _(LR) _(SP) -#define FPRDEF(_) \ - _(D0) _(D1) _(D2) _(D3) _(D4) _(D5) _(D6) _(D7) \ - _(D8) _(D9) _(D10) _(D11) _(D12) _(D13) _(D14) _(D15) \ - _(D16) _(D17) _(D18) _(D19) _(D20) _(D21) _(D22) _(D23) \ - _(D24) _(D25) _(D26) _(D27) _(D28) _(D29) _(D30) _(D31) -#define VRIDDEF(_) - -#define RIDENUM(name) RID_##name, - -enum { - GPRDEF(RIDENUM) /* General-purpose registers (GPRs). */ - FPRDEF(RIDENUM) /* Floating-point registers (FPRs). */ - RID_MAX, - RID_TMP = RID_LR, - RID_ZERO = RID_SP, - - /* Calling conventions. */ - RID_RET = RID_X0, - RID_RETLO = RID_X0, - RID_RETHI = RID_X1, - RID_FPRET = RID_D0, - - /* These definitions must match with the *.dasc file(s): */ - RID_BASE = RID_X19, /* Interpreter BASE. */ - RID_LPC = RID_X21, /* Interpreter PC. */ - RID_GL = RID_X22, /* Interpreter GL. */ - RID_LREG = RID_X23, /* Interpreter L. */ - - /* Register ranges [min, max) and number of registers. */ - RID_MIN_GPR = RID_X0, - RID_MAX_GPR = RID_SP+1, - RID_MIN_FPR = RID_MAX_GPR, - RID_MAX_FPR = RID_D31+1, - RID_NUM_GPR = RID_MAX_GPR - RID_MIN_GPR, - RID_NUM_FPR = RID_MAX_FPR - RID_MIN_FPR -}; - -#define RID_NUM_KREF RID_NUM_GPR -#define RID_MIN_KREF RID_X0 - -/* -- Register sets ------------------------------------------------------- */ - -/* Make use of all registers, except for x18, fp, lr and sp. */ -#define RSET_FIXED \ - (RID2RSET(RID_X18)|RID2RSET(RID_FP)|RID2RSET(RID_LR)|RID2RSET(RID_SP)|\ - RID2RSET(RID_GL)) -#define RSET_GPR (RSET_RANGE(RID_MIN_GPR, RID_MAX_GPR) - RSET_FIXED) -#define RSET_FPR RSET_RANGE(RID_MIN_FPR, RID_MAX_FPR) -#define RSET_ALL (RSET_GPR|RSET_FPR) -#define RSET_INIT RSET_ALL - -/* lr is an implicit scratch register. */ -#define RSET_SCRATCH_GPR (RSET_RANGE(RID_X0, RID_X17+1)) -#define RSET_SCRATCH_FPR \ - (RSET_RANGE(RID_D0, RID_D7+1)|RSET_RANGE(RID_D16, RID_D31+1)) -#define RSET_SCRATCH (RSET_SCRATCH_GPR|RSET_SCRATCH_FPR) -#define REGARG_FIRSTGPR RID_X0 -#define REGARG_LASTGPR RID_X7 -#define REGARG_NUMGPR 8 -#define REGARG_FIRSTFPR RID_D0 -#define REGARG_LASTFPR RID_D7 -#define REGARG_NUMFPR 8 - -/* -- Spill slots --------------------------------------------------------- */ - -/* Spill slots are 32 bit wide. An even/odd pair is used for FPRs. -** -** SPS_FIXED: Available fixed spill slots in interpreter frame. -** This definition must match with the vm_arm64.dasc file. -** Pre-allocate some slots to avoid sp adjust in every root trace. -** -** SPS_FIRST: First spill slot for general use. Reserve min. two 32 bit slots. -*/ -#define SPS_FIXED 4 -#define SPS_FIRST 2 - -#define SPOFS_TMP 0 - -#define sps_scale(slot) (4 * (int32_t)(slot)) -#define sps_align(slot) (((slot) - SPS_FIXED + 3) & ~3) - -/* -- Exit state ---------------------------------------------------------- */ - -/* This definition must match with the *.dasc file(s). */ -typedef struct { - lua_Number fpr[RID_NUM_FPR]; /* Floating-point registers. */ - intptr_t gpr[RID_NUM_GPR]; /* General-purpose registers. */ - int32_t spill[256]; /* Spill slots. */ -} ExitState; - -/* Highest exit + 1 indicates stack check. */ -#define EXITSTATE_CHECKEXIT 1 - -/* Return the address of a per-trace exit stub. */ -static LJ_AINLINE uint32_t *exitstub_trace_addr_(uint32_t *p, uint32_t exitno) -{ - while (*p == (LJ_LE ? 0xd503201f : 0x1f2003d5)) p++; /* Skip A64I_NOP. */ - if ((LJ_LE ? p[1] >> 28 : p[1] & 0xf) == 0xf) p++; /* Skip A64I_LDRx. */ - return p + 3 + exitno; -} -/* Avoid dependence on lj_jit.h if only including lj_target.h. */ -#define exitstub_trace_addr(T, exitno) \ - exitstub_trace_addr_((MCode *)((char *)(T)->mcode + (T)->szmcode), (exitno)) - -/* -- Instructions -------------------------------------------------------- */ - -/* ARM64 instructions are always little-endian. Swap for ARM64BE. */ -#if LJ_BE -#define A64I_LE(x) (lj_bswap(x)) -#else -#define A64I_LE(x) (x) -#endif - -/* Instruction fields. */ -#define A64F_D(r) (r) -#define A64F_N(r) ((r) << 5) -#define A64F_A(r) ((r) << 10) -#define A64F_M(r) ((r) << 16) -#define A64F_IMMS(x) ((x) << 10) -#define A64F_IMMR(x) ((x) << 16) -#define A64F_U16(x) ((x) << 5) -#define A64F_U12(x) ((x) << 10) -#define A64F_S26(x) (((uint32_t)(x) & 0x03ffffffu)) -#define A64F_S19(x) (((uint32_t)(x) & 0x7ffffu) << 5) -#define A64F_S14(x) (((uint32_t)(x) & 0x3fffu) << 5) -#define A64F_S9(x) ((x) << 12) -#define A64F_BIT(x) ((x) << 19) -#define A64F_SH(sh, x) (((sh) << 22) | ((x) << 10)) -#define A64F_EX(ex) (A64I_EX | ((ex) << 13)) -#define A64F_EXSH(ex,x) (A64I_EX | ((ex) << 13) | ((x) << 10)) -#define A64F_FP8(x) ((x) << 13) -#define A64F_CC(cc) ((cc) << 12) -#define A64F_LSL16(x) (((x) / 16) << 21) -#define A64F_BSH(sh) ((sh) << 10) - -/* Check for valid field range. */ -#define A64F_S_OK(x, b) ((((x) + (1 << (b-1))) >> (b)) == 0) - -typedef enum A64Ins { - A64I_S = 0x20000000, - A64I_X = 0x80000000, - A64I_EX = 0x00200000, - A64I_ON = 0x00200000, - A64I_K12 = 0x1a000000, - A64I_K13 = 0x18000000, - A64I_LS_U = 0x01000000, - A64I_LS_S = 0x00800000, - A64I_LS_R = 0x01200800, - A64I_LS_SH = 0x00001000, - A64I_LS_UXTWx = 0x00004000, - A64I_LS_SXTWx = 0x0000c000, - A64I_LS_SXTXx = 0x0000e000, - A64I_LS_LSLx = 0x00006000, - - A64I_ADDw = 0x0b000000, - A64I_ADDx = 0x8b000000, - A64I_ADDSw = 0x2b000000, - A64I_ADDSx = 0xab000000, - A64I_NEGw = 0x4b0003e0, - A64I_NEGx = 0xcb0003e0, - A64I_SUBw = 0x4b000000, - A64I_SUBx = 0xcb000000, - A64I_SUBSw = 0x6b000000, - A64I_SUBSx = 0xeb000000, - - A64I_MULw = 0x1b007c00, - A64I_MULx = 0x9b007c00, - A64I_SMULL = 0x9b207c00, - - A64I_ANDw = 0x0a000000, - A64I_ANDx = 0x8a000000, - A64I_ANDSw = 0x6a000000, - A64I_ANDSx = 0xea000000, - A64I_EORw = 0x4a000000, - A64I_EORx = 0xca000000, - A64I_ORRw = 0x2a000000, - A64I_ORRx = 0xaa000000, - A64I_TSTw = 0x6a00001f, - A64I_TSTx = 0xea00001f, - - A64I_CMPw = 0x6b00001f, - A64I_CMPx = 0xeb00001f, - A64I_CMNw = 0x2b00001f, - A64I_CMNx = 0xab00001f, - A64I_CCMPw = 0x7a400000, - A64I_CCMPx = 0xfa400000, - A64I_CSELw = 0x1a800000, - A64I_CSELx = 0x9a800000, - - A64I_ASRw = 0x13007c00, - A64I_ASRx = 0x9340fc00, - A64I_LSLx = 0xd3400000, - A64I_LSRx = 0xd340fc00, - A64I_SHRw = 0x1ac02000, - A64I_SHRx = 0x9ac02000, /* lsl/lsr/asr/ror x0, x0, x0 */ - A64I_REVw = 0x5ac00800, - A64I_REVx = 0xdac00c00, - - A64I_EXTRw = 0x13800000, - A64I_EXTRx = 0x93c00000, - A64I_BFMw = 0x33000000, - A64I_BFMx = 0xb3400000, - A64I_SBFMw = 0x13000000, - A64I_SBFMx = 0x93400000, - A64I_SXTBw = 0x13001c00, - A64I_SXTHw = 0x13003c00, - A64I_SXTW = 0x93407c00, - A64I_UBFMw = 0x53000000, - A64I_UBFMx = 0xd3400000, - A64I_UXTBw = 0x53001c00, - A64I_UXTHw = 0x53003c00, - - A64I_MOVw = 0x2a0003e0, - A64I_MOVx = 0xaa0003e0, - A64I_MVNw = 0x2a2003e0, - A64I_MVNx = 0xaa2003e0, - A64I_MOVKw = 0x72800000, - A64I_MOVKx = 0xf2800000, - A64I_MOVZw = 0x52800000, - A64I_MOVZx = 0xd2800000, - A64I_MOVNw = 0x12800000, - A64I_MOVNx = 0x92800000, - A64I_ADR = 0x10000000, - A64I_ADRP = 0x90000000, - - A64I_LDRB = 0x39400000, - A64I_LDRH = 0x79400000, - A64I_LDRw = 0xb9400000, - A64I_LDRx = 0xf9400000, - A64I_LDRLw = 0x18000000, - A64I_LDRLx = 0x58000000, - A64I_STRB = 0x39000000, - A64I_STRH = 0x79000000, - A64I_STRw = 0xb9000000, - A64I_STRx = 0xf9000000, - A64I_STPw = 0x29000000, - A64I_STPx = 0xa9000000, - A64I_LDPw = 0x29400000, - A64I_LDPx = 0xa9400000, - - A64I_B = 0x14000000, - A64I_BCC = 0x54000000, - A64I_BL = 0x94000000, - A64I_BR = 0xd61f0000, - A64I_BLR = 0xd63f0000, - A64I_TBZ = 0x36000000, - A64I_TBNZ = 0x37000000, - A64I_CBZ = 0x34000000, - A64I_CBNZ = 0x35000000, - - A64I_BRAAZ = 0xd61f081f, - A64I_BLRAAZ = 0xd63f081f, - - A64I_BTI_C = 0xd503245f, - A64I_BTI_J = 0xd503249f, - A64I_BTI_JC = 0xd50324df, - - A64I_NOP = 0xd503201f, - - /* FP */ - A64I_FADDd = 0x1e602800, - A64I_FSUBd = 0x1e603800, - A64I_FMADDd = 0x1f400000, - A64I_FMSUBd = 0x1f408000, - A64I_FNMADDd = 0x1f600000, - A64I_FNMSUBd = 0x1f608000, - A64I_FMULd = 0x1e600800, - A64I_FDIVd = 0x1e601800, - A64I_FNEGd = 0x1e614000, - A64I_FABS = 0x1e60c000, - A64I_FSQRTd = 0x1e61c000, - A64I_LDRs = 0xbd400000, - A64I_LDRd = 0xfd400000, - A64I_LDRLd = 0x5c000000, - A64I_STRs = 0xbd000000, - A64I_STRd = 0xfd000000, - A64I_LDPs = 0x2d400000, - A64I_LDPd = 0x6d400000, - A64I_STPs = 0x2d000000, - A64I_STPd = 0x6d000000, - A64I_FCMPd = 0x1e602000, - A64I_FCMPZd = 0x1e602008, - A64I_FCSELd = 0x1e600c00, - A64I_FRINTMd = 0x1e654000, - A64I_FRINTPd = 0x1e64c000, - A64I_FRINTZd = 0x1e65c000, - - A64I_FCVT_F32_F64 = 0x1e624000, - A64I_FCVT_F64_F32 = 0x1e22c000, - A64I_FCVT_F32_S32 = 0x1e220000, - A64I_FCVT_F64_S32 = 0x1e620000, - A64I_FCVT_F32_U32 = 0x1e230000, - A64I_FCVT_F64_U32 = 0x1e630000, - A64I_FCVT_F32_S64 = 0x9e220000, - A64I_FCVT_F64_S64 = 0x9e620000, - A64I_FCVT_F32_U64 = 0x9e230000, - A64I_FCVT_F64_U64 = 0x9e630000, - A64I_FCVT_S32_F64 = 0x1e780000, - A64I_FCVT_S32_F32 = 0x1e380000, - A64I_FCVT_U32_F64 = 0x1e790000, - A64I_FCVT_U32_F32 = 0x1e390000, - A64I_FCVT_S64_F64 = 0x9e780000, - A64I_FCVT_S64_F32 = 0x9e380000, - A64I_FCVT_U64_F64 = 0x9e790000, - A64I_FCVT_U64_F32 = 0x9e390000, - - A64I_FMOV_S = 0x1e204000, - A64I_FMOV_D = 0x1e604000, - A64I_FMOV_R_S = 0x1e260000, - A64I_FMOV_S_R = 0x1e270000, - A64I_FMOV_R_D = 0x9e660000, - A64I_FMOV_D_R = 0x9e670000, - A64I_FMOV_DI = 0x1e601000, - A64I_MOVI_DI = 0x2f000400, -} A64Ins; - -#define A64I_BR_AUTH (LJ_ABI_PAUTH ? A64I_BRAAZ : A64I_BR) -#define A64I_BLR_AUTH (LJ_ABI_PAUTH ? A64I_BLRAAZ : A64I_BLR) - -typedef enum A64Shift { - A64SH_LSL, A64SH_LSR, A64SH_ASR, A64SH_ROR -} A64Shift; - -typedef enum A64Extend { - A64EX_UXTB, A64EX_UXTH, A64EX_UXTW, A64EX_UXTX, - A64EX_SXTB, A64EX_SXTH, A64EX_SXTW, A64EX_SXTX, -} A64Extend; - -/* ARM condition codes. */ -typedef enum A64CC { - CC_EQ, CC_NE, CC_CS, CC_CC, CC_MI, CC_PL, CC_VS, CC_VC, - CC_HI, CC_LS, CC_GE, CC_LT, CC_GT, CC_LE, CC_AL, - CC_HS = CC_CS, CC_LO = CC_CC -} A64CC; - -#endif diff --git a/include/luajit/lj_target_mips.h b/include/luajit/lj_target_mips.h deleted file mode 100644 index 38ed226..0000000 --- a/include/luajit/lj_target_mips.h +++ /dev/null @@ -1,417 +0,0 @@ -/* -** Definitions for MIPS CPUs. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_TARGET_MIPS_H -#define _LJ_TARGET_MIPS_H - -/* -- Registers IDs ------------------------------------------------------- */ - -#define GPRDEF(_) \ - _(R0) _(R1) _(R2) _(R3) _(R4) _(R5) _(R6) _(R7) \ - _(R8) _(R9) _(R10) _(R11) _(R12) _(R13) _(R14) _(R15) \ - _(R16) _(R17) _(R18) _(R19) _(R20) _(R21) _(R22) _(R23) \ - _(R24) _(R25) _(SYS1) _(SYS2) _(R28) _(SP) _(R30) _(RA) -#if LJ_SOFTFP -#define FPRDEF(_) -#else -#define FPRDEF(_) \ - _(F0) _(F1) _(F2) _(F3) _(F4) _(F5) _(F6) _(F7) \ - _(F8) _(F9) _(F10) _(F11) _(F12) _(F13) _(F14) _(F15) \ - _(F16) _(F17) _(F18) _(F19) _(F20) _(F21) _(F22) _(F23) \ - _(F24) _(F25) _(F26) _(F27) _(F28) _(F29) _(F30) _(F31) -#endif -#define VRIDDEF(_) - -#define RIDENUM(name) RID_##name, - -enum { - GPRDEF(RIDENUM) /* General-purpose registers (GPRs). */ - FPRDEF(RIDENUM) /* Floating-point registers (FPRs). */ - RID_MAX, - RID_ZERO = RID_R0, - RID_TMP = RID_RA, - RID_GP = RID_R28, - - /* Calling conventions. */ - RID_RET = RID_R2, -#if LJ_LE - RID_RETHI = RID_R3, - RID_RETLO = RID_R2, -#else - RID_RETHI = RID_R2, - RID_RETLO = RID_R3, -#endif -#if LJ_SOFTFP - RID_FPRET = RID_R2, -#else - RID_FPRET = RID_F0, -#endif - RID_CFUNCADDR = RID_R25, - - /* These definitions must match with the *.dasc file(s): */ - RID_BASE = RID_R16, /* Interpreter BASE. */ - RID_LPC = RID_R18, /* Interpreter PC. */ - RID_DISPATCH = RID_R19, /* Interpreter DISPATCH table. */ - RID_LREG = RID_R20, /* Interpreter L. */ - RID_JGL = RID_R30, /* On-trace: global_State + 32768. */ - - /* Register ranges [min, max) and number of registers. */ - RID_MIN_GPR = RID_R0, - RID_MAX_GPR = RID_RA+1, - RID_MIN_FPR = RID_MAX_GPR, -#if LJ_SOFTFP - RID_MAX_FPR = RID_MIN_FPR, -#else - RID_MAX_FPR = RID_F31+1, -#endif - RID_NUM_GPR = RID_MAX_GPR - RID_MIN_GPR, - RID_NUM_FPR = RID_MAX_FPR - RID_MIN_FPR /* Only even regs are used. */ -}; - -#define RID_NUM_KREF RID_NUM_GPR -#define RID_MIN_KREF RID_R0 - -/* -- Register sets ------------------------------------------------------- */ - -/* Make use of all registers, except ZERO, TMP, SP, SYS1, SYS2, JGL and GP. */ -#define RSET_FIXED \ - (RID2RSET(RID_ZERO)|RID2RSET(RID_TMP)|RID2RSET(RID_SP)|\ - RID2RSET(RID_SYS1)|RID2RSET(RID_SYS2)|RID2RSET(RID_JGL)|RID2RSET(RID_GP)) -#define RSET_GPR (RSET_RANGE(RID_MIN_GPR, RID_MAX_GPR) - RSET_FIXED) -#if LJ_SOFTFP -#define RSET_FPR 0 -#else -#if LJ_32 -#define RSET_FPR \ - (RID2RSET(RID_F0)|RID2RSET(RID_F2)|RID2RSET(RID_F4)|RID2RSET(RID_F6)|\ - RID2RSET(RID_F8)|RID2RSET(RID_F10)|RID2RSET(RID_F12)|RID2RSET(RID_F14)|\ - RID2RSET(RID_F16)|RID2RSET(RID_F18)|RID2RSET(RID_F20)|RID2RSET(RID_F22)|\ - RID2RSET(RID_F24)|RID2RSET(RID_F26)|RID2RSET(RID_F28)|RID2RSET(RID_F30)) -#else -#define RSET_FPR RSET_RANGE(RID_MIN_FPR, RID_MAX_FPR) -#endif -#endif -#define RSET_ALL (RSET_GPR|RSET_FPR) -#define RSET_INIT RSET_ALL - -#define RSET_SCRATCH_GPR \ - (RSET_RANGE(RID_R1, RID_R15+1)|\ - RID2RSET(RID_R24)|RID2RSET(RID_R25)) -#if LJ_SOFTFP -#define RSET_SCRATCH_FPR 0 -#else -#if LJ_32 -#define RSET_SCRATCH_FPR \ - (RID2RSET(RID_F0)|RID2RSET(RID_F2)|RID2RSET(RID_F4)|RID2RSET(RID_F6)|\ - RID2RSET(RID_F8)|RID2RSET(RID_F10)|RID2RSET(RID_F12)|RID2RSET(RID_F14)|\ - RID2RSET(RID_F16)|RID2RSET(RID_F18)) -#else -#define RSET_SCRATCH_FPR RSET_RANGE(RID_F0, RID_F24) -#endif -#endif -#define RSET_SCRATCH (RSET_SCRATCH_GPR|RSET_SCRATCH_FPR) -#define REGARG_FIRSTGPR RID_R4 -#if LJ_32 -#define REGARG_LASTGPR RID_R7 -#define REGARG_NUMGPR 4 -#else -#define REGARG_LASTGPR RID_R11 -#define REGARG_NUMGPR 8 -#endif -#if LJ_ABI_SOFTFP -#define REGARG_FIRSTFPR 0 -#define REGARG_LASTFPR 0 -#define REGARG_NUMFPR 0 -#else -#define REGARG_FIRSTFPR RID_F12 -#if LJ_32 -#define REGARG_LASTFPR RID_F14 -#define REGARG_NUMFPR 2 -#else -#define REGARG_LASTFPR RID_F19 -#define REGARG_NUMFPR 8 -#endif -#endif - -/* -- Spill slots --------------------------------------------------------- */ - -/* Spill slots are 32 bit wide. An even/odd pair is used for FPRs. -** -** SPS_FIXED: Available fixed spill slots in interpreter frame. -** This definition must match with the *.dasc file(s). -** -** SPS_FIRST: First spill slot for general use. -*/ -#if LJ_32 -#define SPS_FIXED 5 -#else -#define SPS_FIXED 4 -#endif -#define SPS_FIRST 4 - -#define SPOFS_TMP 0 - -#define sps_scale(slot) (4 * (int32_t)(slot)) -#define sps_align(slot) (((slot) - SPS_FIXED + 1) & ~1) - -/* -- Exit state ---------------------------------------------------------- */ - -/* This definition must match with the *.dasc file(s). */ -typedef struct { -#if !LJ_SOFTFP - lua_Number fpr[RID_NUM_FPR]; /* Floating-point registers. */ -#endif - intptr_t gpr[RID_NUM_GPR]; /* General-purpose registers. */ - int32_t spill[256]; /* Spill slots. */ -} ExitState; - -/* Highest exit + 1 indicates stack check. */ -#define EXITSTATE_CHECKEXIT 1 - -/* Return the address of a per-trace exit stub. */ -static LJ_AINLINE uint32_t *exitstub_trace_addr_(uint32_t *p) -{ - while (*p == 0x00000000) p++; /* Skip MIPSI_NOP. */ - return p; -} -/* Avoid dependence on lj_jit.h if only including lj_target.h. */ -#define exitstub_trace_addr(T, exitno) \ - exitstub_trace_addr_((MCode *)((char *)(T)->mcode + (T)->szmcode)) - -/* -- Instructions -------------------------------------------------------- */ - -/* Instruction fields. */ -#define MIPSF_S(r) ((r) << 21) -#define MIPSF_T(r) ((r) << 16) -#define MIPSF_D(r) ((r) << 11) -#define MIPSF_R(r) ((r) << 21) -#define MIPSF_H(r) ((r) << 16) -#define MIPSF_G(r) ((r) << 11) -#define MIPSF_F(r) ((r) << 6) -#define MIPSF_A(n) ((n) << 6) -#define MIPSF_M(n) ((n) << 11) -#define MIPSF_L(n) ((n) << 6) - -typedef enum MIPSIns { - MIPSI_D = 0x38, - MIPSI_DV = 0x10, - MIPSI_D32 = 0x3c, - /* Integer instructions. */ - MIPSI_MOVE = 0x00000025, - MIPSI_NOP = 0x00000000, - - MIPSI_LI = 0x24000000, - MIPSI_LU = 0x34000000, - MIPSI_LUI = 0x3c000000, - - MIPSI_AND = 0x00000024, - MIPSI_ANDI = 0x30000000, - MIPSI_OR = 0x00000025, - MIPSI_ORI = 0x34000000, - MIPSI_XOR = 0x00000026, - MIPSI_XORI = 0x38000000, - MIPSI_NOR = 0x00000027, - - MIPSI_SLT = 0x0000002a, - MIPSI_SLTU = 0x0000002b, - MIPSI_SLTI = 0x28000000, - MIPSI_SLTIU = 0x2c000000, - - MIPSI_ADDU = 0x00000021, - MIPSI_ADDIU = 0x24000000, - MIPSI_SUB = 0x00000022, - MIPSI_SUBU = 0x00000023, - -#if !LJ_TARGET_MIPSR6 - MIPSI_MUL = 0x70000002, - MIPSI_DIV = 0x0000001a, - MIPSI_DIVU = 0x0000001b, - - MIPSI_MOVZ = 0x0000000a, - MIPSI_MOVN = 0x0000000b, - MIPSI_MFHI = 0x00000010, - MIPSI_MFLO = 0x00000012, - MIPSI_MULT = 0x00000018, -#else - MIPSI_MUL = 0x00000098, - MIPSI_MUH = 0x000000d8, - MIPSI_DIV = 0x0000009a, - MIPSI_DIVU = 0x0000009b, - - MIPSI_SELEQZ = 0x00000035, - MIPSI_SELNEZ = 0x00000037, -#endif - - MIPSI_SLL = 0x00000000, - MIPSI_SRL = 0x00000002, - MIPSI_SRA = 0x00000003, - MIPSI_ROTR = 0x00200002, /* MIPSXXR2 */ - MIPSI_DROTR = 0x0020003a, - MIPSI_DROTR32 = 0x0020003e, - MIPSI_SLLV = 0x00000004, - MIPSI_SRLV = 0x00000006, - MIPSI_SRAV = 0x00000007, - MIPSI_ROTRV = 0x00000046, /* MIPSXXR2 */ - MIPSI_DROTRV = 0x00000056, - - MIPSI_INS = 0x7c000004, /* MIPSXXR2 */ - - MIPSI_SEB = 0x7c000420, /* MIPSXXR2 */ - MIPSI_SEH = 0x7c000620, /* MIPSXXR2 */ - MIPSI_WSBH = 0x7c0000a0, /* MIPSXXR2 */ - MIPSI_DSBH = 0x7c0000a4, - - MIPSI_B = 0x10000000, - MIPSI_J = 0x08000000, - MIPSI_JAL = 0x0c000000, -#if !LJ_TARGET_MIPSR6 - MIPSI_JALX = 0x74000000, - MIPSI_JR = 0x00000008, -#else - MIPSI_JR = 0x00000009, - MIPSI_BALC = 0xe8000000, -#endif - MIPSI_JALR = 0x0000f809, - - MIPSI_BEQ = 0x10000000, - MIPSI_BNE = 0x14000000, - MIPSI_BLEZ = 0x18000000, - MIPSI_BGTZ = 0x1c000000, - MIPSI_BLTZ = 0x04000000, - MIPSI_BGEZ = 0x04010000, - - /* Load/store instructions. */ - MIPSI_LW = 0x8c000000, - MIPSI_LD = 0xdc000000, - MIPSI_SW = 0xac000000, - MIPSI_SD = 0xfc000000, - MIPSI_LB = 0x80000000, - MIPSI_SB = 0xa0000000, - MIPSI_LH = 0x84000000, - MIPSI_SH = 0xa4000000, - MIPSI_LBU = 0x90000000, - MIPSI_LHU = 0x94000000, - MIPSI_LWC1 = 0xc4000000, - MIPSI_SWC1 = 0xe4000000, - MIPSI_LDC1 = 0xd4000000, - MIPSI_SDC1 = 0xf4000000, - - /* MIPS64 instructions. */ - MIPSI_DADD = 0x0000002c, - MIPSI_DADDU = 0x0000002d, - MIPSI_DADDIU = 0x64000000, - MIPSI_DSUB = 0x0000002e, - MIPSI_DSUBU = 0x0000002f, -#if !LJ_TARGET_MIPSR6 - MIPSI_DDIV = 0x0000001e, - MIPSI_DDIVU = 0x0000001f, - MIPSI_DMULT = 0x0000001c, - MIPSI_DMULTU = 0x0000001d, -#else - MIPSI_DDIV = 0x0000009e, - MIPSI_DMOD = 0x000000de, - MIPSI_DDIVU = 0x0000009f, - MIPSI_DMODU = 0x000000df, - MIPSI_DMUL = 0x0000009c, - MIPSI_DMUH = 0x000000dc, -#endif - - MIPSI_DSLL = 0x00000038, - MIPSI_DSRL = 0x0000003a, - MIPSI_DSLLV = 0x00000014, - MIPSI_DSRLV = 0x00000016, - MIPSI_DSRA = 0x0000003b, - MIPSI_DSRAV = 0x00000017, - MIPSI_DSRA32 = 0x0000003f, - MIPSI_DSLL32 = 0x0000003c, - MIPSI_DSRL32 = 0x0000003e, - MIPSI_DSHD = 0x7c000164, - - MIPSI_AADDU = LJ_32 ? MIPSI_ADDU : MIPSI_DADDU, - MIPSI_AADDIU = LJ_32 ? MIPSI_ADDIU : MIPSI_DADDIU, - MIPSI_ASUBU = LJ_32 ? MIPSI_SUBU : MIPSI_DSUBU, - MIPSI_AL = LJ_32 ? MIPSI_LW : MIPSI_LD, - MIPSI_AS = LJ_32 ? MIPSI_SW : MIPSI_SD, -#if LJ_TARGET_MIPSR6 - MIPSI_LSA = 0x00000005, - MIPSI_DLSA = 0x00000015, - MIPSI_ALSA = LJ_32 ? MIPSI_LSA : MIPSI_DLSA, -#endif - - /* Extract/insert instructions. */ - MIPSI_DEXTM = 0x7c000001, - MIPSI_DEXTU = 0x7c000002, - MIPSI_DEXT = 0x7c000003, - MIPSI_DINSM = 0x7c000005, - MIPSI_DINSU = 0x7c000006, - MIPSI_DINS = 0x7c000007, - - MIPSI_FLOOR_D = 0x4620000b, - - /* FP instructions. */ - MIPSI_MOV_S = 0x46000006, - MIPSI_MOV_D = 0x46200006, -#if !LJ_TARGET_MIPSR6 - MIPSI_MOVT_D = 0x46210011, - MIPSI_MOVF_D = 0x46200011, -#else - MIPSI_MIN_D = 0x4620001C, - MIPSI_MAX_D = 0x4620001E, - MIPSI_SEL_D = 0x46200010, -#endif - - MIPSI_ABS_D = 0x46200005, - MIPSI_NEG_D = 0x46200007, - - MIPSI_ADD_D = 0x46200000, - MIPSI_SUB_D = 0x46200001, - MIPSI_MUL_D = 0x46200002, - MIPSI_DIV_D = 0x46200003, - MIPSI_SQRT_D = 0x46200004, - - MIPSI_ADD_S = 0x46000000, - MIPSI_SUB_S = 0x46000001, - - MIPSI_CVT_D_S = 0x46000021, - MIPSI_CVT_W_S = 0x46000024, - MIPSI_CVT_S_D = 0x46200020, - MIPSI_CVT_W_D = 0x46200024, - MIPSI_CVT_S_W = 0x46800020, - MIPSI_CVT_D_W = 0x46800021, - MIPSI_CVT_S_L = 0x46a00020, - MIPSI_CVT_D_L = 0x46a00021, - - MIPSI_TRUNC_W_S = 0x4600000d, - MIPSI_TRUNC_W_D = 0x4620000d, - MIPSI_TRUNC_L_S = 0x46000009, - MIPSI_TRUNC_L_D = 0x46200009, - MIPSI_FLOOR_W_S = 0x4600000f, - MIPSI_FLOOR_W_D = 0x4620000f, - - MIPSI_MFC1 = 0x44000000, - MIPSI_MTC1 = 0x44800000, - MIPSI_DMTC1 = 0x44a00000, - MIPSI_DMFC1 = 0x44200000, - -#if !LJ_TARGET_MIPSR6 - MIPSI_BC1F = 0x45000000, - MIPSI_BC1T = 0x45010000, - MIPSI_C_EQ_D = 0x46200032, - MIPSI_C_OLT_S = 0x46000034, - MIPSI_C_OLT_D = 0x46200034, - MIPSI_C_ULT_D = 0x46200035, - MIPSI_C_OLE_D = 0x46200036, - MIPSI_C_ULE_D = 0x46200037, -#else - MIPSI_BC1EQZ = 0x45200000, - MIPSI_BC1NEZ = 0x45a00000, - MIPSI_CMP_EQ_D = 0x46a00002, - MIPSI_CMP_LT_S = 0x46800004, - MIPSI_CMP_LT_D = 0x46a00004, -#endif - -} MIPSIns; - -#endif diff --git a/include/luajit/lj_target_ppc.h b/include/luajit/lj_target_ppc.h deleted file mode 100644 index 58f3118..0000000 --- a/include/luajit/lj_target_ppc.h +++ /dev/null @@ -1,281 +0,0 @@ -/* -** Definitions for PPC CPUs. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_TARGET_PPC_H -#define _LJ_TARGET_PPC_H - -/* -- Registers IDs ------------------------------------------------------- */ - -#define GPRDEF(_) \ - _(R0) _(SP) _(SYS1) _(R3) _(R4) _(R5) _(R6) _(R7) \ - _(R8) _(R9) _(R10) _(R11) _(R12) _(SYS2) _(R14) _(R15) \ - _(R16) _(R17) _(R18) _(R19) _(R20) _(R21) _(R22) _(R23) \ - _(R24) _(R25) _(R26) _(R27) _(R28) _(R29) _(R30) _(R31) -#define FPRDEF(_) \ - _(F0) _(F1) _(F2) _(F3) _(F4) _(F5) _(F6) _(F7) \ - _(F8) _(F9) _(F10) _(F11) _(F12) _(F13) _(F14) _(F15) \ - _(F16) _(F17) _(F18) _(F19) _(F20) _(F21) _(F22) _(F23) \ - _(F24) _(F25) _(F26) _(F27) _(F28) _(F29) _(F30) _(F31) -#define VRIDDEF(_) - -#define RIDENUM(name) RID_##name, - -enum { - GPRDEF(RIDENUM) /* General-purpose registers (GPRs). */ - FPRDEF(RIDENUM) /* Floating-point registers (FPRs). */ - RID_MAX, - RID_TMP = RID_R0, - - /* Calling conventions. */ - RID_RET = RID_R3, - RID_RETHI = RID_R3, - RID_RETLO = RID_R4, - RID_FPRET = RID_F1, - - /* These definitions must match with the *.dasc file(s): */ - RID_BASE = RID_R14, /* Interpreter BASE. */ - RID_LPC = RID_R16, /* Interpreter PC. */ - RID_DISPATCH = RID_R17, /* Interpreter DISPATCH table. */ - RID_LREG = RID_R18, /* Interpreter L. */ - RID_JGL = RID_R31, /* On-trace: global_State + 32768. */ - - /* Register ranges [min, max) and number of registers. */ - RID_MIN_GPR = RID_R0, - RID_MAX_GPR = RID_R31+1, - RID_MIN_FPR = RID_F0, - RID_MAX_FPR = RID_F31+1, - RID_NUM_GPR = RID_MAX_GPR - RID_MIN_GPR, - RID_NUM_FPR = RID_MAX_FPR - RID_MIN_FPR -}; - -#define RID_NUM_KREF RID_NUM_GPR -#define RID_MIN_KREF RID_R0 - -/* -- Register sets ------------------------------------------------------- */ - -/* Make use of all registers, except TMP, SP, SYS1, SYS2 and JGL. */ -#define RSET_FIXED \ - (RID2RSET(RID_TMP)|RID2RSET(RID_SP)|RID2RSET(RID_SYS1)|\ - RID2RSET(RID_SYS2)|RID2RSET(RID_JGL)) -#define RSET_GPR (RSET_RANGE(RID_MIN_GPR, RID_MAX_GPR) - RSET_FIXED) -#define RSET_FPR RSET_RANGE(RID_MIN_FPR, RID_MAX_FPR) -#define RSET_ALL (RSET_GPR|RSET_FPR) -#define RSET_INIT RSET_ALL - -#define RSET_SCRATCH_GPR (RSET_RANGE(RID_R3, RID_R12+1)) -#define RSET_SCRATCH_FPR (RSET_RANGE(RID_F0, RID_F13+1)) -#define RSET_SCRATCH (RSET_SCRATCH_GPR|RSET_SCRATCH_FPR) -#define REGARG_FIRSTGPR RID_R3 -#define REGARG_LASTGPR RID_R10 -#define REGARG_NUMGPR 8 -#define REGARG_FIRSTFPR RID_F1 -#define REGARG_LASTFPR RID_F8 -#define REGARG_NUMFPR 8 - -/* -- Spill slots --------------------------------------------------------- */ - -/* Spill slots are 32 bit wide. An even/odd pair is used for FPRs. -** -** SPS_FIXED: Available fixed spill slots in interpreter frame. -** This definition must match with the *.dasc file(s). -** -** SPS_FIRST: First spill slot for general use. -** [sp+12] tmplo word \ -** [sp+ 8] tmphi word / tmp dword, parameter area for callee -** [sp+ 4] tmpw, LR of callee -** [sp+ 0] stack chain -*/ -#define SPS_FIXED 7 -#define SPS_FIRST 4 - -/* Stack offsets for temporary slots. Used for FP<->int conversions etc. */ -#define SPOFS_TMPW 4 -#define SPOFS_TMP 8 -#define SPOFS_TMPHI 8 -#define SPOFS_TMPLO 12 - -#define sps_scale(slot) (4 * (int32_t)(slot)) -#define sps_align(slot) (((slot) - SPS_FIXED + 3) & ~3) - -/* -- Exit state ---------------------------------------------------------- */ - -/* This definition must match with the *.dasc file(s). */ -typedef struct { - lua_Number fpr[RID_NUM_FPR]; /* Floating-point registers. */ - intptr_t gpr[RID_NUM_GPR]; /* General-purpose registers. */ - int32_t spill[256]; /* Spill slots. */ -} ExitState; - -/* Highest exit + 1 indicates stack check. */ -#define EXITSTATE_CHECKEXIT 1 - -/* Return the address of a per-trace exit stub. */ -static LJ_AINLINE uint32_t *exitstub_trace_addr_(uint32_t *p, uint32_t exitno) -{ - while (*p == 0x60000000) p++; /* Skip PPCI_NOP. */ - if (p[3] == 0x4e800421) p += 2; /* Indirect branch PPCI_BCTRL. */ - return p + 3 + exitno; -} -/* Avoid dependence on lj_jit.h if only including lj_target.h. */ -#define exitstub_trace_addr(T, exitno) \ - exitstub_trace_addr_((MCode *)((char *)(T)->mcode + (T)->szmcode), (exitno)) - -/* -- Instructions -------------------------------------------------------- */ - -/* Instruction fields. */ -#define PPCF_CC(cc) ((((cc) & 3) << 16) | (((cc) & 4) << 22)) -#define PPCF_T(r) ((r) << 21) -#define PPCF_A(r) ((r) << 16) -#define PPCF_B(r) ((r) << 11) -#define PPCF_C(r) ((r) << 6) -#define PPCF_MB(n) ((n) << 6) -#define PPCF_ME(n) ((n) << 1) -#define PPCF_Y 0x00200000 -#define PPCF_DOT 0x00000001 - -typedef enum PPCIns { - /* Integer instructions. */ - PPCI_MR = 0x7c000378, - PPCI_NOP = 0x60000000, - - PPCI_LI = 0x38000000, - PPCI_LIS = 0x3c000000, - - PPCI_ADD = 0x7c000214, - PPCI_ADDC = 0x7c000014, - PPCI_ADDO = 0x7c000614, - PPCI_ADDE = 0x7c000114, - PPCI_ADDZE = 0x7c000194, - PPCI_ADDME = 0x7c0001d4, - PPCI_ADDI = 0x38000000, - PPCI_ADDIS = 0x3c000000, - PPCI_ADDIC = 0x30000000, - PPCI_ADDICDOT = 0x34000000, - - PPCI_SUBF = 0x7c000050, - PPCI_SUBFC = 0x7c000010, - PPCI_SUBFO = 0x7c000450, - PPCI_SUBFE = 0x7c000110, - PPCI_SUBFZE = 0x7c000190, - PPCI_SUBFME = 0x7c0001d0, - PPCI_SUBFIC = 0x20000000, - - PPCI_NEG = 0x7c0000d0, - - PPCI_AND = 0x7c000038, - PPCI_ANDC = 0x7c000078, - PPCI_NAND = 0x7c0003b8, - PPCI_ANDIDOT = 0x70000000, - PPCI_ANDISDOT = 0x74000000, - - PPCI_OR = 0x7c000378, - PPCI_NOR = 0x7c0000f8, - PPCI_ORI = 0x60000000, - PPCI_ORIS = 0x64000000, - - PPCI_XOR = 0x7c000278, - PPCI_EQV = 0x7c000238, - PPCI_XORI = 0x68000000, - PPCI_XORIS = 0x6c000000, - - PPCI_CMPW = 0x7c000000, - PPCI_CMPLW = 0x7c000040, - PPCI_CMPWI = 0x2c000000, - PPCI_CMPLWI = 0x28000000, - - PPCI_MULLW = 0x7c0001d6, - PPCI_MULLI = 0x1c000000, - PPCI_MULLWO = 0x7c0005d6, - - PPCI_EXTSB = 0x7c000774, - PPCI_EXTSH = 0x7c000734, - - PPCI_SLW = 0x7c000030, - PPCI_SRW = 0x7c000430, - PPCI_SRAW = 0x7c000630, - PPCI_SRAWI = 0x7c000670, - - PPCI_RLWNM = 0x5c000000, - PPCI_RLWINM = 0x54000000, - PPCI_RLWIMI = 0x50000000, - - PPCI_B = 0x48000000, - PPCI_BL = 0x48000001, - PPCI_BC = 0x40800000, - PPCI_BCL = 0x40800001, - PPCI_BCTR = 0x4e800420, - PPCI_BCTRL = 0x4e800421, - - PPCI_CRANDC = 0x4c000102, - PPCI_CRXOR = 0x4c000182, - PPCI_CRAND = 0x4c000202, - PPCI_CREQV = 0x4c000242, - PPCI_CRORC = 0x4c000342, - PPCI_CROR = 0x4c000382, - - PPCI_MFLR = 0x7c0802a6, - PPCI_MTCTR = 0x7c0903a6, - - PPCI_MCRXR = 0x7c000400, - - /* Load/store instructions. */ - PPCI_LWZ = 0x80000000, - PPCI_LBZ = 0x88000000, - PPCI_STW = 0x90000000, - PPCI_STB = 0x98000000, - PPCI_LHZ = 0xa0000000, - PPCI_LHA = 0xa8000000, - PPCI_STH = 0xb0000000, - - PPCI_STWU = 0x94000000, - - PPCI_LFS = 0xc0000000, - PPCI_LFD = 0xc8000000, - PPCI_STFS = 0xd0000000, - PPCI_STFD = 0xd8000000, - - PPCI_LWZX = 0x7c00002e, - PPCI_LBZX = 0x7c0000ae, - PPCI_STWX = 0x7c00012e, - PPCI_STBX = 0x7c0001ae, - PPCI_LHZX = 0x7c00022e, - PPCI_LHAX = 0x7c0002ae, - PPCI_STHX = 0x7c00032e, - - PPCI_LWBRX = 0x7c00042c, - PPCI_STWBRX = 0x7c00052c, - - PPCI_LFSX = 0x7c00042e, - PPCI_LFDX = 0x7c0004ae, - PPCI_STFSX = 0x7c00052e, - PPCI_STFDX = 0x7c0005ae, - - /* FP instructions. */ - PPCI_FMR = 0xfc000090, - PPCI_FNEG = 0xfc000050, - PPCI_FABS = 0xfc000210, - - PPCI_FRSP = 0xfc000018, - PPCI_FCTIWZ = 0xfc00001e, - - PPCI_FADD = 0xfc00002a, - PPCI_FSUB = 0xfc000028, - PPCI_FMUL = 0xfc000032, - PPCI_FDIV = 0xfc000024, - PPCI_FSQRT = 0xfc00002c, - - PPCI_FMADD = 0xfc00003a, - PPCI_FMSUB = 0xfc000038, - PPCI_FNMSUB = 0xfc00003c, - - PPCI_FCMPU = 0xfc000000, - PPCI_FSEL = 0xfc00002e, -} PPCIns; - -typedef enum PPCCC { - CC_GE, CC_LE, CC_NE, CC_NS, CC_LT, CC_GT, CC_EQ, CC_SO -} PPCCC; - -#endif diff --git a/include/luajit/lj_target_x86.h b/include/luajit/lj_target_x86.h deleted file mode 100644 index 193102e..0000000 --- a/include/luajit/lj_target_x86.h +++ /dev/null @@ -1,361 +0,0 @@ -/* -** Definitions for x86 and x64 CPUs. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_TARGET_X86_H -#define _LJ_TARGET_X86_H - -/* -- Registers IDs ------------------------------------------------------- */ - -#if LJ_64 -#define GPRDEF(_) \ - _(EAX) _(ECX) _(EDX) _(EBX) _(ESP) _(EBP) _(ESI) _(EDI) \ - _(R8D) _(R9D) _(R10D) _(R11D) _(R12D) _(R13D) _(R14D) _(R15D) -#define FPRDEF(_) \ - _(XMM0) _(XMM1) _(XMM2) _(XMM3) _(XMM4) _(XMM5) _(XMM6) _(XMM7) \ - _(XMM8) _(XMM9) _(XMM10) _(XMM11) _(XMM12) _(XMM13) _(XMM14) _(XMM15) -#else -#define GPRDEF(_) \ - _(EAX) _(ECX) _(EDX) _(EBX) _(ESP) _(EBP) _(ESI) _(EDI) -#define FPRDEF(_) \ - _(XMM0) _(XMM1) _(XMM2) _(XMM3) _(XMM4) _(XMM5) _(XMM6) _(XMM7) -#endif -#define VRIDDEF(_) \ - _(MRM) _(RIP) - -#define RIDENUM(name) RID_##name, - -enum { - GPRDEF(RIDENUM) /* General-purpose registers (GPRs). */ - FPRDEF(RIDENUM) /* Floating-point registers (FPRs). */ - RID_MAX, - RID_MRM = RID_MAX, /* Pseudo-id for ModRM operand. */ - RID_RIP = RID_MAX+5, /* Pseudo-id for RIP (x64 only), rm bits = 5. */ - - /* Calling conventions. */ - RID_SP = RID_ESP, - RID_RET = RID_EAX, -#if LJ_64 - RID_FPRET = RID_XMM0, -#endif - RID_RETLO = RID_EAX, - RID_RETHI = RID_EDX, - - /* These definitions must match with the *.dasc file(s): */ - RID_BASE = RID_EDX, /* Interpreter BASE. */ -#if LJ_64 && !LJ_ABI_WIN - RID_LPC = RID_EBX, /* Interpreter PC. */ - RID_DISPATCH = RID_R14D, /* Interpreter DISPATCH table. */ -#else - RID_LPC = RID_ESI, /* Interpreter PC. */ - RID_DISPATCH = RID_EBX, /* Interpreter DISPATCH table. */ -#endif - - /* Register ranges [min, max) and number of registers. */ - RID_MIN_GPR = RID_EAX, - RID_MIN_FPR = RID_XMM0, - RID_MAX_GPR = RID_MIN_FPR, - RID_MAX_FPR = RID_MAX, - RID_NUM_GPR = RID_MAX_GPR - RID_MIN_GPR, - RID_NUM_FPR = RID_MAX_FPR - RID_MIN_FPR, -}; - -/* -- Register sets ------------------------------------------------------- */ - -/* Make use of all registers, except the stack pointer (and maybe DISPATCH). */ -#define RSET_GPR (RSET_RANGE(RID_MIN_GPR, RID_MAX_GPR) \ - - RID2RSET(RID_ESP) \ - - LJ_GC64*RID2RSET(RID_DISPATCH)) -#define RSET_FPR (RSET_RANGE(RID_MIN_FPR, RID_MAX_FPR)) -#define RSET_ALL (RSET_GPR|RSET_FPR) -#define RSET_INIT RSET_ALL - -#if LJ_64 -/* Note: this requires the use of FORCE_REX! */ -#define RSET_GPR8 RSET_GPR -#else -#define RSET_GPR8 (RSET_RANGE(RID_EAX, RID_EBX+1)) -#endif - -/* ABI-specific register sets. */ -#define RSET_ACD (RID2RSET(RID_EAX)|RID2RSET(RID_ECX)|RID2RSET(RID_EDX)) -#if LJ_64 -#if LJ_ABI_WIN -/* Windows x64 ABI. */ -#define RSET_SCRATCH \ - (RSET_ACD|RSET_RANGE(RID_R8D, RID_R11D+1)|RSET_RANGE(RID_XMM0, RID_XMM5+1)) -#define REGARG_GPRS \ - (RID_ECX|((RID_EDX|((RID_R8D|(RID_R9D<<5))<<5))<<5)) -#define REGARG_NUMGPR 4 -#define REGARG_NUMFPR 4 -#define REGARG_FIRSTFPR RID_XMM0 -#define REGARG_LASTFPR RID_XMM3 -#define STACKARG_OFS (4*8) -#else -/* The rest of the civilized x64 world has a common ABI. */ -#define RSET_SCRATCH \ - (RSET_ACD|RSET_RANGE(RID_ESI, RID_R11D+1)|RSET_FPR) -#define REGARG_GPRS \ - (RID_EDI|((RID_ESI|((RID_EDX|((RID_ECX|((RID_R8D|(RID_R9D \ - <<5))<<5))<<5))<<5))<<5)) -#define REGARG_NUMGPR 6 -#define REGARG_NUMFPR 8 -#define REGARG_FIRSTFPR RID_XMM0 -#define REGARG_LASTFPR RID_XMM7 -#define STACKARG_OFS 0 -#endif -#else -/* Common x86 ABI. */ -#define RSET_SCRATCH (RSET_ACD|RSET_FPR) -#define REGARG_GPRS (RID_ECX|(RID_EDX<<5)) /* Fastcall only. */ -#define REGARG_NUMGPR 2 /* Fastcall only. */ -#define REGARG_NUMFPR 0 -#define STACKARG_OFS 0 -#endif - -#if LJ_64 -/* Prefer the low 8 regs of each type to reduce REX prefixes. */ -#undef rset_picktop_ -#define rset_picktop_(rs) (lj_fls(lj_bswap(rs)) ^ 0x18) -#endif - -/* -- Spill slots --------------------------------------------------------- */ - -/* Spill slots are 32 bit wide. An even/odd pair is used for FPRs. -** -** SPS_FIXED: Available fixed spill slots in interpreter frame. -** This definition must match with the *.dasc file(s). -** -** SPS_FIRST: First spill slot for general use. Reserve min. two 32 bit slots. -*/ -#if LJ_64 -#if LJ_ABI_WIN -#define SPS_FIXED (4*2) -#define SPS_FIRST (4*2) /* Don't use callee register save area. */ -#else -#if LJ_GC64 -#define SPS_FIXED 2 -#else -#define SPS_FIXED 4 -#endif -#define SPS_FIRST 2 -#endif -#else -#define SPS_FIXED 6 -#define SPS_FIRST 2 -#endif - -#define SPOFS_TMP 0 - -#define sps_scale(slot) (4 * (int32_t)(slot)) -#define sps_align(slot) (((slot) - SPS_FIXED + 3) & ~3) - -/* -- Exit state ---------------------------------------------------------- */ - -/* This definition must match with the *.dasc file(s). */ -typedef struct { - lua_Number fpr[RID_NUM_FPR]; /* Floating-point registers. */ - intptr_t gpr[RID_NUM_GPR]; /* General-purpose registers. */ - int32_t spill[256]; /* Spill slots. */ -} ExitState; - -/* Limited by the range of a short fwd jump (127): (2+2)*(32-1)-2 = 122. */ -#define EXITSTUB_SPACING (2+2) -#define EXITSTUBS_PER_GROUP 32 - -#define EXITTRACE_VMSTATE 1 /* g->vmstate has traceno on exit. */ - -/* -- x86 ModRM operand encoding ------------------------------------------ */ - -typedef enum { - XM_OFS0 = 0x00, XM_OFS8 = 0x40, XM_OFS32 = 0x80, XM_REG = 0xc0, - XM_SCALE1 = 0x00, XM_SCALE2 = 0x40, XM_SCALE4 = 0x80, XM_SCALE8 = 0xc0, - XM_MASK = 0xc0 -} x86Mode; - -/* Structure to hold variable ModRM operand. */ -typedef struct { - int32_t ofs; /* Offset. */ - uint8_t base; /* Base register or RID_NONE. */ - uint8_t idx; /* Index register or RID_NONE. */ - uint8_t scale; /* Index scale (XM_SCALE1 .. XM_SCALE8). */ -} x86ModRM; - -/* -- Opcodes ------------------------------------------------------------- */ - -/* Macros to construct variable-length x86 opcodes. -(len+1) is in LSB. */ -#define XO_(o) ((uint32_t)(0x0000fe + (0x##o<<24))) -#define XO_FPU(a,b) ((uint32_t)(0x00fd + (0x##a<<16)+(0x##b<<24))) -#define XO_0f(o) ((uint32_t)(0x0f00fd + (0x##o<<24))) -#define XO_66(o) ((uint32_t)(0x6600fd + (0x##o<<24))) -#define XO_660f(o) ((uint32_t)(0x0f66fc + (0x##o<<24))) -#define XO_f20f(o) ((uint32_t)(0x0ff2fc + (0x##o<<24))) -#define XO_f30f(o) ((uint32_t)(0x0ff3fc + (0x##o<<24))) - -#define XV_660f38(o) ((uint32_t)(0x79e2c4 + (0x##o<<24))) -#define XV_f20f38(o) ((uint32_t)(0x7be2c4 + (0x##o<<24))) -#define XV_f20f3a(o) ((uint32_t)(0x7be3c4 + (0x##o<<24))) -#define XV_f30f38(o) ((uint32_t)(0x7ae2c4 + (0x##o<<24))) - -/* This list of x86 opcodes is not intended to be complete. Opcodes are only -** included when needed. Take a look at DynASM or jit.dis_x86 to see the -** whole mess. -*/ -typedef enum { - /* Fixed length opcodes. XI_* prefix. */ - XI_O16 = 0x66, - XI_NOP = 0x90, - XI_XCHGa = 0x90, - XI_CALL = 0xe8, - XI_JMP = 0xe9, - XI_JMPs = 0xeb, - XI_PUSH = 0x50, /* Really 50+r. */ - XI_JCCs = 0x70, /* Really 7x. */ - XI_JCCn = 0x80, /* Really 0f8x. */ - XI_LEA = 0x8d, - XI_MOVrib = 0xb0, /* Really b0+r. */ - XI_MOVri = 0xb8, /* Really b8+r. */ - XI_ARITHib = 0x80, - XI_ARITHi = 0x81, - XI_ARITHi8 = 0x83, - XI_PUSHi8 = 0x6a, - XI_TESTb = 0x84, - XI_TEST = 0x85, - XI_INT3 = 0xcc, - XI_MOVmi = 0xc7, - XI_GROUP5 = 0xff, - - /* Note: little-endian byte-order! */ - XI_FLDZ = 0xeed9, - XI_FLD1 = 0xe8d9, - XI_FDUP = 0xc0d9, /* Really fld st0. */ - XI_FPOP = 0xd8dd, /* Really fstp st0. */ - XI_FPOP1 = 0xd9dd, /* Really fstp st1. */ - XI_FRNDINT = 0xfcd9, - XI_FSCALE = 0xfdd9, - XI_FYL2X = 0xf1d9, - - /* VEX-encoded instructions. XV_* prefix. */ - XV_RORX = XV_f20f3a(f0), - XV_SARX = XV_f30f38(f7), - XV_SHLX = XV_660f38(f7), - XV_SHRX = XV_f20f38(f7), - - /* Special NOP instructions. */ - XI_ENDBR64 = 0xfa1e0ff3, - - /* Variable-length opcodes. XO_* prefix. */ - XO_OR = XO_(0b), - XO_MOV = XO_(8b), - XO_MOVto = XO_(89), - XO_MOVtow = XO_66(89), - XO_MOVtob = XO_(88), - XO_MOVmi = XO_(c7), - XO_MOVmib = XO_(c6), - XO_LEA = XO_(8d), - XO_ARITHib = XO_(80), - XO_ARITHi = XO_(81), - XO_ARITHi8 = XO_(83), - XO_ARITHiw8 = XO_66(83), - XO_SHIFTi = XO_(c1), - XO_SHIFT1 = XO_(d1), - XO_SHIFTcl = XO_(d3), - XO_IMUL = XO_0f(af), - XO_IMULi = XO_(69), - XO_IMULi8 = XO_(6b), - XO_CMP = XO_(3b), - XO_TESTb = XO_(84), - XO_TEST = XO_(85), - XO_GROUP3b = XO_(f6), - XO_GROUP3 = XO_(f7), - XO_GROUP5b = XO_(fe), - XO_GROUP5 = XO_(ff), - XO_MOVZXb = XO_0f(b6), - XO_MOVZXw = XO_0f(b7), - XO_MOVSXb = XO_0f(be), - XO_MOVSXw = XO_0f(bf), - XO_MOVSXd = XO_(63), - XO_BSWAP = XO_0f(c8), - XO_CMOV = XO_0f(40), - - XO_MOVSD = XO_f20f(10), - XO_MOVSDto = XO_f20f(11), - XO_MOVSS = XO_f30f(10), - XO_MOVSSto = XO_f30f(11), - XO_MOVLPD = XO_660f(12), - XO_MOVAPS = XO_0f(28), - XO_XORPS = XO_0f(57), - XO_ANDPS = XO_0f(54), - XO_ADDSD = XO_f20f(58), - XO_SUBSD = XO_f20f(5c), - XO_MULSD = XO_f20f(59), - XO_DIVSD = XO_f20f(5e), - XO_SQRTSD = XO_f20f(51), - XO_MINSD = XO_f20f(5d), - XO_MAXSD = XO_f20f(5f), - XO_ROUNDSD = 0x0b3a0ffc, /* Really 66 0f 3a 0b. See asm_fpmath. */ - XO_UCOMISD = XO_660f(2e), - XO_CVTSI2SD = XO_f20f(2a), - XO_CVTTSD2SI= XO_f20f(2c), - XO_CVTSI2SS = XO_f30f(2a), - XO_CVTTSS2SI= XO_f30f(2c), - XO_CVTSS2SD = XO_f30f(5a), - XO_CVTSD2SS = XO_f20f(5a), - XO_ADDSS = XO_f30f(58), - XO_MOVD = XO_660f(6e), - XO_MOVDto = XO_660f(7e), - - XO_FLDd = XO_(d9), XOg_FLDd = 0, - XO_FLDq = XO_(dd), XOg_FLDq = 0, - XO_FILDd = XO_(db), XOg_FILDd = 0, - XO_FILDq = XO_(df), XOg_FILDq = 5, - XO_FSTPd = XO_(d9), XOg_FSTPd = 3, - XO_FSTPq = XO_(dd), XOg_FSTPq = 3, - XO_FISTPq = XO_(df), XOg_FISTPq = 7, - XO_FISTTPq = XO_(dd), XOg_FISTTPq = 1, - XO_FADDd = XO_(d8), XOg_FADDd = 0, - XO_FADDq = XO_(dc), XOg_FADDq = 0, - XO_FLDCW = XO_(d9), XOg_FLDCW = 5, - XO_FNSTCW = XO_(d9), XOg_FNSTCW = 7 -} x86Op; - -/* x86 opcode groups. */ -typedef uint32_t x86Group; - -#define XG_(i8, i, g) ((x86Group)(((i8) << 16) + ((i) << 8) + (g))) -#define XG_ARITHi(g) XG_(XI_ARITHi8, XI_ARITHi, g) -#define XG_TOXOi(xg) ((x86Op)(0x000000fe + (((xg)<<16) & 0xff000000))) -#define XG_TOXOi8(xg) ((x86Op)(0x000000fe + (((xg)<<8) & 0xff000000))) - -#define XO_ARITH(a) ((x86Op)(0x030000fe + ((a)<<27))) -#define XO_ARITHw(a) ((x86Op)(0x036600fd + ((a)<<27))) - -typedef enum { - XOg_ADD, XOg_OR, XOg_ADC, XOg_SBB, XOg_AND, XOg_SUB, XOg_XOR, XOg_CMP, - XOg_X_IMUL -} x86Arith; - -typedef enum { - XOg_ROL, XOg_ROR, XOg_RCL, XOg_RCR, XOg_SHL, XOg_SHR, XOg_SAL, XOg_SAR -} x86Shift; - -typedef enum { - XOg_TEST, XOg_TEST_, XOg_NOT, XOg_NEG, XOg_MUL, XOg_IMUL, XOg_DIV, XOg_IDIV -} x86Group3; - -typedef enum { - XOg_INC, XOg_DEC, XOg_CALL, XOg_CALLfar, XOg_JMP, XOg_JMPfar, XOg_PUSH -} x86Group5; - -/* x86 condition codes. */ -typedef enum { - CC_O, CC_NO, CC_B, CC_NB, CC_E, CC_NE, CC_BE, CC_NBE, - CC_S, CC_NS, CC_P, CC_NP, CC_L, CC_NL, CC_LE, CC_NLE, - CC_C = CC_B, CC_NAE = CC_C, CC_NC = CC_NB, CC_AE = CC_NB, - CC_Z = CC_E, CC_NZ = CC_NE, CC_NA = CC_BE, CC_A = CC_NBE, - CC_PE = CC_P, CC_PO = CC_NP, CC_NGE = CC_L, CC_GE = CC_NL, - CC_NG = CC_LE, CC_G = CC_NLE -} x86CC; - -#endif diff --git a/include/luajit/lj_trace.h b/include/luajit/lj_trace.h deleted file mode 100644 index ff2c761..0000000 --- a/include/luajit/lj_trace.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -** Trace management. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_TRACE_H -#define _LJ_TRACE_H - -#include "lj_obj.h" - -#if LJ_HASJIT -#include "lj_jit.h" -#include "lj_dispatch.h" - -/* Trace errors. */ -typedef enum { -#define TREDEF(name, msg) LJ_TRERR_##name, -#include "lj_traceerr.h" - LJ_TRERR__MAX -} TraceError; - -LJ_FUNC_NORET void lj_trace_err(jit_State *J, TraceError e); -LJ_FUNC_NORET void lj_trace_err_info(jit_State *J, TraceError e); - -/* Trace management. */ -LJ_FUNC GCtrace * LJ_FASTCALL lj_trace_alloc(lua_State *L, GCtrace *T); -LJ_FUNC void LJ_FASTCALL lj_trace_free(global_State *g, GCtrace *T); -LJ_FUNC void lj_trace_reenableproto(GCproto *pt); -LJ_FUNC void lj_trace_flushproto(global_State *g, GCproto *pt); -LJ_FUNC void lj_trace_flush(jit_State *J, TraceNo traceno); -LJ_FUNC int lj_trace_flushall(lua_State *L); -LJ_FUNC void lj_trace_initstate(global_State *g); -LJ_FUNC void lj_trace_freestate(global_State *g); - -/* Event handling. */ -LJ_FUNC void lj_trace_ins(jit_State *J, const BCIns *pc); -LJ_FUNCA void LJ_FASTCALL lj_trace_hot(jit_State *J, const BCIns *pc); -LJ_FUNCA void LJ_FASTCALL lj_trace_stitch(jit_State *J, const BCIns *pc); -LJ_FUNCA int LJ_FASTCALL lj_trace_exit(jit_State *J, void *exptr); -#if LJ_UNWIND_EXT -LJ_FUNC uintptr_t LJ_FASTCALL lj_trace_unwind(jit_State *J, uintptr_t addr, ExitNo *ep); -#endif - -/* Signal asynchronous abort of trace or end of trace. */ -#define lj_trace_abort(g) (G2J(g)->state &= ~LJ_TRACE_ACTIVE) -#define lj_trace_end(J) (J->state = LJ_TRACE_END) - -#else - -#define lj_trace_flushall(L) (UNUSED(L), 0) -#define lj_trace_initstate(g) UNUSED(g) -#define lj_trace_freestate(g) UNUSED(g) -#define lj_trace_abort(g) UNUSED(g) -#define lj_trace_end(J) UNUSED(J) - -#endif - -#endif diff --git a/include/luajit/lj_traceerr.h b/include/luajit/lj_traceerr.h deleted file mode 100644 index d283a9d..0000000 --- a/include/luajit/lj_traceerr.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -** Trace compiler error messages. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -/* This file may be included multiple times with different TREDEF macros. */ - -/* Recording. */ -TREDEF(RECERR, "error thrown or hook called during recording") -TREDEF(TRACEUV, "trace too short") -TREDEF(TRACEOV, "trace too long") -TREDEF(STACKOV, "trace too deep") -TREDEF(SNAPOV, "too many snapshots") -TREDEF(BLACKL, "blacklisted") -TREDEF(RETRY, "retry recording") -TREDEF(NYIBC, "NYI: bytecode %s") - -/* Recording loop ops. */ -TREDEF(LLEAVE, "leaving loop in root trace") -TREDEF(LINNER, "inner loop in root trace") -TREDEF(LUNROLL, "loop unroll limit reached") - -/* Recording calls/returns. */ -TREDEF(BADTYPE, "bad argument type") -TREDEF(CJITOFF, "JIT compilation disabled for function") -TREDEF(CUNROLL, "call unroll limit reached") -TREDEF(DOWNREC, "down-recursion, restarting") -TREDEF(NYIFFU, "NYI: unsupported variant of FastFunc %s") -TREDEF(NYIRETL, "NYI: return to lower frame") - -/* Recording indexed load/store. */ -TREDEF(STORENN, "store with nil or NaN key") -TREDEF(NOMM, "missing metamethod") -TREDEF(IDXLOOP, "looping index lookup") -TREDEF(NYITMIX, "NYI: mixed sparse/dense table") - -/* Recording C data operations. */ -TREDEF(NOCACHE, "symbol not in cache") -TREDEF(NYICONV, "NYI: unsupported C type conversion") -TREDEF(NYICALL, "NYI: unsupported C function type") - -/* Optimizations. */ -TREDEF(GFAIL, "guard would always fail") -TREDEF(PHIOV, "too many PHIs") -TREDEF(TYPEINS, "persistent type instability") - -/* Assembler. */ -TREDEF(MCODEAL, "failed to allocate mcode memory") -TREDEF(MCODEOV, "machine code too long") -TREDEF(MCODELM, "hit mcode limit (retrying)") -TREDEF(SPILLOV, "too many spill slots") -TREDEF(BADRA, "inconsistent register allocation") -TREDEF(NYIIR, "NYI: cannot assemble IR instruction %d") -TREDEF(NYIPHI, "NYI: PHI shuffling too complex") -TREDEF(NYICOAL, "NYI: register coalescing too complex") - -#undef TREDEF - -/* Detecting unused error messages: - awk -F, '/^TREDEF/ { gsub(/TREDEF./, ""); printf "grep -q LJ_TRERR_%s *.[ch] || echo %s\n", $1, $1}' lj_traceerr.h | sh -*/ diff --git a/include/luajit/lj_udata.h b/include/luajit/lj_udata.h deleted file mode 100644 index d6bab23..0000000 --- a/include/luajit/lj_udata.h +++ /dev/null @@ -1,17 +0,0 @@ -/* -** Userdata handling. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_UDATA_H -#define _LJ_UDATA_H - -#include "lj_obj.h" - -LJ_FUNC GCudata *lj_udata_new(lua_State *L, MSize sz, GCtab *env); -LJ_FUNC void LJ_FASTCALL lj_udata_free(global_State *g, GCudata *ud); -#if LJ_64 -LJ_FUNC void * LJ_FASTCALL lj_lightud_intern(lua_State *L, void *p); -#endif - -#endif diff --git a/include/luajit/lj_vm.h b/include/luajit/lj_vm.h deleted file mode 100644 index 01da1bd..0000000 --- a/include/luajit/lj_vm.h +++ /dev/null @@ -1,122 +0,0 @@ -/* -** Assembler VM interface definitions. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_VM_H -#define _LJ_VM_H - -#include "lj_obj.h" - -/* Entry points for ASM parts of VM. */ -LJ_ASMF void lj_vm_call(lua_State *L, TValue *base, int nres1); -LJ_ASMF int lj_vm_pcall(lua_State *L, TValue *base, int nres1, ptrdiff_t ef); -typedef TValue *(*lua_CPFunction)(lua_State *L, lua_CFunction func, void *ud); -LJ_ASMF int lj_vm_cpcall(lua_State *L, lua_CFunction func, void *ud, - lua_CPFunction cp); -LJ_ASMF int lj_vm_resume(lua_State *L, TValue *base, int nres1, ptrdiff_t ef); -LJ_ASMF_NORET void LJ_FASTCALL lj_vm_unwind_c(void *cframe, int errcode); -LJ_ASMF_NORET void LJ_FASTCALL lj_vm_unwind_ff(void *cframe); -#if LJ_ABI_WIN && LJ_TARGET_X86 -LJ_ASMF_NORET void LJ_FASTCALL lj_vm_rtlunwind(void *cframe, void *excptrec, - void *unwinder, int errcode); -#endif -LJ_ASMF void lj_vm_unwind_c_eh(void); -LJ_ASMF void lj_vm_unwind_ff_eh(void); -#if LJ_TARGET_X86ORX64 -LJ_ASMF void lj_vm_unwind_rethrow(void); -#endif -#if LJ_TARGET_MIPS -LJ_ASMF void lj_vm_unwind_stub(void); -#endif - -/* Miscellaneous functions. */ -#if LJ_TARGET_X86ORX64 -LJ_ASMF int lj_vm_cpuid(uint32_t f, uint32_t res[4]); -#endif -#if LJ_TARGET_PPC -void lj_vm_cachesync(void *start, void *end); -#endif -LJ_ASMF LJ_CONSTF double lj_vm_foldarith(double x, double y, int op); -#if LJ_HASJIT -LJ_ASMF LJ_CONSTF double lj_vm_foldfpm(double x, int op); -#endif -#if LJ_SOFTFP && LJ_TARGET_MIPS64 -LJ_ASMF int32_t lj_vm_tointg(double x); -#endif -/* Declared in lj_obj.h: -** LJ_ASMF LJ_CONSTF int64_t lj_vm_num2int_check(double x); -** LJ_ASMF LJ_CONSTF int64_t lj_vm_num2i64(double x); -** LJ_ASMF LJ_CONSTF uint64_t lj_vm_num2u64(double x); -** LJ_ASMF LJ_CONSTF int32_t lj_vm_tobit(double x); -*/ - -/* Dispatch targets for recording and hooks. */ -LJ_ASMF void lj_vm_record(void); -LJ_ASMF void lj_vm_inshook(void); -LJ_ASMF void lj_vm_rethook(void); -LJ_ASMF void lj_vm_callhook(void); -LJ_ASMF void lj_vm_profhook(void); -LJ_ASMF void lj_vm_IITERN(void); - -/* Trace exit handling. */ -LJ_ASMF char lj_vm_exit_handler[]; -LJ_ASMF char lj_vm_exit_interp[]; - -/* Internal math helper functions. */ -#if LJ_TARGET_PPC || LJ_TARGET_ARM64 || (LJ_TARGET_MIPS && LJ_ABI_SOFTFP) -#define lj_vm_floor floor -#define lj_vm_ceil ceil -#else -LJ_ASMF LJ_CONSTF double lj_vm_floor(double); -LJ_ASMF LJ_CONSTF double lj_vm_ceil(double); -#if LJ_TARGET_ARM -LJ_ASMF double lj_vm_floor_sf(double); -LJ_ASMF double lj_vm_ceil_sf(double); -#endif -#endif -#ifdef LUAJIT_NO_LOG2 -LJ_ASMF LJ_CONSTF double lj_vm_log2(double); -#else -#define lj_vm_log2 log2 -#endif -#if !(defined(_LJ_DISPATCH_H) && LJ_TARGET_MIPS) -LJ_ASMF int32_t LJ_FASTCALL lj_vm_modi(int32_t, int32_t); -#endif - -#if LJ_HASJIT -#if LJ_TARGET_X86ORX64 -LJ_ASMF void lj_vm_floor_sse(void); -LJ_ASMF void lj_vm_ceil_sse(void); -LJ_ASMF void lj_vm_trunc_sse(void); -#endif -#if LJ_TARGET_PPC || LJ_TARGET_ARM64 -#define lj_vm_trunc trunc -#else -LJ_ASMF LJ_CONSTF double lj_vm_trunc(double); -#if LJ_TARGET_ARM -LJ_ASMF double lj_vm_trunc_sf(double); -#endif -#endif -#if LJ_HASFFI -LJ_ASMF int lj_vm_errno(void); -#endif -LJ_ASMF TValue *lj_vm_next(GCtab *t, uint32_t idx); -#endif - -/* Continuations for metamethods. */ -LJ_ASMF void lj_cont_cat(void); /* Continue with concatenation. */ -LJ_ASMF void lj_cont_ra(void); /* Store result in RA from instruction. */ -LJ_ASMF void lj_cont_nop(void); /* Do nothing, just continue execution. */ -LJ_ASMF void lj_cont_condt(void); /* Branch if result is true. */ -LJ_ASMF void lj_cont_condf(void); /* Branch if result is false. */ -LJ_ASMF void lj_cont_hook(void); /* Continue from hook yield. */ -LJ_ASMF void lj_cont_stitch(void); /* Trace stitching. */ - -/* Start of the ASM code. */ -LJ_ASMF char lj_vm_asm_begin[]; - -/* Bytecode offsets are relative to lj_vm_asm_begin. */ -#define makeasmfunc(ofs) lj_ptr_sign((ASMFunction)(lj_vm_asm_begin + (ofs)), 0) - -#endif diff --git a/include/luajit/lj_vmevent.h b/include/luajit/lj_vmevent.h deleted file mode 100644 index cdd4f75..0000000 --- a/include/luajit/lj_vmevent.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -** VM event handling. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LJ_VMEVENT_H -#define _LJ_VMEVENT_H - -#include "lj_obj.h" - -/* Registry key for VM event handler table. */ -#define LJ_VMEVENTS_REGKEY "_VMEVENTS" -#define LJ_VMEVENTS_HSIZE 4 - -#define VMEVENT_MASK(ev) ((uint8_t)1 << ((int)(ev) & 7)) -#define VMEVENT_HASH(ev) ((int)(ev) & ~7) -#define VMEVENT_HASHIDX(h) ((int)(h) << 3) -#define VMEVENT_NOCACHE 255 - -#define VMEVENT_DEF(name, hash) \ - LJ_VMEVENT_##name##_, \ - LJ_VMEVENT_##name = ((LJ_VMEVENT_##name##_) & 7)|((hash) << 3) - -/* VM event IDs. */ -typedef enum { - VMEVENT_DEF(BC, 0x00003883), - VMEVENT_DEF(TRACE, 0x12d91467), - VMEVENT_DEF(RECORD, 0x1284bf4f), - VMEVENT_DEF(TEXIT, 0x129df2b0), - VMEVENT_DEF(ERRFIN, 0x12d93888), - LJ_VMEVENT__MAX -} VMEvent; - -#ifdef LUAJIT_DISABLE_VMEVENT -#define lj_vmevent_send(g, ev, args) UNUSED(g) -#define lj_vmevent_send_(g, ev, args, post) UNUSED(g) -#else -#define lj_vmevent_send(g, ev, args) \ - if ((g)->vmevmask & VMEVENT_MASK(LJ_VMEVENT_##ev)) { \ - lua_State *V = vmthread(g); \ - ptrdiff_t argbase = lj_vmevent_prepare(V, LJ_VMEVENT_##ev); \ - if (argbase) { \ - args \ - lj_vmevent_call(V, argbase); \ - } \ - } -#define lj_vmevent_send_(g, ev, args, post) \ - if ((g)->vmevmask & VMEVENT_MASK(LJ_VMEVENT_##ev)) { \ - lua_State *V = vmthread(g); \ - ptrdiff_t argbase = lj_vmevent_prepare(V, LJ_VMEVENT_##ev); \ - if (argbase) { \ - args \ - lj_vmevent_call(V, argbase); \ - post \ - } \ - } - -LJ_FUNC ptrdiff_t lj_vmevent_prepare(lua_State *L, VMEvent ev); -LJ_FUNC void lj_vmevent_call(lua_State *L, ptrdiff_t argbase); -#endif - -#endif diff --git a/include/luajit/lua.h b/include/luajit/lua.h deleted file mode 100644 index 6d1634d..0000000 --- a/include/luajit/lua.h +++ /dev/null @@ -1,402 +0,0 @@ -/* -** $Id: lua.h,v 1.218.1.5 2008/08/06 13:30:12 roberto Exp $ -** Lua - An Extensible Extension Language -** Lua.org, PUC-Rio, Brazil (https://www.lua.org) -** See Copyright Notice at the end of this file -*/ - - -#ifndef lua_h -#define lua_h - -#include -#include - - -#include "luaconf.h" - - -#define LUA_VERSION "Lua 5.1" -#define LUA_RELEASE "Lua 5.1.4" -#define LUA_VERSION_NUM 501 -#define LUA_COPYRIGHT "Copyright (C) 1994-2008 Lua.org, PUC-Rio" -#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo & W. Celes" - - -/* mark for precompiled code (`Lua') */ -#define LUA_SIGNATURE "\033Lua" - -/* option for multiple returns in `lua_pcall' and `lua_call' */ -#define LUA_MULTRET (-1) - - -/* -** pseudo-indices -*/ -#define LUA_REGISTRYINDEX (-10000) -#define LUA_ENVIRONINDEX (-10001) -#define LUA_GLOBALSINDEX (-10002) -#define lua_upvalueindex(i) (LUA_GLOBALSINDEX-(i)) - - -/* thread status */ -#define LUA_OK 0 -#define LUA_YIELD 1 -#define LUA_ERRRUN 2 -#define LUA_ERRSYNTAX 3 -#define LUA_ERRMEM 4 -#define LUA_ERRERR 5 - - -typedef struct lua_State lua_State; - -typedef int (*lua_CFunction) (lua_State *L); - - -/* -** functions that read/write blocks when loading/dumping Lua chunks -*/ -typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz); - -typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud); - - -/* -** prototype for memory-allocation functions -*/ -typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); - - -/* -** basic types -*/ -#define LUA_TNONE (-1) - -#define LUA_TNIL 0 -#define LUA_TBOOLEAN 1 -#define LUA_TLIGHTUSERDATA 2 -#define LUA_TNUMBER 3 -#define LUA_TSTRING 4 -#define LUA_TTABLE 5 -#define LUA_TFUNCTION 6 -#define LUA_TUSERDATA 7 -#define LUA_TTHREAD 8 - - - -/* minimum Lua stack available to a C function */ -#define LUA_MINSTACK 20 - - -/* -** generic extra include file -*/ -#if defined(LUA_USER_H) -#include LUA_USER_H -#endif - - -/* type of numbers in Lua */ -typedef LUA_NUMBER lua_Number; - - -/* type for integer functions */ -typedef LUA_INTEGER lua_Integer; - - - -/* -** state manipulation -*/ -LUA_API lua_State *(lua_newstate) (lua_Alloc f, void *ud); -LUA_API void (lua_close) (lua_State *L); -LUA_API lua_State *(lua_newthread) (lua_State *L); - -LUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf); - - -/* -** basic stack manipulation -*/ -LUA_API int (lua_gettop) (lua_State *L); -LUA_API void (lua_settop) (lua_State *L, int idx); -LUA_API void (lua_pushvalue) (lua_State *L, int idx); -LUA_API void (lua_remove) (lua_State *L, int idx); -LUA_API void (lua_insert) (lua_State *L, int idx); -LUA_API void (lua_replace) (lua_State *L, int idx); -LUA_API int (lua_checkstack) (lua_State *L, int sz); - -LUA_API void (lua_xmove) (lua_State *from, lua_State *to, int n); - - -/* -** access functions (stack -> C) -*/ - -LUA_API int (lua_isnumber) (lua_State *L, int idx); -LUA_API int (lua_isstring) (lua_State *L, int idx); -LUA_API int (lua_iscfunction) (lua_State *L, int idx); -LUA_API int (lua_isuserdata) (lua_State *L, int idx); -LUA_API int (lua_type) (lua_State *L, int idx); -LUA_API const char *(lua_typename) (lua_State *L, int tp); - -LUA_API int (lua_equal) (lua_State *L, int idx1, int idx2); -LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2); -LUA_API int (lua_lessthan) (lua_State *L, int idx1, int idx2); - -LUA_API lua_Number (lua_tonumber) (lua_State *L, int idx); -LUA_API lua_Integer (lua_tointeger) (lua_State *L, int idx); -LUA_API int (lua_toboolean) (lua_State *L, int idx); -LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len); -LUA_API size_t (lua_objlen) (lua_State *L, int idx); -LUA_API lua_CFunction (lua_tocfunction) (lua_State *L, int idx); -LUA_API void *(lua_touserdata) (lua_State *L, int idx); -LUA_API lua_State *(lua_tothread) (lua_State *L, int idx); -LUA_API const void *(lua_topointer) (lua_State *L, int idx); - - -/* -** push functions (C -> stack) -*/ -LUA_API void (lua_pushnil) (lua_State *L); -LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n); -LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n); -LUA_API void (lua_pushlstring) (lua_State *L, const char *s, size_t l); -LUA_API void (lua_pushstring) (lua_State *L, const char *s); -LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt, - va_list argp); -LUA_API const char *(lua_pushfstring) (lua_State *L, const char *fmt, ...); -LUA_API void (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n); -LUA_API void (lua_pushboolean) (lua_State *L, int b); -LUA_API void (lua_pushlightuserdata) (lua_State *L, void *p); -LUA_API int (lua_pushthread) (lua_State *L); - - -/* -** get functions (Lua -> stack) -*/ -LUA_API void (lua_gettable) (lua_State *L, int idx); -LUA_API void (lua_getfield) (lua_State *L, int idx, const char *k); -LUA_API void (lua_rawget) (lua_State *L, int idx); -LUA_API void (lua_rawgeti) (lua_State *L, int idx, int n); -LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec); -LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz); -LUA_API int (lua_getmetatable) (lua_State *L, int objindex); -LUA_API void (lua_getfenv) (lua_State *L, int idx); - - -/* -** set functions (stack -> Lua) -*/ -LUA_API void (lua_settable) (lua_State *L, int idx); -LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k); -LUA_API void (lua_rawset) (lua_State *L, int idx); -LUA_API void (lua_rawseti) (lua_State *L, int idx, int n); -LUA_API int (lua_setmetatable) (lua_State *L, int objindex); -LUA_API int (lua_setfenv) (lua_State *L, int idx); - - -/* -** `load' and `call' functions (load and run Lua code) -*/ -LUA_API void (lua_call) (lua_State *L, int nargs, int nresults); -LUA_API int (lua_pcall) (lua_State *L, int nargs, int nresults, int errfunc); -LUA_API int (lua_cpcall) (lua_State *L, lua_CFunction func, void *ud); -LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt, - const char *chunkname); - -LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data); - - -/* -** coroutine functions -*/ -LUA_API int (lua_yield) (lua_State *L, int nresults); -LUA_API int (lua_resume) (lua_State *L, int narg); -LUA_API int (lua_status) (lua_State *L); - -/* -** garbage-collection function and options -*/ - -#define LUA_GCSTOP 0 -#define LUA_GCRESTART 1 -#define LUA_GCCOLLECT 2 -#define LUA_GCCOUNT 3 -#define LUA_GCCOUNTB 4 -#define LUA_GCSTEP 5 -#define LUA_GCSETPAUSE 6 -#define LUA_GCSETSTEPMUL 7 -#define LUA_GCISRUNNING 9 - -LUA_API int (lua_gc) (lua_State *L, int what, int data); - - -/* -** miscellaneous functions -*/ - -LUA_API int (lua_error) (lua_State *L); - -LUA_API int (lua_next) (lua_State *L, int idx); - -LUA_API void (lua_concat) (lua_State *L, int n); - -LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud); -LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud); - - - -/* -** =============================================================== -** some useful macros -** =============================================================== -*/ - -#define lua_pop(L,n) lua_settop(L, -(n)-1) - -#define lua_newtable(L) lua_createtable(L, 0, 0) - -#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n))) - -#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0) - -#define lua_strlen(L,i) lua_objlen(L, (i)) - -#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION) -#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE) -#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA) -#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL) -#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN) -#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD) -#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE) -#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0) - -#define lua_pushliteral(L, s) \ - lua_pushlstring(L, "" s, (sizeof(s)/sizeof(char))-1) - -#define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, (s)) -#define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, (s)) - -#define lua_tostring(L,i) lua_tolstring(L, (i), NULL) - - - -/* -** compatibility macros and functions -*/ - -#define lua_open() luaL_newstate() - -#define lua_getregistry(L) lua_pushvalue(L, LUA_REGISTRYINDEX) - -#define lua_getgccount(L) lua_gc(L, LUA_GCCOUNT, 0) - -#define lua_Chunkreader lua_Reader -#define lua_Chunkwriter lua_Writer - - -/* hack */ -LUA_API void lua_setlevel (lua_State *from, lua_State *to); - - -/* -** {====================================================================== -** Debug API -** ======================================================================= -*/ - - -/* -** Event codes -*/ -#define LUA_HOOKCALL 0 -#define LUA_HOOKRET 1 -#define LUA_HOOKLINE 2 -#define LUA_HOOKCOUNT 3 -#define LUA_HOOKTAILRET 4 - - -/* -** Event masks -*/ -#define LUA_MASKCALL (1 << LUA_HOOKCALL) -#define LUA_MASKRET (1 << LUA_HOOKRET) -#define LUA_MASKLINE (1 << LUA_HOOKLINE) -#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT) - -typedef struct lua_Debug lua_Debug; /* activation record */ - - -/* Functions to be called by the debuger in specific events */ -typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); - - -LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar); -LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); -LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n); -LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n); -LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n); -LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n); -LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count); -LUA_API lua_Hook lua_gethook (lua_State *L); -LUA_API int lua_gethookmask (lua_State *L); -LUA_API int lua_gethookcount (lua_State *L); - -/* From Lua 5.2. */ -LUA_API void *lua_upvalueid (lua_State *L, int idx, int n); -LUA_API void lua_upvaluejoin (lua_State *L, int idx1, int n1, int idx2, int n2); -LUA_API int lua_loadx (lua_State *L, lua_Reader reader, void *dt, - const char *chunkname, const char *mode); -LUA_API const lua_Number *lua_version (lua_State *L); -LUA_API void lua_copy (lua_State *L, int fromidx, int toidx); -LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *isnum); -LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *isnum); - -/* From Lua 5.3. */ -LUA_API int lua_isyieldable (lua_State *L); - - -struct lua_Debug { - int event; - const char *name; /* (n) */ - const char *namewhat; /* (n) `global', `local', `field', `method' */ - const char *what; /* (S) `Lua', `C', `main', `tail' */ - const char *source; /* (S) */ - int currentline; /* (l) */ - int nups; /* (u) number of upvalues */ - int linedefined; /* (S) */ - int lastlinedefined; /* (S) */ - char short_src[LUA_IDSIZE]; /* (S) */ - /* private part */ - int i_ci; /* active function */ -}; - -/* }====================================================================== */ - - -/****************************************************************************** -* Copyright (C) 1994-2008 Lua.org, PUC-Rio. All rights reserved. -* -* Permission is hereby granted, free of charge, to any person obtaining -* a copy of this software and associated documentation files (the -* "Software"), to deal in the Software without restriction, including -* without limitation the rights to use, copy, modify, merge, publish, -* distribute, sublicense, and/or sell copies of the Software, and to -* permit persons to whom the Software is furnished to do so, subject to -* the following conditions: -* -* The above copyright notice and this permission notice shall be -* included in all copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ - - -#endif diff --git a/include/luajit/lua.hpp b/include/luajit/lua.hpp deleted file mode 100644 index 07e9002..0000000 --- a/include/luajit/lua.hpp +++ /dev/null @@ -1,9 +0,0 @@ -// C++ wrapper for LuaJIT header files. - -extern "C" { -#include "lua.h" -#include "lauxlib.h" -#include "lualib.h" -#include "luajit.h" -} - diff --git a/include/luajit/luaconf.h b/include/luajit/luaconf.h deleted file mode 100644 index 6959313..0000000 --- a/include/luajit/luaconf.h +++ /dev/null @@ -1,156 +0,0 @@ -/* -** Configuration header. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef luaconf_h -#define luaconf_h - -#ifndef WINVER -#define WINVER 0x0501 -#endif -#include - -/* Default path for loading Lua and C modules with require(). */ -#if defined(_WIN32) -/* -** In Windows, any exclamation mark ('!') in the path is replaced by the -** path of the directory of the executable file of the current process. -*/ -#define LUA_LDIR "!\\lua\\" -#define LUA_CDIR "!\\" -#define LUA_PATH_DEFAULT \ - ".\\?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" -#define LUA_CPATH_DEFAULT \ - ".\\?.dll;" LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll" -#else -/* -** Note to distribution maintainers: do NOT patch the following lines! -** Please read ../doc/install.html#distro and pass PREFIX=/usr instead. -*/ -#ifndef LUA_MULTILIB -#define LUA_MULTILIB "lib" -#endif -#ifndef LUA_LMULTILIB -#define LUA_LMULTILIB "lib" -#endif -#define LUA_LROOT "/usr/local" -#define LUA_LUADIR "/lua/5.1/" - -#ifdef LUA_ROOT -#define LUA_JROOT LUA_ROOT -#define LUA_RLDIR LUA_ROOT "/share" LUA_LUADIR -#define LUA_RCDIR LUA_ROOT "/" LUA_MULTILIB LUA_LUADIR -#define LUA_RLPATH ";" LUA_RLDIR "?.lua;" LUA_RLDIR "?/init.lua" -#define LUA_RCPATH ";" LUA_RCDIR "?.so" -#else -#define LUA_JROOT LUA_LROOT -#define LUA_RLPATH -#define LUA_RCPATH -#endif - -#ifndef LUA_LJDIR -#define LUA_LJDIR LUA_JROOT "/share/luajit-2.1" -#endif - -#define LUA_JPATH ";" LUA_LJDIR "/?.lua" -#define LUA_LLDIR LUA_LROOT "/share" LUA_LUADIR -#define LUA_LCDIR LUA_LROOT "/" LUA_LMULTILIB LUA_LUADIR -#define LUA_LLPATH ";" LUA_LLDIR "?.lua;" LUA_LLDIR "?/init.lua" -#define LUA_LCPATH1 ";" LUA_LCDIR "?.so" -#define LUA_LCPATH2 ";" LUA_LCDIR "loadall.so" - -#define LUA_PATH_DEFAULT "./?.lua" LUA_JPATH LUA_LLPATH LUA_RLPATH -#define LUA_CPATH_DEFAULT "./?.so" LUA_LCPATH1 LUA_RCPATH LUA_LCPATH2 -#endif - -/* Environment variable names for path overrides and initialization code. */ -#define LUA_PATH "LUA_PATH" -#define LUA_CPATH "LUA_CPATH" -#define LUA_INIT "LUA_INIT" - -/* Special file system characters. */ -#if defined(_WIN32) -#define LUA_DIRSEP "\\" -#else -#define LUA_DIRSEP "/" -#endif -#define LUA_PATHSEP ";" -#define LUA_PATH_MARK "?" -#define LUA_EXECDIR "!" -#define LUA_IGMARK "-" -#define LUA_PATH_CONFIG \ - LUA_DIRSEP "\n" LUA_PATHSEP "\n" LUA_PATH_MARK "\n" \ - LUA_EXECDIR "\n" LUA_IGMARK "\n" - -/* Quoting in error messages. */ -#define LUA_QL(x) "'" x "'" -#define LUA_QS LUA_QL("%s") - -/* Various tunables. */ -#define LUAI_MAXSTACK 65500 /* Max. # of stack slots for a thread (<64K). */ -#define LUAI_MAXCSTACK 8000 /* Max. # of stack slots for a C func (<10K). */ -#define LUAI_GCPAUSE 200 /* Pause GC until memory is at 200%. */ -#define LUAI_GCMUL 200 /* Run GC at 200% of allocation speed. */ -#define LUA_MAXCAPTURES 32 /* Max. pattern captures. */ - -/* Configuration for the frontend (the luajit executable). */ -#if defined(luajit_c) -#define LUA_PROGNAME "luajit" /* Fallback frontend name. */ -#define LUA_PROMPT "> " /* Interactive prompt. */ -#define LUA_PROMPT2 ">> " /* Continuation prompt. */ -#define LUA_MAXINPUT 512 /* Max. input line length. */ -#endif - -/* Note: changing the following defines breaks the Lua 5.1 ABI. */ -#define LUA_INTEGER ptrdiff_t -#define LUA_IDSIZE 60 /* Size of lua_Debug.short_src. */ -/* -** Size of lauxlib and io.* on-stack buffers. Weird workaround to avoid using -** unreasonable amounts of stack space, but still retain ABI compatibility. -** Blame Lua for depending on BUFSIZ in the ABI, blame **** for wrecking it. -*/ -#define LUAL_BUFFERSIZE (BUFSIZ > 16384 ? 8192 : BUFSIZ) - -/* The following defines are here only for compatibility with luaconf.h -** from the standard Lua distribution. They must not be changed for LuaJIT. -*/ -#define LUA_NUMBER_DOUBLE -#define LUA_NUMBER double -#define LUAI_UACNUMBER double -#define LUA_NUMBER_SCAN "%lf" -#define LUA_NUMBER_FMT "%.14g" -#define lua_number2str(s, n) sprintf((s), LUA_NUMBER_FMT, (n)) -#define LUAI_MAXNUMBER2STR 32 -#define LUA_INTFRMLEN "l" -#define LUA_INTFRM_T long - -/* Linkage of public API functions. */ -#if defined(LUA_BUILD_AS_DLL) -#if defined(LUA_CORE) || defined(LUA_LIB) -#define LUA_API __declspec(dllexport) -#else -#define LUA_API __declspec(dllimport) -#endif -#elif (defined(__ELF__) || defined(__MACH__) || defined(__psp2__)) && !((defined(__sun__) && defined(__svr4__)) || defined(__CELLOS_LV2__)) -#define LUA_API extern __attribute__((visibility("default"))) -#else -#define LUA_API extern -#endif - -#define LUALIB_API LUA_API - -/* Compatibility support for assertions. */ -#if defined(LUA_USE_ASSERT) || defined(LUA_USE_APICHECK) -#include -#endif -#ifdef LUA_USE_ASSERT -#define lua_assert(x) assert(x) -#endif -#ifdef LUA_USE_APICHECK -#define luai_apicheck(L, o) { (void)L; assert(o); } -#else -#define luai_apicheck(L, o) { (void)L; } -#endif - -#endif diff --git a/include/luajit/luajit.h b/include/luajit/luajit.h deleted file mode 100644 index e31546a..0000000 --- a/include/luajit/luajit.h +++ /dev/null @@ -1,79 +0,0 @@ -/* -** LuaJIT -- a Just-In-Time Compiler for Lua. https://luajit.org/ -** -** Copyright (C) 2005-2025 Mike Pall. All rights reserved. -** -** Permission is hereby granted, free of charge, to any person obtaining -** a copy of this software and associated documentation files (the -** "Software"), to deal in the Software without restriction, including -** without limitation the rights to use, copy, modify, merge, publish, -** distribute, sublicense, and/or sell copies of the Software, and to -** permit persons to whom the Software is furnished to do so, subject to -** the following conditions: -** -** The above copyright notice and this permission notice shall be -** included in all copies or substantial portions of the Software. -** -** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -** -** [ MIT license: https://www.opensource.org/licenses/mit-license.php ] -*/ - -#ifndef _LUAJIT_H -#define _LUAJIT_H - -#include "lua.h" - -#define LUAJIT_VERSION "LuaJIT 2.1.1765228720" -#define LUAJIT_VERSION_NUM 20199 /* Deprecated. */ -#define LUAJIT_VERSION_SYM luaJIT_version_2_1_1765228720 -#define LUAJIT_COPYRIGHT "Copyright (C) 2005-2025 Mike Pall" -#define LUAJIT_URL "https://luajit.org/" - -/* Modes for luaJIT_setmode. */ -#define LUAJIT_MODE_MASK 0x00ff - -enum { - LUAJIT_MODE_ENGINE, /* Set mode for whole JIT engine. */ - LUAJIT_MODE_DEBUG, /* Set debug mode (idx = level). */ - - LUAJIT_MODE_FUNC, /* Change mode for a function. */ - LUAJIT_MODE_ALLFUNC, /* Recurse into subroutine protos. */ - LUAJIT_MODE_ALLSUBFUNC, /* Change only the subroutines. */ - - LUAJIT_MODE_TRACE, /* Flush a compiled trace. */ - - LUAJIT_MODE_WRAPCFUNC = 0x10, /* Set wrapper mode for C function calls. */ - - LUAJIT_MODE_MAX -}; - -/* Flags or'ed in to the mode. */ -#define LUAJIT_MODE_OFF 0x0000 /* Turn feature off. */ -#define LUAJIT_MODE_ON 0x0100 /* Turn feature on. */ -#define LUAJIT_MODE_FLUSH 0x0200 /* Flush JIT-compiled code. */ - -/* LuaJIT public C API. */ - -/* Control the JIT engine. */ -LUA_API int luaJIT_setmode(lua_State *L, int idx, int mode); - -/* Low-overhead profiling API. */ -typedef void (*luaJIT_profile_callback)(void *data, lua_State *L, - int samples, int vmstate); -LUA_API void luaJIT_profile_start(lua_State *L, const char *mode, - luaJIT_profile_callback cb, void *data); -LUA_API void luaJIT_profile_stop(lua_State *L); -LUA_API const char *luaJIT_profile_dumpstack(lua_State *L, const char *fmt, - int depth, size_t *len); - -/* Enforce (dynamic) linker error for version mismatches. Call from main. */ -LUA_API void LUAJIT_VERSION_SYM(void); - -#endif diff --git a/include/luajit/luajit_rolling.h b/include/luajit/luajit_rolling.h deleted file mode 100644 index 73639aa..0000000 --- a/include/luajit/luajit_rolling.h +++ /dev/null @@ -1,80 +0,0 @@ -/* -** LuaJIT -- a Just-In-Time Compiler for Lua. https://luajit.org/ -** -** Copyright (C) 2005-2025 Mike Pall. All rights reserved. -** -** Permission is hereby granted, free of charge, to any person obtaining -** a copy of this software and associated documentation files (the -** "Software"), to deal in the Software without restriction, including -** without limitation the rights to use, copy, modify, merge, publish, -** distribute, sublicense, and/or sell copies of the Software, and to -** permit persons to whom the Software is furnished to do so, subject to -** the following conditions: -** -** The above copyright notice and this permission notice shall be -** included in all copies or substantial portions of the Software. -** -** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -** -** [ MIT license: https://www.opensource.org/licenses/mit-license.php ] -*/ - -#ifndef _LUAJIT_H -#define _LUAJIT_H - -#include "lua.h" - -#define LUAJIT_VERSION "LuaJIT 2.1.ROLLING" -#define LUAJIT_VERSION_NUM 20199 /* Deprecated. */ -#define LUAJIT_VERSION_SYM luaJIT_version_2_1_ROLLING -#define LUAJIT_COPYRIGHT "Copyright (C) 2005-2025 Mike Pall" -#define LUAJIT_URL "https://luajit.org/" - -/* Modes for luaJIT_setmode. */ -#define LUAJIT_MODE_MASK 0x00ff - -enum { - LUAJIT_MODE_ENGINE, /* Set mode for whole JIT engine. */ - LUAJIT_MODE_DEBUG, /* Set debug mode (idx = level). */ - - LUAJIT_MODE_FUNC, /* Change mode for a function. */ - LUAJIT_MODE_ALLFUNC, /* Recurse into subroutine protos. */ - LUAJIT_MODE_ALLSUBFUNC, /* Change only the subroutines. */ - - LUAJIT_MODE_TRACE, /* Flush a compiled trace. */ - - LUAJIT_MODE_WRAPCFUNC = 0x10, /* Set wrapper mode for C function calls. */ - - LUAJIT_MODE_MAX -}; - -/* Flags or'ed in to the mode. */ -#define LUAJIT_MODE_OFF 0x0000 /* Turn feature off. */ -#define LUAJIT_MODE_ON 0x0100 /* Turn feature on. */ -#define LUAJIT_MODE_FLUSH 0x0200 /* Flush JIT-compiled code. */ - -/* LuaJIT public C API. */ - -/* Control the JIT engine. */ -LUA_API int luaJIT_setmode(lua_State *L, int idx, int mode); - -/* Low-overhead profiling API. */ -typedef void (*luaJIT_profile_callback)(void *data, lua_State *L, - int samples, int vmstate); -LUA_API void luaJIT_profile_start(lua_State *L, const char *mode, - luaJIT_profile_callback cb, void *data); -LUA_API void luaJIT_profile_stop(lua_State *L); -LUA_API const char *luaJIT_profile_dumpstack(lua_State *L, const char *fmt, - int depth, size_t *len); - -/* Enforce (dynamic) linker error for version mismatches. Call from main. */ -LUA_API void LUAJIT_VERSION_SYM(void); - -#error "DO NOT USE luajit_rolling.h -- only include build-generated luajit.h" -#endif diff --git a/include/luajit/lualib.h b/include/luajit/lualib.h deleted file mode 100644 index 2f91427..0000000 --- a/include/luajit/lualib.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -** Standard library header. -** Copyright (C) 2005-2025 Mike Pall. See Copyright Notice in luajit.h -*/ - -#ifndef _LUALIB_H -#define _LUALIB_H - -#include "lua.h" - -#define LUA_FILEHANDLE "FILE*" - -#define LUA_COLIBNAME "coroutine" -#define LUA_MATHLIBNAME "math" -#define LUA_STRLIBNAME "string" -#define LUA_TABLIBNAME "table" -#define LUA_IOLIBNAME "io" -#define LUA_OSLIBNAME "os" -#define LUA_LOADLIBNAME "package" -#define LUA_DBLIBNAME "debug" -#define LUA_BITLIBNAME "bit" -#define LUA_JITLIBNAME "jit" -#define LUA_FFILIBNAME "ffi" - -LUALIB_API int luaopen_base(lua_State *L); -LUALIB_API int luaopen_math(lua_State *L); -LUALIB_API int luaopen_string(lua_State *L); -LUALIB_API int luaopen_table(lua_State *L); -LUALIB_API int luaopen_io(lua_State *L); -LUALIB_API int luaopen_os(lua_State *L); -LUALIB_API int luaopen_package(lua_State *L); -LUALIB_API int luaopen_debug(lua_State *L); -LUALIB_API int luaopen_bit(lua_State *L); -LUALIB_API int luaopen_jit(lua_State *L); -LUALIB_API int luaopen_ffi(lua_State *L); -LUALIB_API int luaopen_string_buffer(lua_State *L); - -LUALIB_API void luaL_openlibs(lua_State *L); - -#ifndef lua_assert -#define lua_assert(x) ((void)0) -#endif - -#endif diff --git a/include/nfd.h b/include/nfd.h deleted file mode 100644 index adb1c81..0000000 --- a/include/nfd.h +++ /dev/null @@ -1,564 +0,0 @@ -/* - Native File Dialog Extended - Repository: https://github.com/btzy/nativefiledialog-extended - License: Zlib - Authors: Bernard Teo, Michael Labbe - - This header contains the functions that can be called by user code. - */ - -#ifndef _NFD_H -#define _NFD_H - -#if defined(_WIN32) -#if defined(NFD_EXPORT) -#define NFD_API __declspec(dllexport) -#elif defined(NFD_SHARED) -#define NFD_API __declspec(dllimport) -#endif -#else -#if defined(NFD_EXPORT) || defined(NFD_SHARED) -#if defined(__GNUC__) || defined(__clang__) -#define NFD_API __attribute__((visibility("default"))) -#endif -#endif -#endif -#ifndef NFD_API -#define NFD_API -#endif - -#ifdef __cplusplus -extern "C" { -#define NFD_INLINE inline -#else -#define NFD_INLINE static inline -#endif // __cplusplus - -#include - -typedef char nfdu8char_t; - -#ifdef _WIN32 -/** @typedef UTF-16 character */ -typedef wchar_t nfdnchar_t; -#else -/** @typedef UTF-8 character */ -typedef nfdu8char_t nfdnchar_t; -#endif // _WIN32 - -/** @typedef Opaque data structure -- see NFD_PathSet_* */ -typedef void nfdpathset_t; -#ifndef NFD_PORTAL -typedef struct { - void* ptr; -} nfdpathsetenum_t; -#else -typedef struct { - void* d1; - void* d2; - unsigned int d3; - int d4; - int d5; - int d6; - int d7; - int d8; - int d9; - int d10; - int d11; - int p1; - void* p2; - void* p3; -} nfdpathsetenum_t; -#endif - -typedef unsigned int nfdfiltersize_t; - -typedef enum { - NFD_ERROR, /**< Programmatic error */ - NFD_OKAY, /**< User pressed okay, or successful return */ - NFD_CANCEL /**< User pressed cancel */ -} nfdresult_t; - -/** @typedef UTF-8 Filter Item */ -typedef struct { - const nfdu8char_t* name; - const nfdu8char_t* spec; -} nfdu8filteritem_t; - -#ifdef _WIN32 -/** @typedef UTF-16 Filter Item */ -typedef struct { - const nfdnchar_t* name; - const nfdnchar_t* spec; -} nfdnfilteritem_t; -#else -/** @typedef UTF-8 Filter Item */ -typedef nfdu8filteritem_t nfdnfilteritem_t; -#endif // _WIN32 - -// The native window handle type. -enum { - NFD_WINDOW_HANDLE_TYPE_UNSET = 0, - // Windows: handle is HWND (the Windows API typedefs this to void*) - NFD_WINDOW_HANDLE_TYPE_WINDOWS = 1, - // Cocoa: handle is NSWindow* - NFD_WINDOW_HANDLE_TYPE_COCOA = 2, - // X11: handle is Window - NFD_WINDOW_HANDLE_TYPE_X11 = 3, - // Wayland support will be implemented separately in the future -}; -// The native window handle. If using a platform abstraction framework (e.g. SDL2), this should be -// obtained using the corresponding NFD glue header (e.g. nfd_sdl2.h). -typedef struct { - size_t type; // this is one of the values of the enum above - void* handle; -} nfdwindowhandle_t; - -typedef size_t nfdversion_t; - -typedef struct { - const nfdu8filteritem_t* filterList; - nfdfiltersize_t filterCount; - const nfdu8char_t* defaultPath; - nfdwindowhandle_t parentWindow; -} nfdopendialogu8args_t; - -#ifdef _WIN32 -typedef struct { - const nfdnfilteritem_t* filterList; - nfdfiltersize_t filterCount; - const nfdnchar_t* defaultPath; - nfdwindowhandle_t parentWindow; -} nfdopendialognargs_t; -#else -typedef nfdopendialogu8args_t nfdopendialognargs_t; -#endif // _WIN32 - -typedef struct { - const nfdu8filteritem_t* filterList; - nfdfiltersize_t filterCount; - const nfdu8char_t* defaultPath; - const nfdu8char_t* defaultName; - nfdwindowhandle_t parentWindow; -} nfdsavedialogu8args_t; - -#ifdef _WIN32 -typedef struct { - const nfdnfilteritem_t* filterList; - nfdfiltersize_t filterCount; - const nfdnchar_t* defaultPath; - const nfdnchar_t* defaultName; - nfdwindowhandle_t parentWindow; -} nfdsavedialognargs_t; -#else -typedef nfdsavedialogu8args_t nfdsavedialognargs_t; -#endif // _WIN32 - -typedef struct { - const nfdu8char_t* defaultPath; - nfdwindowhandle_t parentWindow; -} nfdpickfolderu8args_t; - -#ifdef _WIN32 -typedef struct { - const nfdnchar_t* defaultPath; - nfdwindowhandle_t parentWindow; -} nfdpickfoldernargs_t; -#else -typedef nfdpickfolderu8args_t nfdpickfoldernargs_t; -#endif // _WIN32 - -// This is a unique identifier tagged to all the NFD_*With() function calls, for backward -// compatibility purposes. There is usually no need to use this directly, unless you want to use -// NFD differently depending on the version you're building with. -#define NFD_INTERFACE_VERSION 1 - -/** Free a file path that was returned by the dialogs. - * - * Note: use NFD_PathSet_FreePathN() to free path from pathset instead of this function. */ -NFD_API void NFD_FreePathN(nfdnchar_t* filePath); - -/** Free a file path that was returned by the dialogs. - * - * Note: use NFD_PathSet_FreePathU8() to free path from pathset instead of this function. */ -NFD_API void NFD_FreePathU8(nfdu8char_t* filePath); - -/** Initialize NFD. Call this for every thread that might use NFD, before calling any other NFD - * functions on that thread. */ -NFD_API nfdresult_t NFD_Init(void); - -/** Call this to de-initialize NFD, if NFD_Init returned NFD_OKAY. */ -NFD_API void NFD_Quit(void); - -/** Single file open dialog - * - * It's the caller's responsibility to free `outPath` via NFD_FreePathN() if this function returns - * NFD_OKAY. - * @param[out] outPath - * @param filterCount If zero, filterList is ignored (you can use null). - * @param defaultPath If null, the operating system will decide. */ -NFD_API nfdresult_t NFD_OpenDialogN(nfdnchar_t** outPath, - const nfdnfilteritem_t* filterList, - nfdfiltersize_t filterCount, - const nfdnchar_t* defaultPath); - -/** Single file open dialog - * - * It is the caller's responsibility to free `outPath` via NFD_FreePathU8() if this function - * returns NFD_OKAY. - * @param[out] outPath - * @param filterCount If zero, filterList is ignored (you can use null). - * @param defaultPath If null, the operating system will decide. */ -NFD_API nfdresult_t NFD_OpenDialogU8(nfdu8char_t** outPath, - const nfdu8filteritem_t* filterList, - nfdfiltersize_t filterCount, - const nfdu8char_t* defaultPath); - -/** This function is a library implementation detail. Please use NFD_OpenDialogN_With() instead. */ -NFD_API nfdresult_t NFD_OpenDialogN_With_Impl(nfdversion_t version, - nfdnchar_t** outPath, - const nfdopendialognargs_t* args); - -/** Single file open dialog, with additional parameters. - * - * It is the caller's responsibility to free `outPath` via NFD_FreePathN() if this function - * returns NFD_OKAY. See documentation of nfdopendialognargs_t for details. */ -NFD_INLINE nfdresult_t NFD_OpenDialogN_With(nfdnchar_t** outPath, - const nfdopendialognargs_t* args) { - return NFD_OpenDialogN_With_Impl(NFD_INTERFACE_VERSION, outPath, args); -} - -/** This function is a library implementation detail. Please use NFD_OpenDialogU8_With() instead. - */ -NFD_API nfdresult_t NFD_OpenDialogU8_With_Impl(nfdversion_t version, - nfdu8char_t** outPath, - const nfdopendialogu8args_t* args); - -/** Single file open dialog, with additional parameters. - * - * It is the caller's responsibility to free `outPath` via NFD_FreePathU8() if this function - * returns NFD_OKAY. See documentation of nfdopendialogu8args_t for details. */ -NFD_INLINE nfdresult_t NFD_OpenDialogU8_With(nfdu8char_t** outPath, - const nfdopendialogu8args_t* args) { - return NFD_OpenDialogU8_With_Impl(NFD_INTERFACE_VERSION, outPath, args); -} - -/** Multiple file open dialog - * - * It is the caller's responsibility to free `outPaths` via NFD_PathSet_FreeN() if this function - * returns NFD_OKAY. - * @param[out] outPaths - * @param filterCount If zero, filterList is ignored (you can use null). - * @param defaultPath If null, the operating system will decide. */ -NFD_API nfdresult_t NFD_OpenDialogMultipleN(const nfdpathset_t** outPaths, - const nfdnfilteritem_t* filterList, - nfdfiltersize_t filterCount, - const nfdnchar_t* defaultPath); - -/** Multiple file open dialog - * - * It is the caller's responsibility to free `outPaths` via NFD_PathSet_FreeU8() if this function - * returns NFD_OKAY. - * @param[out] outPaths - * @param filterCount If zero, filterList is ignored (you can use null). - * @param defaultPath If null, the operating system will decide. */ -NFD_API nfdresult_t NFD_OpenDialogMultipleU8(const nfdpathset_t** outPaths, - const nfdu8filteritem_t* filterList, - nfdfiltersize_t filterCount, - const nfdu8char_t* defaultPath); - -/** This function is a library implementation detail. Please use NFD_OpenDialogMultipleN_With() - * instead. */ -NFD_API nfdresult_t NFD_OpenDialogMultipleN_With_Impl(nfdversion_t version, - const nfdpathset_t** outPaths, - const nfdopendialognargs_t* args); - -/** Multiple file open dialog, with additional parameters. - * - * It is the caller's responsibility to free `outPaths` via NFD_PathSet_FreeN() if this function - * returns NFD_OKAY. See documentation of nfdopendialognargs_t for details. */ -NFD_INLINE nfdresult_t NFD_OpenDialogMultipleN_With(const nfdpathset_t** outPaths, - const nfdopendialognargs_t* args) { - return NFD_OpenDialogMultipleN_With_Impl(NFD_INTERFACE_VERSION, outPaths, args); -} - -/** This function is a library implementation detail. Please use NFD_OpenDialogU8_With() instead. - */ -NFD_API nfdresult_t NFD_OpenDialogMultipleU8_With_Impl(nfdversion_t version, - const nfdpathset_t** outPaths, - const nfdopendialogu8args_t* args); - -/** Multiple file open dialog, with additional parameters. - * - * It is the caller's responsibility to free `outPaths` via NFD_PathSet_FreeU8() if this function - * returns NFD_OKAY. See documentation of nfdopendialogu8args_t for details. */ -NFD_INLINE nfdresult_t NFD_OpenDialogMultipleU8_With(const nfdpathset_t** outPaths, - const nfdopendialogu8args_t* args) { - return NFD_OpenDialogMultipleU8_With_Impl(NFD_INTERFACE_VERSION, outPaths, args); -} - -/** Save dialog - * - * It is the caller's responsibility to free `outPath` via NFD_FreePathN() if this function returns - * NFD_OKAY. - * @param[out] outPath - * @param filterCount If zero, filterList is ignored (you can use null). - * @param defaultPath If null, the operating system will decide. */ -NFD_API nfdresult_t NFD_SaveDialogN(nfdnchar_t** outPath, - const nfdnfilteritem_t* filterList, - nfdfiltersize_t filterCount, - const nfdnchar_t* defaultPath, - const nfdnchar_t* defaultName); - -/** Save dialog - * - * It is the caller's responsibility to free `outPath` via NFD_FreePathU8() if this function - * returns NFD_OKAY. - * @param[out] outPath - * @param filterCount If zero, filterList is ignored (you can use null). - * @param defaultPath If null, the operating system will decide. */ -NFD_API nfdresult_t NFD_SaveDialogU8(nfdu8char_t** outPath, - const nfdu8filteritem_t* filterList, - nfdfiltersize_t filterCount, - const nfdu8char_t* defaultPath, - const nfdu8char_t* defaultName); - -/** This function is a library implementation detail. Please use NFD_SaveDialogN_With() instead. */ -NFD_API nfdresult_t NFD_SaveDialogN_With_Impl(nfdversion_t version, - nfdnchar_t** outPath, - const nfdsavedialognargs_t* args); - -/** Single file save dialog, with additional parameters. - * - * It is the caller's responsibility to free `outPath` via NFD_FreePathN() if this function - * returns NFD_OKAY. See documentation of nfdsavedialognargs_t for details. */ -NFD_INLINE nfdresult_t NFD_SaveDialogN_With(nfdnchar_t** outPath, - const nfdsavedialognargs_t* args) { - return NFD_SaveDialogN_With_Impl(NFD_INTERFACE_VERSION, outPath, args); -} - -/** This function is a library implementation detail. Please use NFD_SaveDialogU8_With() instead. - */ -NFD_API nfdresult_t NFD_SaveDialogU8_With_Impl(nfdversion_t version, - nfdu8char_t** outPath, - const nfdsavedialogu8args_t* args); - -/** Single file save dialog, with additional parameters. - * - * It is the caller's responsibility to free `outPath` via NFD_FreePathU8() if this function - * returns NFD_OKAY. See documentation of nfdsavedialogu8args_t for details. */ -NFD_INLINE nfdresult_t NFD_SaveDialogU8_With(nfdu8char_t** outPath, - const nfdsavedialogu8args_t* args) { - return NFD_SaveDialogU8_With_Impl(NFD_INTERFACE_VERSION, outPath, args); -} - -/** Select single folder dialog - * - * It is the caller's responsibility to free `outPath` via NFD_FreePathN() if this function returns - * NFD_OKAY. - * @param[out] outPath - * @param defaultPath If null, the operating system will decide. */ -NFD_API nfdresult_t NFD_PickFolderN(nfdnchar_t** outPath, const nfdnchar_t* defaultPath); - -/** Select single folder dialog - * - * It is the caller's responsibility to free `outPath` via NFD_FreePathU8() if this function - * returns NFD_OKAY. - * @param[out] outPath - * @param defaultPath If null, the operating system will decide. */ -NFD_API nfdresult_t NFD_PickFolderU8(nfdu8char_t** outPath, const nfdu8char_t* defaultPath); - -/** This function is a library implementation detail. Please use NFD_PickFolderN_With() instead. */ -NFD_API nfdresult_t NFD_PickFolderN_With_Impl(nfdversion_t version, - nfdnchar_t** outPath, - const nfdpickfoldernargs_t* args); - -/** Select single folder dialog, with additional parameters. - * - * It is the caller's responsibility to free `outPath` via NFD_FreePathN() if this function - * returns NFD_OKAY. See documentation of nfdpickfoldernargs_t for details. */ -NFD_INLINE nfdresult_t NFD_PickFolderN_With(nfdnchar_t** outPath, - const nfdpickfoldernargs_t* args) { - return NFD_PickFolderN_With_Impl(NFD_INTERFACE_VERSION, outPath, args); -} - -/** This function is a library implementation detail. Please use NFD_PickFolderU8_With() instead. - */ -NFD_API nfdresult_t NFD_PickFolderU8_With_Impl(nfdversion_t version, - nfdu8char_t** outPath, - const nfdpickfolderu8args_t* args); - -/** Select single folder dialog, with additional parameters. - * - * It is the caller's responsibility to free `outPath` via NFD_FreePathU8() if this function - * returns NFD_OKAY. See documentation of nfdpickfolderu8args_t for details. */ -NFD_INLINE nfdresult_t NFD_PickFolderU8_With(nfdu8char_t** outPath, - const nfdpickfolderu8args_t* args) { - return NFD_PickFolderU8_With_Impl(NFD_INTERFACE_VERSION, outPath, args); -} - -/** Select multiple folder dialog - * - * It is the caller's responsibility to free `outPaths` via NFD_PathSet_FreeN() if this function - * returns NFD_OKAY. - * @param[out] outPaths - * @param defaultPath If null, the operating system will decide. */ -NFD_API nfdresult_t NFD_PickFolderMultipleN(const nfdpathset_t** outPaths, - const nfdnchar_t* defaultPath); - -/** Select multiple folder dialog - * - * It is the caller's responsibility to free `outPaths` via NFD_PathSet_FreeU8() if this function - * returns NFD_OKAY. - * @param[out] outPaths - * @param defaultPath If null, the operating system will decide. */ -NFD_API nfdresult_t NFD_PickFolderMultipleU8(const nfdpathset_t** outPaths, - const nfdu8char_t* defaultPath); - -/** This function is a library implementation detail. Please use NFD_PickFolderMultipleN_With() - * instead. */ -NFD_API nfdresult_t NFD_PickFolderMultipleN_With_Impl(nfdversion_t version, - const nfdpathset_t** outPaths, - const nfdpickfoldernargs_t* args); - -/** Select multiple folder dialog, with additional parameters. - * - * It is the caller's responsibility to free `outPaths` via NFD_PathSet_FreeN() if this function - * returns NFD_OKAY. See documentation of nfdopendialogargs_t for details. */ -NFD_INLINE nfdresult_t NFD_PickFolderMultipleN_With(const nfdpathset_t** outPaths, - const nfdpickfoldernargs_t* args) { - return NFD_PickFolderMultipleN_With_Impl(NFD_INTERFACE_VERSION, outPaths, args); -} - -/** This function is a library implementation detail. Please use NFD_PickFolderMultipleU8_With() - * instead. - */ -NFD_API nfdresult_t NFD_PickFolderMultipleU8_With_Impl(nfdversion_t version, - const nfdpathset_t** outPaths, - const nfdpickfolderu8args_t* args); - -/** Select multiple folder dialog, with additional parameters. - * - * It is the caller's responsibility to free `outPaths` via NFD_PathSet_FreeU8() if this function - * returns NFD_OKAY. See documentation of nfdpickfolderargs_t for details. */ -NFD_INLINE nfdresult_t NFD_PickFolderMultipleU8_With(const nfdpathset_t** outPaths, - const nfdpickfolderu8args_t* args) { - return NFD_PickFolderMultipleU8_With_Impl(NFD_INTERFACE_VERSION, outPaths, args); -} - -/** Get the last error - * - * This is set when a function returns NFD_ERROR. - * The memory is owned by NFD and should not be freed by user code. - * This is *always* ASCII printable characters, so it can be interpreted as UTF-8 without any - * conversion. - * @return The last error that was set, or null if there is no error. */ -NFD_API const char* NFD_GetError(void); - -/** Clear the error. */ -NFD_API void NFD_ClearError(void); - -/* path set operations */ -#ifdef _WIN32 -typedef unsigned long nfdpathsetsize_t; -#elif __APPLE__ -typedef unsigned long nfdpathsetsize_t; -#else -typedef unsigned int nfdpathsetsize_t; -#endif // _WIN32, __APPLE__ - -/** Get the number of entries stored in pathSet. - * - * Note: some paths might be invalid (NFD_ERROR will be returned by NFD_PathSet_GetPath), - * so we might not actually have this number of usable paths. */ -NFD_API nfdresult_t NFD_PathSet_GetCount(const nfdpathset_t* pathSet, nfdpathsetsize_t* count); - -/** Get the UTF-8 path at offset index. - * - * It is the caller's responsibility to free `outPath` via NFD_PathSet_FreePathN() if this function - * returns NFD_OKAY. */ -NFD_API nfdresult_t NFD_PathSet_GetPathN(const nfdpathset_t* pathSet, - nfdpathsetsize_t index, - nfdnchar_t** outPath); - -/** Get the native path at offset index. - * - * It is the caller's responsibility to free `outPath` via NFD_PathSet_FreePathU8() if this - * function returns NFD_OKAY. */ -NFD_API nfdresult_t NFD_PathSet_GetPathU8(const nfdpathset_t* pathSet, - nfdpathsetsize_t index, - nfdu8char_t** outPath); - -/** Free the path gotten by NFD_PathSet_GetPathN(). */ -NFD_API void NFD_PathSet_FreePathN(const nfdnchar_t* filePath); - -/** Free the path gotten by NFD_PathSet_GetPathU8(). */ -NFD_API void NFD_PathSet_FreePathU8(const nfdu8char_t* filePath); - -/** Gets an enumerator of the path set. - * - * It is the caller's responsibility to free `enumerator` via NFD_PathSet_FreeEnum() - * if this function returns NFD_OKAY, and it should be freed before freeing the pathset. */ -NFD_API nfdresult_t NFD_PathSet_GetEnum(const nfdpathset_t* pathSet, - nfdpathsetenum_t* outEnumerator); - -/** Frees an enumerator of the path set. */ -NFD_API void NFD_PathSet_FreeEnum(nfdpathsetenum_t* enumerator); - -/** Gets the next item from the path set enumerator. - * - * If there are no more items, then *outPaths will be set to null. - * It is the caller's responsibility to free `*outPath` via NFD_PathSet_FreePathN() - * if this function returns NFD_OKAY and `*outPath` is not null. */ -NFD_API nfdresult_t NFD_PathSet_EnumNextN(nfdpathsetenum_t* enumerator, nfdnchar_t** outPath); - -/** Gets the next item from the path set enumerator. - * - * If there are no more items, then *outPaths will be set to null. - * It is the caller's responsibility to free `*outPath` via NFD_PathSet_FreePathU8() - * if this function returns NFD_OKAY and `*outPath` is not null. */ -NFD_API nfdresult_t NFD_PathSet_EnumNextU8(nfdpathsetenum_t* enumerator, nfdu8char_t** outPath); - -/** Free the pathSet */ -NFD_API void NFD_PathSet_Free(const nfdpathset_t* pathSet); - -#ifdef _WIN32 - -/* say that the U8 versions of functions are not just __attribute__((alias(""))) to the native - * versions */ -#define NFD_DIFFERENT_NATIVE_FUNCTIONS - -#endif // _WIN32 - -#ifdef NFD_NATIVE -typedef nfdnchar_t nfdchar_t; -typedef nfdnfilteritem_t nfdfilteritem_t; -#define NFD_FreePath NFD_FreePathN -#define NFD_OpenDialog NFD_OpenDialogN -#define NFD_OpenDialogMultiple NFD_OpenDialogMultipleN -#define NFD_SaveDialog NFD_SaveDialogN -#define NFD_PickFolder NFD_PickFolderN -#define NFD_PickFolderMultiple NFD_PickFolderMultipleN -#define NFD_PathSet_GetPath NFD_PathSet_GetPathN -#define NFD_PathSet_FreePath NFD_PathSet_FreePathN -#define NFD_PathSet_EnumNext NFD_PathSet_EnumNextN -#else -typedef nfdu8char_t nfdchar_t; -typedef nfdu8filteritem_t nfdfilteritem_t; -#define NFD_FreePath NFD_FreePathU8 -#define NFD_OpenDialog NFD_OpenDialogU8 -#define NFD_OpenDialogMultiple NFD_OpenDialogMultipleU8 -#define NFD_SaveDialog NFD_SaveDialogU8 -#define NFD_PickFolder NFD_PickFolderU8 -#define NFD_PickFolderMultiple NFD_PickFolderMultipleU8 -#define NFD_PathSet_GetPath NFD_PathSet_GetPathU8 -#define NFD_PathSet_FreePath NFD_PathSet_FreePathU8 -#define NFD_PathSet_EnumNext NFD_PathSet_EnumNextU8 -#endif // NFD_NATIVE - -#undef NFD_INLINE -#ifdef __cplusplus -} -#endif // __cplusplus - -#endif // _NFD_H diff --git a/include/nlohmann/json.hpp b/include/nlohmann/json.hpp deleted file mode 100644 index ceb7a9f..0000000 --- a/include/nlohmann/json.hpp +++ /dev/null @@ -1,25712 +0,0 @@ -// __ _____ _____ _____ -// __| | __| | | | JSON for Modern C++ -// | | |__ | | | | | | version 3.12.0 -// |_____|_____|_____|_|___| https://github.com/nlohmann/json -// -// SPDX-FileCopyrightText: 2013-2025 Niels Lohmann -// SPDX-License-Identifier: MIT - -/****************************************************************************\ - * Note on documentation: The source files contain links to the online * - * documentation of the public API at https://json.nlohmann.me. This URL * - * contains the most recent documentation and should also be applicable to * - * previous versions; documentation for deprecated functions is not * - * removed, but marked deprecated. See "Generate documentation" section in * - * file docs/README.md. * -\****************************************************************************/ - -#ifndef INCLUDE_NLOHMANN_JSON_HPP_ -#define INCLUDE_NLOHMANN_JSON_HPP_ - -#include // all_of, find, for_each -#include // nullptr_t, ptrdiff_t, size_t -#include // hash, less -#include // initializer_list -#ifndef JSON_NO_IO - #include // istream, ostream -#endif // JSON_NO_IO -#include // random_access_iterator_tag -#include // unique_ptr -#include // string, stoi, to_string -#include // declval, forward, move, pair, swap -#include // vector - -// #include -// __ _____ _____ _____ -// __| | __| | | | JSON for Modern C++ -// | | |__ | | | | | | version 3.12.0 -// |_____|_____|_____|_|___| https://github.com/nlohmann/json -// -// SPDX-FileCopyrightText: 2013-2025 Niels Lohmann -// SPDX-License-Identifier: MIT - - - -#include - -// #include -// __ _____ _____ _____ -// __| | __| | | | JSON for Modern C++ -// | | |__ | | | | | | version 3.12.0 -// |_____|_____|_____|_|___| https://github.com/nlohmann/json -// -// SPDX-FileCopyrightText: 2013-2025 Niels Lohmann -// SPDX-License-Identifier: MIT - - - -// This file contains all macro definitions affecting or depending on the ABI - -#ifndef JSON_SKIP_LIBRARY_VERSION_CHECK - #if defined(NLOHMANN_JSON_VERSION_MAJOR) && defined(NLOHMANN_JSON_VERSION_MINOR) && defined(NLOHMANN_JSON_VERSION_PATCH) - #if NLOHMANN_JSON_VERSION_MAJOR != 3 || NLOHMANN_JSON_VERSION_MINOR != 12 || NLOHMANN_JSON_VERSION_PATCH != 0 - #warning "Already included a different version of the library!" - #endif - #endif -#endif - -#define NLOHMANN_JSON_VERSION_MAJOR 3 // NOLINT(modernize-macro-to-enum) -#define NLOHMANN_JSON_VERSION_MINOR 12 // NOLINT(modernize-macro-to-enum) -#define NLOHMANN_JSON_VERSION_PATCH 0 // NOLINT(modernize-macro-to-enum) - -#ifndef JSON_DIAGNOSTICS - #define JSON_DIAGNOSTICS 0 -#endif - -#ifndef JSON_DIAGNOSTIC_POSITIONS - #define JSON_DIAGNOSTIC_POSITIONS 0 -#endif - -#ifndef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON - #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0 -#endif - -#if JSON_DIAGNOSTICS - #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag -#else - #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS -#endif - -#if JSON_DIAGNOSTIC_POSITIONS - #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS _dp -#else - #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS -#endif - -#if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON - #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON _ldvcmp -#else - #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON -#endif - -#ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION - #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0 -#endif - -// Construct the namespace ABI tags component -#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c) json_abi ## a ## b ## c -#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b, c) \ - NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c) - -#define NLOHMANN_JSON_ABI_TAGS \ - NLOHMANN_JSON_ABI_TAGS_CONCAT( \ - NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS, \ - NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON, \ - NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS) - -// Construct the namespace version component -#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \ - _v ## major ## _ ## minor ## _ ## patch -#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(major, minor, patch) \ - NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) - -#if NLOHMANN_JSON_NAMESPACE_NO_VERSION -#define NLOHMANN_JSON_NAMESPACE_VERSION -#else -#define NLOHMANN_JSON_NAMESPACE_VERSION \ - NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(NLOHMANN_JSON_VERSION_MAJOR, \ - NLOHMANN_JSON_VERSION_MINOR, \ - NLOHMANN_JSON_VERSION_PATCH) -#endif - -// Combine namespace components -#define NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) a ## b -#define NLOHMANN_JSON_NAMESPACE_CONCAT(a, b) \ - NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) - -#ifndef NLOHMANN_JSON_NAMESPACE -#define NLOHMANN_JSON_NAMESPACE \ - nlohmann::NLOHMANN_JSON_NAMESPACE_CONCAT( \ - NLOHMANN_JSON_ABI_TAGS, \ - NLOHMANN_JSON_NAMESPACE_VERSION) -#endif - -#ifndef NLOHMANN_JSON_NAMESPACE_BEGIN -#define NLOHMANN_JSON_NAMESPACE_BEGIN \ - namespace nlohmann \ - { \ - inline namespace NLOHMANN_JSON_NAMESPACE_CONCAT( \ - NLOHMANN_JSON_ABI_TAGS, \ - NLOHMANN_JSON_NAMESPACE_VERSION) \ - { -#endif - -#ifndef NLOHMANN_JSON_NAMESPACE_END -#define NLOHMANN_JSON_NAMESPACE_END \ - } /* namespace (inline namespace) NOLINT(readability/namespace) */ \ - } // namespace nlohmann -#endif - -// #include -// __ _____ _____ _____ -// __| | __| | | | JSON for Modern C++ -// | | |__ | | | | | | version 3.12.0 -// |_____|_____|_____|_|___| https://github.com/nlohmann/json -// -// SPDX-FileCopyrightText: 2013-2025 Niels Lohmann -// SPDX-License-Identifier: MIT - - - -#include // transform -#include // array -#include // forward_list -#include // inserter, front_inserter, end -#include // map -#include // string -#include // tuple, make_tuple -#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible -#include // unordered_map -#include // pair, declval -#include // valarray - -// #include -// __ _____ _____ _____ -// __| | __| | | | JSON for Modern C++ -// | | |__ | | | | | | version 3.12.0 -// |_____|_____|_____|_|___| https://github.com/nlohmann/json -// -// SPDX-FileCopyrightText: 2013-2025 Niels Lohmann -// SPDX-License-Identifier: MIT - - - -#include // nullptr_t -#include // exception -#if JSON_DIAGNOSTICS - #include // accumulate -#endif -#include // runtime_error -#include // to_string -#include // vector - -// #include -// __ _____ _____ _____ -// __| | __| | | | JSON for Modern C++ -// | | |__ | | | | | | version 3.12.0 -// |_____|_____|_____|_|___| https://github.com/nlohmann/json -// -// SPDX-FileCopyrightText: 2013-2025 Niels Lohmann -// SPDX-License-Identifier: MIT - - - -#include // array -#include // size_t -#include // uint8_t -#include // string - -// #include -// __ _____ _____ _____ -// __| | __| | | | JSON for Modern C++ -// | | |__ | | | | | | version 3.12.0 -// |_____|_____|_____|_|___| https://github.com/nlohmann/json -// -// SPDX-FileCopyrightText: 2013-2025 Niels Lohmann -// SPDX-License-Identifier: MIT - - - -#include // declval, pair -// #include -// __ _____ _____ _____ -// __| | __| | | | JSON for Modern C++ -// | | |__ | | | | | | version 3.12.0 -// |_____|_____|_____|_|___| https://github.com/nlohmann/json -// -// SPDX-FileCopyrightText: 2013-2025 Niels Lohmann -// SPDX-License-Identifier: MIT - - - -#include - -// #include -// __ _____ _____ _____ -// __| | __| | | | JSON for Modern C++ -// | | |__ | | | | | | version 3.12.0 -// |_____|_____|_____|_|___| https://github.com/nlohmann/json -// -// SPDX-FileCopyrightText: 2013-2025 Niels Lohmann -// SPDX-License-Identifier: MIT - - - -// #include - - -NLOHMANN_JSON_NAMESPACE_BEGIN -namespace detail -{ - -template struct make_void -{ - using type = void; -}; -template using void_t = typename make_void::type; - -} // namespace detail -NLOHMANN_JSON_NAMESPACE_END - - -NLOHMANN_JSON_NAMESPACE_BEGIN -namespace detail -{ - -// https://en.cppreference.com/w/cpp/experimental/is_detected -struct nonesuch -{ - nonesuch() = delete; - ~nonesuch() = delete; - nonesuch(nonesuch const&) = delete; - nonesuch(nonesuch const&&) = delete; - void operator=(nonesuch const&) = delete; - void operator=(nonesuch&&) = delete; -}; - -template class Op, - class... Args> -struct detector -{ - using value_t = std::false_type; - using type = Default; -}; - -template class Op, class... Args> -struct detector>, Op, Args...> -{ - using value_t = std::true_type; - using type = Op; -}; - -template class Op, class... Args> -using is_detected = typename detector::value_t; - -template class Op, class... Args> -struct is_detected_lazy : is_detected { }; - -template class Op, class... Args> -using detected_t = typename detector::type; - -template class Op, class... Args> -using detected_or = detector; - -template class Op, class... Args> -using detected_or_t = typename detected_or::type; - -template class Op, class... Args> -using is_detected_exact = std::is_same>; - -template class Op, class... Args> -using is_detected_convertible = - std::is_convertible, To>; - -} // namespace detail -NLOHMANN_JSON_NAMESPACE_END - -// #include - - -// __ _____ _____ _____ -// __| | __| | | | JSON for Modern C++ -// | | |__ | | | | | | version 3.12.0 -// |_____|_____|_____|_|___| https://github.com/nlohmann/json -// -// SPDX-FileCopyrightText: 2013-2025 Niels Lohmann -// SPDX-FileCopyrightText: 2016-2021 Evan Nemerson -// SPDX-License-Identifier: MIT - -/* Hedley - https://nemequ.github.io/hedley - * Created by Evan Nemerson - * SPDX-License-Identifier: CC0-1.0 - */ - -#if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15) -#if defined(JSON_HEDLEY_VERSION) - #undef JSON_HEDLEY_VERSION -#endif -#define JSON_HEDLEY_VERSION 15 - -#if defined(JSON_HEDLEY_STRINGIFY_EX) - #undef JSON_HEDLEY_STRINGIFY_EX -#endif -#define JSON_HEDLEY_STRINGIFY_EX(x) #x - -#if defined(JSON_HEDLEY_STRINGIFY) - #undef JSON_HEDLEY_STRINGIFY -#endif -#define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) - -#if defined(JSON_HEDLEY_CONCAT_EX) - #undef JSON_HEDLEY_CONCAT_EX -#endif -#define JSON_HEDLEY_CONCAT_EX(a,b) a##b - -#if defined(JSON_HEDLEY_CONCAT) - #undef JSON_HEDLEY_CONCAT -#endif -#define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) - -#if defined(JSON_HEDLEY_CONCAT3_EX) - #undef JSON_HEDLEY_CONCAT3_EX -#endif -#define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c - -#if defined(JSON_HEDLEY_CONCAT3) - #undef JSON_HEDLEY_CONCAT3 -#endif -#define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) - -#if defined(JSON_HEDLEY_VERSION_ENCODE) - #undef JSON_HEDLEY_VERSION_ENCODE -#endif -#define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) - -#if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) - #undef JSON_HEDLEY_VERSION_DECODE_MAJOR -#endif -#define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) - -#if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) - #undef JSON_HEDLEY_VERSION_DECODE_MINOR -#endif -#define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) - -#if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) - #undef JSON_HEDLEY_VERSION_DECODE_REVISION -#endif -#define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) - -#if defined(JSON_HEDLEY_GNUC_VERSION) - #undef JSON_HEDLEY_GNUC_VERSION -#endif -#if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) - #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) -#elif defined(__GNUC__) - #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) -#endif - -#if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) - #undef JSON_HEDLEY_GNUC_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_GNUC_VERSION) - #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_MSVC_VERSION) - #undef JSON_HEDLEY_MSVC_VERSION -#endif -#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL) - #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) -#elif defined(_MSC_FULL_VER) && !defined(__ICL) - #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) -#elif defined(_MSC_VER) && !defined(__ICL) - #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) -#endif - -#if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) - #undef JSON_HEDLEY_MSVC_VERSION_CHECK -#endif -#if !defined(JSON_HEDLEY_MSVC_VERSION) - #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) -#elif defined(_MSC_VER) && (_MSC_VER >= 1400) - #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) -#elif defined(_MSC_VER) && (_MSC_VER >= 1200) - #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) -#else - #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) -#endif - -#if defined(JSON_HEDLEY_INTEL_VERSION) - #undef JSON_HEDLEY_INTEL_VERSION -#endif -#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL) - #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) -#elif defined(__INTEL_COMPILER) && !defined(__ICL) - #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) -#endif - -#if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) - #undef JSON_HEDLEY_INTEL_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_INTEL_VERSION) - #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_INTEL_CL_VERSION) - #undef JSON_HEDLEY_INTEL_CL_VERSION -#endif -#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL) - #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0) -#endif - -#if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK) - #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_INTEL_CL_VERSION) - #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_PGI_VERSION) - #undef JSON_HEDLEY_PGI_VERSION -#endif -#if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) - #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) -#endif - -#if defined(JSON_HEDLEY_PGI_VERSION_CHECK) - #undef JSON_HEDLEY_PGI_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_PGI_VERSION) - #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_SUNPRO_VERSION) - #undef JSON_HEDLEY_SUNPRO_VERSION -#endif -#if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) - #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) -#elif defined(__SUNPRO_C) - #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) -#elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) - #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) -#elif defined(__SUNPRO_CC) - #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) -#endif - -#if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) - #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_SUNPRO_VERSION) - #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) - #undef JSON_HEDLEY_EMSCRIPTEN_VERSION -#endif -#if defined(__EMSCRIPTEN__) - #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) -#endif - -#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) - #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) - #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_ARM_VERSION) - #undef JSON_HEDLEY_ARM_VERSION -#endif -#if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) - #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) -#elif defined(__CC_ARM) && defined(__ARMCC_VERSION) - #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) -#endif - -#if defined(JSON_HEDLEY_ARM_VERSION_CHECK) - #undef JSON_HEDLEY_ARM_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_ARM_VERSION) - #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_IBM_VERSION) - #undef JSON_HEDLEY_IBM_VERSION -#endif -#if defined(__ibmxl__) - #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) -#elif defined(__xlC__) && defined(__xlC_ver__) - #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) -#elif defined(__xlC__) - #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) -#endif - -#if defined(JSON_HEDLEY_IBM_VERSION_CHECK) - #undef JSON_HEDLEY_IBM_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_IBM_VERSION) - #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_VERSION) - #undef JSON_HEDLEY_TI_VERSION -#endif -#if \ - defined(__TI_COMPILER_VERSION__) && \ - ( \ - defined(__TMS470__) || defined(__TI_ARM__) || \ - defined(__MSP430__) || \ - defined(__TMS320C2000__) \ - ) -#if (__TI_COMPILER_VERSION__ >= 16000000) - #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif -#endif - -#if defined(JSON_HEDLEY_TI_VERSION_CHECK) - #undef JSON_HEDLEY_TI_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_VERSION) - #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_CL2000_VERSION) - #undef JSON_HEDLEY_TI_CL2000_VERSION -#endif -#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) - #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif - -#if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) - #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_CL2000_VERSION) - #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_CL430_VERSION) - #undef JSON_HEDLEY_TI_CL430_VERSION -#endif -#if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) - #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif - -#if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) - #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_CL430_VERSION) - #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) - #undef JSON_HEDLEY_TI_ARMCL_VERSION -#endif -#if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) - #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif - -#if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) - #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) - #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_CL6X_VERSION) - #undef JSON_HEDLEY_TI_CL6X_VERSION -#endif -#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) - #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif - -#if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) - #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_CL6X_VERSION) - #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_CL7X_VERSION) - #undef JSON_HEDLEY_TI_CL7X_VERSION -#endif -#if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) - #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif - -#if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) - #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_CL7X_VERSION) - #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) - #undef JSON_HEDLEY_TI_CLPRU_VERSION -#endif -#if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) - #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif - -#if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) - #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) - #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_CRAY_VERSION) - #undef JSON_HEDLEY_CRAY_VERSION -#endif -#if defined(_CRAYC) - #if defined(_RELEASE_PATCHLEVEL) - #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) - #else - #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) - #endif -#endif - -#if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) - #undef JSON_HEDLEY_CRAY_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_CRAY_VERSION) - #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_IAR_VERSION) - #undef JSON_HEDLEY_IAR_VERSION -#endif -#if defined(__IAR_SYSTEMS_ICC__) - #if __VER__ > 1000 - #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) - #else - #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0) - #endif -#endif - -#if defined(JSON_HEDLEY_IAR_VERSION_CHECK) - #undef JSON_HEDLEY_IAR_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_IAR_VERSION) - #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TINYC_VERSION) - #undef JSON_HEDLEY_TINYC_VERSION -#endif -#if defined(__TINYC__) - #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) -#endif - -#if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) - #undef JSON_HEDLEY_TINYC_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TINYC_VERSION) - #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_DMC_VERSION) - #undef JSON_HEDLEY_DMC_VERSION -#endif -#if defined(__DMC__) - #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) -#endif - -#if defined(JSON_HEDLEY_DMC_VERSION_CHECK) - #undef JSON_HEDLEY_DMC_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_DMC_VERSION) - #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_COMPCERT_VERSION) - #undef JSON_HEDLEY_COMPCERT_VERSION -#endif -#if defined(__COMPCERT_VERSION__) - #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) -#endif - -#if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) - #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_COMPCERT_VERSION) - #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_PELLES_VERSION) - #undef JSON_HEDLEY_PELLES_VERSION -#endif -#if defined(__POCC__) - #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) -#endif - -#if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) - #undef JSON_HEDLEY_PELLES_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_PELLES_VERSION) - #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_MCST_LCC_VERSION) - #undef JSON_HEDLEY_MCST_LCC_VERSION -#endif -#if defined(__LCC__) && defined(__LCC_MINOR__) - #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__) -#endif - -#if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK) - #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_MCST_LCC_VERSION) - #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_GCC_VERSION) - #undef JSON_HEDLEY_GCC_VERSION -#endif -#if \ - defined(JSON_HEDLEY_GNUC_VERSION) && \ - !defined(__clang__) && \ - !defined(JSON_HEDLEY_INTEL_VERSION) && \ - !defined(JSON_HEDLEY_PGI_VERSION) && \ - !defined(JSON_HEDLEY_ARM_VERSION) && \ - !defined(JSON_HEDLEY_CRAY_VERSION) && \ - !defined(JSON_HEDLEY_TI_VERSION) && \ - !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ - !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ - !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ - !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ - !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ - !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ - !defined(__COMPCERT__) && \ - !defined(JSON_HEDLEY_MCST_LCC_VERSION) - #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION -#endif - -#if defined(JSON_HEDLEY_GCC_VERSION_CHECK) - #undef JSON_HEDLEY_GCC_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_GCC_VERSION) - #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_HAS_ATTRIBUTE) - #undef JSON_HEDLEY_HAS_ATTRIBUTE -#endif -#if \ - defined(__has_attribute) && \ - ( \ - (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \ - ) -# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) -#else -# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) - #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE -#endif -#if defined(__has_attribute) - #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) -#else - #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) - #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE -#endif -#if defined(__has_attribute) - #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) -#else - #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) - #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE -#endif -#if \ - defined(__has_cpp_attribute) && \ - defined(__cplusplus) && \ - (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) - #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) -#else - #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) -#endif - -#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) - #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS -#endif -#if !defined(__cplusplus) || !defined(__has_cpp_attribute) - #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) -#elif \ - !defined(JSON_HEDLEY_PGI_VERSION) && \ - !defined(JSON_HEDLEY_IAR_VERSION) && \ - (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ - (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) - #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) -#else - #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE) - #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE -#endif -#if defined(__has_cpp_attribute) && defined(__cplusplus) - #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) -#else - #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE) - #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE -#endif -#if defined(__has_cpp_attribute) && defined(__cplusplus) - #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) -#else - #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_HAS_BUILTIN) - #undef JSON_HEDLEY_HAS_BUILTIN -#endif -#if defined(__has_builtin) - #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin) -#else - #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN) - #undef JSON_HEDLEY_GNUC_HAS_BUILTIN -#endif -#if defined(__has_builtin) - #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) -#else - #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_BUILTIN) - #undef JSON_HEDLEY_GCC_HAS_BUILTIN -#endif -#if defined(__has_builtin) - #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) -#else - #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_HAS_FEATURE) - #undef JSON_HEDLEY_HAS_FEATURE -#endif -#if defined(__has_feature) - #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature) -#else - #define JSON_HEDLEY_HAS_FEATURE(feature) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_FEATURE) - #undef JSON_HEDLEY_GNUC_HAS_FEATURE -#endif -#if defined(__has_feature) - #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) -#else - #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_FEATURE) - #undef JSON_HEDLEY_GCC_HAS_FEATURE -#endif -#if defined(__has_feature) - #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) -#else - #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_HAS_EXTENSION) - #undef JSON_HEDLEY_HAS_EXTENSION -#endif -#if defined(__has_extension) - #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension) -#else - #define JSON_HEDLEY_HAS_EXTENSION(extension) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION) - #undef JSON_HEDLEY_GNUC_HAS_EXTENSION -#endif -#if defined(__has_extension) - #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) -#else - #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_EXTENSION) - #undef JSON_HEDLEY_GCC_HAS_EXTENSION -#endif -#if defined(__has_extension) - #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) -#else - #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE) - #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE -#endif -#if defined(__has_declspec_attribute) - #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute) -#else - #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE) - #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE -#endif -#if defined(__has_declspec_attribute) - #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) -#else - #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE) - #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE -#endif -#if defined(__has_declspec_attribute) - #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) -#else - #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_HAS_WARNING) - #undef JSON_HEDLEY_HAS_WARNING -#endif -#if defined(__has_warning) - #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning) -#else - #define JSON_HEDLEY_HAS_WARNING(warning) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_WARNING) - #undef JSON_HEDLEY_GNUC_HAS_WARNING -#endif -#if defined(__has_warning) - #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) -#else - #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_WARNING) - #undef JSON_HEDLEY_GCC_HAS_WARNING -#endif -#if defined(__has_warning) - #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) -#else - #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if \ - (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ - defined(__clang__) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \ - JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \ - (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR)) - #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value) -#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) - #define JSON_HEDLEY_PRAGMA(value) __pragma(value) -#else - #define JSON_HEDLEY_PRAGMA(value) -#endif - -#if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH) - #undef JSON_HEDLEY_DIAGNOSTIC_PUSH -#endif -#if defined(JSON_HEDLEY_DIAGNOSTIC_POP) - #undef JSON_HEDLEY_DIAGNOSTIC_POP -#endif -#if defined(__clang__) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push") - #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop") -#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") - #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") -#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") - #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push)) - #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop)) -#elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push") - #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop") -#elif \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push") - #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop") -#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") - #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") -#else - #define JSON_HEDLEY_DIAGNOSTIC_PUSH - #define JSON_HEDLEY_DIAGNOSTIC_POP -#endif - -/* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for - HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ -#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) - #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ -#endif -#if defined(__cplusplus) -# if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat") -# if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions") -# if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions") -# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ - _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ - _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \ - xpr \ - JSON_HEDLEY_DIAGNOSTIC_POP -# else -# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ - _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ - xpr \ - JSON_HEDLEY_DIAGNOSTIC_POP -# endif -# else -# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ - xpr \ - JSON_HEDLEY_DIAGNOSTIC_POP -# endif -# endif -#endif -#if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x -#endif - -#if defined(JSON_HEDLEY_CONST_CAST) - #undef JSON_HEDLEY_CONST_CAST -#endif -#if defined(__cplusplus) -# define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast(expr)) -#elif \ - JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) -# define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ - ((T) (expr)); \ - JSON_HEDLEY_DIAGNOSTIC_POP \ - })) -#else -# define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr)) -#endif - -#if defined(JSON_HEDLEY_REINTERPRET_CAST) - #undef JSON_HEDLEY_REINTERPRET_CAST -#endif -#if defined(__cplusplus) - #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast(expr)) -#else - #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr)) -#endif - -#if defined(JSON_HEDLEY_STATIC_CAST) - #undef JSON_HEDLEY_STATIC_CAST -#endif -#if defined(__cplusplus) - #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast(expr)) -#else - #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr)) -#endif - -#if defined(JSON_HEDLEY_CPP_CAST) - #undef JSON_HEDLEY_CPP_CAST -#endif -#if defined(__cplusplus) -# if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast") -# define JSON_HEDLEY_CPP_CAST(T, expr) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ - ((T) (expr)) \ - JSON_HEDLEY_DIAGNOSTIC_POP -# elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0) -# define JSON_HEDLEY_CPP_CAST(T, expr) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("diag_suppress=Pe137") \ - JSON_HEDLEY_DIAGNOSTIC_POP -# else -# define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr)) -# endif -#else -# define JSON_HEDLEY_CPP_CAST(T, expr) (expr) -#endif - -#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED) - #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations") - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") -#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)") -#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786)) -#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445") -#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") -#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") -#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996)) -#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") -#elif \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718") -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)") -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)") -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215") -#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)") -#else - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED -#endif - -#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS) - #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"") -#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)") -#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161)) -#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675") -#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") -#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068)) -#elif \ - JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") -#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161") -#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161") -#else - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS -#endif - -#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES) - #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes") - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"") -#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") -#elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)") -#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292)) -#elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030)) -#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098") -#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)") -#elif \ - JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173") -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097") -#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") -#else - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES -#endif - -#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL) - #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wcast-qual") - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"") -#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)") -#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") -#else - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL -#endif - -#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION) - #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wunused-function") - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"") -#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"") -#elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505)) -#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142") -#else - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION -#endif - -#if defined(JSON_HEDLEY_DEPRECATED) - #undef JSON_HEDLEY_DEPRECATED -#endif -#if defined(JSON_HEDLEY_DEPRECATED_FOR) - #undef JSON_HEDLEY_DEPRECATED_FOR -#endif -#if \ - JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since)) - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement)) -#elif \ - (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since))) - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement))) -#elif defined(__cplusplus) && (__cplusplus >= 201402L) - #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]]) - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]]) -#elif \ - JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ - JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) - #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__)) - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__)) -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ - JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated) - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated) -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated") - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated") -#else - #define JSON_HEDLEY_DEPRECATED(since) - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) -#endif - -#if defined(JSON_HEDLEY_UNAVAILABLE) - #undef JSON_HEDLEY_UNAVAILABLE -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since))) -#else - #define JSON_HEDLEY_UNAVAILABLE(available_since) -#endif - -#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT) - #undef JSON_HEDLEY_WARN_UNUSED_RESULT -#endif -#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG) - #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) - #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__)) -#elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L) - #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) - #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]]) -#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) - #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) - #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) -#elif defined(_Check_return_) /* SAL */ - #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_ - #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_ -#else - #define JSON_HEDLEY_WARN_UNUSED_RESULT - #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) -#endif - -#if defined(JSON_HEDLEY_SENTINEL) - #undef JSON_HEDLEY_SENTINEL -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position))) -#else - #define JSON_HEDLEY_SENTINEL(position) -#endif - -#if defined(JSON_HEDLEY_NO_RETURN) - #undef JSON_HEDLEY_NO_RETURN -#endif -#if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_NO_RETURN __noreturn -#elif \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) -#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L - #define JSON_HEDLEY_NO_RETURN _Noreturn -#elif defined(__cplusplus) && (__cplusplus >= 201103L) - #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]]) -#elif \ - JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) - #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) - #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return") -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) -#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) - #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;") -#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) - #define JSON_HEDLEY_NO_RETURN __attribute((noreturn)) -#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) - #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) -#else - #define JSON_HEDLEY_NO_RETURN -#endif - -#if defined(JSON_HEDLEY_NO_ESCAPE) - #undef JSON_HEDLEY_NO_ESCAPE -#endif -#if JSON_HEDLEY_HAS_ATTRIBUTE(noescape) - #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__)) -#else - #define JSON_HEDLEY_NO_ESCAPE -#endif - -#if defined(JSON_HEDLEY_UNREACHABLE) - #undef JSON_HEDLEY_UNREACHABLE -#endif -#if defined(JSON_HEDLEY_UNREACHABLE_RETURN) - #undef JSON_HEDLEY_UNREACHABLE_RETURN -#endif -#if defined(JSON_HEDLEY_ASSUME) - #undef JSON_HEDLEY_ASSUME -#endif -#if \ - JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_ASSUME(expr) __assume(expr) -#elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume) - #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr) -#elif \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) - #if defined(__cplusplus) - #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr) - #else - #define JSON_HEDLEY_ASSUME(expr) _nassert(expr) - #endif -#endif -#if \ - (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \ - JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable() -#elif defined(JSON_HEDLEY_ASSUME) - #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) -#endif -#if !defined(JSON_HEDLEY_ASSUME) - #if defined(JSON_HEDLEY_UNREACHABLE) - #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1))) - #else - #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr) - #endif -#endif -#if defined(JSON_HEDLEY_UNREACHABLE) - #if \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) - #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value)) - #else - #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE() - #endif -#else - #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value) -#endif -#if !defined(JSON_HEDLEY_UNREACHABLE) - #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) -#endif - -JSON_HEDLEY_DIAGNOSTIC_PUSH -#if JSON_HEDLEY_HAS_WARNING("-Wpedantic") - #pragma clang diagnostic ignored "-Wpedantic" -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus) - #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" -#endif -#if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wvariadic-macros" - #elif defined(JSON_HEDLEY_GCC_VERSION) - #pragma GCC diagnostic ignored "-Wvariadic-macros" - #endif -#endif -#if defined(JSON_HEDLEY_NON_NULL) - #undef JSON_HEDLEY_NON_NULL -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) - #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__))) -#else - #define JSON_HEDLEY_NON_NULL(...) -#endif -JSON_HEDLEY_DIAGNOSTIC_POP - -#if defined(JSON_HEDLEY_PRINTF_FORMAT) - #undef JSON_HEDLEY_PRINTF_FORMAT -#endif -#if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO) - #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check))) -#elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO) - #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check))) -#elif \ - JSON_HEDLEY_HAS_ATTRIBUTE(format) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check))) -#elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0) - #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check)) -#else - #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) -#endif - -#if defined(JSON_HEDLEY_CONSTEXPR) - #undef JSON_HEDLEY_CONSTEXPR -#endif -#if defined(__cplusplus) - #if __cplusplus >= 201103L - #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr) - #endif -#endif -#if !defined(JSON_HEDLEY_CONSTEXPR) - #define JSON_HEDLEY_CONSTEXPR -#endif - -#if defined(JSON_HEDLEY_PREDICT) - #undef JSON_HEDLEY_PREDICT -#endif -#if defined(JSON_HEDLEY_LIKELY) - #undef JSON_HEDLEY_LIKELY -#endif -#if defined(JSON_HEDLEY_UNLIKELY) - #undef JSON_HEDLEY_UNLIKELY -#endif -#if defined(JSON_HEDLEY_UNPREDICTABLE) - #undef JSON_HEDLEY_UNPREDICTABLE -#endif -#if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable) - #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr)) -#endif -#if \ - (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) -# define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability)) -# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability)) -# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability)) -# define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 ) -# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 ) -#elif \ - (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \ - JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) -# define JSON_HEDLEY_PREDICT(expr, expected, probability) \ - (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))) -# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \ - (__extension__ ({ \ - double hedley_probability_ = (probability); \ - ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \ - })) -# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \ - (__extension__ ({ \ - double hedley_probability_ = (probability); \ - ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \ - })) -# define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1) -# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0) -#else -# define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)) -# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr)) -# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr)) -# define JSON_HEDLEY_LIKELY(expr) (!!(expr)) -# define JSON_HEDLEY_UNLIKELY(expr) (!!(expr)) -#endif -#if !defined(JSON_HEDLEY_UNPREDICTABLE) - #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5) -#endif - -#if defined(JSON_HEDLEY_MALLOC) - #undef JSON_HEDLEY_MALLOC -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_MALLOC __attribute__((__malloc__)) -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) - #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory") -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_MALLOC __declspec(restrict) -#else - #define JSON_HEDLEY_MALLOC -#endif - -#if defined(JSON_HEDLEY_PURE) - #undef JSON_HEDLEY_PURE -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) -# define JSON_HEDLEY_PURE __attribute__((__pure__)) -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) -# define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data") -#elif defined(__cplusplus) && \ - ( \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \ - ) -# define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;") -#else -# define JSON_HEDLEY_PURE -#endif - -#if defined(JSON_HEDLEY_CONST) - #undef JSON_HEDLEY_CONST -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(const) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_CONST __attribute__((__const__)) -#elif \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) - #define JSON_HEDLEY_CONST _Pragma("no_side_effect") -#else - #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE -#endif - -#if defined(JSON_HEDLEY_RESTRICT) - #undef JSON_HEDLEY_RESTRICT -#endif -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) - #define JSON_HEDLEY_RESTRICT restrict -#elif \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ - JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \ - JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ - defined(__clang__) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_RESTRICT __restrict -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus) - #define JSON_HEDLEY_RESTRICT _Restrict -#else - #define JSON_HEDLEY_RESTRICT -#endif - -#if defined(JSON_HEDLEY_INLINE) - #undef JSON_HEDLEY_INLINE -#endif -#if \ - (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ - (defined(__cplusplus) && (__cplusplus >= 199711L)) - #define JSON_HEDLEY_INLINE inline -#elif \ - defined(JSON_HEDLEY_GCC_VERSION) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0) - #define JSON_HEDLEY_INLINE __inline__ -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_INLINE __inline -#else - #define JSON_HEDLEY_INLINE -#endif - -#if defined(JSON_HEDLEY_ALWAYS_INLINE) - #undef JSON_HEDLEY_ALWAYS_INLINE -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ - JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) -# define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) -# define JSON_HEDLEY_ALWAYS_INLINE __forceinline -#elif defined(__cplusplus) && \ - ( \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \ - ) -# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;") -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) -# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced") -#else -# define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE -#endif - -#if defined(JSON_HEDLEY_NEVER_INLINE) - #undef JSON_HEDLEY_NEVER_INLINE -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ - JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) - #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__)) -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) -#elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0) - #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline") -#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) - #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;") -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never") -#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) - #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline)) -#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) - #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) -#else - #define JSON_HEDLEY_NEVER_INLINE -#endif - -#if defined(JSON_HEDLEY_PRIVATE) - #undef JSON_HEDLEY_PRIVATE -#endif -#if defined(JSON_HEDLEY_PUBLIC) - #undef JSON_HEDLEY_PUBLIC -#endif -#if defined(JSON_HEDLEY_IMPORT) - #undef JSON_HEDLEY_IMPORT -#endif -#if defined(_WIN32) || defined(__CYGWIN__) -# define JSON_HEDLEY_PRIVATE -# define JSON_HEDLEY_PUBLIC __declspec(dllexport) -# define JSON_HEDLEY_IMPORT __declspec(dllimport) -#else -# if \ - JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ - ( \ - defined(__TI_EABI__) && \ - ( \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \ - ) \ - ) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) -# define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden"))) -# define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default"))) -# else -# define JSON_HEDLEY_PRIVATE -# define JSON_HEDLEY_PUBLIC -# endif -# define JSON_HEDLEY_IMPORT extern -#endif - -#if defined(JSON_HEDLEY_NO_THROW) - #undef JSON_HEDLEY_NO_THROW -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__)) -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) - #define JSON_HEDLEY_NO_THROW __declspec(nothrow) -#else - #define JSON_HEDLEY_NO_THROW -#endif - -#if defined(JSON_HEDLEY_FALL_THROUGH) - #undef JSON_HEDLEY_FALL_THROUGH -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__)) -#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough) - #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]]) -#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough) - #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]]) -#elif defined(__fallthrough) /* SAL */ - #define JSON_HEDLEY_FALL_THROUGH __fallthrough -#else - #define JSON_HEDLEY_FALL_THROUGH -#endif - -#if defined(JSON_HEDLEY_RETURNS_NON_NULL) - #undef JSON_HEDLEY_RETURNS_NON_NULL -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__)) -#elif defined(_Ret_notnull_) /* SAL */ - #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_ -#else - #define JSON_HEDLEY_RETURNS_NON_NULL -#endif - -#if defined(JSON_HEDLEY_ARRAY_PARAM) - #undef JSON_HEDLEY_ARRAY_PARAM -#endif -#if \ - defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - !defined(__STDC_NO_VLA__) && \ - !defined(__cplusplus) && \ - !defined(JSON_HEDLEY_PGI_VERSION) && \ - !defined(JSON_HEDLEY_TINYC_VERSION) - #define JSON_HEDLEY_ARRAY_PARAM(name) (name) -#else - #define JSON_HEDLEY_ARRAY_PARAM(name) -#endif - -#if defined(JSON_HEDLEY_IS_CONSTANT) - #undef JSON_HEDLEY_IS_CONSTANT -#endif -#if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR) - #undef JSON_HEDLEY_REQUIRE_CONSTEXPR -#endif -/* JSON_HEDLEY_IS_CONSTEXPR_ is for - HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ -#if defined(JSON_HEDLEY_IS_CONSTEXPR_) - #undef JSON_HEDLEY_IS_CONSTEXPR_ -#endif -#if \ - JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ - (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \ - JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr) -#endif -#if !defined(__cplusplus) -# if \ - JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ - JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ - JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24) -#if defined(__INTPTR_TYPE__) - #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*) -#else - #include - #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*) -#endif -# elif \ - ( \ - defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ - !defined(JSON_HEDLEY_SUNPRO_VERSION) && \ - !defined(JSON_HEDLEY_PGI_VERSION) && \ - !defined(JSON_HEDLEY_IAR_VERSION)) || \ - (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0) -#if defined(__INTPTR_TYPE__) - #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0) -#else - #include - #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0) -#endif -# elif \ - defined(JSON_HEDLEY_GCC_VERSION) || \ - defined(JSON_HEDLEY_INTEL_VERSION) || \ - defined(JSON_HEDLEY_TINYC_VERSION) || \ - defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \ - defined(JSON_HEDLEY_TI_CL2000_VERSION) || \ - defined(JSON_HEDLEY_TI_CL6X_VERSION) || \ - defined(JSON_HEDLEY_TI_CL7X_VERSION) || \ - defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \ - defined(__clang__) -# define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \ - sizeof(void) != \ - sizeof(*( \ - 1 ? \ - ((void*) ((expr) * 0L) ) : \ -((struct { char v[sizeof(void) * 2]; } *) 1) \ - ) \ - ) \ - ) -# endif -#endif -#if defined(JSON_HEDLEY_IS_CONSTEXPR_) - #if !defined(JSON_HEDLEY_IS_CONSTANT) - #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr) - #endif - #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1)) -#else - #if !defined(JSON_HEDLEY_IS_CONSTANT) - #define JSON_HEDLEY_IS_CONSTANT(expr) (0) - #endif - #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr) -#endif - -#if defined(JSON_HEDLEY_BEGIN_C_DECLS) - #undef JSON_HEDLEY_BEGIN_C_DECLS -#endif -#if defined(JSON_HEDLEY_END_C_DECLS) - #undef JSON_HEDLEY_END_C_DECLS -#endif -#if defined(JSON_HEDLEY_C_DECL) - #undef JSON_HEDLEY_C_DECL -#endif -#if defined(__cplusplus) - #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" { - #define JSON_HEDLEY_END_C_DECLS } - #define JSON_HEDLEY_C_DECL extern "C" -#else - #define JSON_HEDLEY_BEGIN_C_DECLS - #define JSON_HEDLEY_END_C_DECLS - #define JSON_HEDLEY_C_DECL -#endif - -#if defined(JSON_HEDLEY_STATIC_ASSERT) - #undef JSON_HEDLEY_STATIC_ASSERT -#endif -#if \ - !defined(__cplusplus) && ( \ - (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \ - (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - defined(_Static_assert) \ - ) -# define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message) -#elif \ - (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ - JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) -# define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message)) -#else -# define JSON_HEDLEY_STATIC_ASSERT(expr, message) -#endif - -#if defined(JSON_HEDLEY_NULL) - #undef JSON_HEDLEY_NULL -#endif -#if defined(__cplusplus) - #if __cplusplus >= 201103L - #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr) - #elif defined(NULL) - #define JSON_HEDLEY_NULL NULL - #else - #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0) - #endif -#elif defined(NULL) - #define JSON_HEDLEY_NULL NULL -#else - #define JSON_HEDLEY_NULL ((void*) 0) -#endif - -#if defined(JSON_HEDLEY_MESSAGE) - #undef JSON_HEDLEY_MESSAGE -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") -# define JSON_HEDLEY_MESSAGE(msg) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ - JSON_HEDLEY_PRAGMA(message msg) \ - JSON_HEDLEY_DIAGNOSTIC_POP -#elif \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) -# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg) -#elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) -# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg) -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) -# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) -#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0) -# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) -#else -# define JSON_HEDLEY_MESSAGE(msg) -#endif - -#if defined(JSON_HEDLEY_WARNING) - #undef JSON_HEDLEY_WARNING -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") -# define JSON_HEDLEY_WARNING(msg) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ - JSON_HEDLEY_PRAGMA(clang warning msg) \ - JSON_HEDLEY_DIAGNOSTIC_POP -#elif \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) -# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg) -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) -# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg)) -#else -# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg) -#endif - -#if defined(JSON_HEDLEY_REQUIRE) - #undef JSON_HEDLEY_REQUIRE -#endif -#if defined(JSON_HEDLEY_REQUIRE_MSG) - #undef JSON_HEDLEY_REQUIRE_MSG -#endif -#if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if) -# if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat") -# define JSON_HEDLEY_REQUIRE(expr) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ - __attribute__((diagnose_if(!(expr), #expr, "error"))) \ - JSON_HEDLEY_DIAGNOSTIC_POP -# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ - __attribute__((diagnose_if(!(expr), msg, "error"))) \ - JSON_HEDLEY_DIAGNOSTIC_POP -# else -# define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error"))) -# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error"))) -# endif -#else -# define JSON_HEDLEY_REQUIRE(expr) -# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) -#endif - -#if defined(JSON_HEDLEY_FLAGS) - #undef JSON_HEDLEY_FLAGS -#endif -#if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion")) - #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__)) -#else - #define JSON_HEDLEY_FLAGS -#endif - -#if defined(JSON_HEDLEY_FLAGS_CAST) - #undef JSON_HEDLEY_FLAGS_CAST -#endif -#if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0) -# define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("warning(disable:188)") \ - ((T) (expr)); \ - JSON_HEDLEY_DIAGNOSTIC_POP \ - })) -#else -# define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr) -#endif - -#if defined(JSON_HEDLEY_EMPTY_BASES) - #undef JSON_HEDLEY_EMPTY_BASES -#endif -#if \ - (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases) -#else - #define JSON_HEDLEY_EMPTY_BASES -#endif - -/* Remaining macros are deprecated. */ - -#if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK) - #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK -#endif -#if defined(__clang__) - #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0) -#else - #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE) - #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE -#endif -#define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) - -#if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE) - #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE -#endif -#define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) - -#if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN) - #undef JSON_HEDLEY_CLANG_HAS_BUILTIN -#endif -#define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin) - -#if defined(JSON_HEDLEY_CLANG_HAS_FEATURE) - #undef JSON_HEDLEY_CLANG_HAS_FEATURE -#endif -#define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature) - -#if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION) - #undef JSON_HEDLEY_CLANG_HAS_EXTENSION -#endif -#define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension) - -#if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE) - #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE -#endif -#define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) - -#if defined(JSON_HEDLEY_CLANG_HAS_WARNING) - #undef JSON_HEDLEY_CLANG_HAS_WARNING -#endif -#define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning) - -#endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ - - -// This file contains all internal macro definitions (except those affecting ABI) -// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them - -// #include - - -// exclude unsupported compilers -#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) - #if defined(__clang__) - #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 - #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" - #endif - #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) - #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 - #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" - #endif - #endif -#endif - -// C++ language standard detection -// if the user manually specified the used C++ version, this is skipped -#if !defined(JSON_HAS_CPP_26) && !defined(JSON_HAS_CPP_23) && !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11) - #if (defined(__cplusplus) && __cplusplus > 202302L) || (defined(_MSVC_LANG) && _MSVC_LANG > 202302L) - #define JSON_HAS_CPP_26 - #define JSON_HAS_CPP_23 - #define JSON_HAS_CPP_20 - #define JSON_HAS_CPP_17 - #define JSON_HAS_CPP_14 - #elif (defined(__cplusplus) && __cplusplus > 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG > 202002L) - #define JSON_HAS_CPP_23 - #define JSON_HAS_CPP_20 - #define JSON_HAS_CPP_17 - #define JSON_HAS_CPP_14 - #elif (defined(__cplusplus) && __cplusplus > 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG > 201703L) - #define JSON_HAS_CPP_20 - #define JSON_HAS_CPP_17 - #define JSON_HAS_CPP_14 - #elif (defined(__cplusplus) && __cplusplus > 201402L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 - #define JSON_HAS_CPP_17 - #define JSON_HAS_CPP_14 - #elif (defined(__cplusplus) && __cplusplus > 201103L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) - #define JSON_HAS_CPP_14 - #endif - // the cpp 11 flag is always specified because it is the minimal required version - #define JSON_HAS_CPP_11 -#endif - -#ifdef __has_include - #if __has_include() - #include - #endif -#endif - -#if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM) - #ifdef JSON_HAS_CPP_17 - #if defined(__cpp_lib_filesystem) - #define JSON_HAS_FILESYSTEM 1 - #elif defined(__cpp_lib_experimental_filesystem) - #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 - #elif !defined(__has_include) - #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 - #elif __has_include() - #define JSON_HAS_FILESYSTEM 1 - #elif __has_include() - #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 - #endif - - // std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/ - #if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8 - #undef JSON_HAS_FILESYSTEM - #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #endif - - // no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support - #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8 - #undef JSON_HAS_FILESYSTEM - #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #endif - - // no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support - #if defined(__clang_major__) && __clang_major__ < 7 - #undef JSON_HAS_FILESYSTEM - #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #endif - - // no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support - #if defined(_MSC_VER) && _MSC_VER < 1914 - #undef JSON_HAS_FILESYSTEM - #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #endif - - // no filesystem support before iOS 13 - #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000 - #undef JSON_HAS_FILESYSTEM - #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #endif - - // no filesystem support before macOS Catalina - #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500 - #undef JSON_HAS_FILESYSTEM - #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #endif - #endif -#endif - -#ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0 -#endif - -#ifndef JSON_HAS_FILESYSTEM - #define JSON_HAS_FILESYSTEM 0 -#endif - -#ifndef JSON_HAS_THREE_WAY_COMPARISON - #if defined(__cpp_impl_three_way_comparison) && __cpp_impl_three_way_comparison >= 201907L \ - && defined(__cpp_lib_three_way_comparison) && __cpp_lib_three_way_comparison >= 201907L - #define JSON_HAS_THREE_WAY_COMPARISON 1 - #else - #define JSON_HAS_THREE_WAY_COMPARISON 0 - #endif -#endif - -#ifndef JSON_HAS_RANGES - // ranges header shipping in GCC 11.1.0 (released 2021-04-27) has a syntax error - #if defined(__GLIBCXX__) && __GLIBCXX__ == 20210427 - #define JSON_HAS_RANGES 0 - #elif defined(__cpp_lib_ranges) - #define JSON_HAS_RANGES 1 - #else - #define JSON_HAS_RANGES 0 - #endif -#endif - -#ifndef JSON_HAS_STATIC_RTTI - #if !defined(_HAS_STATIC_RTTI) || _HAS_STATIC_RTTI != 0 - #define JSON_HAS_STATIC_RTTI 1 - #else - #define JSON_HAS_STATIC_RTTI 0 - #endif -#endif - -#ifdef JSON_HAS_CPP_17 - #define JSON_INLINE_VARIABLE inline -#else - #define JSON_INLINE_VARIABLE -#endif - -#if JSON_HEDLEY_HAS_ATTRIBUTE(no_unique_address) - #define JSON_NO_UNIQUE_ADDRESS [[no_unique_address]] -#else - #define JSON_NO_UNIQUE_ADDRESS -#endif - -// disable documentation warnings on clang -#if defined(__clang__) - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wdocumentation" - #pragma clang diagnostic ignored "-Wdocumentation-unknown-command" -#endif - -// allow disabling exceptions -#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) - #define JSON_THROW(exception) throw exception - #define JSON_TRY try - #define JSON_CATCH(exception) catch(exception) - #define JSON_INTERNAL_CATCH(exception) catch(exception) -#else - #include - #define JSON_THROW(exception) std::abort() - #define JSON_TRY if(true) - #define JSON_CATCH(exception) if(false) - #define JSON_INTERNAL_CATCH(exception) if(false) -#endif - -// override exception macros -#if defined(JSON_THROW_USER) - #undef JSON_THROW - #define JSON_THROW JSON_THROW_USER -#endif -#if defined(JSON_TRY_USER) - #undef JSON_TRY - #define JSON_TRY JSON_TRY_USER -#endif -#if defined(JSON_CATCH_USER) - #undef JSON_CATCH - #define JSON_CATCH JSON_CATCH_USER - #undef JSON_INTERNAL_CATCH - #define JSON_INTERNAL_CATCH JSON_CATCH_USER -#endif -#if defined(JSON_INTERNAL_CATCH_USER) - #undef JSON_INTERNAL_CATCH - #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER -#endif - -// allow overriding assert -#if !defined(JSON_ASSERT) - #include // assert - #define JSON_ASSERT(x) assert(x) -#endif - -// allow accessing some private functions (needed by the test suite) -#if defined(JSON_TESTS_PRIVATE) - #define JSON_PRIVATE_UNLESS_TESTED public -#else - #define JSON_PRIVATE_UNLESS_TESTED private -#endif - -/*! -@brief macro to briefly define a mapping between an enum and JSON -@def NLOHMANN_JSON_SERIALIZE_ENUM -@since version 3.4.0 -*/ -#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ - template \ - inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ - { \ - /* NOLINTNEXTLINE(modernize-type-traits) we use C++11 */ \ - static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ - /* NOLINTNEXTLINE(modernize-avoid-c-arrays) we don't want to depend on */ \ - static const std::pair m[] = __VA_ARGS__; \ - auto it = std::find_if(std::begin(m), std::end(m), \ - [e](const std::pair& ej_pair) -> bool \ - { \ - return ej_pair.first == e; \ - }); \ - j = ((it != std::end(m)) ? it : std::begin(m))->second; \ - } \ - template \ - inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ - { \ - /* NOLINTNEXTLINE(modernize-type-traits) we use C++11 */ \ - static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ - /* NOLINTNEXTLINE(modernize-avoid-c-arrays) we don't want to depend on */ \ - static const std::pair m[] = __VA_ARGS__; \ - auto it = std::find_if(std::begin(m), std::end(m), \ - [&j](const std::pair& ej_pair) -> bool \ - { \ - return ej_pair.second == j; \ - }); \ - e = ((it != std::end(m)) ? it : std::begin(m))->first; \ - } - -// Ugly macros to avoid uglier copy-paste when specializing basic_json. They -// may be removed in the future once the class is split. - -#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ - template class ObjectType, \ - template class ArrayType, \ - class StringType, class BooleanType, class NumberIntegerType, \ - class NumberUnsignedType, class NumberFloatType, \ - template class AllocatorType, \ - template class JSONSerializer, \ - class BinaryType, \ - class CustomBaseClass> - -#define NLOHMANN_BASIC_JSON_TPL \ - basic_json - -// Macros to simplify conversion from/to types - -#define NLOHMANN_JSON_EXPAND( x ) x -#define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME -#define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ - NLOHMANN_JSON_PASTE64, \ - NLOHMANN_JSON_PASTE63, \ - NLOHMANN_JSON_PASTE62, \ - NLOHMANN_JSON_PASTE61, \ - NLOHMANN_JSON_PASTE60, \ - NLOHMANN_JSON_PASTE59, \ - NLOHMANN_JSON_PASTE58, \ - NLOHMANN_JSON_PASTE57, \ - NLOHMANN_JSON_PASTE56, \ - NLOHMANN_JSON_PASTE55, \ - NLOHMANN_JSON_PASTE54, \ - NLOHMANN_JSON_PASTE53, \ - NLOHMANN_JSON_PASTE52, \ - NLOHMANN_JSON_PASTE51, \ - NLOHMANN_JSON_PASTE50, \ - NLOHMANN_JSON_PASTE49, \ - NLOHMANN_JSON_PASTE48, \ - NLOHMANN_JSON_PASTE47, \ - NLOHMANN_JSON_PASTE46, \ - NLOHMANN_JSON_PASTE45, \ - NLOHMANN_JSON_PASTE44, \ - NLOHMANN_JSON_PASTE43, \ - NLOHMANN_JSON_PASTE42, \ - NLOHMANN_JSON_PASTE41, \ - NLOHMANN_JSON_PASTE40, \ - NLOHMANN_JSON_PASTE39, \ - NLOHMANN_JSON_PASTE38, \ - NLOHMANN_JSON_PASTE37, \ - NLOHMANN_JSON_PASTE36, \ - NLOHMANN_JSON_PASTE35, \ - NLOHMANN_JSON_PASTE34, \ - NLOHMANN_JSON_PASTE33, \ - NLOHMANN_JSON_PASTE32, \ - NLOHMANN_JSON_PASTE31, \ - NLOHMANN_JSON_PASTE30, \ - NLOHMANN_JSON_PASTE29, \ - NLOHMANN_JSON_PASTE28, \ - NLOHMANN_JSON_PASTE27, \ - NLOHMANN_JSON_PASTE26, \ - NLOHMANN_JSON_PASTE25, \ - NLOHMANN_JSON_PASTE24, \ - NLOHMANN_JSON_PASTE23, \ - NLOHMANN_JSON_PASTE22, \ - NLOHMANN_JSON_PASTE21, \ - NLOHMANN_JSON_PASTE20, \ - NLOHMANN_JSON_PASTE19, \ - NLOHMANN_JSON_PASTE18, \ - NLOHMANN_JSON_PASTE17, \ - NLOHMANN_JSON_PASTE16, \ - NLOHMANN_JSON_PASTE15, \ - NLOHMANN_JSON_PASTE14, \ - NLOHMANN_JSON_PASTE13, \ - NLOHMANN_JSON_PASTE12, \ - NLOHMANN_JSON_PASTE11, \ - NLOHMANN_JSON_PASTE10, \ - NLOHMANN_JSON_PASTE9, \ - NLOHMANN_JSON_PASTE8, \ - NLOHMANN_JSON_PASTE7, \ - NLOHMANN_JSON_PASTE6, \ - NLOHMANN_JSON_PASTE5, \ - NLOHMANN_JSON_PASTE4, \ - NLOHMANN_JSON_PASTE3, \ - NLOHMANN_JSON_PASTE2, \ - NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) -#define NLOHMANN_JSON_PASTE2(func, v1) func(v1) -#define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) -#define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) -#define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) -#define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) -#define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) -#define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) -#define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) -#define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) -#define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) -#define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) -#define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) -#define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) -#define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) -#define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) -#define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) -#define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) -#define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) -#define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) -#define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) -#define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) -#define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) -#define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) -#define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) -#define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) -#define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) -#define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) -#define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) -#define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) -#define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) -#define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) -#define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) -#define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) -#define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) -#define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) -#define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) -#define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) -#define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) -#define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) -#define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) -#define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) -#define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) -#define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) -#define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) -#define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) -#define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) -#define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) -#define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) -#define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) -#define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) -#define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) -#define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) -#define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) -#define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) -#define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) -#define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) -#define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) -#define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) -#define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) -#define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) -#define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) -#define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) -#define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) - -#define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; -#define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); -#define NLOHMANN_JSON_FROM_WITH_DEFAULT(v1) nlohmann_json_t.v1 = !nlohmann_json_j.is_null() ? nlohmann_json_j.value(#v1, nlohmann_json_default_obj.v1) : nlohmann_json_default_obj.v1; - -/*! -@brief macro -@def NLOHMANN_DEFINE_TYPE_INTRUSIVE -@since version 3.9.0 -@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ -*/ -#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \ - template::value, int> = 0> \ - friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ - template::value, int> = 0> \ - friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } - -/*! -@brief macro -@def NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT -@since version 3.11.0 -@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ -*/ -#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(Type, ...) \ - template::value, int> = 0> \ - friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ - template::value, int> = 0> \ - friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } - -/*! -@brief macro -@def NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE -@since version 3.11.3 -@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ -*/ -#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \ - template::value, int> = 0> \ - friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } - -/*! -@brief macro -@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE -@since version 3.9.0 -@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ -*/ -#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \ - template::value, int> = 0> \ - void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ - template::value, int> = 0> \ - void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } - -/*! -@brief macro -@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT -@since version 3.11.0 -@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ -*/ -#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(Type, ...) \ - template::value, int> = 0> \ - void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ - template::value, int> = 0> \ - void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } - -/*! -@brief macro -@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE -@since version 3.11.3 -@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ -*/ -#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \ - template::value, int> = 0> \ - void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } - -/*! -@brief macro -@def NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE -@since version 3.12.0 -@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ -*/ -#define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE(Type, BaseType, ...) \ - template::value, int> = 0> \ - friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ - template::value, int> = 0> \ - friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } - -/*! -@brief macro -@def NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT -@since version 3.12.0 -@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ -*/ -#define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT(Type, BaseType, ...) \ - template::value, int> = 0> \ - friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ - template::value, int> = 0> \ - friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } - -/*! -@brief macro -@def NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE -@since version 3.12.0 -@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ -*/ -#define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE(Type, BaseType, ...) \ - template::value, int> = 0> \ - friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } - -/*! -@brief macro -@def NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE -@since version 3.12.0 -@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ -*/ -#define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE(Type, BaseType, ...) \ - template::value, int> = 0> \ - void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ - template::value, int> = 0> \ - void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } - -/*! -@brief macro -@def NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT -@since version 3.12.0 -@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ -*/ -#define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT(Type, BaseType, ...) \ - template::value, int> = 0> \ - void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ - template::value, int> = 0> \ - void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } - -/*! -@brief macro -@def NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE -@since version 3.12.0 -@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ -*/ -#define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(Type, BaseType, ...) \ - template::value, int> = 0> \ - void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } - -// inspired from https://stackoverflow.com/a/26745591 -// allows calling any std function as if (e.g., with begin): -// using std::begin; begin(x); -// -// it allows using the detected idiom to retrieve the return type -// of such an expression -#define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \ - namespace detail { \ - using std::std_name; \ - \ - template \ - using result_of_##std_name = decltype(std_name(std::declval()...)); \ - } \ - \ - namespace detail2 { \ - struct std_name##_tag \ - { \ - }; \ - \ - template \ - std_name##_tag std_name(T&&...); \ - \ - template \ - using result_of_##std_name = decltype(std_name(std::declval()...)); \ - \ - template \ - struct would_call_std_##std_name \ - { \ - static constexpr auto const value = ::nlohmann::detail:: \ - is_detected_exact::value; \ - }; \ - } /* namespace detail2 */ \ - \ - template \ - struct would_call_std_##std_name : detail2::would_call_std_##std_name \ - { \ - } - -#ifndef JSON_USE_IMPLICIT_CONVERSIONS - #define JSON_USE_IMPLICIT_CONVERSIONS 1 -#endif - -#if JSON_USE_IMPLICIT_CONVERSIONS - #define JSON_EXPLICIT -#else - #define JSON_EXPLICIT explicit -#endif - -#ifndef JSON_DISABLE_ENUM_SERIALIZATION - #define JSON_DISABLE_ENUM_SERIALIZATION 0 -#endif - -#ifndef JSON_USE_GLOBAL_UDLS - #define JSON_USE_GLOBAL_UDLS 1 -#endif - -#if JSON_HAS_THREE_WAY_COMPARISON - #include // partial_ordering -#endif - -NLOHMANN_JSON_NAMESPACE_BEGIN -namespace detail -{ - -/////////////////////////// -// JSON type enumeration // -/////////////////////////// - -/*! -@brief the JSON type enumeration - -This enumeration collects the different JSON types. It is internally used to -distinguish the stored values, and the functions @ref basic_json::is_null(), -@ref basic_json::is_object(), @ref basic_json::is_array(), -@ref basic_json::is_string(), @ref basic_json::is_boolean(), -@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), -@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), -@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and -@ref basic_json::is_structured() rely on it. - -@note There are three enumeration entries (number_integer, number_unsigned, and -number_float), because the library distinguishes these three types for numbers: -@ref basic_json::number_unsigned_t is used for unsigned integers, -@ref basic_json::number_integer_t is used for signed integers, and -@ref basic_json::number_float_t is used for floating-point numbers or to -approximate integers which do not fit in the limits of their respective type. - -@sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON -value with the default value for a given type - -@since version 1.0.0 -*/ -enum class value_t : std::uint8_t -{ - null, ///< null value - object, ///< object (unordered set of name/value pairs) - array, ///< array (ordered collection of values) - string, ///< string value - boolean, ///< boolean value - number_integer, ///< number value (signed integer) - number_unsigned, ///< number value (unsigned integer) - number_float, ///< number value (floating-point) - binary, ///< binary array (ordered collection of bytes) - discarded ///< discarded by the parser callback function -}; - -/*! -@brief comparison operator for JSON types - -Returns an ordering that is similar to Python: -- order: null < boolean < number < object < array < string < binary -- furthermore, each type is not smaller than itself -- discarded values are not comparable -- binary is represented as a b"" string in python and directly comparable to a - string; however, making a binary array directly comparable with a string would - be surprising behavior in a JSON file. - -@since version 1.0.0 -*/ -#if JSON_HAS_THREE_WAY_COMPARISON - inline std::partial_ordering operator<=>(const value_t lhs, const value_t rhs) noexcept // *NOPAD* -#else - inline bool operator<(const value_t lhs, const value_t rhs) noexcept -#endif -{ - static constexpr std::array order = {{ - 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, - 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, - 6 /* binary */ - } - }; - - const auto l_index = static_cast(lhs); - const auto r_index = static_cast(rhs); -#if JSON_HAS_THREE_WAY_COMPARISON - if (l_index < order.size() && r_index < order.size()) - { - return order[l_index] <=> order[r_index]; // *NOPAD* - } - return std::partial_ordering::unordered; -#else - return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; -#endif -} - -// GCC selects the built-in operator< over an operator rewritten from -// a user-defined spaceship operator -// Clang, MSVC, and ICC select the rewritten candidate -// (see GCC bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105200) -#if JSON_HAS_THREE_WAY_COMPARISON && defined(__GNUC__) -inline bool operator<(const value_t lhs, const value_t rhs) noexcept -{ - return std::is_lt(lhs <=> rhs); // *NOPAD* -} -#endif - -} // namespace detail -NLOHMANN_JSON_NAMESPACE_END - -// #include -// __ _____ _____ _____ -// __| | __| | | | JSON for Modern C++ -// | | |__ | | | | | | version 3.12.0 -// |_____|_____|_____|_|___| https://github.com/nlohmann/json -// -// SPDX-FileCopyrightText: 2013-2025 Niels Lohmann -// SPDX-License-Identifier: MIT - - - -// #include - - -NLOHMANN_JSON_NAMESPACE_BEGIN -namespace detail -{ - -/*! -@brief replace all occurrences of a substring by another string - -@param[in,out] s the string to manipulate; changed so that all - occurrences of @a f are replaced with @a t -@param[in] f the substring to replace with @a t -@param[in] t the string to replace @a f - -@pre The search string @a f must not be empty. **This precondition is -enforced with an assertion.** - -@since version 2.0.0 -*/ -template -inline void replace_substring(StringType& s, const StringType& f, - const StringType& t) -{ - JSON_ASSERT(!f.empty()); - for (auto pos = s.find(f); // find the first occurrence of f - pos != StringType::npos; // make sure f was found - s.replace(pos, f.size(), t), // replace with t, and - pos = s.find(f, pos + t.size())) // find the next occurrence of f - {} -} - -/*! - * @brief string escaping as described in RFC 6901 (Sect. 4) - * @param[in] s string to escape - * @return escaped string - * - * Note the order of escaping "~" to "~0" and "/" to "~1" is important. - */ -template -inline StringType escape(StringType s) -{ - replace_substring(s, StringType{"~"}, StringType{"~0"}); - replace_substring(s, StringType{"/"}, StringType{"~1"}); - return s; -} - -/*! - * @brief string unescaping as described in RFC 6901 (Sect. 4) - * @param[in] s string to unescape - * @return unescaped string - * - * Note the order of escaping "~1" to "/" and "~0" to "~" is important. - */ -template -inline void unescape(StringType& s) -{ - replace_substring(s, StringType{"~1"}, StringType{"/"}); - replace_substring(s, StringType{"~0"}, StringType{"~"}); -} - -} // namespace detail -NLOHMANN_JSON_NAMESPACE_END - -// #include -// __ _____ _____ _____ -// __| | __| | | | JSON for Modern C++ -// | | |__ | | | | | | version 3.12.0 -// |_____|_____|_____|_|___| https://github.com/nlohmann/json -// -// SPDX-FileCopyrightText: 2013-2025 Niels Lohmann -// SPDX-License-Identifier: MIT - - - -#include // size_t - -// #include - - -NLOHMANN_JSON_NAMESPACE_BEGIN -namespace detail -{ - -/// struct to capture the start position of the current token -struct position_t -{ - /// the total number of characters read - std::size_t chars_read_total = 0; - /// the number of characters read in the current line - std::size_t chars_read_current_line = 0; - /// the number of lines read - std::size_t lines_read = 0; - - /// conversion to size_t to preserve SAX interface - constexpr operator size_t() const - { - return chars_read_total; - } -}; - -} // namespace detail -NLOHMANN_JSON_NAMESPACE_END - -// #include - -// #include -// __ _____ _____ _____ -// __| | __| | | | JSON for Modern C++ -// | | |__ | | | | | | version 3.12.0 -// |_____|_____|_____|_|___| https://github.com/nlohmann/json -// -// SPDX-FileCopyrightText: 2013-2025 Niels Lohmann -// SPDX-FileCopyrightText: 2018 The Abseil Authors -// SPDX-License-Identifier: MIT - - - -#include // array -#include // size_t -#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type -#include // index_sequence, make_index_sequence, index_sequence_for - -// #include - - -NLOHMANN_JSON_NAMESPACE_BEGIN -namespace detail -{ - -template -using uncvref_t = typename std::remove_cv::type>::type; - -#ifdef JSON_HAS_CPP_14 - -// the following utilities are natively available in C++14 -using std::enable_if_t; -using std::index_sequence; -using std::make_index_sequence; -using std::index_sequence_for; - -#else - -// alias templates to reduce boilerplate -template -using enable_if_t = typename std::enable_if::type; - -// The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h -// which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. - -//// START OF CODE FROM GOOGLE ABSEIL - -// integer_sequence -// -// Class template representing a compile-time integer sequence. An instantiation -// of `integer_sequence` has a sequence of integers encoded in its -// type through its template arguments (which is a common need when -// working with C++11 variadic templates). `absl::integer_sequence` is designed -// to be a drop-in replacement for C++14's `std::integer_sequence`. -// -// Example: -// -// template< class T, T... Ints > -// void user_function(integer_sequence); -// -// int main() -// { -// // user_function's `T` will be deduced to `int` and `Ints...` -// // will be deduced to `0, 1, 2, 3, 4`. -// user_function(make_integer_sequence()); -// } -template -struct integer_sequence -{ - using value_type = T; - static constexpr std::size_t size() noexcept - { - return sizeof...(Ints); - } -}; - -// index_sequence -// -// A helper template for an `integer_sequence` of `size_t`, -// `absl::index_sequence` is designed to be a drop-in replacement for C++14's -// `std::index_sequence`. -template -using index_sequence = integer_sequence; - -namespace utility_internal -{ - -template -struct Extend; - -// Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency. -template -struct Extend, SeqSize, 0> -{ - using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >; -}; - -template -struct Extend, SeqSize, 1> -{ - using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >; -}; - -// Recursion helper for 'make_integer_sequence'. -// 'Gen::type' is an alias for 'integer_sequence'. -template -struct Gen -{ - using type = - typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type; -}; - -template -struct Gen -{ - using type = integer_sequence; -}; - -} // namespace utility_internal - -// Compile-time sequences of integers - -// make_integer_sequence -// -// This template alias is equivalent to -// `integer_sequence`, and is designed to be a drop-in -// replacement for C++14's `std::make_integer_sequence`. -template -using make_integer_sequence = typename utility_internal::Gen::type; - -// make_index_sequence -// -// This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`, -// and is designed to be a drop-in replacement for C++14's -// `std::make_index_sequence`. -template -using make_index_sequence = make_integer_sequence; - -// index_sequence_for -// -// Converts a typename pack into an index sequence of the same length, and -// is designed to be a drop-in replacement for C++14's -// `std::index_sequence_for()` -template -using index_sequence_for = make_index_sequence; - -//// END OF CODE FROM GOOGLE ABSEIL - -#endif - -// dispatch utility (taken from ranges-v3) -template struct priority_tag : priority_tag < N - 1 > {}; -template<> struct priority_tag<0> {}; - -// taken from ranges-v3 -template -struct static_const -{ - static JSON_INLINE_VARIABLE constexpr T value{}; -}; - -#ifndef JSON_HAS_CPP_17 - template - constexpr T static_const::value; -#endif - -template -constexpr std::array make_array(Args&& ... args) -{ - return std::array {{static_cast(std::forward(args))...}}; -} - -} // namespace detail -NLOHMANN_JSON_NAMESPACE_END - -// #include -// __ _____ _____ _____ -// __| | __| | | | JSON for Modern C++ -// | | |__ | | | | | | version 3.12.0 -// |_____|_____|_____|_|___| https://github.com/nlohmann/json -// -// SPDX-FileCopyrightText: 2013-2025 Niels Lohmann -// SPDX-License-Identifier: MIT - - - -#include // numeric_limits -#include // char_traits -#include // tuple -#include // false_type, is_constructible, is_integral, is_same, true_type -#include // declval -#if defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603L - #include // byte -#endif -// #include -// __ _____ _____ _____ -// __| | __| | | | JSON for Modern C++ -// | | |__ | | | | | | version 3.12.0 -// |_____|_____|_____|_|___| https://github.com/nlohmann/json -// -// SPDX-FileCopyrightText: 2013-2025 Niels Lohmann -// SPDX-License-Identifier: MIT - - - -#include // random_access_iterator_tag - -// #include - -// #include - -// #include - - -NLOHMANN_JSON_NAMESPACE_BEGIN -namespace detail -{ - -template -struct iterator_types {}; - -template -struct iterator_types < - It, - void_t> -{ - using difference_type = typename It::difference_type; - using value_type = typename It::value_type; - using pointer = typename It::pointer; - using reference = typename It::reference; - using iterator_category = typename It::iterator_category; -}; - -// This is required as some compilers implement std::iterator_traits in a way that -// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. -template -struct iterator_traits -{ -}; - -template -struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> - : iterator_types -{ -}; - -template -struct iterator_traits::value>> -{ - using iterator_category = std::random_access_iterator_tag; - using value_type = T; - using difference_type = ptrdiff_t; - using pointer = T*; - using reference = T&; -}; - -} // namespace detail -NLOHMANN_JSON_NAMESPACE_END - -// #include - -// #include -// __ _____ _____ _____ -// __| | __| | | | JSON for Modern C++ -// | | |__ | | | | | | version 3.12.0 -// |_____|_____|_____|_|___| https://github.com/nlohmann/json -// -// SPDX-FileCopyrightText: 2013-2025 Niels Lohmann -// SPDX-License-Identifier: MIT - - - -// #include - - -NLOHMANN_JSON_NAMESPACE_BEGIN - -NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin); - -NLOHMANN_JSON_NAMESPACE_END - -// #include -// __ _____ _____ _____ -// __| | __| | | | JSON for Modern C++ -// | | |__ | | | | | | version 3.12.0 -// |_____|_____|_____|_|___| https://github.com/nlohmann/json -// -// SPDX-FileCopyrightText: 2013-2025 Niels Lohmann -// SPDX-License-Identifier: MIT - - - -// #include - - -NLOHMANN_JSON_NAMESPACE_BEGIN - -NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end); - -NLOHMANN_JSON_NAMESPACE_END - -// #include - -// #include - -// #include -// __ _____ _____ _____ -// __| | __| | | | JSON for Modern C++ -// | | |__ | | | | | | version 3.12.0 -// |_____|_____|_____|_|___| https://github.com/nlohmann/json -// -// SPDX-FileCopyrightText: 2013-2025 Niels Lohmann -// SPDX-License-Identifier: MIT - -#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ - #define INCLUDE_NLOHMANN_JSON_FWD_HPP_ - - #include // int64_t, uint64_t - #include // map - #include // allocator - #include // string - #include // vector - - // #include - - - /*! - @brief namespace for Niels Lohmann - @see https://github.com/nlohmann - @since version 1.0.0 - */ - NLOHMANN_JSON_NAMESPACE_BEGIN - - /*! - @brief default JSONSerializer template argument - - This serializer ignores the template arguments and uses ADL - ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) - for serialization. - */ - template - struct adl_serializer; - - /// a class to store JSON values - /// @sa https://json.nlohmann.me/api/basic_json/ - template class ObjectType = - std::map, - template class ArrayType = std::vector, - class StringType = std::string, class BooleanType = bool, - class NumberIntegerType = std::int64_t, - class NumberUnsignedType = std::uint64_t, - class NumberFloatType = double, - template class AllocatorType = std::allocator, - template class JSONSerializer = - adl_serializer, - class BinaryType = std::vector, // cppcheck-suppress syntaxError - class CustomBaseClass = void> - class basic_json; - - /// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document - /// @sa https://json.nlohmann.me/api/json_pointer/ - template - class json_pointer; - - /*! - @brief default specialization - @sa https://json.nlohmann.me/api/json/ - */ - using json = basic_json<>; - - /// @brief a minimal map-like container that preserves insertion order - /// @sa https://json.nlohmann.me/api/ordered_map/ - template - struct ordered_map; - - /// @brief specialization that maintains the insertion order of object keys - /// @sa https://json.nlohmann.me/api/ordered_json/ - using ordered_json = basic_json; - - NLOHMANN_JSON_NAMESPACE_END - -#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ - - -NLOHMANN_JSON_NAMESPACE_BEGIN -/*! -@brief detail namespace with internal helper functions - -This namespace collects functions that should not be exposed, -implementations of some @ref basic_json methods, and meta-programming helpers. - -@since version 2.1.0 -*/ -namespace detail -{ - -///////////// -// helpers // -///////////// - -// Note to maintainers: -// -// Every trait in this file expects a non-CV-qualified type. -// The only exceptions are in the 'aliases for detected' section -// (i.e., those of the form: decltype(T::member_function(std::declval()))) -// -// In this case, T has to be properly CV-qualified to constraint the function arguments -// (e.g., to_json(BasicJsonType&, const T&)) - -template struct is_basic_json : std::false_type {}; - -NLOHMANN_BASIC_JSON_TPL_DECLARATION -struct is_basic_json : std::true_type {}; - -// used by exceptions create() member functions -// true_type for the pointer to possibly cv-qualified basic_json or std::nullptr_t -// false_type otherwise -template -struct is_basic_json_context : - std::integral_constant < bool, - is_basic_json::type>::type>::value - || std::is_same::value > -{}; - -////////////////////// -// json_ref helpers // -////////////////////// - -template -class json_ref; - -template -struct is_json_ref : std::false_type {}; - -template -struct is_json_ref> : std::true_type {}; - -////////////////////////// -// aliases for detected // -////////////////////////// - -template -using mapped_type_t = typename T::mapped_type; - -template -using key_type_t = typename T::key_type; - -template -using value_type_t = typename T::value_type; - -template -using difference_type_t = typename T::difference_type; - -template -using pointer_t = typename T::pointer; - -template -using reference_t = typename T::reference; - -template -using iterator_category_t = typename T::iterator_category; - -template -using to_json_function = decltype(T::to_json(std::declval()...)); - -template -using from_json_function = decltype(T::from_json(std::declval()...)); - -template -using get_template_function = decltype(std::declval().template get()); - -// trait checking if JSONSerializer::from_json(json const&, udt&) exists -template -struct has_from_json : std::false_type {}; - -// trait checking if j.get is valid -// use this trait instead of std::is_constructible or std::is_convertible, -// both rely on, or make use of implicit conversions, and thus fail when T -// has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) -template -struct is_getable -{ - static constexpr bool value = is_detected::value; -}; - -template -struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> -{ - using serializer = typename BasicJsonType::template json_serializer; - - static constexpr bool value = - is_detected_exact::value; -}; - -// This trait checks if JSONSerializer::from_json(json const&) exists -// this overload is used for non-default-constructible user-defined-types -template -struct has_non_default_from_json : std::false_type {}; - -template -struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> -{ - using serializer = typename BasicJsonType::template json_serializer; - - static constexpr bool value = - is_detected_exact::value; -}; - -// This trait checks if BasicJsonType::json_serializer::to_json exists -// Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. -template -struct has_to_json : std::false_type {}; - -template -struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> -{ - using serializer = typename BasicJsonType::template json_serializer; - - static constexpr bool value = - is_detected_exact::value; -}; - -template -using detect_key_compare = typename T::key_compare; - -template -struct has_key_compare : std::integral_constant::value> {}; - -// obtains the actual object key comparator -template -struct actual_object_comparator -{ - using object_t = typename BasicJsonType::object_t; - using object_comparator_t = typename BasicJsonType::default_object_comparator_t; - using type = typename std::conditional < has_key_compare::value, - typename object_t::key_compare, object_comparator_t>::type; -}; - -template -using actual_object_comparator_t = typename actual_object_comparator::type; - -///////////////// -// char_traits // -///////////////// - -// Primary template of char_traits calls std char_traits -template -struct char_traits : std::char_traits -{}; - -// Explicitly define char traits for unsigned char since it is not standard -template<> -struct char_traits : std::char_traits -{ - using char_type = unsigned char; - using int_type = uint64_t; - - // Redefine to_int_type function - static int_type to_int_type(char_type c) noexcept - { - return static_cast(c); - } - - static char_type to_char_type(int_type i) noexcept - { - return static_cast(i); - } - - static constexpr int_type eof() noexcept - { - return static_cast(std::char_traits::eof()); - } -}; - -// Explicitly define char traits for signed char since it is not standard -template<> -struct char_traits : std::char_traits -{ - using char_type = signed char; - using int_type = uint64_t; - - // Redefine to_int_type function - static int_type to_int_type(char_type c) noexcept - { - return static_cast(c); - } - - static char_type to_char_type(int_type i) noexcept - { - return static_cast(i); - } - - static constexpr int_type eof() noexcept - { - return static_cast(std::char_traits::eof()); - } -}; - -#if defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603L -template<> -struct char_traits : std::char_traits -{ - using char_type = std::byte; - using int_type = uint64_t; - - static int_type to_int_type(char_type c) noexcept - { - return static_cast(std::to_integer(c)); - } - - static char_type to_char_type(int_type i) noexcept - { - return std::byte(static_cast(i)); - } - - static constexpr int_type eof() noexcept - { - return static_cast(std::char_traits::eof()); - } -}; -#endif - -/////////////////// -// is_ functions // -/////////////////// - -// https://en.cppreference.com/w/cpp/types/conjunction -template struct conjunction : std::true_type { }; -template struct conjunction : B { }; -template -struct conjunction -: std::conditional(B::value), conjunction, B>::type {}; - -// https://en.cppreference.com/w/cpp/types/negation -template struct negation : std::integral_constant < bool, !B::value > { }; - -// Reimplementation of is_constructible and is_default_constructible, due to them being broken for -// std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367). -// This causes compile errors in e.g., Clang 3.5 or GCC 4.9. -template -struct is_default_constructible : std::is_default_constructible {}; - -template -struct is_default_constructible> - : conjunction, is_default_constructible> {}; - -template -struct is_default_constructible> - : conjunction, is_default_constructible> {}; - -template -struct is_default_constructible> - : conjunction...> {}; - -template -struct is_default_constructible> - : conjunction...> {}; - -template -struct is_constructible : std::is_constructible {}; - -template -struct is_constructible> : is_default_constructible> {}; - -template -struct is_constructible> : is_default_constructible> {}; - -template -struct is_constructible> : is_default_constructible> {}; - -template -struct is_constructible> : is_default_constructible> {}; - -template -struct is_iterator_traits : std::false_type {}; - -template -struct is_iterator_traits> -{ - private: - using traits = iterator_traits; - - public: - static constexpr auto value = - is_detected::value && - is_detected::value && - is_detected::value && - is_detected::value && - is_detected::value; -}; - -template -struct is_range -{ - private: - using t_ref = typename std::add_lvalue_reference::type; - - using iterator = detected_t; - using sentinel = detected_t; - - // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator - // and https://en.cppreference.com/w/cpp/iterator/sentinel_for - // but reimplementing these would be too much work, as a lot of other concepts are used underneath - static constexpr auto is_iterator_begin = - is_iterator_traits>::value; - - public: - static constexpr bool value = !std::is_same::value && !std::is_same::value && is_iterator_begin; -}; - -template -using iterator_t = enable_if_t::value, result_of_begin())>>; - -template -using range_value_t = value_type_t>>; - -// The following implementation of is_complete_type is taken from -// https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ -// and is written by Xiang Fan who agreed to use it in this library. - -template -struct is_complete_type : std::false_type {}; - -template -struct is_complete_type : std::true_type {}; - -template -struct is_compatible_object_type_impl : std::false_type {}; - -template -struct is_compatible_object_type_impl < - BasicJsonType, CompatibleObjectType, - enable_if_t < is_detected::value&& - is_detected::value >> -{ - using object_t = typename BasicJsonType::object_t; - - // macOS's is_constructible does not play well with nonesuch... - static constexpr bool value = - is_constructible::value && - is_constructible::value; -}; - -template -struct is_compatible_object_type - : is_compatible_object_type_impl {}; - -template -struct is_constructible_object_type_impl : std::false_type {}; - -template -struct is_constructible_object_type_impl < - BasicJsonType, ConstructibleObjectType, - enable_if_t < is_detected::value&& - is_detected::value >> -{ - using object_t = typename BasicJsonType::object_t; - - static constexpr bool value = - (is_default_constructible::value && - (std::is_move_assignable::value || - std::is_copy_assignable::value) && - (is_constructible::value && - std::is_same < - typename object_t::mapped_type, - typename ConstructibleObjectType::mapped_type >::value)) || - (has_from_json::value || - has_non_default_from_json < - BasicJsonType, - typename ConstructibleObjectType::mapped_type >::value); -}; - -template -struct is_constructible_object_type - : is_constructible_object_type_impl {}; - -template -struct is_compatible_string_type -{ - static constexpr auto value = - is_constructible::value; -}; - -template -struct is_constructible_string_type -{ - // launder type through decltype() to fix compilation failure on ICPC -#ifdef __INTEL_COMPILER - using laundered_type = decltype(std::declval()); -#else - using laundered_type = ConstructibleStringType; -#endif - - static constexpr auto value = - conjunction < - is_constructible, - is_detected_exact>::value; -}; - -template -struct is_compatible_array_type_impl : std::false_type {}; - -template -struct is_compatible_array_type_impl < - BasicJsonType, CompatibleArrayType, - enable_if_t < - is_detected::value&& - is_iterator_traits>>::value&& -// special case for types like std::filesystem::path whose iterator's value_type are themselves -// c.f. https://github.com/nlohmann/json/pull/3073 - !std::is_same>::value >> -{ - static constexpr bool value = - is_constructible>::value; -}; - -template -struct is_compatible_array_type - : is_compatible_array_type_impl {}; - -template -struct is_constructible_array_type_impl : std::false_type {}; - -template -struct is_constructible_array_type_impl < - BasicJsonType, ConstructibleArrayType, - enable_if_t::value >> - : std::true_type {}; - -template -struct is_constructible_array_type_impl < - BasicJsonType, ConstructibleArrayType, - enable_if_t < !std::is_same::value&& - !is_compatible_string_type::value&& - is_default_constructible::value&& -(std::is_move_assignable::value || - std::is_copy_assignable::value)&& -is_detected::value&& -is_iterator_traits>>::value&& -is_detected::value&& -// special case for types like std::filesystem::path whose iterator's value_type are themselves -// c.f. https://github.com/nlohmann/json/pull/3073 -!std::is_same>::value&& -is_complete_type < -detected_t>::value >> -{ - using value_type = range_value_t; - - static constexpr bool value = - std::is_same::value || - has_from_json::value || - has_non_default_from_json < - BasicJsonType, - value_type >::value; -}; - -template -struct is_constructible_array_type - : is_constructible_array_type_impl {}; - -template -struct is_compatible_integer_type_impl : std::false_type {}; - -template -struct is_compatible_integer_type_impl < - RealIntegerType, CompatibleNumberIntegerType, - enable_if_t < std::is_integral::value&& - std::is_integral::value&& - !std::is_same::value >> -{ - // is there an assert somewhere on overflows? - using RealLimits = std::numeric_limits; - using CompatibleLimits = std::numeric_limits; - - static constexpr auto value = - is_constructible::value && - CompatibleLimits::is_integer && - RealLimits::is_signed == CompatibleLimits::is_signed; -}; - -template -struct is_compatible_integer_type - : is_compatible_integer_type_impl {}; - -template -struct is_compatible_type_impl: std::false_type {}; - -template -struct is_compatible_type_impl < - BasicJsonType, CompatibleType, - enable_if_t::value >> -{ - static constexpr bool value = - has_to_json::value; -}; - -template -struct is_compatible_type - : is_compatible_type_impl {}; - -template -struct is_constructible_tuple : std::false_type {}; - -template -struct is_constructible_tuple> : conjunction...> {}; - -template -struct is_json_iterator_of : std::false_type {}; - -template -struct is_json_iterator_of : std::true_type {}; - -template -struct is_json_iterator_of : std::true_type -{}; - -// checks if a given type T is a template specialization of Primary -template